version
stringclasses
1 value
style
stringclasses
2 values
subset
stringclasses
12 values
question_id
stringlengths
9
23
question
stringlengths
27
8.13k
solution
stringlengths
99
5.97k
test
stringlengths
105
4.45k
test_info
listlengths
0
13
gpt_pass_sequence
listlengths
1
10
gpt_pass_trial_num
int64
1
10
gpt_difficulty
stringclasses
3 values
gpt_pass_percentage
float64
0.1
1
trials
dict
chosen_trial
stringclasses
10 values
metadata
dict
benchmark_similarity
float64
0.16
0.93
benchmark_instruction
stringclasses
1 value
benchmark_task_id
stringclasses
1 value
filter_reason
stringclasses
1 value
base_id
stringlengths
7
21
variant
stringclasses
2 values
top_function_names
listlengths
2
13
n_top_functions
int64
2
13
helper_call_edges
listlengths
1
16
n_helper_call_edges
int64
1
16
harness_functions
listlengths
0
3
structural_wrapper
bool
1 class
class_names
listlengths
0
5
has_class
bool
2 classes
test_kind
stringclasses
1 value
test_has_solution_import
bool
2 classes
third_party_imports
listlengths
0
5
stdlib_only
bool
2 classes
question_norm_sha1
stringlengths
40
40
solution_ast_sha1
stringlengths
40
40
v1.0
instruct
Docs
Docs: Python310_6961_I
**XML Document Traversal and Modification Using `xml.dom`** Given an XML document, create a Python function named `transform_xml_document` that modifies certain elements and attributes based on specific criteria and returns the modified XML document as a string. ### Function Signature ```python def transform_xml_doc...
from xml.dom.minidom import parseString, Node from xml.parsers.expat import ExpatError class XMLTransformationError(Exception): def __init__(self, message): self.message = message super().__init__(self.message) def transform_xml_document(xml_string: str) -> str: try: # Parse the XML ...
import pytest from solution import transform_xml_document, XMLTransformationError def test_transform_xml_document_success(): input_xml = '''<store> <item type="fruit"> <name>Apple</name> <quantity>10</quantity> </item> <item type="vegetable"> <name>Carrot...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import xml.dom.minidom\n\nclass XMLTransformationError(Exception):\n def __init__(self, message):\n self.message = message\n super().__init__(self.mess...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006961", "row_id": 6961, "seed_ids": "[244]" }
0.569979
Docs: Python310_6961
I
[ "transform_xml_document", "change_tag" ]
2
[ [ "transform_xml_document", "change_tag" ] ]
1
[]
false
[ "XMLTransformationError" ]
true
pytest
true
[]
true
9292b2b167bbe184d6dff216e1c4d8aec280bdf1
f26905105f6bc200d6a7394dbeee0ca680a4a687
v1.0
instruct
Docs
Docs: Python310_6985_I
### Question: Context Managers in `contextlib` #### Objective: Create a custom context manager using the `contextlib.contextmanager` decorator to manage a resource. Additionally, implement a synchronous function that makes use of this context manager to demonstrate its utility. #### Instructions: 1. Define a function...
from contextlib import contextmanager @contextmanager def managed_file(filename, mode): """ Context manager to open, yield, and then close a file. Ensures the file is closed even if an exception occurs. """ f = open(filename, mode) try: yield f finally: f.close() def write_...
from solution import managed_file, write_to_file import os def test_managed_file(): # Test that the file is opened and closed properly with managed_file('test.txt', 'w') as f: f.write('Test content') assert os.path.exists('test.txt'), "File was not created by managed_file." # Test that it thro...
[ { "docstring": "Context manager to open, yield, and then close a file.\nEnsures the file is closed even if an exception occurs.", "function_declaration": "def managed_file(filename, mode):", "function_name": "managed_file", "parameter_list": "(filename, mode)" }, { "docstring": "Writes the s...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from contextlib import contextmanager\n\n@contextmanager\ndef managed_file(filename, mode):\n \"\"\"\n A context manager to handle opening and closing of a file.\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006985", "row_id": 6985, "seed_ids": "[177]" }
0.435995
Docs: Python310_6985
I
[ "managed_file", "write_to_file" ]
2
[ [ "write_to_file", "managed_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
09b0bfdb5582cec0f9861b03c5fcfa67c51f953f
89ed922081c55552d4cc9532e4e031472f99024e
v1.0
instruct
Docs
Docs: Python310_7104_I
### Signal Handling in Python You are required to implement a Python program that demonstrates the use of the `signal` module to handle various types of signals. You will set up signal handlers for `SIGINT`, `SIGALRM`, and `SIGTERM` and ensure the application handles these signals gracefully. ### Requirements: 1. **...
import signal import time import os def sigint_handler(signum, frame): print("SIGINT received") raise KeyboardInterrupt def sigalrm_handler(signum, frame): print("Alarm Triggered") def sigterm_handler(signum, frame): print("SIGTERM received, shutting down gracefully") clean_up() exit(0) def ...
import signal import os import time import subprocess from threading import Timer import pytest def test_sigint_handling(): def send_sigint(): os.kill(os.getpid(), signal.SIGINT) Timer(2, send_sigint).start() with pytest.raises(KeyboardInterrupt): signal.signal(signal.SIGINT, sigint_handle...
[ { "docstring": null, "function_declaration": "def sigint_handler(signum, frame):", "function_name": "sigint_handler", "parameter_list": "(signum, frame)" }, { "docstring": null, "function_declaration": "def sigalrm_handler(signum, frame):", "function_name": "sigalrm_handler", "pa...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import signal\nimport time\nimport os\n\ndef sigint_handler(signum, frame):\n print(\"SIGINT received\")\n raise KeyboardInterrupt\n\ndef sigalrm_handler(signum, ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00007104", "row_id": 7104, "seed_ids": "[253]" }
0.463643
Docs: Python310_7104
I
[ "sigint_handler", "sigalrm_handler", "sigterm_handler", "clean_up", "main" ]
5
[ [ "sigterm_handler", "clean_up" ] ]
1
[]
false
[]
false
pytest
false
[]
true
58a6f96760fc9b20cc0db83c623ec046622df849
12213d7bb5966a2af35be04fbaf88a77f4a5f965
v1.0
instruct
Docs
Docs: Python310_7165_I
### Question: Asynchronous HTTP Fetcher **Objective:** Implement an asynchronous HTTP fetcher using the `asyncio` module in Python. **Requirements:** - Create an asynchronous function `fetch_url(url: str) -> dict` that takes a URL as input and returns a dictionary with the keys `"url"`, `"status"`, and `"content_leng...
import aiohttp import asyncio from typing import List, Dict async def fetch_url(url: str) -> Dict[str, any]: async with aiohttp.ClientSession() as session: try: async with session.get(url) as response: content = await response.read() return { ...
import pytest import asyncio from solution import fetch_url, fetch_all @pytest.mark.asyncio async def test_fetch_url_success(): result = await fetch_url("http://example.com") assert result["url"] == "http://example.com" assert result["status"] == 200 assert result["content_length"] > 0 @pytest.mark.as...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import aiohttp\nimport asyncio\nfrom typing import List, Dict\n\nasync def fetch_url(url: str) -> Dict[str, any]:\n async with aiohttp.ClientSession() as session:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00007165", "row_id": 7165, "seed_ids": "[151]" }
0.649324
Docs: Python310_7165
I
[ "fetch_url", "fetch_all" ]
2
[ [ "fetch_all", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
517878530988583f7a7bf378e4a220b5d77481a3
cc70489252740661d469709c7e648df1069a8678
v1.0
instruct
Docs
Docs: Python310_7254_I
#### Objective: Demonstrate your understanding of `asyncio` for asynchronous operations and `socket` for low-level networking by designing and implementing a simple asynchronous chat server and client. #### Task: 1. **Chat Server**: - Implement an asynchronous chat server using the `asyncio` and `socket` module. ...
import asyncio import socket async def handle_client(client_socket, clients): reader, writer = await asyncio.open_connection(sock=client_socket) clients.add(writer) try: while True: message = await reader.read(100) if not message: break # Broadcas...
import asyncio import pytest from solution import start_chat_server, start_chat_client @pytest.mark.asyncio async def test_chat_server_and_client(): server_host, server_port = 'localhost', 8888 server = asyncio.create_task(start_chat_server(server_host, server_port)) # Allow server to start await...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport socket\n\nasync def handle_client(client_socket, clients):\n reader, writer = await asyncio.open_connection(sock=client_socket)\n clients.a...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00007254", "row_id": 7254, "seed_ids": "[151]" }
0.529241
Docs: Python310_7254
I
[ "handle_client", "start_chat_server", "send_message", "receive_message", "start_chat_client", "input_loop" ]
6
[ [ "input_loop", "send_message" ], [ "start_chat_client", "input_loop" ], [ "start_chat_client", "receive_message" ], [ "start_chat_server", "handle_client" ] ]
4
[]
false
[]
false
pytest
true
[]
true
4cb7398386d1f3060e591132778dbdbe10e0f111
beb292ffed62f25fd2d4dcf49a4754d46eceeb7a
v1.0
instruct
Docs
Docs: Python310_7261_I
#### Objective: Implement an asynchronous task processor using `asyncio.Queue`. The processor should be able to handle multiple types of queues (FIFO, LIFO, Priority) and manage tasks with error handling, ensuring that all tasks are processed correctly. #### Problem Statement: You are required to write a function `asy...
import asyncio from asyncio import Queue, LifoQueue, PriorityQueue, QueueFull, QueueEmpty async def worker(name, queue): while True: try: task = await queue.get() if isinstance(queue, PriorityQueue): priority, task_id, duration = task print(f'{name} p...
import asyncio import pytest from solution import async_task_processor @pytest.mark.asyncio async def test_fifo_queue(): task_list = [(1, 2), (2, 1), (3, 0.5)] queue_type = 'fifo' maxsize = 5 await async_task_processor(task_list, queue_type, maxsize) @pytest.mark.asyncio async def test_lifo_queue(): ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def worker(queue):\n while True:\n try:\n task = await queue.get()\n if isinstance(task, tuple) and len(task) ==...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00007261", "row_id": 7261, "seed_ids": "[111]" }
0.538856
Docs: Python310_7261
I
[ "worker", "async_task_processor" ]
2
[ [ "async_task_processor", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0514f7fffc593955e359976ef506a783a0e76d4a
5c5a4914fb56f4f681bbbb5f9421159bfc0d2739
v1.0
instruct
Docs
Docs: Python310_7276_I
### Asynchronous Chat Server #### Objective: Implement a simple chat server using the `asyncio` and `socket` modules that supports multiple clients connecting and sending messages to a chat room. #### Task: 1. Implement an asynchronous chat server that can handle multiple clients. 2. The server should allow clients t...
import asyncio import socket clients = [] async def broadcast(message, writer): for client_writer in clients: if client_writer != writer: client_writer.write(message) await client_writer.drain() async def handle_client(reader, writer): addr = writer.get_extra_info('peername') ...
import asyncio import socket import pytest @pytest.fixture async def echo_server(): server = await asyncio.start_server( handle_client, 'localhost', 12345) async with server: yield server @pytest.mark.asyncio async def test_client_connection(echo_server): reader, writer = await asyncio.ope...
[]
[ 0, 0, 0, 0, 1, 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 asyncio\n\nclients = {}\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n print(f\"New connection from {addr}\")\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00007276", "row_id": 7276, "seed_ids": "[151]" }
0.656389
Docs: Python310_7276
I
[ "broadcast", "handle_client", "start_chat_server" ]
3
[ [ "handle_client", "broadcast" ], [ "start_chat_server", "handle_client" ] ]
2
[]
false
[]
false
pytest
false
[]
true
546870f93753b978451a7a5b65bd45552e64b097
d8a1c4357ebfbfbc5402e21817e7c9c1f11d0b3d
v1.0
instruct
Docs
Docs: Python310_7323_I
### Question: Concurrent Prime Number Calculation You are tasked with implementing a concurrent prime number calculation using the low-level threading API provided by the `_thread` module. The goal is to determine the prime numbers within a given range `[start, end]` using multiple threads to speed up the computation....
import _thread from typing import List def is_prime(n: int) -> bool: if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return...
def test_concurrent_prime_calculation_small_range(): assert concurrent_prime_calculation(1, 10, 2) == [2, 3, 5, 7] def test_concurrent_prime_calculation_large_range(): assert concurrent_prime_calculation(1, 50, 4) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] def test_concurrent_prime_calculatio...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def concurrent_prime_calculation(start, end, num_threads):", "function_name": "concurrent_prime_calculation", "pa...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import _thread\nimport math\n\ndef is_prime(num):\n \"\"\"Check if a number is prime.\"\"\"\n if num < 2:\n return False\n if num in (2, 3):\n re...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00007323", "row_id": 7323, "seed_ids": "[223]" }
0.538152
Docs: Python310_7323
I
[ "is_prime", "concurrent_prime_calculation" ]
2
[ [ "concurrent_prime_calculation", "is_prime" ] ]
1
[]
false
[]
false
pytest
false
[]
true
e471dc266f3fa8543e3e163fae467120fef1d195
f41540465719c30dd03d847d8830738b6bd6288b
v1.0
instruct
Docs
Docs: Python310_7418_I
### Concurrent Futures Assessment #### Objective Implement a function using the `concurrent.futures` module to perform parallel processing on a set of tasks, demonstrating the ability to manage asynchronous operations and handle exceptions properly. #### Problem Statement You are given a list of URLs to fetch data fr...
import requests from concurrent.futures import ThreadPoolExecutor, as_completed from typing import List, Optional def fetch_url(url: str, timeout: int) -> Optional[str]: """ Helper function to fetch the content of a single URL with a specified timeout. Returns the content of the URL or None if the request ...
import pytest from solution import fetch_parallel # Mocking requests.get to simulate different scenarios from unittest.mock import patch, MagicMock URLs = ["http://example.com/success", "http://example.com/fail", "http://example.com/timeout", "http://example.com/another"] def mock_requests_get(url, timeout): if ...
[ { "docstring": "Helper function to fetch the content of a single URL with a specified timeout.\nReturns the content of the URL or None if the request fails.", "function_declaration": "def fetch_url(url, timeout):", "function_name": "fetch_url", "parameter_list": "(url, timeout)" }, { "docstr...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom typing import List, Optional\n\ndef fetch_url(url: str, timeout: int) -> Optional...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00007418", "row_id": 7418, "seed_ids": "[224]" }
0.551882
Docs: Python310_7418
I
[ "fetch_url", "fetch_parallel" ]
2
[ [ "fetch_parallel", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
5e1e99a8e395dc29b11f82b6b29133007c7c6bd8
07cb22d50d8991080809c7c1e518606dd34e118a
v1.0
instruct
Docs
Docs: Python310_7473_I
**Question: Implementing a Dynamic Class with Special Attributes** Objective: You are required to create a dynamic class using the `types.new_class` function from the `types` module. The class should be named `DynamicPerson`, have a couple of special methods and attributes, and demonstrate the utility of the `SimpleNa...
import types from types import SimpleNamespace def create_dynamic_person_class(): def init(self, name, age): self.name = name self.age = age self.history = [] def add_to_history(self, record): self.history.append(record) def repr(self): return f"DynamicPerson(name=...
from solution import create_dynamic_person_class, test_dynamic_person_class def test_dynamic_person_creation(): DynamicPerson = create_dynamic_person_class() assert DynamicPerson.__name__ == 'DynamicPerson' def test_dynamic_person_initialization(): DynamicPerson = create_dynamic_person_class() person ...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import types\nfrom types import SimpleNamespace\n\ndef create_dynamic_person_class():\n def exec_body(ns):\n def __init__(self, name, age):\n self....
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00007473", "row_id": 7473, "seed_ids": "[372]" }
0.409745
Docs: Python310_7473
I
[ "create_dynamic_person_class", "test_dynamic_person_class" ]
2
[ [ "test_dynamic_person_class", "create_dynamic_person_class" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2d95e4b9672d0f260cee3ab0b503dffd865ceced
49c3ad0ccc19e54d3dc0361fcc6a1a7427120f52
v1.0
instruct
Docs
Docs: Python310_7475_I
### Coding Assessment: Turtle Graphics Drawing with Events **Objective:** Demonstrate your understanding of the `turtle` module by creating an interactive drawing program using specified turtle graphics concepts. **Description:** Create a turtle graphics program in Python where the turtle will draw different shapes b...
import turtle def setup_screen(): screen = turtle.Screen() screen.bgcolor("lightgrey") return screen def setup_turtle(): t = turtle.Turtle() t.shape("turtle") t.speed(5) return t def move_forward(): turtle.forward(50) def move_backward(): turtle.backward(50) def turn_left(): ...
# Since the turtle module and its graphics interface doesn't support automated unit tests in a traditional # manner, we can only provide a structured way to manually verify the functionality by running the code. # Automated tests for turtle graphics would require a mock environment that does not exist here. # Thus, no ...
[ { "docstring": null, "function_declaration": "def setup_screen():", "function_name": "setup_screen", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def setup_turtle():", "function_name": "setup_turtle", "parameter_list": "()" }, { "docstring": nul...
[ 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 turtle\n\ndef setup_screen():\n screen = turtle.Screen()\n screen.bgcolor(\"lightblue\")\n screen.title(\"Interactive Turtle Graphics\")\n \n return ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00007475", "row_id": 7475, "seed_ids": "[296]" }
0.737388
Docs: Python310_7475
I
[ "setup_screen", "setup_turtle", "move_forward", "move_backward", "turn_left", "turn_right", "toggle_color", "draw_circle", "draw_square", "reset_screen", "main" ]
11
[ [ "draw_circle", "toggle_color" ], [ "draw_square", "toggle_color" ], [ "reset_screen", "main" ] ]
3
[]
false
[]
false
pytest
false
[]
true
0c4f51c30c0e664df4f6acffb9a21063f0cf7935
6fa604be81b664ec61c0fb1c03609c36709da268
v1.0
instruct
Docs
Docs: Python310_7483_I
#### Objective: To design a function that utilizes iterators, generators, and other functional programming constructs to solve a practical problem. This will test the student's understanding and ability to implement Python's functional programming features. #### Problem Statement: You are to implement a Python functio...
from typing import Iterator, List import itertools def generate_primes() -> Iterator[int]: """ A generator that yields an infinite sequence of prime numbers. """ D = {} q = 2 while True: if q not in D: # q is a prime number yield q D[q * q] = [q] ...
from solution import generate_primes, filter_primes_below def test_generate_primes(): prime_gen = generate_primes() primes_expected = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] primes_actual = [next(prime_gen) for _ in range(10)] assert primes_actual == primes_expected def test_filter_primes_below_10(): ...
[ { "docstring": "A generator that yields an infinite sequence of prime numbers.", "function_declaration": "def generate_primes():", "function_name": "generate_primes", "parameter_list": "()" }, { "docstring": "Filters out all prime numbers below a given integer n.", "function_declaration"...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import Iterator, List\n\ndef generate_primes() -> Iterator[int]:\n \"\"\"\n Generates an infinite sequence of prime numbers using a generator.\n Ut...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00007483", "row_id": 7483, "seed_ids": "[78]" }
0.743783
Docs: Python310_7483
I
[ "generate_primes", "filter_primes_below" ]
2
[ [ "filter_primes_below", "generate_primes" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c29d1658bf529d28486f9105746bc250b3ebf281
97777d7de966b510c41980410578876e043ba276
v1.0
instruct
Docs
Docs: Python310_7484_I
### Python310 Coding Assessment Question #### Objective: To assess the ability to work with specialized data types and collections provided in python310. #### Problem Statement: You are required to write a function `event_scheduler()` that schedules events based on their start and end times. Each event is represented...
from datetime import datetime, timedelta from typing import List, Tuple from collections import defaultdict, OrderedDict # A global variable to maintain events events_by_date = defaultdict(OrderedDict) def event_scheduler(events: List[Tuple[str, datetime, datetime]]) -> None: """ Initialize the scheduler with...
from datetime import datetime, timedelta import pytest from solution import event_scheduler, add_event, get_daily_events def test_event_scheduler(): events = [ ("Meeting", datetime(2023, 10, 1, 9, 0), datetime(2023, 10, 1, 10, 0)), ("Workshop", datetime(2023, 10, 1, 10, 30), datetime(2023, 10, 1, 1...
[ { "docstring": "Initialize the scheduler with a list of events.", "function_declaration": "def event_scheduler(events):", "function_name": "event_scheduler", "parameter_list": "(events)" }, { "docstring": "Add an event if it does not conflict with existing events.", "function_declaration...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from datetime import datetime, timedelta\nfrom typing import List, Tuple\nfrom collections import defaultdict, OrderedDict\n\n# A global variable to maintain events\nev...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00007484", "row_id": 7484, "seed_ids": "[257]" }
0.605205
Docs: Python310_7484
I
[ "event_scheduler", "add_event", "get_daily_events" ]
3
[ [ "event_scheduler", "add_event" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3a6f413fe1233781de41af7d34a6b512f245ad32
0455561575cd35a2beb7501dffc35c65f02eec98
v1.0
instruct
Docs
Docs: Python310_7501_I
**Question: HMAC Message Authentication** You are tasked with creating a secure verification system for messages using the HMAC (Keyed-Hashing for Message Authentication) algorithm provided by the Python `hmac` module. Your goal is to implement several functions to handle the creation, updating, and verification of HM...
import hmac import hashlib def create_hmac(key: bytes, msg: bytes, digestmod: str) -> hmac.HMAC: """ Creates and returns an HMAC object initialized with the given key, message, and hash algorithm. """ return hmac.new(key, msg, digestmod=getattr(hashlib, digestmod)) def update_hmac(h: hmac.HMAC, m...
import pytest from solution import create_hmac, update_hmac, get_hexdigest, compare_hmacs, verify_message def test_create_hmac(): key = b'secret_key' msg = b'hello' digestmod = 'sha256' h = create_hmac(key, msg, digestmod) assert isinstance(h, hmac.HMAC) def test_update_hmac(): key = b'secret_...
[ { "docstring": "Creates and returns an HMAC object initialized with the given key, \nmessage, and hash algorithm.", "function_declaration": "def create_hmac(key, msg, digestmod):", "function_name": "create_hmac", "parameter_list": "(key, msg, digestmod)" }, { "docstring": "Updates the HMAC o...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hmac\nimport hashlib\n\ndef create_hmac(key: bytes, msg: bytes, digestmod: str) -> hmac.HMAC:\n \"\"\"\n Returns an initialized HMAC object.\n \"\"\"\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00007501", "row_id": 7501, "seed_ids": "[298]" }
0.815272
Docs: Python310_7501
I
[ "create_hmac", "update_hmac", "get_hexdigest", "compare_hmacs", "verify_message" ]
5
[ [ "verify_message", "compare_hmacs" ], [ "verify_message", "create_hmac" ], [ "verify_message", "get_hexdigest" ] ]
3
[]
false
[]
false
pytest
true
[]
true
38e4c8d6fd323bb67400f9f013d6a68c08bec57e
579054e7eebfadc62861397c692c623abb271beb
v1.0
instruct
Docs
Docs: Python310_7512_I
### Python Coding Assessment Question **Objective:** Implement a Python application using `asyncio` that processes multiple tasks concurrently while ensuring that no task blocks the event loop. The application must also handle logging and have debug mode enabled to help trace any issues during execution. #### Problem...
import asyncio import logging from typing import List, Any async def process_chunk(chunk: bytes) -> Any: """ Simulate processing of a single chunk of data. Can be CPU-bound or I/O-bound. """ # Simulate CPU-bound operation await asyncio.sleep(1) # Simulate IO-bound task return f"Processed {...
import asyncio import pytest from solution import process_data_concurrently @pytest.mark.asyncio async def test_process_data_concurrently(): data = [b'123', b'456', b'78910'] results = await process_data_concurrently(data) expected = [f"Processed {len(chunk)} bytes" for chunk in data] assert results ==...
[]
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport logging\nfrom typing import List, Any\n\nasync def process_chunk(chunk: bytes) -> Any:\n \"\"\"\n Simulate processing of a single chunk of ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00007512", "row_id": 7512, "seed_ids": "[200]" }
0.531814
Docs: Python310_7512
I
[ "process_chunk", "process_data_concurrently" ]
2
[ [ "process_data_concurrently", "process_chunk" ] ]
1
[]
false
[]
false
pytest
true
[]
true
206690f34af044d552d9fdcdad453dc64eb25854
bc7d96632f99f2040c5c757908b7dbb7f1907197
v1.0
instruct
Docs
Docs: Python310_7521_I
### Asyncio Task Management and Timeout Handling You are tasked with building a simple simulation of a data processing system using `asyncio`. Your goal is to create multiple concurrent tasks that simulate data fetching and processing. You need to demonstrate your understanding of asyncio by implementing functions to:...
import asyncio async def fetch_data(id, delay): """ Simulate fetching data by awaiting asyncio.sleep(delay). """ await asyncio.sleep(delay) return f"Data from source {id}" async def process_data(data): """ Simulate data processing by awaiting asyncio.sleep(2). """ await asyncio.sle...
import asyncio import pytest from solution import fetch_data, process_data, main @pytest.mark.asyncio async def test_fetch_data(): result = await fetch_data(1, 1) assert result == "Data from source 1" @pytest.mark.asyncio async def test_process_data(): result = await process_data("Data from source 1") ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def fetch_data(id, delay):\n \"\"\"\n Simulate fetching data by awaiting asyncio.sleep(delay).\n \"\"\"\n await asyncio.sleep(delay)...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00007521", "row_id": 7521, "seed_ids": "[317]" }
0.545837
Docs: Python310_7521
I
[ "fetch_data", "process_data", "fetch_and_process", "main" ]
4
[ [ "fetch_and_process", "fetch_data" ], [ "fetch_and_process", "process_data" ] ]
2
[ "process_data" ]
false
[]
false
pytest
true
[]
true
abda46ec3f8bac73afb5ba81dc81a34bdfa5eb7c
c199601beae67bc20f347fe527573f2bb4b7c4c8
v1.0
instruct
Docs
Docs: Scikit_7554_I
#### Objective: Implement a simplified version of the `PLSCanonical` algorithm described in the scikit-learn cross decomposition module. #### Problem Statement: You are required to create a function `pls_canonical(X, Y, n_components)` that performs Partial Least Squares Canonical (PLSCanonical) decomposition on two ma...
import numpy as np from typing import Tuple def nipals(X, Y, n_components): T = np.zeros((X.shape[0], n_components)) U = np.zeros((Y.shape[0], n_components)) P = np.zeros((X.shape[1], n_components)) Q = np.zeros((Y.shape[1], n_components)) for i in range(n_components): u = Y[:, 0] ...
import numpy as np from solution import pls_canonical def test_pls_canonical(): # Test case 1 X = np.array([[0.1, -0.2], [0.9, 1.1], [1.1, 0.9]]) Y = np.array([[0.2, 0.5], [-0.5, 0.9], [0.8, -1.1]]) n_components = 2 X_scores, Y_scores, X_loadings, Y_loadings = pls_canonical(X, Y, n_components) ...
[ { "docstring": null, "function_declaration": "def nipals(X, Y, n_components):", "function_name": "nipals", "parameter_list": "(X, Y, n_components)" }, { "docstring": null, "function_declaration": "def pls_canonical(X, Y, n_components):", "function_name": "pls_canonical", "paramet...
[ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom typing import Tuple\n\ndef pls_canonical(X: np.ndarray, Y: np.ndarray, n_components: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarr...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00007554", "row_id": 7554, "seed_ids": "[28]" }
0.61029
Docs: Scikit_7554
I
[ "nipals", "pls_canonical" ]
2
[ [ "pls_canonical", "nipals" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
47484f9cb42d8a596c6b67cd9b45f6675cc183f6
fef461a63f8745468dae62e9e7301046ae1edf9d
v1.0
instruct
Docs
Docs: Python310_7606_I
### Advanced Python Asynchronous Programming Assessment **Objective**: To assess your understanding of Python's asyncio library and your ability to apply asynchronous programming concepts to implement a network-based task processing system. --- #### Question: You are tasked with building an asynchronous TCP server ...
import asyncio async def start_server(host: str, port: int): server = await asyncio.start_server(handle_client, host, port) async with server: await server.serve_forever() async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): try: while True: data...
import asyncio import pytest from asyncio import StreamReader, StreamWriter from unittest.mock import Mock, patch from solution import start_server, handle_client, process_tasks, do_something_with @pytest.mark.asyncio async def test_server_starts(): server_task = asyncio.create_task(start_server('127.0.0.1', 8888)...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def start_server(host: str, port: int):\n server = await asyncio.start_server(handle_client, host, port)\n async with server:\n awa...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00007606", "row_id": 7606, "seed_ids": "[360]" }
0.623658
Docs: Python310_7606
I
[ "start_server", "handle_client", "process_tasks", "do_something_with", "main" ]
5
[ [ "process_tasks", "do_something_with" ], [ "start_server", "handle_client" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5a1f8a2790dc176bdd33a6b89a2dedfa60525f00
7d85758232fab68b9ec5938c16e2b3f979234e92
v1.0
instruct
Docs
Docs: Python310_7694_I
**Question: Advanced Resource Management with Python Development Mode** You are required to write a Python script that processes multiple text files concurrently using asyncio. The script should: 1. Read the list of text file paths from a given input file. 2. For each text file, count the number of lines and print the...
import asyncio async def count_lines_in_file(file_path): """ Counts and returns the number of lines in the given file. """ lines_count = 0 try: async with aiofiles.open(file_path, 'r') as file: async for _ in file: lines_count += 1 except FileNotFoundError: ...
import asyncio import pytest from solution import count_lines_in_file, process_files, read_input_file @pytest.mark.asyncio async def test_count_lines_in_file(tmp_path): test_file = tmp_path / "test_file.txt" test_content = "\n".join(["line1", "line2", "line3"]) test_file.write_text(test_content) lines...
[ { "docstring": "Reads the file paths from the input file and returns them as a list.", "function_declaration": "def read_input_file(input_file):", "function_name": "read_input_file", "parameter_list": "(input_file)" }, { "docstring": null, "function_declaration": "def main():", "func...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def count_lines_in_file(file_path):\n \"\"\"\n Counts and returns the number of lines in the given file.\n \"\"\"\n lines_count = 0\...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00007694", "row_id": 7694, "seed_ids": "[249]" }
0.556921
Docs: Python310_7694
I
[ "count_lines_in_file", "process_files", "read_input_file", "main" ]
4
[ [ "process_files", "count_lines_in_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0923b3e0f44a030ef42714805fa5d828fb3323d3
d78129abbd214fb0c1d44df77104d4b985e8649c
v1.0
instruct
Docs
Docs: Python310_7711_I
### Serialization and Deserialization with Custom Constraints In this exercise, you are required to implement custom serialization and deserialization functionality in Python, using the provided format. You will need to marshal (serialize) both primitive types and Python objects, ensuring they can later be accurately ...
import struct def _serialize_int(value): return struct.pack('<I', value & 0xFFFFFFFF) def _serialize_float(value): return struct.pack('<d', value) def _serialize_str(value): encoded_value = value.encode('utf-8') return struct.pack('<I', len(encoded_value)) + encoded_value def _serialize_list(value, ...
from solution import serialize_data, deserialize_data def test_serialize_deserialize_int(): data = 42 serialized = serialize_data(data) deserialized, _ = deserialize_data(serialized) assert deserialized == data def test_serialize_deserialize_float(): data = 3.14159 serialized = serialize_data(...
[ { "docstring": null, "function_declaration": "def _serialize_int(value):", "function_name": "_serialize_int", "parameter_list": "(value)" }, { "docstring": null, "function_declaration": "def _serialize_float(value):", "function_name": "_serialize_float", "parameter_list": "(value...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import struct\n\ndef serialize_data(data, version=2):\n if version != 2:\n raise ValueError(\"Only version 2 is supported\")\n \n if isinstance(data, in...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00007711", "row_id": 7711, "seed_ids": "[14]" }
0.591325
Docs: Python310_7711
I
[ "_serialize_int", "_serialize_float", "_serialize_str", "_serialize_list", "_serialize_dict", "serialize_data", "_deserialize_int", "_deserialize_float", "_deserialize_str", "_deserialize_list", "_deserialize_dict", "deserialize_data" ]
12
[ [ "_deserialize_dict", "deserialize_data" ], [ "_deserialize_list", "deserialize_data" ], [ "_serialize_dict", "serialize_data" ], [ "_serialize_list", "serialize_data" ], [ "deserialize_data", "_deserialize_dict" ], [ "deserialize_data", "_deseria...
14
[]
false
[]
false
pytest
true
[]
true
a3f2cebaecf3f86d9d3a3cb3453ef42e5e053993
569c710d45a2503703941c34236bdc855b828b8a
v1.0
instruct
Docs
Docs: Python310_7713_I
#### Objective: Implement and demonstrate the usage of context-local state management using the `contextvars` module in Python 3.10 by creating a contextual counter system. This system should be able to handle multiple independent counters in an asynchronous environment, ensuring that the counters remain isolated in th...
import asyncio import contextvars from contextvars import ContextVar, copy_context # Step 1: Initialize a ContextVar with a default value of 0 counter: ContextVar[int] = ContextVar('counter', default=0) def increment(): """Increment the context counter by 1.""" token = counter.set(counter.get() + 1) retur...
import asyncio import contextvars from contextvars import ContextVar, copy_context import pytest # Assuming the solution is stored in a module named `context_counter` counter: ContextVar[int] = ContextVar('counter', default=0) def increment(): token = counter.set(counter.get() + 1) return token def get_coun...
[ { "docstring": "Increment the context counter by 1.", "function_declaration": "def increment():", "function_name": "increment", "parameter_list": "()" }, { "docstring": "Retrieve the current value of the context counter.", "function_declaration": "def get_counter_value():", "function...
[ 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 asyncio\nimport contextvars\nfrom contextvars import ContextVar, copy_context\n\n# Step 1: Initialize a ContextVar with a default value of 0\ncounter: ContextVar...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00007713", "row_id": 7713, "seed_ids": "[392]" }
0.505053
Docs: Python310_7713
I
[ "increment", "get_counter_value", "reset_counter", "increment_counter", "main" ]
5
[ [ "increment_counter", "increment" ] ]
1
[]
false
[]
false
pytest
false
[]
true
cd0785c3140c650f4316894b4c5a6a66ad541592
dd4b64a80c911d953e22a0942b0b736db43d3c23
v1.0
instruct
Docs
Docs: Python310_7740_I
### Advanced Python DateTime API Integration You are required to write a Python extension module using the C API for the `datetime` module in Python. Your task is to create several date and time objects, extract certain fields from them, and perform some operations. You will be implementing this in `C` and integrating...
from datetime import date, time, datetime, timezone def create_date(year, month, day): """ Creates a date object with given year, month, and day. """ return date(year, month, day) def create_time(hour, minute, second, microsecond): """ Creates a time object with given hour, minute, second, and...
from solution import * def test_create_date(): d = create_date(2023, 10, 5) assert d.year == 2023 assert d.month == 10 assert d.day == 5 def test_create_time(): t = create_time(12, 34, 56, 789000) assert t.hour == 12 assert t.minute == 34 assert t.second == 56 assert t.microsecond ...
[ { "docstring": "Creates a date object with given year, month, and day.", "function_declaration": "def create_date(year, month, day):", "function_name": "create_date", "parameter_list": "(year, month, day)" }, { "docstring": "Creates a time object with given hour, minute, second, and microsec...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from datetime import date, time, datetime, timezone\n\ndef create_date(year, month, day):\n \"\"\"Creates a datetime.date object for given year, month and day.\"\"\"...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00007740", "row_id": 7740, "seed_ids": "[21]" }
0.66077
Docs: Python310_7740
I
[ "create_date", "create_time", "get_date_fields", "get_time_fields", "create_datetime", "print_and_validate" ]
6
[ [ "print_and_validate", "create_date" ], [ "print_and_validate", "create_datetime" ], [ "print_and_validate", "create_time" ], [ "print_and_validate", "get_date_fields" ], [ "print_and_validate", "get_time_fields" ] ]
5
[]
false
[]
false
pytest
true
[]
true
0674200bd007acc288a675e353396b79b16b5b00
66830db1d0f352368635f617e0bb066d51086f8b
v1.0
instruct
Docs
Docs: Seaborn_7746_I
**Question**: Exploring Seaborn Styles and Plotting Functions You are provided with data on a fictional company's employee metrics, including hours worked and productivity scores. You need to visualize this data using Seaborn, leveraging different styles and plotting functions to illustrate the relationship between th...
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt def load_data(file_path): """ Load the data from a CSV file. """ return pd.read_csv(file_path) def create_scatter_plot(data, style=None, output_file='scatter.png'): """ Creates and saves a scatter plot of HoursWorked vs ...
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import os # Assuming `solution.py` contains the provided solution functions from solution import load_data, create_scatter_plot, create_bar_plot, process_visualizations def create_fake_csv(filepath): """ Create a fake CSV file for testi...
[ { "docstring": "Load the data from a CSV file.", "function_declaration": "def load_data(file_path):", "function_name": "load_data", "parameter_list": "(file_path)" }, { "docstring": "Creates and saves a scatter plot of HoursWorked vs ProductivityScore.", "function_declaration": "def crea...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef load_data(csv_file):\n \"\"\"\n Load the data from a CSV file.\n \"\"\"\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00007746", "row_id": 7746, "seed_ids": "[63]" }
0.690543
Docs: Seaborn_7746
I
[ "load_data", "create_scatter_plot", "create_bar_plot", "process_visualizations" ]
4
[ [ "process_visualizations", "create_bar_plot" ], [ "process_visualizations", "create_scatter_plot" ], [ "process_visualizations", "load_data" ] ]
3
[]
false
[]
false
pytest
true
[ "matplotlib", "pandas", "seaborn" ]
false
81b8220a07ffc47e4efea06ab715f98ffd1af186
85fd12c3d5c75161c9c9f6aabffa97e943ae205d
v1.0
instruct
Docs
Docs: Python310_7769_I
**Challenging Coding Assessment Question: Understanding CPython Instrumentation with DTrace and SystemTap** **Objective:** Write a Python script that simulates a basic program's execution and design a corresponding DTrace or SystemTap script that monitors its function call entries and exits. **Python Script Requireme...
# sample_program.py def function_1(): print("Function 1") def function_2(): function_1() print("Function 2") def function_3(): function_2() print("Function 3") def start(): function_3() if __name__ == "__main__": start()
from solution import function_1, function_2, function_3, start def test_function_1(capsys): function_1() captured = capsys.readouterr() assert captured.out == "Function 1\n" def test_function_2(capsys): function_2() captured = capsys.readouterr() assert captured.out == "Function 1\nFunction 2\...
[ { "docstring": null, "function_declaration": "def function_1():", "function_name": "function_1", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def function_2():", "function_name": "function_2", "parameter_list": "()" }, { "docstring": null, "...
[ 1, 0, 1, 0, 0, 0, 0, 0, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "# sample_program.py\ndef function_1():\n print(\"Function 1\")\n\ndef function_2():\n function_1()\n print(\"Function 2\")\n\ndef func...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00007769", "row_id": 7769, "seed_ids": "[79]" }
0.51643
Docs: Python310_7769
I
[ "function_1", "function_2", "function_3", "start" ]
4
[ [ "function_2", "function_1" ], [ "function_3", "function_2" ], [ "start", "function_3" ] ]
3
[]
false
[]
false
pytest
true
[]
true
2c0d1b6449ca3e4a4b289abfca00f41f3b58a0a8
42afbee4414a05f81df59190841b233bd57c2130
v1.0
instruct
Docs
Docs: Python310_7775_I
### Asynchronous Chat Server with `asyncio` Event Loop ### Objective: Design and implement an asynchronous chat server using Python's `asyncio` event loop. Your task is to handle multiple client connections, manage messages asynchronously, and implement a way to broadcast messages to all connected clients. ### Specif...
import asyncio import signal clients = {} async def handle_client(reader, writer): addr = writer.get_extra_info('peername') username = (await reader.read(100)).decode().strip() clients[username] = writer try: while data := await reader.read(100): message = f"{username}: {data.decod...
import asyncio import pytest from unittest.mock import Mock from solution import handle_client, broadcast_message, clients @pytest.mark.asyncio async def test_handle_client(): reader = Mock() writer = Mock() writer.get_extra_info.return_value = ('127.0.0.1', 12345) reader.read = Mock(side_effect=[b"te...
[]
[ 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 asyncio\nimport signal\n\nclients = {}\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n username = (await reader.re...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00007775", "row_id": 7775, "seed_ids": "[267]" }
0.630384
Docs: Python310_7775
I
[ "handle_client", "broadcast_message", "main" ]
3
[ [ "handle_client", "broadcast_message" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4880d62b1d0c18b8b60b1b9b6a15f887f882bc2c
8a3e8d55abdb99521f6bbe3b69748e161a6fed07
v1.0
instruct
Docs
Docs: Python310_7787_I
### Custom Exception Implementation and Handling You are asked to implement a custom hierarchical exception handling system for a hypothetical library that processes data files. The objectives are as follows: 1. **Define Custom Exceptions:** - Implement the following custom exceptions and their hierarchy: ...
class DataError(Exception): pass class FileFormatError(DataError): pass class FileEmptyError(DataError): pass class CorruptDataError(DataError): pass def process_file(file_content: str) -> None: """ Simulates the processing of a data file. Raises appropriate exceptions based on the conte...
import pytest from solution import ( DataError, FileFormatError, FileEmptyError, CorruptDataError, process_file, run_processing ) def test_process_file_empty(): with pytest.raises(FileEmptyError): process_file("") def test_process_file_corrupt(): with pytest.raises(Corrupt...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class DataError(Exception):\n pass\n\nclass FileFormatError(DataError):\n pass\n\nclass FileEmptyError(DataError):\n pass\n\nclass CorruptDataError(DataError):...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00007787", "row_id": 7787, "seed_ids": "[256]" }
0.484819
Docs: Python310_7787
I
[ "process_file", "run_processing" ]
2
[ [ "run_processing", "process_file" ] ]
1
[]
false
[ "DataError", "FileFormatError", "FileEmptyError", "CorruptDataError" ]
true
pytest
true
[]
true
170e14d09796196aa5b6e51a9e7cd43cbfb745e4
99eb09b12b634eac2106942dc027deabda8b2f40
v1.0
instruct
Docs
Docs: Python310_7904_I
#### Problem Statement You are required to implement an asynchronous function that runs three coroutines concurrently. Each coroutine performs a different task: one simulates an I/O-bound operation, the second simulates a CPU-bound operation, and the third waits for a signal from an external source to complete. Your f...
import asyncio import logging import random # Configure logging logging.basicConfig(level=logging.INFO) async def io_bound_task(): # Simulate I/O-bound task await asyncio.sleep(random.uniform(1, 3)) logging.info("I/O-bound task completed") def cpu_bound_task(): # Simulate CPU-bound task def fib(n...
from solution import manage_tasks import asyncio import pytest from unittest.mock import patch @pytest.mark.asyncio async def test_manage_tasks(): with patch('solution.io_bound_task', return_value=asyncio.sleep(0.5)), \ patch('solution.cpu_bound_task'), \ patch('solution.signal_wait_task', return...
[ { "docstring": null, "function_declaration": "def cpu_bound_task():", "function_name": "cpu_bound_task", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def fib(n):", "function_name": "fib", "parameter_list": "(n)" } ]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport logging\nimport random\n\n# Configure logging\nlogging.basicConfig(level=logging.INFO)\n\nasync def io_bound_task():\n try:\n # Simulat...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00007904", "row_id": 7904, "seed_ids": "[200]" }
0.549544
Docs: Python310_7904
I
[ "io_bound_task", "cpu_bound_task", "signal_wait_task", "manage_tasks" ]
4
[ [ "manage_tasks", "cpu_bound_task" ], [ "manage_tasks", "io_bound_task" ], [ "manage_tasks", "signal_wait_task" ] ]
3
[]
false
[]
false
pytest
true
[]
true
170476f1608dc1698a35618d1c963e33fa492d22
ca019dfddb3c8ab0ddd20420eb577c2da9448b4b
v1.0
instruct
Docs
Docs: Python310_7911_I
**Custom Interactive Python Shell with Enhanced Readline Features** You are tasked with creating your own custom interactive Python shell utilizing the "readline" module. Your shell should support the following features: 1. **History Management**: - Load history from a file during startup. - Save the history t...
import readline import atexit import os COMMANDS = ["start", "stop", "pause", "resume", "status"] def init_history(histfile): if os.path.exists(histfile): readline.read_history_file(histfile) readline.set_history_length(1000) atexit.register(save_history, histfile) def save_history(histfile): ...
import os from solution import init_history, save_history, custom_completer, configure_readline, custom_shell def test_init_history(tmpdir): histfile = tmpdir.join("test_history").strpath init_history(histfile) assert os.path.exists(histfile) or readline.get_current_history_length() == 0 def test_save_his...
[ { "docstring": null, "function_declaration": "def init_history(histfile):", "function_name": "init_history", "parameter_list": "(histfile)" }, { "docstring": null, "function_declaration": "def save_history(histfile):", "function_name": "save_history", "parameter_list": "(histfile...
[ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import readline\nimport atexit\nimport os\n\nCOMMANDS = [\"start\", \"stop\", \"pause\", \"resume\", \"status\"]\n\ndef init_history(histfile):\n \"\"\"\n Initial...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00007911", "row_id": 7911, "seed_ids": "[362]" }
0.41658
Docs: Python310_7911
I
[ "init_history", "save_history", "custom_completer", "configure_readline", "custom_shell" ]
5
[ [ "custom_shell", "custom_completer" ], [ "custom_shell", "init_history" ], [ "init_history", "save_history" ] ]
3
[]
false
[]
false
pytest
true
[]
true
080996cb7fa2ea1d02864018272245f344ce0169
b0ec2ad844286f6ba1bf7918b825d47202866395
v1.0
instruct
Docs
Docs: Python310_7923_I
### Question: Persistence Layer with Python Serialization and SQLite Database You are tasked with creating a persistence layer for complex data structures using Python. You will use the `pickle` module for object serialization and the `sqlite3` module for database storage. #### Requirements 1. **Define a class** `Per...
import pickle import sqlite3 class Person: def __init__(self, name: str, age: int, address: str): self.name = name self.age = age self.address = address def serialize_person(person: Person) -> bytes: """ Serializes the Person instance into bytes using pickle. """ return pic...
import pytest import os from solution import Person, serialize_person, deserialize_person, save_person_to_db, load_person_from_db def setup_module(module): """ setup any state specific to the execution of the given module.""" db_path = "test_people.db" if os.path.exists(db_path): os.remove(db_path)...
[]
[ 0, 0, 0, 0, 1, 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": "import pickle\nimport sqlite3\n\nclass Person:\n def __init__(self, name: str, age: int, address: str):\n self.name = name\n self.age = age\n se...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00007923", "row_id": 7923, "seed_ids": "[140]" }
0.492869
Docs: Python310_7923
I
[ "serialize_person", "deserialize_person", "save_person_to_db", "load_person_from_db" ]
4
[ [ "load_person_from_db", "deserialize_person" ], [ "save_person_to_db", "serialize_person" ] ]
2
[]
false
[ "Person" ]
true
pytest
true
[]
true
5080bdd4182ea0cb3704e39103da7b76c4d7c2cf
76d177133d82940cee4de296e7d002996d638f57
v1.0
instruct
Docs
Docs: Python310_7930_I
### Asynchronous Web Scraping with Subprocesses and Queues **Objective:** Implement an asynchronous web scraping solution using the `asyncio` library's tasks, queues, and subprocesses to scrape data from multiple URLs simultaneously. **Problem Statement:** You are required to write a function `async_scraper(urls: Li...
import asyncio from asyncio.subprocess import create_subprocess_exec, PIPE from typing import List async def fetch_url_content(url: str) -> str: process = await create_subprocess_exec( 'curl', '-s', url, stdout=PIPE, stderr=PIPE ) stdout, stderr = await process.communicate() if process....
import pytest import asyncio from solution import async_scraper @pytest.mark.asyncio async def test_async_scraper_single_url(): urls = ["http://example.com"] contents = await async_scraper(urls) assert len(contents) == 1 assert "Example Domain" in contents[0] @pytest.mark.asyncio async def test_async_...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom asyncio.subprocess import create_subprocess_exec, PIPE\nfrom typing import List\n\nasync def fetch_url_content(url: str) -> str:\n process = awa...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00007930", "row_id": 7930, "seed_ids": "[360]" }
0.58022
Docs: Python310_7930
I
[ "fetch_url_content", "worker", "async_scraper" ]
3
[ [ "async_scraper", "worker" ], [ "worker", "fetch_url_content" ] ]
2
[]
false
[]
false
pytest
true
[]
true
be983049cc13e0e3499b1b2ab88f32617de30052
ebe406f264d947f608f1ecc2b9fdc344e0bd7a80
v1.0
instruct
Docs
Docs: Pytorch_7949_I
### PyTorch Environment Variables and CUDA You are tasked with setting up a PyTorch project that utilizes CUDA for GPU acceleration. The project involves: 1. Creating a simple neural network for image classification on CIFAR-10 dataset. 2. Ensuring optimized and efficient use of CUDA. 3. Debugging CUDA memory errors ...
import os import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms def set_environment_variables(): os.environ['PYTORCH_NO_CUDA_MEMORY_CACHING'] = '1' os.environ['TORCH_NCCL_USE_COMM_NONBLOCKING'] = '1' os.environ['CUDA_VISIBLE_DEVICES'] ...
import os import torch from solution import set_environment_variables, build_cnn_model def test_set_environment_variables(): set_environment_variables() assert os.environ['PYTORCH_NO_CUDA_MEMORY_CACHING'] == '1' assert os.environ['TORCH_NCCL_USE_COMM_NONBLOCKING'] == '1' assert os.environ['CUDA_VISIBLE...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\n\ndef set_environment_vari...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00007949", "row_id": 7949, "seed_ids": "[107]" }
0.510601
Docs: Pytorch_7949
I
[ "set_environment_variables", "build_cnn_model", "train_model" ]
3
[ [ "train_model", "build_cnn_model" ], [ "train_model", "set_environment_variables" ] ]
2
[]
false
[]
false
pytest
true
[ "torch", "torchvision" ]
false
0ba95e9577ff010666a2360cf3d20e9ad3f40634
37b4679202eb2d251ea5e7219bf808c4485985b2
v1.0
instruct
Docs
Docs: Python310_7967_I
### Advanced Cryptographic Hashing and HMAC Implementation #### Problem Statement You are tasked with implementing a secure file manipulation pipeline involving hashing and authentication processes. Your solution must include the following functionalities: 1. **File Hashing**: - Implement a function `hash_file(fi...
import hashlib import hmac def hash_file(filepath: str, algorithm: str='sha256') -> str: """ Returns the hex digest of the file's contents using the specified hashing algorithm. """ hash_func = None if algorithm == 'sha256': hash_func = hashlib.sha256() elif algorithm == 'sha512': ...
import os import tempfile from solution import hash_file, generate_hmac, verify_hmac def create_temp_file(contents: bytes): temp_fd, temp_filename = tempfile.mkstemp() with os.fdopen(temp_fd, 'wb') as f: f.write(contents) return temp_filename def test_hash_file_sha256(): contents = b'Hello, Wo...
[ { "docstring": "Returns the hex digest of the file's contents using the specified hashing algorithm.", "function_declaration": "def hash_file(filepath, algorithm='sha256'):", "function_name": "hash_file", "parameter_list": "(filepath, algorithm='sha256')" }, { "docstring": "Generates an HMAC...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\nimport hmac\n\ndef hash_file(filepath: str, algorithm: str = 'sha256') -> str:\n \"\"\"\n Returns the hex digest of the file's contents using the ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00007967", "row_id": 7967, "seed_ids": "[394]" }
0.682131
Docs: Python310_7967
I
[ "hash_file", "generate_hmac", "verify_hmac" ]
3
[ [ "verify_hmac", "generate_hmac" ] ]
1
[]
false
[]
false
pytest
true
[]
true
248a05ae7a9d709a5c206f084633f9dc83496a13
d05b7c6d5e0abe978c9921f2151c8597fd3261fe
v1.0
instruct
Docs
Docs: Python310_8020_I
### Timeit Module Exercise: Measuring and Optimizing Code Performance #### Objective Write a function that measures and compares the execution time of two different implementations of a task using the `timeit` module. You will then report which implementation is faster and by how much. #### Task Description The task ...
import timeit def sum_using_loop(n): total = 0 for i in range(1, n + 1): total += i return total def sum_using_formula(n): return n * (n + 1) // 2 def compare_execution_times(n: int) -> str: if n < 0: return "n should be a non-negative integer" loop_time = timeit.timeit(l...
from solution import compare_execution_times def test_compare_execution_times_positive(): result = compare_execution_times(1000) assert "Loop method: " in result assert "Formula method: " in result assert "times faster" in result def test_compare_execution_times_zero(): result = compare_execution_...
[ { "docstring": null, "function_declaration": "def sum_using_loop(n):", "function_name": "sum_using_loop", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def sum_using_formula(n):", "function_name": "sum_using_formula", "parameter_list": "(n)" }, { ...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import timeit\n\ndef loop_sum(n):\n total = 0\n for i in range(1, n + 1):\n total += i\n return total\n\ndef formula_sum(n):\n return n * (n + 1) // ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008020", "row_id": 8020, "seed_ids": "[328]" }
0.57871
Docs: Python310_8020
I
[ "sum_using_loop", "sum_using_formula", "compare_execution_times" ]
3
[ [ "compare_execution_times", "sum_using_formula" ], [ "compare_execution_times", "sum_using_loop" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d6b81372c77d5bfd47fe920a6d57115fc5a48482
74fb80b34f808c93247715ad723837934264a141
v1.0
instruct
Docs
Docs: Pandas_8032_I
Advanced DataFrame Operations and Memory Management #### Objective: You are required to demonstrate your understanding of advanced DataFrame operations in pandas, including memory usage inspection and handling DataFrame mutations with User Defined Functions (UDFs). #### Problem Statement: You are given a DataFrame `d...
import pandas as pd def get_memory_usage(df, deep=False): """ Prints and returns the memory usage of the DataFrame in bytes. If deep is True, perform a deep memory usage analysis. """ usage = df.memory_usage(deep=deep).sum() human_readable = format_bytes(usage) print(f"Memory usage: {human_...
import pandas as pd import numpy as np from solution import get_memory_usage, apply_transformation, check_condition def test_get_memory_usage(): df = pd.DataFrame({ 'A': range(100), 'B': range(100, 200) }) usage = get_memory_usage(df) assert usage > 0 def test_apply_transformation(): ...
[ { "docstring": "Prints and returns the memory usage of the DataFrame in bytes.\nIf deep is True, perform a deep memory usage analysis.", "function_declaration": "def get_memory_usage(df, deep=False):", "function_name": "get_memory_usage", "parameter_list": "(df, deep=False)" }, { "docstring"...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\n\ndef get_memory_usage(df, deep=False):\n \"\"\"\n Prints and returns the memory usage of a DataFrame in bytes.\n If deep is True, perform...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008032", "row_id": 8032, "seed_ids": "[11]" }
0.593846
Docs: Pandas_8032
I
[ "get_memory_usage", "format_bytes", "apply_transformation", "check_condition" ]
4
[ [ "get_memory_usage", "format_bytes" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "pandas" ]
false
5f4d28a7cbc1139e95b991fb5b79f4d705e1e360
676d7be053ea1219321db30849126b1003216540
v1.0
instruct
Docs
Docs: Python310_8061_I
You are tasked with processing a large list of numerical data. Each element of the list needs to be processed by a computational heavy function. To efficiently handle this workload, you decide to implement a function using the `concurrent.futures` module to parallelize the computation. Your task is to complete the impl...
import concurrent.futures import time def heavy_computation(n): time.sleep(0.1) return n * n def parallel_processing(data): """ Processes a list of integers using heavy_computation function in parallel. Parameters: data (list): A list of integers to be processed. Returns: lis...
from solution import parallel_processing def test_parallel_processing_basic(): data = [1, 2, 3, 4, 5] assert parallel_processing(data) == [1, 4, 9, 16, 25] def test_parallel_processing_empty_list(): data = [] assert parallel_processing(data) == [] def test_parallel_processing_single_element(): da...
[ { "docstring": null, "function_declaration": "def heavy_computation(n):", "function_name": "heavy_computation", "parameter_list": "(n)" }, { "docstring": "Processes a list of integers using heavy_computation function in parallel.\n\nParameters:\ndata (list): A list of integers to be processe...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from concurrent.futures import ProcessPoolExecutor, as_completed\n\ndef heavy_computation(n: int) -> int:\n \"\"\"\n Simulate a heavy computational task\n \"\"...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008061", "row_id": 8061, "seed_ids": "[224]" }
0.615832
Docs: Python310_8061
I
[ "heavy_computation", "parallel_processing" ]
2
[ [ "parallel_processing", "heavy_computation" ] ]
1
[]
false
[]
false
pytest
true
[]
true
24c30c10d5f8259030666f7c0a9332ae641fee20
e4524ceb29ab2fbf902050b02c97ae3f3138f789
v1.0
instruct
Docs
Docs: Python310_8101_I
### Advanced Python Debugging and Profiling Assignment **Objective:** You are tasked with developing a Python script that performs detailed profiling and debugging on a provided code snippet. Your solution should demonstrate proficiency with the `pdb`, `cProfile`, and `tracemalloc` modules. **Task:** 1. **Debugging...
import cProfile import traceback import tracemalloc def faulty_factorial(n): # Intentionally faulty implementation if n == 0: return 1 else: # the following line will cause maximum recursion depth error with large n return n * faulty_factorial(n - 1) def correct_factorial(n): #...
import pytest from solution import faulty_factorial, correct_factorial, profile_code, trace_memory def test_faulty_factorial_correctness(): with pytest.raises(RecursionError): faulty_factorial(1000) def test_correct_factorial(): assert correct_factorial(0) == 1 assert correct_factorial(1) == 1 ...
[ { "docstring": null, "function_declaration": "def faulty_factorial(n):", "function_name": "faulty_factorial", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def correct_factorial(n):", "function_name": "correct_factorial", "parameter_list": "(n)" }, ...
[ 0, 0, 0, 1, 1, 0, 1, 1, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cProfile\nimport pstats\nimport tracemalloc\nimport sys\n\ndef faulty_factorial(n):\n # Intentionally faulty implementation\n if n == 0 or n == 1:\n ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00008101", "row_id": 8101, "seed_ids": "[364]" }
0.612002
Docs: Python310_8101
I
[ "faulty_factorial", "correct_factorial", "fibonacci", "profile_code", "trace_memory" ]
5
[ [ "profile_code", "correct_factorial" ], [ "profile_code", "faulty_factorial" ], [ "profile_code", "fibonacci" ], [ "trace_memory", "correct_factorial" ] ]
4
[]
false
[]
false
pytest
true
[]
true
53adda3285d9614a805160c41d35694830f02338
0fe4cc48ea626a81b3e510ea7e4a1211c85d124e
v1.0
instruct
Docs
Docs: Pytorch_8116_I
**Distributed Training with RPC and Autograd in PyTorch** **Objective:** Implement a distributed training workflow using PyTorch's distributed RPC framework and autograd mechanics. The solution should demonstrate an understanding of remote procedure calls, distributed autograd context management, and optimizer steps. ...
import torch import torch.distributed.rpc as rpc import torch.distributed.autograd as dist_autograd from torch import nn, optim from torch.distributed.optim import DistributedOptimizer from torch.distributed.rpc.api import RRef # Define a simple model class SimpleModelPart1(nn.Module): def __init__(self): ...
import torch import torch.distributed.rpc as rpc from torch.multiprocessing import Process from solution import run_worker def test_distributed_training(): world_size = 2 processes = [] for rank in range(world_size): p = Process(target=run_worker, args=(rank, world_size)) p.start() ...
[]
[ 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.distributed.rpc as rpc\nimport torch.distributed.autograd as dist_autograd\nfrom torch import nn, optim\nfrom torch.distributed.optim import ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00008116", "row_id": 8116, "seed_ids": "[159]" }
0.494193
Docs: Pytorch_8116
I
[ "remote_forward", "run_worker" ]
2
[ [ "run_worker", "remote_forward" ] ]
1
[]
false
[ "SimpleModelPart1", "SimpleModelPart2" ]
true
pytest
true
[ "torch" ]
false
b79f44bcce007e8831d046d2e50997e0013c7b4d
c6080dd1dd1f8a631bae75f3804a9d5ea0dec548
v1.0
instruct
Docs
Docs: Scikit_8162_I
Implementing Out-of-Core Learning for Text Classification #### Objective Design and implement an out-of-core learning system using scikit-learn for a text classification task. The system should process data in mini-batches, perform feature extraction, and update the model incrementally. #### Description You are given...
import os from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def stream_data(batch_size, directory='data/text_files'): """ Generator that streams data in mini-batches of the specified size. :param batc...
import os import tempfile import pytest from solution import stream_data, train_incremental_model # Helper function to create temporary dataset def create_temp_dataset(file_data): tmp_dir = tempfile.mkdtemp() file_paths = [] for i, content in enumerate(file_data): file_path = os.path.join(tmp_dir, ...
[ { "docstring": "Generator that streams data in mini-batches of the specified size.\n\n:param batch_size: Size of each mini-batch.\n:param directory: Directory containing the text files.\n:yield: A list of tuples (label, text).", "function_declaration": "def stream_data(batch_size, directory='data/text_files...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\n\n...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008162", "row_id": 8162, "seed_ids": "[63]" }
0.511084
Docs: Scikit_8162
I
[ "stream_data", "train_incremental_model" ]
2
[ [ "train_incremental_model", "stream_data" ] ]
1
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
572b7bbece1a76b7f2bef934b2e8d23315446558
91fe6add540b5438f0d4f508a501a05d11ee4108
v1.0
instruct
Docs
Docs: Python310_8254_I
### Contextual Data Management in Asynchronous Programming You are tasked with implementing a data processing system that manages context-specific configurations, especially useful in an asynchronous environment. Using the `contextvars` module, you will create context variables and manage different configurations that...
import contextvars import asyncio # Create the ContextVar object config_var = contextvars.ContextVar('config_var', default="DefaultConfig") def setup_config(initial_config): """ Sets up initial configuration. """ config_var.set(initial_config) def get_config(): """ Retrieves the current confi...
import contextvars import asyncio from solution import setup_config, get_config, process_data, async_process_data # To run the async tests, we'll use the pytest-asyncio plugin def test_setup_and_get_config(): setup_config("TestConfig") assert get_config() == "TestConfig" def test_get_default_config(): co...
[ { "docstring": "Sets up initial configuration.", "function_declaration": "def setup_config(initial_config):", "function_name": "setup_config", "parameter_list": "(initial_config)" }, { "docstring": "Retrieves the current configuration.", "function_declaration": "def get_config():", "...
[ 0, 0, 0, 0, 0, 1, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import contextvars\nimport asyncio\n\n# Create the ContextVar object\nconfig_var = contextvars.ContextVar('config_var', default=\"DefaultConfig\")\n\ndef setup_config(i...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00008254", "row_id": 8254, "seed_ids": "[392]" }
0.454497
Docs: Python310_8254
I
[ "setup_config", "get_config", "process_data", "async_process_data", "main" ]
5
[ [ "async_process_data", "get_config" ], [ "process_data", "get_config" ] ]
2
[ "process_data" ]
false
[]
false
pytest
true
[]
true
147a75ae8d7af177cc47f6441ebff66f1ac0f59f
3c655f0f8fd966416cffc5f7296f4ed936a883bf
v1.0
instruct
Docs
Docs: Scikit_8293_I
You are provided with a dataset and tasked with implementing a function that computes the polynomial kernel matrix and uses it in an SVM classifier. This exercise will test your understanding of kernel functions and their application in machine learning. ### Requirements 1. Implement a function that computes the poly...
import numpy as np from sklearn.svm import SVC def polynomial_kernel(X, Y, degree, gamma, coef0): """ Computes the polynomial kernel between matrices X and Y. Parameters: - X (np.ndarray): Input matrix X. - Y (np.ndarray): Input matrix Y. - degree (int): Degree of the polynomial kernel. ...
import pytest import numpy as np from solution import kernel_svm_prediction def test_kernel_svm_prediction_basic(): X_train = np.array([[0, 1], [1, 0], [.2, .8], [.7, .3]]) y_train = np.array([0, 1, 0, 1]) X_test = np.array([[0.5, 0.5], [1.5, 1.5]]) # Predictions with specific degree, gamma, and c...
[ { "docstring": "Computes the polynomial kernel between matrices X and Y.\n\nParameters:\n- X (np.ndarray): Input matrix X.\n- Y (np.ndarray): Input matrix Y.\n- degree (int): Degree of the polynomial kernel.\n- gamma (float): Kernel coefficient.\n- coef0 (float): Independent term in the polynomial kernel.\n\nRe...
[ 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 numpy as np\nfrom sklearn.svm import SVC\n\ndef polynomial_kernel(X, Y, degree, gamma, coef0):\n \"\"\"\n Computes the polynomial kernel between two matric...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00008293", "row_id": 8293, "seed_ids": "[38]" }
0.48419
Docs: Scikit_8293
I
[ "polynomial_kernel", "kernel_svm_prediction" ]
2
[ [ "kernel_svm_prediction", "polynomial_kernel" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
500603a8a692d5ba02c1425034dcd0e3f3f75fc4
bb8facf32d06e8511547c41479684ae1eb065e32
v1.0
instruct
Docs
Docs: Seaborn_8319_I
**Question: Advanced Seaborn Aesthetics** As a data analyst, you are tasked with creating a series of visualizations that explore a dataset and present insights in an aesthetically pleasing manner. Your task involves using the Seaborn library to control figure aesthetics and context effectively. ### Instructions: 1....
import numpy as np import seaborn as sns import matplotlib.pyplot as plt def generate_data(): """ Generates a 2D NumPy array with shape (100, 4), where each column follows a normal distribution with different means. """ np.random.seed(0) means = [10, 20, 30, 40] data = np.array([np.random....
import numpy as np from solution import generate_data, advanced_visualizer def test_generate_data_shape(): data = generate_data() assert data.shape == (100, 4), "Generated data does not have the expected shape of (100, 4)" def test_generate_data_means(): data = generate_data() means = data.mean(axis=0...
[ { "docstring": "Generates a 2D NumPy array with shape (100, 4), \nwhere each column follows a normal distribution with different means.", "function_declaration": "def generate_data():", "function_name": "generate_data", "parameter_list": "()" }, { "docstring": "Plots a set of offset sine wav...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef generate_data():\n np.random.seed(0)\n means = [10, 20, 30, 40]\n data = np.a...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008319", "row_id": 8319, "seed_ids": "[2]" }
0.670608
Docs: Seaborn_8319
I
[ "generate_data", "sinplot", "advanced_visualizer" ]
3
[ [ "advanced_visualizer", "sinplot" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "seaborn" ]
false
005cbd5bddb427112034c765f02584965caf99b1
83eb75c66d241bc4798da7befc317959e083cd93
v1.0
instruct
Docs
Docs: Python310_8331_I
### Email Policy Customization and Application The `email.policy` module in Python provides flexibility in handling email messages through various policy objects. In this task, you are required to implement a custom policy that modifies certain default behaviors and apply this policy to parse and generate an email mes...
import email from email import policy from email.message import EmailMessage from email.parser import BytesParser from email.generator import BytesGenerator from io import BytesIO def create_custom_policy(): """ Creates a custom email policy. """ return policy.EmailPolicy( max_line_length=100, ...
import pytest from solution import create_custom_policy, parse_and_modify_email def test_create_custom_policy(): policy = create_custom_policy() assert policy.max_line_length == 100 assert policy.linesep == '\r\n' assert policy.cte_type == '8bit' assert policy.raise_on_defect == True def test_pars...
[ { "docstring": "Creates a custom email policy.", "function_declaration": "def create_custom_policy():", "function_name": "create_custom_policy", "parameter_list": "()" }, { "docstring": "Parses an email message from a string, modifies it by adding a custom header and\nupdating the subject, t...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import email\nfrom email.policy import EmailPolicy\nimport email.message\nfrom email.generator import BytesGenerator\nimport io\n\ndef create_custom_policy() -> EmailPo...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00008331", "row_id": 8331, "seed_ids": "[321]" }
0.624015
Docs: Python310_8331
I
[ "create_custom_policy", "parse_and_modify_email" ]
2
[ [ "parse_and_modify_email", "create_custom_policy" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5060716e4a56524e920babc02fd3202a49385adf
cf427e04c3f5d52f68a3adc612b31ebf9b7d17d6
v1.0
instruct
Docs
Docs: Python310_8364_I
### Question: Implement a Web Browser Controller for Scheduled URL Openings **Objective**: Your task is to implement a function `schedule_browser_openings(schedule: List[Tuple[str, str]]) -> None` that processes a schedule of URLs to be opened at specific times. This function should use the `webbrowser` module to ope...
import webbrowser import datetime import time import threading import re from typing import List, Tuple def is_valid_time(time_str: str) -> bool: return bool(re.match(r'^([01]\d|2[0-3]):([0-5]\d)$', time_str)) def is_valid_url(url: str) -> bool: return url.startswith("http://") or url.startswith("https://") ...
from solution import schedule_browser_openings def test_schedule_with_invalid_time(): schedule = [("https://www.google.com", "25:00")] schedule_browser_openings(schedule) # Expecting a print statement about the invalid time def test_schedule_with_invalid_url(): schedule = [("ftp://example.com", "14:00")]...
[ { "docstring": null, "function_declaration": "def is_valid_time(time_str):", "function_name": "is_valid_time", "parameter_list": "(time_str)" }, { "docstring": null, "function_declaration": "def is_valid_url(url):", "function_name": "is_valid_url", "parameter_list": "(url)" }, ...
[ 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 webbrowser\nimport time\nfrom threading import Timer\nfrom datetime import datetime\n\ndef validate_time_format(time_str):\n \"\"\" Validate the time format H...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00008364", "row_id": 8364, "seed_ids": "[290]" }
0.686726
Docs: Python310_8364
I
[ "is_valid_time", "is_valid_url", "open_url", "schedule_browser_openings" ]
4
[ [ "schedule_browser_openings", "is_valid_time" ], [ "schedule_browser_openings", "is_valid_url" ], [ "schedule_browser_openings", "open_url" ] ]
3
[]
false
[]
false
pytest
true
[]
true
7b333c766efc9096c64222a7fbb906c02b328c3c
1b6878bc121cf5359eed8860b133f9bfdc9242dd
v1.0
instruct
Docs
Docs: Scikit_8417_I
**Problem Description:** You are given a dataset and required to implement and optimize a machine learning model using scikit-learn. Your task involves: 1. Loading and preparing the data. 2. Implementing a machine learning model. 3. Profiling the existing implementation to identify bottlenecks. 4. Optimizing the ident...
import numpy as np from sklearn.datasets import load_digits from sklearn.decomposition import NMF def load_and_prepare_data(): # Load the "digits" dataset X, _ = load_digits(return_X_y=True) return X def original_nmf(X): # Original NMF implementation model = NMF(n_components=16, tol=1e-2) mode...
from solution import load_and_prepare_data, original_nmf def test_load_and_prepare_data(): X = load_and_prepare_data() assert X is not None assert len(X) > 0 def test_original_nmf(): X = load_and_prepare_data() model = original_nmf(X) assert model is not None assert hasattr(model, 'compone...
[ { "docstring": null, "function_declaration": "def load_and_prepare_data():", "function_name": "load_and_prepare_data", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def original_nmf(X):", "function_name": "original_nmf", "parameter_list": "(X)" }, { ...
[ 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": "from sklearn.datasets import load_digits\nfrom sklearn.decomposition import NMF\nimport numpy as np\nfrom time import time\n\n\ndef optimize_nmf():\n # Load the \"di...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00008417", "row_id": 8417, "seed_ids": "[11]" }
0.494865
Docs: Scikit_8417
I
[ "load_and_prepare_data", "original_nmf", "optimize_nmf" ]
3
[ [ "optimize_nmf", "load_and_prepare_data" ], [ "optimize_nmf", "original_nmf" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
910e2d75ef9ef1caf259b72cedf671910f7c84fc
f97785cfa743eea64ba97c659218109eb23335da
v1.0
instruct
Docs
Docs: Python310_8485_I
**Title: Managing Contextual State in Asynchronous Tasks** #### Objective: Design and implement an asynchronous logging system using context variables to manage log levels that are unique to each task. This system should allow each task to define and update its log level, which will not interfere with the log levels o...
import asyncio import contextvars # 1. Declare the context variable log_level_var = contextvars.ContextVar('log_level', default='INFO') # 2. Function to set log level def set_log_level(level: str) -> None: log_level_var.set(level) # 3. Function to log messages def log(message: str) -> None: log_level = log_l...
import asyncio import contextvars import pytest # Reimport the solution functions from solution import set_log_level, log, main # Capturing standard output to test the logs from io import StringIO import sys @pytest.fixture def capture_stdout(): old_stdout = sys.stdout sys.stdout = StringIO() yield sys.s...
[ { "docstring": null, "function_declaration": "def set_log_level(level):", "function_name": "set_log_level", "parameter_list": "(level)" }, { "docstring": null, "function_declaration": "def log(message):", "function_name": "log", "parameter_list": "(message)" } ]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport contextvars\n\n# 1. Declare the context variable\nlog_level_var = contextvars.ContextVar('log_level', default='INFO')\n\n# 2. Function to set log...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008485", "row_id": 8485, "seed_ids": "[392]" }
0.467054
Docs: Python310_8485
I
[ "set_log_level", "log", "task_one", "task_two", "main" ]
5
[ [ "task_one", "log" ], [ "task_one", "set_log_level" ], [ "task_two", "log" ], [ "task_two", "set_log_level" ] ]
4
[]
false
[]
false
pytest
true
[]
true
ef7c566eeb2ca138add60fafd74b6a6649ecd210
c72124fd39602a2d134ef9353eab1017d67ba15d
v1.0
instruct
Docs
Docs: Python310_8496_I
Implement a Python function named `custom_traceback_formatter` that captures an exception, extracts its traceback, and returns a formatted string of the entire traceback using the `traceback` module. ### Function Signature ```python def custom_traceback_formatter() -> str: ``` ### Requirements 1. **Capture Exception:...
import traceback def function_nested_caller(): raise ValueError("This is a custom error for testing traceback") def function_caller(): function_nested_caller() def custom_traceback_formatter() -> str: try: function_caller() except Exception as e: tb_str = ''.join(traceback.format_exce...
from solution import custom_traceback_formatter def test_custom_traceback_formatter(): formatted_traceback = custom_traceback_formatter() assert "Traceback (most recent call last):" in formatted_traceback assert 'function_caller' in formatted_traceback assert 'function_nested_caller' in formatted_trace...
[ { "docstring": null, "function_declaration": "def function_nested_caller():", "function_name": "function_nested_caller", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def function_caller():", "function_name": "function_caller", "parameter_list": "()" }...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import traceback\n\ndef function_that_raises():\n raise ValueError(\"This is a custom error for testing traceback\")\n\ndef function_nested_caller():\n function_t...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008496", "row_id": 8496, "seed_ids": "[335]" }
0.571536
Docs: Python310_8496
I
[ "function_nested_caller", "function_caller", "custom_traceback_formatter" ]
3
[ [ "custom_traceback_formatter", "function_caller" ], [ "function_caller", "function_nested_caller" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f5bde21f8f4e5f321cc41773ece1d38f97ef7372
49226665da813980a1b6b5306b806f9b0b586940
v1.0
instruct
Docs
Docs: Python310_8500_I
**Python Coding Assessment Question: Using `unittest.mock` to Test Functionality** ### Objective Create a series of unit tests for a function using the `unittest.mock` library. The function to be tested interacts with external dependencies that should be mocked to ensure isolated testing. ### Function Under Test ```p...
import requests def fetch_data_and_process(url): try: response = requests.get(url) response.raise_for_status() data = response.json() processed_data = process_data(data) save_data(processed_data) except requests.HTTPError as http_err: handle_error(f"HTTP error oc...
import unittest from unittest.mock import patch, Mock, call import requests from solution import fetch_data_and_process class TestFetchDataAndProcess(unittest.TestCase): @patch('solution.requests.get') @patch('solution.process_data') @patch('solution.save_data') def test_successful_fetch_and_process(s...
[ { "docstring": null, "function_declaration": "def fetch_data_and_process(url):", "function_name": "fetch_data_and_process", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def process_data(data):", "function_name": "process_data", "parameter_list": "(da...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\n\ndef fetch_data_and_process(url):\n try:\n response = requests.get(url)\n response.raise_for_status()\n data = response.json()...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008500", "row_id": 8500, "seed_ids": "[375]" }
0.698745
Docs: Python310_8500
I
[ "fetch_data_and_process", "process_data", "save_data", "handle_error" ]
4
[ [ "fetch_data_and_process", "handle_error" ], [ "fetch_data_and_process", "process_data" ], [ "fetch_data_and_process", "save_data" ] ]
3
[ "process_data" ]
false
[]
false
pytest
true
[ "requests" ]
false
7cd3d18e5460dee2c14f7a9dcb69fce8dae8762c
4af45369b4dcafd95e9fbd894f95efec27bf7b65
v1.0
instruct
Docs
Docs: Python310_8537_I
### Question: Implementing a Custom Interactive Shell with `readline` In this task, you are required to implement a custom interactive shell in Python using the `readline` module. This shell should support: 1. Custom history management. 2. Custom word completion. 3. Saving the session's history to a file, and loading ...
import os import readline import atexit def load_history(history_file: str) -> None: """ Load command history from history_file if it exists. """ try: readline.read_history_file(history_file) except FileNotFoundError: pass def save_history(history_file: str, max_commands: int) ->...
import os import readline import pytest from solution import load_history, save_history, custom_completer # Define test file paths TEST_HISTORY_FILE = "/tmp/.test_myshell_history" def test_load_history(): # Ensure clean state if os.path.exists(TEST_HISTORY_FILE): os.remove(TEST_HISTORY_FILE) ...
[ { "docstring": "Load command history from history_file if it exists.", "function_declaration": "def load_history(history_file):", "function_name": "load_history", "parameter_list": "(history_file)" }, { "docstring": "Save command history to history_file (max length max_commands).", "func...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport readline\nimport atexit\n\ndef load_history(history_file: str) -> None:\n \"\"\"\n Load history from the specified file. If the file doesn't exi...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008537", "row_id": 8537, "seed_ids": "[362]" }
0.400928
Docs: Python310_8537
I
[ "load_history", "save_history", "custom_completer", "interactive_shell" ]
4
[ [ "interactive_shell", "custom_completer" ], [ "interactive_shell", "load_history" ], [ "interactive_shell", "save_history" ] ]
3
[]
false
[]
false
pytest
true
[]
true
269a8ca168a81b836bbacc8f084c924c415eae8e
1eca9b7712dc54d5c80fe237865209dcb0dec905
v1.0
instruct
Docs
Docs: Python310_8570_I
### Custom Signal Handling and Alarm Management #### Objective: Implement a Python function to handle periodic tasks using signals and alarms. Use the `signal` module to set up signal handlers, manage alarms, and ensure clean termination upon receiving a specific termination signal. #### Problem Statement: Write a Py...
import signal import time import os # Flag to indicate if the process should terminate terminate = False def periodic_task_handler(signum, frame): """ Signal handler for SIGALRM """ print(f"Periodic task executed at {time.ctime()}") # Schedule the next alarm signal.alarm(5) def termination_ha...
import os import signal import time from multiprocessing import Process from solution import periodic_task_runner def run_periodic_task(): periodic_task_runner() def test_periodic_task_runner(): # Run the periodic task runner in a separate process process = Process(target=run_periodic_task) process.st...
[ { "docstring": "Signal handler for SIGALRM", "function_declaration": "def periodic_task_handler(signum, frame):", "function_name": "periodic_task_handler", "parameter_list": "(signum, frame)" }, { "docstring": "Signal handler for SIGUSR1", "function_declaration": "def termination_handler...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import signal\nimport time\nimport os\n\n# Flag to indicate if the process should terminate\nterminate = False\n\ndef periodic_task_handler(signum, frame):\n \"\"\"\...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00008570", "row_id": 8570, "seed_ids": "[253]" }
0.612001
Docs: Python310_8570
I
[ "periodic_task_handler", "termination_handler", "periodic_task_runner" ]
3
[ [ "periodic_task_runner", "periodic_task_handler" ], [ "periodic_task_runner", "termination_handler" ] ]
2
[]
false
[]
false
pytest
true
[]
true
41c86dbfbcf453333bc8f0a21442d19b2e3a5b4b
1a5a603a117e42349c3bcf58eb2a2fc0cb83f116
v1.0
instruct
Docs
Docs: Python310_8592_I
#### Objective Implement a recursive function that computes the factorial of a number using caching for efficiency. Additionally, create a class that calculates the factorial without recursion but demonstrates an understanding of function and method transformation using `functools.partial`. Finally, evaluate the perfo...
import functools @functools.cache def cached_factorial(n): """ Calculate the factorial of n using recursion with caching. """ if n == 0: return 1 else: return n * cached_factorial(n - 1) from functools import partial class FactorialCalculator: def __init__(self, n): se...
from solution import cached_factorial, FactorialCalculator, evaluate_performance def test_cached_factorial(): assert cached_factorial(0) == 1 assert cached_factorial(5) == 120 assert cached_factorial(10) == 3628800 assert cached_factorial(15) == 1307674368000 def test_factorial_calculator(): fc1 =...
[]
[ 0, 0, 0, 1, 0, 1, 1, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from functools import cache, partial\nimport time\n\n# Part 1: Recursive Factorial with Caching\n@cache\ndef cached_factorial(n):\n if n == 0:\n return 1\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00008592", "row_id": 8592, "seed_ids": "[236]" }
0.608093
Docs: Python310_8592
I
[ "cached_factorial", "evaluate_performance" ]
2
[ [ "evaluate_performance", "cached_factorial" ] ]
1
[]
false
[ "FactorialCalculator" ]
true
pytest
true
[]
true
9d3ed235157162c33a823b8ac1aa2dff36d8a173
f66b3e21afb04070ad456b5a2d9c5d69345698f6
v1.0
instruct
Docs
Docs: Seaborn_8710_I
**Coding Assessment Question: Seaborn ECDF Plot** **Objective:** Your task is to load a dataset and create specific ECDF plots using Seaborn, demonstrating your comprehension of fundamental and advanced concepts of this package. **Problem Statement:** 1. Load the 'penguins' dataset from seaborn. 2. Create an ECDF pl...
import seaborn as sns import matplotlib.pyplot as plt # Load the penguins dataset def load_penguins_dataset(): return sns.load_dataset("penguins") # Create ECDF plots def create_ecdf_plots(): penguins = load_penguins_dataset() # Plot 1: ECDF with flipper_length_mm along x-axis, hue for species, stat='cou...
from solution import load_penguins_dataset, create_ecdf_plots def test_load_penguins_dataset(): data = load_penguins_dataset() assert data is not None, "Failed to load the dataset" assert not data.empty, "Dataset is empty" assert "flipper_length_mm" in data.columns, "Missing 'flipper_length_mm' column"...
[ { "docstring": null, "function_declaration": "def load_penguins_dataset():", "function_name": "load_penguins_dataset", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def create_ecdf_plots():", "function_name": "create_ecdf_plots", "parameter_list": "()" ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef plot_ecdf():\n sns.set_theme()\n\n # Load the penguins dataset\n penguins = sns.load_dataset(\"pe...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00008710", "row_id": 8710, "seed_ids": "[58]" }
0.66463
Docs: Seaborn_8710
I
[ "load_penguins_dataset", "create_ecdf_plots" ]
2
[ [ "create_ecdf_plots", "load_penguins_dataset" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "seaborn" ]
false
079e7cdd4938b2a194ac049df932f6bc16350b9b
21d7c61b7d2bdc85195771391171e06dad7448fa
v1.0
instruct
Docs
Docs: Python310_8715_I
**Objective:** Implement a Python program that generates and manipulates UUIDs using the `uuid` module according to specified criteria. #### Problem Statement: 1. **UUID Generation:** - Generate 10 UUIDs using `uuid4()` and store them in a list. - Generate 1 UUID using `uuid1()`, ensuring it is multiprocessing...
import uuid def generate_uuids(): # Generate 10 UUIDs using uuid4() and store them in a list uuid4_list = [uuid.uuid4() for _ in range(10)] # Generate 1 UUID using uuid1(), ensuring it is multiprocessing-safe try: uuid1 = uuid.uuid1() safe = uuid1.is_safe except AttributeError: ...
import uuid from solution import generate_uuids, validate_uuids def test_generate_uuids(): # Generate UUIDs and check console output # It's hard to validate via unit tests since the output is dynamic, but ensuring the function runs without error is key generate_uuids() def test_validate_uuids(): # Gen...
[ { "docstring": null, "function_declaration": "def generate_uuids():", "function_name": "generate_uuids", "parameter_list": "()" }, { "docstring": "Validate a list of UUIDs.\nReturns True if all UUIDs are unique, otherwise False.", "function_declaration": "def validate_uuids(uuid_list):",...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import uuid\n\ndef generate_uuids():\n uuid4_list = [uuid.uuid4() for _ in range(10)]\n try:\n uuid1_value = uuid.uuid1()\n except Exception as e:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008715", "row_id": 8715, "seed_ids": "[295]" }
0.522968
Docs: Python310_8715
I
[ "generate_uuids", "validate_uuids" ]
2
[ [ "generate_uuids", "validate_uuids" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2602225be4abc4810314e6bcb937a26c823f8b17
d5393a9e3244c5a873166a6e90a2efe79c501d8f
v1.0
instruct
Docs
Docs: Python310_8718_I
**Question: MIME Type Handling with Mailcap** You are tasked with implementing a function that processes MIME types using the `mailcap` module. Given a MIME type, this function should find the appropriate application command to handle files of that type using the mailcap configuration. The function should be named `p...
import mailcap import re def sanitize_filename(filename: str) -> str: """ Sanitize the filename to remove disallowed characters. """ return re.sub(r'[^a-zA-Z0-9@+=:,./-_]', '', filename) def sanitize_plist(plist: list) -> list: """ Sanitize the plist to remove disallowed characters from parame...
from solution import process_mime_type def test_process_with_valid_mime_type(): command, entry = process_mime_type('text/plain', 'example.txt') assert command is not None assert 'view' in entry def test_process_with_nonexistent_mime_type(): command, entry = process_mime_type('application/unknown', 'ex...
[ { "docstring": "Sanitize the filename to remove disallowed characters.", "function_declaration": "def sanitize_filename(filename):", "function_name": "sanitize_filename", "parameter_list": "(filename)" }, { "docstring": "Sanitize the plist to remove disallowed characters from parameters.", ...
[ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import mailcap\nimport re\n\ndef sanitize_filename(filename: str) -> str:\n \"\"\"\n Sanitize the filename to remove disallowed characters.\n \"\"\"\n retur...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00008718", "row_id": 8718, "seed_ids": "[399]" }
0.54198
Docs: Python310_8718
I
[ "sanitize_filename", "sanitize_plist", "process_mime_type" ]
3
[ [ "process_mime_type", "sanitize_filename" ], [ "process_mime_type", "sanitize_plist" ] ]
2
[]
false
[]
false
pytest
true
[]
true
0fc96cd5568900a33c0bfca5857fede06bab92f8
2aa5e1472c0e7e48cf438695b6e822ff4c392321
v1.0
instruct
Docs
Docs: Python310_8804_I
### Asynchronous File Processing with Platform Considerations #### Background: You have been tasked with developing a Python script to process a large number of text files asynchronously using the "asyncio" module. However, you need to take into account platform-specific limitations described in the provided documenta...
import asyncio from typing import List, Dict import os async def count_async_in_file(file_path: str) -> int: count = 0 async with aiofiles.open(file_path, 'r') as f: async for line in f: if 'async' in line: count += 1 return count async def process_files(file_paths: Lis...
import pytest import asyncio from solution import process_files # Mock aiofiles for testing purpose, since we cannot use actual file IO in tests # This would be normally defined in a `conftest.py` file for pytest fixtures class MockAiofiles: def __init__(self, file_content): self.file_content = file_conte...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport os\nimport platform\n\nasync def count_async_lines_of_file(file_path):\n \"\"\"\n Asynchronously counts the number of lines containing the ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008804", "row_id": 8804, "seed_ids": "[370]" }
0.552981
Docs: Python310_8804
I
[ "count_async_in_file", "process_files" ]
2
[ [ "process_files", "count_async_in_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
79fd94879c99d4f334e5e56773b7f6d337df117a
8cffd1852c98939bf0c55a7636a97555ba53d2af
v1.0
instruct
Docs
Docs: Scikit_8888_I
### Anomaly Detection with Scikit-Learn **Objective:** Implement and compare various anomaly detection methods provided by the scikit-learn package on a synthetic dataset. This will test your understanding of how to use `LocalOutlierFactor`, `IsolationForest`, `OneClassSVM`, and `EllipticEnvelope`. **Instructions:** ...
import numpy as np from sklearn.datasets import make_blobs def generate_synthetic_data(n_samples=300, n_outliers=30, random_state=42): """ Generate a two-featured synthetic dataset with blobs for inliers and manually added outliers. Parameters: - n_samples (int): Total number of inlier samples ...
from solution import generate_synthetic_data, anomaly_detection_comparison, evaluate_performance def test_generate_synthetic_data_shape(): X, y = generate_synthetic_data(n_samples=300, n_outliers=30, random_state=42) assert X.shape == (330, 2) assert y.shape == (330,) def test_generate_synthetic_data_labe...
[ { "docstring": "Generate a two-featured synthetic dataset with blobs for inliers and manually added outliers.\n\nParameters:\n- n_samples (int): Total number of inlier samples\n- n_outliers (int): Number of outlier samples\n- random_state (int): Seed for random number generator\n\nReturns:\n- X (np.ndarray): Fe...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.datasets import make_blobs\n\ndef generate_synthetic_data(n_samples=300, n_outliers=30, random_state=42):\n \"\"\"\n Generate a t...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008888", "row_id": 8888, "seed_ids": "[36]" }
0.598842
Docs: Scikit_8888
I
[ "generate_synthetic_data", "anomaly_detection_comparison", "evaluate_performance" ]
3
[ [ "anomaly_detection_comparison", "evaluate_performance" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
33f08ea6745bf98e81f94fb3cca78e5d6d8880da
4427715ef5efddd4027f188b35f67280560e3cc6
v1.0
instruct
Docs
Docs: Python310_8898_I
You have been given the task of writing unit tests for a data processing application. The application has a function `process_data`, which reads from a file, processes the data, and writes the results to another file. Your task is to use the `unittest.mock` module to create mock objects in order to unit test this funct...
from unittest.mock import mock_open, patch def read_input_file(file_path: str) -> str: """Reads and returns content of a file.""" with open(file_path, 'r') as file: return file.read() def write_output_file(file_path: str, content: str): """Writes content to a file.""" with open(file_path, 'w')...
import pytest from unittest.mock import mock_open, patch from solution import process_data @patch('builtins.open', new_callable=mock_open, read_data='sample data') def test_process_data(mock_open): input_file_path = 'input.txt' output_file_path = 'output.txt' # Call the function to test process_data(...
[ { "docstring": "Reads and returns content of a file.", "function_declaration": "def read_input_file(file_path):", "function_name": "read_input_file", "parameter_list": "(file_path)" }, { "docstring": "Writes content to a file.", "function_declaration": "def write_output_file(file_path, c...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def read_input_file(file_path: str) -> str:\n \"\"\"Reads and returns content of a file.\"\"\"\n with open(file_path, 'r') as file:\n return file.read()\n\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008898", "row_id": 8898, "seed_ids": "[375]" }
0.625313
Docs: Python310_8898
I
[ "read_input_file", "write_output_file", "process_data" ]
3
[ [ "process_data", "read_input_file" ], [ "process_data", "write_output_file" ] ]
2
[ "process_data" ]
false
[]
false
pytest
true
[]
true
75c618314a597572d9e38a9761fee0eb2a5e114a
6b72367895bc87b5351132e859d215ee35c38826
v1.0
instruct
Docs
Docs: Pytorch_8901_I
### PyTorch MPS Environment Configuration Task You are working on optimizing a machine learning model that runs on Apple's Metal Performance Shaders (MPS) backend using PyTorch. During testing, you need to ensure your model runs efficiently on different devices and configurations. Specifically, you want to control mem...
import os import torch import torch.nn as nn def configure_mps_environment(): """Configures MPS environment variables for optimization and logging.""" os.environ["PYTORCH_DEBUG_MPS_ALLOCATOR"] = "1" os.environ["PYTORCH_MPS_HIGH_WATERMARK_RATIO"] = "1.5" if torch.cuda.is_available(): os.env...
import os import pytest import torch from solution import configure_mps_environment, create_and_run_model def test_configure_mps_environment(): configure_mps_environment() assert os.environ["PYTORCH_DEBUG_MPS_ALLOCATOR"] == "1" assert os.environ["PYTORCH_MPS_HIGH_WATERMARK_RATIO"] == "1.5" if...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport torch\nimport torch.nn as nn\n\n# Function to set environment variables for MPS configuration\ndef configure_mps_environment(unified_memory=True):\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00008901", "row_id": 8901, "seed_ids": "[64]" }
0.468212
Docs: Pytorch_8901
I
[ "configure_mps_environment", "create_and_run_model" ]
2
[ [ "create_and_run_model", "configure_mps_environment" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
97e2c1fb9c9247fdaa38700f71cbd59b90b112de
5d80672f4cce218960ef782a29f765498d997128
v1.0
instruct
Docs
Docs: Scikit_8981_I
### Question: Implementing and Analyzing Kernel Density Estimation (KDE) **Objective:** In this task, you are required to implement a Kernel Density Estimation (KDE) using different kernels from the scikit-learn library to visualize the density estimation on a bimodal dataset. You will analyze and compare the results...
import numpy as np import matplotlib.pyplot as plt from sklearn.neighbors import KernelDensity def generate_bimodal_dataset(): """ Generates a bimodal dataset with: - 100 points from N(-2, 0.5) - 100 points from N(3, 0.5) Returns: np.ndarray: A (200, 1) numpy array containing the dataset. ...
from solution import generate_bimodal_dataset, perform_kde, plot_histogram, visualize_kde def test_generate_bimodal_dataset(): data = generate_bimodal_dataset() assert data.shape == (200, 1) assert len(data[data < 0]) > 0 assert len(data[data >= 0]) > 0 def test_perform_kde(): data = generate_bimo...
[ { "docstring": "Generates a bimodal dataset with:\n- 100 points from N(-2, 0.5)\n- 100 points from N(3, 0.5)\nReturns:\n np.ndarray: A (200, 1) numpy array containing the dataset.", "function_declaration": "def generate_bimodal_dataset():", "function_name": "generate_bimodal_dataset", "parameter_...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.neighbors import KernelDensity\n\ndef generate_bimodal_dataset():\n \"\"\"\n Generates a bimodal...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00008981", "row_id": 8981, "seed_ids": "[51]" }
0.587701
Docs: Scikit_8981
I
[ "generate_bimodal_dataset", "plot_histogram", "perform_kde", "visualize_kde", "compare_kernels" ]
5
[ [ "compare_kernels", "generate_bimodal_dataset" ], [ "compare_kernels", "perform_kde" ], [ "compare_kernels", "visualize_kde" ], [ "visualize_kde", "plot_histogram" ] ]
4
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "sklearn" ]
false
05dc400aa8c54f1d529fa1a5769ee9d616753d8c
40719a9b98e8b8371b7ffdbf877672f868c86ae7
v1.0
instruct
Docs
Docs: Pytorch_8988_I
### PyTorch Function Transformation Assessment #### Objective: Demonstrate your understanding of PyTorch's `torch.func` module by implementing and transforming a function using function transforms while adhering to the constraints provided. #### Problem Statement: You are required to implement a function that compute...
import torch from torch.func import grad, vmap def squared_error(tensor1, tensor2): """ Computes the element-wise squared error between two tensors. """ return (tensor1 - tensor2) ** 2 def gradient_squared_error(tensor1, tensor2): """ Computes the gradient of the squared_error with respect to ...
import torch from solution import squared_error, gradient_squared_error, batched_squared_error def test_squared_error(): tensor1 = torch.tensor([1.0, 2.0, 3.0]) tensor2 = torch.tensor([4.0, 5.0, 6.0]) expected_result = torch.tensor([9.0, 9.0, 9.0]) assert torch.equal(squared_error(tensor1, tensor2), ex...
[ { "docstring": "Computes the element-wise squared error between two tensors.", "function_declaration": "def squared_error(tensor1, tensor2):", "function_name": "squared_error", "parameter_list": "(tensor1, tensor2)" }, { "docstring": "Computes the gradient of the squared_error with respect t...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.func import grad, vmap\n\ndef squared_error(tensor1, tensor2):\n \"\"\"\n Computes the element-wise squared error between two tensors.\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00008988", "row_id": 8988, "seed_ids": "[136]" }
0.52487
Docs: Pytorch_8988
I
[ "squared_error", "gradient_squared_error", "batched_squared_error" ]
3
[ [ "batched_squared_error", "squared_error" ], [ "gradient_squared_error", "squared_error" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
29e1f9eebcfda4c3273211a7ace4c3797ffc04cd
a5455181cb05caaa7ef786d302aba8cb769456e4
v1.0
instruct
Docs
Docs: Scikit_9078_I
#### Problem Statement You are given a dataset of 2D points. Your task is to implement a kernel density estimation (KDE) model using scikit-learn and apply it to the dataset. You will need to experiment with different kernel types and bandwidth parameters, and then visualize the density estimation for comparison. Fina...
import numpy as np import matplotlib.pyplot as plt from sklearn.neighbors import KernelDensity def generate_dataset(): np.random.seed(0) X = np.vstack([np.random.normal(loc=-1, scale=1, size=(100, 2)), np.random.normal(loc=1, scale=0.5, size=(100, 2))]) return X def fit_kde_models(X, ke...
from solution import generate_dataset, fit_kde_models import numpy as np def test_generate_dataset(): X = generate_dataset() assert X.shape == (200, 2) assert np.mean(X[:100, :]) < 0 # Check for the first cluster's mean assert np.mean(X[100:, :]) > 0 # Check for the second cluster's mean def test_fi...
[ { "docstring": null, "function_declaration": "def generate_dataset():", "function_name": "generate_dataset", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def fit_kde_models(X, kernels, bandwidths):", "function_name": "fit_kde_models", "parameter_list": ...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.neighbors import KernelDensity\n\n# Task 1: Generate dataset\nnp.random.seed(0)\nX = np.vstack([np.ran...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009078", "row_id": 9078, "seed_ids": "[51]" }
0.585961
Docs: Scikit_9078
I
[ "generate_dataset", "fit_kde_models", "plot_kde", "visualize_kde_models" ]
4
[ [ "visualize_kde_models", "plot_kde" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "sklearn" ]
false
bc2f0efb434ba1d77a0e2e49f33138ddde153d23
98df83d671f9792dbb2b166d677d8b284e86b59a
v1.0
instruct
Docs
Docs: Python310_9099_I
You are provided with a dataset consisting of large integers that require computationally intensive operations to determine certain properties of these numbers. Your task is to implement a Python function that uses both thread-based and process-based parallelism to improve the performance of your computations. #### Pr...
from concurrent.futures import ProcessPoolExecutor, as_completed from typing import List, Dict import math def is_prime(n: int) -> bool: """ Determines if the given number n is a prime number. """ if n < 2: return False if n == 2: return True if n % 2 == 0: return False ...
import pytest from solution import parallel_prime_check def test_parallel_prime_check_single_prime_number(): assert parallel_prime_check([7]) == {7: True} def test_parallel_prime_check_single_non_prime_number(): assert parallel_prime_check([8]) == {8: False} def test_parallel_prime_check_mixed_numbers(): ...
[ { "docstring": "Determines if the given number n is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Use ProcessPoolExecutor to check if numbers in the list are prime.\nReturns a dictionary with the numbers ...
[ 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": "from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\nfrom typing import List, Dict\nimport math\n\ndef is_prime(n: int) -> bool:\n if n < 2:\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00009099", "row_id": 9099, "seed_ids": "[347]" }
0.636409
Docs: Python310_9099
I
[ "is_prime", "parallel_prime_check" ]
2
[ [ "parallel_prime_check", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0619ef52801daff63e84d5f6e412c21d84c28870
9121101239d905d44ac9b0755794ff855a293c08
v1.0
instruct
Docs
Docs: Pytorch_9115_I
**Attention Mechanism Implementation in PyTorch** You are tasked with implementing a simplified attention mechanism in PyTorch. Attention mechanisms are widely used in models such as Transformers for natural language processing and other sequential tasks. ### Task Description Implement the following functions to bui...
import torch import torch.nn.functional as F def scaled_dot_product_attention(query, key, value, mask=None): """ Compute the scaled dot-product attention. Args: - query: A tensor of shape (batch_size, seq_length, d_k) - key: A tensor of shape (batch_size, seq_length, d_k) - value: A tensor...
import torch from solution import scaled_dot_product_attention, multi_head_attention def test_scaled_dot_product_attention(): torch.manual_seed(0) query = torch.randn(2, 5, 10) key = torch.randn(2, 5, 10) value = torch.randn(2, 5, 15) output = scaled_dot_product_attention(query, key, value) ...
[ { "docstring": "Compute the scaled dot-product attention.\n\nArgs:\n- query: A tensor of shape (batch_size, seq_length, d_k)\n- key: A tensor of shape (batch_size, seq_length, d_k)\n- value: A tensor of shape (batch_size, seq_length, d_v)\n- mask: An optional tensor that can be broadcasted to shape (batch_size,...
[ 0, 0, 0, 0, 1, 1, 0, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn.functional as F\n\ndef scaled_dot_product_attention(query, key, value, mask=None):\n \"\"\"\n Computes the scaled dot product attent...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00009115", "row_id": 9115, "seed_ids": "[117]" }
0.51669
Docs: Pytorch_9115
I
[ "scaled_dot_product_attention", "multi_head_attention" ]
2
[ [ "multi_head_attention", "scaled_dot_product_attention" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
08e97ce262eb629ceba48516cad52db617ff7eee
6ede2a89ef85117ef6638be3823a8ac944f0935c
v1.0
instruct
Docs
Docs: Python310_9118_I
### **Question: Implementing a Functional Pipeline with Iterators and Generators** You are given a text file `data.txt` that contains multiple lines of text. Each line consists of words separated by spaces. Your task is to implement a function `process_file(file_path: str) -> List[Tuple[str, int]]` that reads the file...
from typing import Iterator, Dict, List, Tuple from collections import defaultdict def read_lines(file_path: str) -> Iterator[str]: """ Generator that reads lines from a file. """ with open(file_path, 'r') as file: for line in file: yield line def process_lines(lines: Iterator[str]...
import pytest from solution import read_lines, process_lines, count_words, process_file def test_read_lines(): # This test should go in the pytest temporary file system, requiring that we mock a file. file_path = 'test_data.txt' with open(file_path, 'w') as f: f.write("Hello world\nHello\nFunctiona...
[ { "docstring": "Generator that reads lines from a file.", "function_declaration": "def read_lines(file_path):", "function_name": "read_lines", "parameter_list": "(file_path)" }, { "docstring": "Generator that processes lines.\nStrips leading/trailing whitespace, converts to lowercase, and sp...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import Iterator, Dict, List, Tuple\n\ndef read_lines(file_path: str) -> Iterator[str]:\n with open(file_path, 'r') as file:\n for line in file:\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00009118", "row_id": 9118, "seed_ids": "[78]" }
0.579976
Docs: Python310_9118
I
[ "read_lines", "process_lines", "count_words", "process_file" ]
4
[ [ "process_file", "count_words" ], [ "process_file", "process_lines" ], [ "process_file", "read_lines" ] ]
3
[ "read_lines", "process_lines" ]
false
[]
false
pytest
true
[]
true
93d10c27f806c3da0e13c44741814c17c971ad56
b214f55baaf77edc5bc4abf20dbad6d298a45794
v1.0
instruct
Docs
Docs: Python310_9155_I
### Advanced Coding Assessment Question #### Objective: Implement a function that accepts a list of integers and performs a series of mathematical and statistical operations as defined below. #### Problem Statement: You are provided with a list of integers. Implement a function `analyze_numbers` that performs the fo...
import math import statistics def is_prime(n): """ Returns True if n is a prime number, else False. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: return F...
from solution import analyze_numbers def test_analyze_numbers_all_primes(): data = [2, 3, 5, 7, 11] result = analyze_numbers(data) assert result == { "primes": [True, True, True, True, True], "mean": 5.6, "variance": statistics.variance(data) } def test_analyze_numbers_no_prime...
[ { "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": "Analyzes the input list of integers.", "function_declaration": "def analyze_numbers(data):", "functio...
[ 0, 1 ]
1
medium
0.5
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import math\nfrom statistics import mean, variance\n\ndef is_prime(n):\n \"\"\"\n Function to check if a number is a prime number.\n \...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009155", "row_id": 9155, "seed_ids": "[398]" }
0.628763
Docs: Python310_9155
I
[ "is_prime", "analyze_numbers" ]
2
[ [ "analyze_numbers", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f41abd13b3c3f41b289c38ffd763302510459e45
0e7b26ec25ff4b7135a96ad8c7849fa354ace053
v1.0
instruct
Docs
Docs: Pytorch_9346_I
#### Objective The objective of this question is to assess your understanding of PyTorch's TorchInductor GPU profiling tools and your ability to work with environment variables, run benchmarks, and analyze generated performance logs. #### Problem Statement You are given a PyTorch model and need to profile its performa...
import os import json # Step 1: Set up environment variables os.environ['TORCHINDUCTOR_UNIQUE_KERNEL_NAMES'] = '1' os.environ['TORCHINDUCTOR_BENCHMARK_KERNEL'] = '1' os.environ['TORCHINDUCTOR_MAX_AUTOTUNE'] = '1' # Step 2: Define function to run the benchmark def run_benchmark(): os.system("python -u model_benchm...
import os import pytest import json from unittest.mock import patch, mock_open from solution import analyze_profiling_logs, profile_model def create_fake_log(): return json.dumps([ {'category': 'pointwise', 'percentage': 30}, {'category': 'reduction', 'percentage': 20}, {'category': 'cutlas...
[ { "docstring": null, "function_declaration": "def run_benchmark():", "function_name": "run_benchmark", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def analyze_profiling_logs(log_path='/tmp/compiled_module_profile.json'):", "function_name": "analyze_profili...
[ 0, 0, 0, 0, 0, 0, 0, 1, 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 json\n\ndef set_environment_variables():\n os.environ['TORCHINDUCTOR_UNIQUE_KERNEL_NAMES'] = '1'\n os.environ['TORCHINDUCTOR_BENCHMARK_KERNEL'] ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00009346", "row_id": 9346, "seed_ids": "[15]" }
0.420336
Docs: Pytorch_9346
I
[ "run_benchmark", "analyze_profiling_logs", "profile_model" ]
3
[ [ "profile_model", "analyze_profiling_logs" ], [ "profile_model", "run_benchmark" ] ]
2
[]
false
[]
false
pytest
true
[]
true
12442d0b3ac37d06e46a81085e983f880142c2ed
e210d1f27a0c7445a83f4c8dbf2c00b9ef6b2468
v1.0
instruct
Docs
Docs: Python310_9377_I
### Question **Title: Implement a Custom Asynchronous Server-Client Model using asyncio** **Difficulty: Advanced** **Objective:** Your task is to implement a custom server-client model using the `asyncio` module in Python. The server will handle multiple clients concurrently, echoing received messages but with a sim...
import asyncio async def handle_client(reader, writer): addr = writer.get_extra_info('peername') print(f"Connected to {addr}") while True: data = await reader.read(100) message = data.decode() if not message: break print(f"Received '{message}' from {addr}") ...
import asyncio import pytest from solution import handle_client, run_server, run_client @pytest.mark.asyncio async def test_server_client_interaction(): server_task = asyncio.create_task(run_server('localhost', 8888)) await asyncio.sleep(1) # Give server time to start client_task = asyncio.create_task(r...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n print(f\"Connected to {addr}\")\n\n while True:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009377", "row_id": 9377, "seed_ids": "[267]" }
0.641464
Docs: Python310_9377
I
[ "handle_client", "run_server", "run_client" ]
3
[ [ "run_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
76162f60e8414e5168c67e1083f584452bb654e2
16ca23cb4e887f2bb0581743401d6d4ec80ec46e
v1.0
instruct
Docs
Docs: Pandas_9418_I
### Coding Assessment: Working with PyArrow and pandas #### Objective: Demonstrate understanding and application of integrating PyArrow with pandas for efficient data manipulation and I/O operations. #### Problem Statement: You are provided with a CSV file named `data.csv` which contains mixed data types including i...
import pandas as pd import pyarrow as pa import pyarrow.csv as pv import pyarrow.compute as pc def read_csv_with_pyarrow(file_path): """ Reads a CSV file into a Pandas DataFrame using PyArrow as the engine. @param: file_path: str: Path to the CSV file @return: pd.DataFrame backed with PyArrow """ ...
import pandas as pd import pyarrow as pa import pyarrow.parquet as pq import pyarrow.csv as pv import pytest from solution import read_csv_with_pyarrow, clean_data, transform_data, analyze_data, save_to_csv @pytest.fixture def sample_data(tmp_path): # Creating a sample CSV file data = """id,value,status,name,...
[ { "docstring": "Reads a CSV file into a Pandas DataFrame using PyArrow as the engine.\n@param: file_path: str: Path to the CSV file\n@return: pd.DataFrame backed with PyArrow", "function_declaration": "def read_csv_with_pyarrow(file_path):", "function_name": "read_csv_with_pyarrow", "parameter_list"...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nimport pyarrow as pa\nimport pyarrow.csv as pv\nimport pyarrow.compute as pc\nfrom sklearn.preprocessing import MinMaxScaler\n\ndef process_csv(fil...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009418", "row_id": 9418, "seed_ids": "[27]" }
0.639335
Docs: Pandas_9418
I
[ "read_csv_with_pyarrow", "clean_data", "transform_data", "analyze_data", "save_to_csv", "process_csv" ]
6
[ [ "process_csv", "analyze_data" ], [ "process_csv", "clean_data" ], [ "process_csv", "read_csv_with_pyarrow" ], [ "process_csv", "save_to_csv" ], [ "process_csv", "transform_data" ] ]
5
[]
false
[]
false
pytest
true
[ "pandas", "pyarrow" ]
false
22a2050579955bfb3457300d668fefa8da708f83
e911fa57c999ce18a660e6ec7c72d4628fb46d2e
v1.0
instruct
Docs
Docs: Python310_9427_I
### Memory Leak Analysis with tracemalloc #### Objective In this task, you are required to analyze a Python program for memory leaks using the `tracemalloc` module. Specifically, you need to identify which parts of the code are responsible for the most memory allocations and determine if there are any memory leaks. #...
import tracemalloc def computation_function(): """Represents a function performing some computations and data processing.""" data = [] for i in range(1000): data.append([j for j in range(1000)]) # Simulate some other memory consumption temp_data = [k * 2 for k in range(10000)] del temp...
from solution import computation_function, analyze_memory_leak def test_computation_function(): result = computation_function() assert len(result) == 1000 assert len(result[0]) == 1000 def test_analyze_memory_leak(): top_allocation_lines, memory_leaks = analyze_memory_leak() assert isinstan...
[ { "docstring": "Represents a function performing some computations and data processing.", "function_declaration": "def computation_function():", "function_name": "computation_function", "parameter_list": "()" }, { "docstring": "Analyzes the provided computation_function() for memory allocati...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import tracemalloc\n\ndef computation_function():\n \"\"\"Represents a function performing some computations and data processing.\"\"\"\n data = []\n for i in ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009427", "row_id": 9427, "seed_ids": "[404]" }
0.473785
Docs: Python310_9427
I
[ "computation_function", "analyze_memory_leak" ]
2
[ [ "analyze_memory_leak", "computation_function" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c2b8f04e2b7e893b252dcb772fa5aec584f2621e
323c52564513b69c9cda57fa53e6247ab98175a6
v1.0
instruct
Docs
Docs: Pytorch_9474_I
**Objective:** Demonstrate your understanding of PyTorch's MPS backend by verifying its availability, performing tensor operations, and using it to execute a neural network's inference on a GPU. **Question:** You are tasked with verifying the availability of the MPS backend in PyTorch, performing simple tensor manipu...
import torch import torch.nn as nn def check_mps_availability(): """ Checks if the MPS backend is available. """ return torch.backends.mps.is_available() def tensor_operations_on_mps(): """ Performs simple tensor operations on MPS. - Creates a tensor of shape (5,) filled with ones directly...
import pytest import torch from solution import check_mps_availability, tensor_operations_on_mps, SimpleNet, model_inference_on_mps def test_check_mps_availability(): assert check_mps_availability() == torch.backends.mps.is_available() def test_tensor_operations_on_mps(): if check_mps_availability(): ...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\n\ndef check_mps_availability():\n \"\"\"\n Check whether the MPS backend is available.\n Returns a boolean indicating the ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00009474", "row_id": 9474, "seed_ids": "[167]" }
0.456335
Docs: Pytorch_9474
I
[ "check_mps_availability", "tensor_operations_on_mps", "model_inference_on_mps" ]
3
[ [ "model_inference_on_mps", "check_mps_availability" ], [ "tensor_operations_on_mps", "check_mps_availability" ] ]
2
[]
false
[ "SimpleNet" ]
true
pytest
true
[ "torch" ]
false
6b7d1ae51d7827400dbff61470f9d0b12be65ad6
bcff8316a004cc5772a039c966e97253f899dec5
v1.0
instruct
Docs
Docs: Pytorch_9485_I
#### Objective Implement a custom multi-headed attention mechanism using PyTorch's `torch.nn.attention.flex_attention` and `BlockMask` utilities. #### Problem Statement You are required to implement a function `multi_headed_attention` that performs multi-headed attention on a given set of queries, keys, and values. Yo...
import torch from torch.nn.functional import softmax def split_heads(tensor, num_heads): """ Splits the last dimension of a tensor into (num_heads, depth), where depth is d_model // num_heads. Arguments: tensor -- tensor to split, shape (batch_size, seq_len, d_model) num_heads -- number of attentio...
import torch from solution import multi_headed_attention def test_multi_headed_attention_output_shape(): batch_size, seq_len, d_model = 2, 5, 16 num_heads = 4 query = torch.rand((batch_size, seq_len, d_model)) key = torch.rand((batch_size, seq_len, d_model)) value = torch.rand((batch_size, seq...
[ { "docstring": "Splits the last dimension of a tensor into (num_heads, depth), where depth is d_model // num_heads.\nArguments:\ntensor -- tensor to split, shape (batch_size, seq_len, d_model)\nnum_heads -- number of attention heads\nReturns:\ntensor -- tensor of shape (batch_size, num_heads, seq_len, depth)", ...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn.functional as F\nfrom transformer_utils import flex_attention, BlockMask # Assuming these are the given utilities\n\ndef multi_headed_att...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00009485", "row_id": 9485, "seed_ids": "[0]" }
0.479855
Docs: Pytorch_9485
I
[ "split_heads", "combine_heads", "scaled_dot_product_attention", "multi_headed_attention" ]
4
[ [ "multi_headed_attention", "combine_heads" ], [ "multi_headed_attention", "scaled_dot_product_attention" ], [ "multi_headed_attention", "split_heads" ] ]
3
[]
false
[]
false
pytest
true
[ "torch" ]
false
5d4302a7ee65e3ef7adcf402054027ea29f6d48d
49038e02ec15419092d6c874e68cad96c1bb1fd1
v1.0
instruct
Docs
Docs: Pytorch_9618_I
### PyTorch Profiling Hooks Implementation #### Objective: Implement a mechanism to add global profiling hooks to monitor the execution time of PyTorch operations. This will help collect runtime statistics and performance data for all operations executed in a script. #### Problem Statement: You are required to write ...
import torch import torch.nn as nn import torch.optim as optim from torch.autograd import profiler def init_profiling_hook(): """ Initializes a global profiling hook to monitor PyTorch operation execution times. """ # Define the profiling context manager class ProfilerContextManager: def ...
import torch from solution import init_profiling_hook, SimpleNN # Import pytest for testing import pytest def test_profiling_hook_initialization(): """ Test if the profiling hook is initialized without errors. """ ctx = init_profiling_hook() assert ctx is not None def test_training_runs_with_prof...
[]
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\ndef init_profiling_hook():\n def profiling_hook(prof):\n # Filter events to log only top-l...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00009618", "row_id": 9618, "seed_ids": "[162]" }
0.499409
Docs: Pytorch_9618
I
[ "init_profiling_hook", "run_training_with_profiling" ]
2
[ [ "run_training_with_profiling", "init_profiling_hook" ] ]
1
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
6202912973c865f557c0ce139771db787e00965c
1afcd655d5209875df55da849cb22b286c9d2905
v1.0
instruct
Docs
Docs: Python310_9677_I
You are required to implement a program that reads the attributes of a file and modifies some of its properties using Unix-specific system calls. The program must be capable of: 1. Retrieving the current size, permissions, and owner of a specified file. 2. Changing the file's permissions and truncating its size to a gi...
import os import pwd import syslog def get_file_info(filepath: str) -> dict: """ Retrieves the size, permissions, and owner of the specified file. """ try: file_stat = os.stat(filepath) file_info = { 'size': file_stat.st_size, 'permissions': f'{oct(file_stat.st_m...
import os import pytest from unittest import mock from solution import get_file_info, modify_file, log_operation # Create a temporary file to test our functions @pytest.fixture def temp_file(tmp_path): file = tmp_path / "testfile" file.write_text("Hello, world!") return file def test_get_file_info(temp_fi...
[ { "docstring": "Retrieves the size, permissions, and owner of the specified file.", "function_declaration": "def get_file_info(filepath):", "function_name": "get_file_info", "parameter_list": "(filepath)" }, { "docstring": "Changes the file's permissions and truncates its size.", "functi...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport pwd\nimport syslog\n\ndef get_file_info(filepath: str) -> dict:\n \"\"\"\n Retrieves the current size, permissions, and owner of a specified fil...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009677", "row_id": 9677, "seed_ids": "[149]" }
0.480987
Docs: Python310_9677
I
[ "get_file_info", "modify_file", "log_operation" ]
3
[ [ "get_file_info", "log_operation" ], [ "modify_file", "log_operation" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a4383204e7465a6a953ab258d3f65779a4a847c6
ff570c04576dcd573d60a1301357c046386781a3
v1.0
instruct
Docs
Docs: Python310_9683_I
Implementing Safe Reference Counting in a Python C Extension **Objective:** Design and implement a small part of a Python C extension that demonstrates proper reference counting using the functions provided in the Python C API. **Problem Statement:** You are tasked with implementing a C function that manages the r...
# This is a Python file that mimics the safe_assign_object function described in the problem statement. # For the actual implementation in C, the code provided here is a reference and should be used accordingly # in a .c file. def safe_assign_object(target, source): """ Python mimic of the safe_assign_object f...
from solution import safe_assign_object, _RefCountedObject def test_safe_assign_object_with_non_null_source(): target = [None] source = _RefCountedObject() assert source.ref_count == 1 safe_assign_object(target, source) assert source.ref_count == 2 assert target[0] is source def test_safe_ass...
[]
[ 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": "c\n#include <Python.h>\n\n// Function to safely assign source object to target\nvoid safe_assign_object(PyObject **target, PyObject *source) {\n if (target == NULL) ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00009683", "row_id": 9683, "seed_ids": "[34]" }
0.380207
Docs: Python310_9683
I
[ "safe_assign_object", "Py_INCREF", "Py_DECREF" ]
3
[ [ "safe_assign_object", "Py_DECREF" ], [ "safe_assign_object", "Py_INCREF" ] ]
2
[]
false
[ "_RefCountedObject" ]
true
pytest
true
[]
true
7c9aafdcfb9b05d826eff706682b2e90b793c3f7
6cb46af28ffec21039da9b1f3135beb54c000920
v1.0
instruct
Docs
Docs: Python310_9792_I
### Coding Challenge: #### Objective: Evaluate your ability to use Python's `asyncio` library to manage subprocesses. #### Task: You are required to write an asynchronous Python function that takes a list of shell commands and runs them concurrently. The function should return a dictionary with the command as the key...
import asyncio async def run_command(command): proc = await asyncio.create_subprocess_shell( command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, stderr = await proc.communicate() return command, (stdout.decode().strip() if stdout else stde...
import asyncio from solution import run_commands def test_echo_command(): commands = ["echo 'Hello World'"] results = asyncio.run(run_commands(commands)) assert results == {"echo 'Hello World'": ("Hello World", 0)} def test_invalid_directory_command(): commands = ["ls /non_existent_dir"] results =...
[]
[ 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 asyncio\n\nasync def run_command(command):\n proc = await asyncio.create_subprocess_shell(\n command,\n stdout=asyncio.subprocess.PIPE,\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009792", "row_id": 9792, "seed_ids": "[264]" }
0.711388
Docs: Python310_9792
I
[ "run_command", "run_commands" ]
2
[ [ "run_commands", "run_command" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e2d86fe15dfeb2c33d241381ec51ac701e6cd0d8
efb5c9aecb7687f72a01237e57aeec67f7d3817e
v1.0
instruct
Docs
Docs: Python310_9837_I
### Question: Advanced Python Logging System #### Objective: You are required to design and implement a logging system for a Python application that processes multiple tasks concurrently. The system should utilize advanced logging features such as multiple handlers, custom formatters, filters, and context-specific log...
import logging import threading from logging.handlers import RotatingFileHandler import time class ContextFilter(logging.Filter): def __init__(self, task_id, user): super().__init__() self.task_id = task_id self.user = user def filter(self, record): record.task_id = self.task_i...
import os import threading import logging import time from solution import setup_logging, task_function, ContextFilter def test_single_task_logging(): task_id, user = 0, 'TestUser' logger = setup_logging(task_id, user) logger.info("Test task started") assert logger.handlers[0].level == logging.INFO ...
[]
[ 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 logging\nfrom logging.handlers import RotatingFileHandler\nimport threading\nfrom functools import wraps\nimport time\n\nclass ContextFilter(logging.Filter):\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00009837", "row_id": 9837, "seed_ids": "[75]" }
0.636178
Docs: Python310_9837
I
[ "setup_logging", "task_function" ]
2
[ [ "task_function", "setup_logging" ] ]
1
[]
false
[ "ContextFilter" ]
true
pytest
true
[]
true
e3b088d1be168f01c63ea3844b619561bdde877b
835d048e8a84bc0fd0c5207cd7554510fca8dd98
v1.0
instruct
Docs
Docs: Python310_9845_I
### Asynchronous Web Scraper with Timeout #### Problem Statement You are required to implement an asynchronous web scraper that fetches data from multiple URLs concurrently, with a specified timeout for each request. The web scraper should also handle exceptions gracefully, logging any errors encountered during the s...
import asyncio import aiohttp async def fetch_with_timeout(url: str, timeout: int) -> str: """ Fetch the content of a URL with a specified timeout. Args: url (str): The URL to fetch. timeout (int): Timeout in seconds. Returns: str: The content of the URL if fetched successfull...
import asyncio from solution import fetch_with_timeout, fetch_all async def test_fetch_with_timeout(): # Test a valid URL with sufficient timeout content = await fetch_with_timeout("http://example.com", 10) assert 'html' in content # Test a valid URL with insufficient timeout content = await fetch...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\n\nasync def fetch_with_timeout(url: str, timeout: int) -> str:\n \"\"\"\n Fetch the content of a URL with a specified timeout.\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009845", "row_id": 9845, "seed_ids": "[360]" }
0.65221
Docs: Python310_9845
I
[ "fetch_with_timeout", "fetch_all", "main" ]
3
[ [ "fetch_all", "fetch_with_timeout" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
eb9d670bdc3ea7d687e2de740313902ececf212c
31350656294def26bb239caaf367e72db0da93d0
v1.0
instruct
Docs
Docs: Pytorch_9878_I
#### Objective Implement a neural network training loop using PyTorch's Automatic Mixed Precision (AMP) functionalities to improve performance and stability. #### Problem Statement You are provided with a simple convolutional neural network (CNN) and a dummy dataset. Your task is to write a training loop for this net...
import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, TensorDataset # Define a simple CNN class SimpleCNN(nn.Module): def __init__(self): super(SimpleCNN, self).__init__() self.conv1 = nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1) sel...
def test_train_model(): train_model() # Expecting no exceptions and loss should decrease progressively (manually inspect printed output). if __name__ == "__main__": test_train_model()
[]
[ 1, 1, 0, 0, 1, 0, 1, 1, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, TensorDataset\n\n# Define a simple CNN\nclass SimpleCNN(nn.Mo...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00009878", "row_id": 9878, "seed_ids": "[113]" }
0.595877
Docs: Pytorch_9878
I
[ "get_dataloader", "train_model" ]
2
[ [ "train_model", "get_dataloader" ] ]
1
[]
false
[ "SimpleCNN" ]
true
pytest
false
[ "torch" ]
false
fc120ee146991f3fceda09fdf2f6454cc38d28ef
1cc442182375d7f0ab44e23814cae7a6b77fc931
v1.0
instruct
Docs
Docs: Python310_9922_I
**Objective**: The objective of this assessment is to test the understanding and practical ability to use iterators, generators, and itertools to process and transform data in Python. **Question**: You are given a list of tuples, where each tuple represents a city's name and its corresponding temperature readings for...
import itertools def temperature_generator(city_temperatures): """ Generator function that yields tuples of (city, average temperature). """ for city, temps in city_temperatures: avg_temp = sum(temps) / len(temps) yield (city, avg_temp) def highest_temperature_city(city_temperatures): ...
from solution import temperature_generator, highest_temperature_city, top_cities def test_temperature_generator(): city_temperatures = [ ("New York", [75, 80, 82, 78, 76, 77, 79]), ("Los Angeles", [85, 87, 89, 90, 84, 83, 88]), ("Chicago", [70, 68, 71, 72, 69, 67, 73]), ("Houston", ...
[ { "docstring": "Generator function that yields tuples of (city, average temperature).", "function_declaration": "def temperature_generator(city_temperatures):", "function_name": "temperature_generator", "parameter_list": "(city_temperatures)" }, { "docstring": "Uses itertools to find the cit...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import itertools\n\ndef temperature_generator(city_temperatures):\n for city, temps in city_temperatures:\n average_temp = sum(temps) / len(temps)\n yi...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00009922", "row_id": 9922, "seed_ids": "[78]" }
0.619015
Docs: Python310_9922
I
[ "temperature_generator", "highest_temperature_city", "top_cities" ]
3
[ [ "highest_temperature_city", "temperature_generator" ], [ "top_cities", "temperature_generator" ] ]
2
[]
false
[]
false
pytest
true
[]
true
4f542ae6d5ccb2c4412e4eff1c391930c8118572
88d3d710543bbda5133f52cdf5f6ba44c7c39688
v1.0
instruct
Docs
Docs: Python310_9993_I
Securely Extracting Files from a Tar Archive You are given a tar archive (`example.tar.gz`) that contains various files, some of which may potentially have malicious paths or be of file types that should not be extracted for security reasons (e.g., device files, symbolic links). This archive may also have different fo...
import tarfile import os def is_within_directory(directory, target): """ Check whether a target path is within the given directory. """ abs_directory = os.path.abspath(directory) abs_target = os.path.abspath(os.path.join(directory, target)) return abs_target.startswith(abs_directory) def secur...
import os import tarfile import pytest import shutil from solution import secure_extract_tar @pytest.fixture def setup_test_environment(tmp_path): # Create tar file with various types of files, including invalid paths and special files tar_file_path = os.path.join(tmp_path, 'test.tar.gz') extract_path = o...
[ { "docstring": "Check whether a target path is within the given directory.", "function_declaration": "def is_within_directory(directory, target):", "function_name": "is_within_directory", "parameter_list": "(directory, target)" }, { "docstring": "Securely extract files from a tar archive to ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import tarfile\nimport os\n\ndef secure_extract_tar(tar_path: str, extract_path: str) -> None:\n \"\"\"\n Extracts files from a tar archive securely.\n\n Param...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00009993", "row_id": 9993, "seed_ids": "[163]" }
0.653453
Docs: Python310_9993
I
[ "is_within_directory", "secure_extract_tar" ]
2
[ [ "secure_extract_tar", "is_within_directory" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0cab2ab2382edb6c6ca9731246a472850e8a6685
d21c4b91e6772c17e7446c87135a9f324f6ba2f5
v1.0
instruct
Docs
Docs: Python310_10041_I
**Question: Secure User Authentication System** You are tasked with implementing a secure user authentication system. This system will prompt users to enter their username and password securely. You must ensure that passwords are input without being displayed on the screen. After the user inputs their credentials, mat...
import getpass import hashlib # Predefined credentials (username: hashed_password) credentials = { 'user1': hashlib.sha256('password123'.encode()).hexdigest(), 'user2': hashlib.sha256('mysecurepassword'.encode()).hexdigest(), } def hash_password(password): """ Hash the given password using SHA-256 and...
import hashlib from solution import hash_password, check_password def test_hash_password(): assert hash_password('password123') == hashlib.sha256('password123'.encode()).hexdigest() def test_check_password_valid(): # Assuming credentials are as per the solution snippet credentials = { 'user1': has...
[ { "docstring": "Hash the given password using SHA-256 and return the hexadecimal digest.", "function_declaration": "def hash_password(password):", "function_name": "hash_password", "parameter_list": "(password)" }, { "docstring": "Check if the entered password matches the stored hashed passw...
[ 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 getpass\nimport hashlib\n\n# Predefined credentials (username: hashed_password)\ncredentials = {\n 'user1': '5e884898da28047151d0e56f8dc6292773603d0d6aabbdd01...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00010041", "row_id": 10041, "seed_ids": "[164]" }
0.625402
Docs: Python310_10041
I
[ "hash_password", "check_password", "authenticate_user" ]
3
[ [ "authenticate_user", "check_password" ], [ "check_password", "hash_password" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e95cfe9439ca5766d141dc00386a98eedf7319e7
24964082d1b746e4c73d1887b6cc4cbdbde0576a
v1.0
instruct
Docs
Docs: Python310_10112_I
**Coding Assessment Question** ### Objective: Create an asynchronous Python program to manage multiple tasks and demonstrate an understanding of asyncio's concurrency, timeouts, and task cancellation handling. ### Requirements: Implement an asynchronous function `process_tasks` that performs the following steps: 1. R...
import asyncio from typing import List, Tuple, Dict, Any async def worker(task_name: str, duration: int) -> str: await asyncio.sleep(duration) return f"{task_name} completed" async def process_tasks(task_list: List[Tuple[str, int]], timeout: float) -> Dict[str, Any]: tasks = {task_name: asyncio.create_tas...
import asyncio import pytest from solution import process_tasks @pytest.mark.asyncio async def test_all_tasks_complete_before_timeout(): task_list = [("Task1", 1), ("Task2", 2)] timeout = 5.0 result = await process_tasks(task_list, timeout) assert result == {"Task1": "Task1 completed", "Task2": "Task2 ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple, Dict, Any\n\nasync def worker(task_name: str, duration: int) -> str:\n await asyncio.sleep(duration)\n return f\"{...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010112", "row_id": 10112, "seed_ids": "[317]" }
0.644483
Docs: Python310_10112
I
[ "worker", "process_tasks" ]
2
[ [ "process_tasks", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f3b1a91162a6b13dc3a6c29de32f25df0ecbc1f7
42abfdeee8d33687f92ff94abc17864f6abbd690
v1.0
instruct
Docs
Docs: Python310_10115_I
**Question: Implement a Concurrent Chat Server Using asyncio** You are required to implement a basic concurrent chat server using the asyncio library. The server should be able to handle multiple clients simultaneously, allowing them to send and receive messages in real-time. ### Requirements and Constraints: 1. **F...
import asyncio clients = [] async def handle_client(reader, writer): addr = writer.get_extra_info('peername') clients.append(writer) print(f"Connected with {addr}") while True: try: data = await reader.read(100) if not data: break message = ...
import pytest import asyncio from asyncio import StreamReader, StreamWriter from solution import chat_server, handle_client, clients async def mock_client(message="Hello"): reader, writer = await asyncio.open_connection('127.0.0.1', 8888) writer.write(message.encode()) await writer.drain() return reade...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def broadcast_message(message, clients):\n for client in clients:\n client.write(message)\n await client.drain()\n\nasync def h...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010115", "row_id": 10115, "seed_ids": "[270]" }
0.550141
Docs: Python310_10115
I
[ "handle_client", "broadcast", "chat_server", "main" ]
4
[ [ "chat_server", "handle_client" ], [ "handle_client", "broadcast" ] ]
2
[]
false
[]
false
pytest
true
[]
true
4ae299e72ad3260b5563af8d500626c1f8a97d5d
d2c4b38e14222c67d98bc2e0fd997d3cbea23775
v1.0
instruct
Docs
Docs: Pytorch_10153_I
Advanced Mask Manipulation in Attention Mechanisms One of the core aspects of attention mechanisms in neural networks is the ability to create and manipulate masks to control how attention is distributed across input sequences. In this task, you are required to implement a function that combines several utilities from...
import torch from torch.nn.functional import pad def create_block_mask(block_size: int, sequence_length: int) -> torch.Tensor: mask = torch.zeros((sequence_length, sequence_length), dtype=torch.bool) for i in range(0, sequence_length, block_size): mask[i:i + block_size, i:i + block_size] = True ret...
import torch from solution import custom_block_attention_mask def test_custom_block_attention_mask_shape(): mask = custom_block_attention_mask(4, 16) assert mask.shape == (16, 16) def test_custom_block_attention_mask_blocks(): mask = custom_block_attention_mask(4, 16) block_size = 4 sequence_lengt...
[ { "docstring": null, "function_declaration": "def create_block_mask(block_size, sequence_length):", "function_name": "create_block_mask", "parameter_list": "(block_size, sequence_length)" }, { "docstring": null, "function_declaration": "def create_mask(sequence_length):", "function_n...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.nn.attention.flex_attention import create_block_mask, create_mask, or_masks\n\ndef custom_block_attention_mask(block_size: int, sequence_length...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00010153", "row_id": 10153, "seed_ids": "[0]" }
0.448119
Docs: Pytorch_10153
I
[ "create_block_mask", "create_mask", "or_masks", "custom_block_attention_mask" ]
4
[ [ "custom_block_attention_mask", "create_block_mask" ], [ "custom_block_attention_mask", "create_mask" ], [ "custom_block_attention_mask", "or_masks" ] ]
3
[]
false
[]
false
pytest
true
[ "torch" ]
false
3cc602b18bfcc9310f822295ca33014dc20fe7f5
fb6cc6d78149559322eb4dba817c39a1e4fa85a3
v1.0
instruct
Docs
Docs: Python310_10164_I
### Custom File Operations with Tkinter Dialogs You are given the task of creating a small program that helps users to search for text files within a directory and read the contents of these files. You will need to make use of tkinter dialogs to handle directory selection and file reading. #### Requirements 1. Create...
import os import tkinter as tk from tkinter import filedialog, messagebox, simpledialog from typing import List, Dict, Optional def select_directory() -> str: """ Prompts the user to select a directory and returns the directory path as a string. """ root = tk.Tk() root.withdraw() dir_path = fil...
import os import pytest import tkinter as tk from tkinter import simpledialog from solution import select_directory, list_text_files, show_search_dialog, search_in_files # Assuming you have a folder structure to test against (mock file system for integration tests) @pytest.fixture def mock_directory_structure(tmpdir):...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport tkinter as tk\nfrom tkinter import filedialog, messagebox, simpledialog\nfrom typing import List, Dict, Optional\n\ndef select_directory() -> str:\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010164", "row_id": 10164, "seed_ids": "[271]" }
0.538902
Docs: Python310_10164
I
[ "select_directory", "list_text_files", "show_search_dialog", "search_in_files" ]
4
[ [ "search_in_files", "list_text_files" ] ]
1
[]
false
[ "SearchDialog" ]
true
pytest
true
[]
true
8e397f48eb7e6ba0949d8bc909e4e46c60a88ece
449fceb6fa09801967b41615f562b30b331c4616
v1.0
instruct
Docs
Docs: Pytorch_10184_I
#### Objective Design a function to initiate a distributed training job using PyTorch's `torchrun` (Elastic Launch). This function should configure the necessary settings and handle the launch process, ensuring the job can scale elastically and recover from failures. #### Problem Statement You are tasked with implemen...
import subprocess import logging def validate_inputs(module_name, num_nodes, nproc_per_node, min_nodes, max_restarts, rdzv_id, rdzv_backend): if not isinstance(module_name, str) or not module_name.endswith(".py"): raise ValueError("module_name must be a string ending with .py") if not isinstance(num_no...
import pytest from solution import launch_distributed_training def test_valid_input(): try: launch_distributed_training("train.py", 1, 1, 1, 3, "rdzv_id", "c10d") except Exception: pytest.fail("Exception raised for valid input") def test_invalid_module_name(): with pytest.raises(ValueError...
[ { "docstring": null, "function_declaration": "def validate_inputs(module_name, num_nodes, nproc_per_node, min_nodes, max_restarts, rdzv_id, rdzv_backend):", "function_name": "validate_inputs", "parameter_list": "(module_name, num_nodes, nproc_per_node, min_nodes, max_restarts, rdzv_id, rdzv_backend)...
[ 0, 0, 0, 1, 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": "import subprocess\nimport logging\n\ndef launch_distributed_training(module_name: str, num_nodes: int, nproc_per_node: int, min_nodes: int, \n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00010184", "row_id": 10184, "seed_ids": "[145]" }
0.418479
Docs: Pytorch_10184
I
[ "validate_inputs", "launch_distributed_training" ]
2
[ [ "launch_distributed_training", "validate_inputs" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6b42baa26a99a27c9fb5b5f8410e774d12b828fa
3c8743319fa8615632f8ab19235e5b88862b0ea0
v1.0
instruct
Docs
Docs: Python310_10239_I
### Asynchronous Task Dispatcher using `asyncio.Queue` #### Problem Statement: You are required to implement an asynchronous task dispatcher system using `asyncio.Queue`. The dispatcher should manage and process tasks concurrently using multiple worker tasks. Each task consists of a priority number and a string repres...
import asyncio from typing import List, Tuple async def worker(name: str, queue: asyncio.PriorityQueue): while True: priority, task_content = await queue.get() await asyncio.sleep(1) # Simulate task processing with sleep print(f"{name} processed task: {task_content} with priority {priority...
import pytest import asyncio from solution import task_dispatcher @pytest.mark.asyncio async def test_single_worker(): tasks = [(2, "Task 2"), (1, "Task 1"), (3, "Task 3")] await task_dispatcher(tasks, 1) @pytest.mark.asyncio async def test_multiple_workers(): tasks = [(2, "Task 2"), (1, "Task 1"), (3, "T...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def worker(name: str, queue: asyncio.PriorityQueue):\n while True:\n priority, task_content = await qu...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010239", "row_id": 10239, "seed_ids": "[111]" }
0.630273
Docs: Python310_10239
I
[ "worker", "task_dispatcher" ]
2
[ [ "task_dispatcher", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e6a51d27ce57bd8fd44fdddf7ccce1cb0832b47f
019e1af6db06bae8a20a5bee4b9cd308adfb4390
v1.0
instruct
Docs
Docs: Python310_10343_I
**Objective:** Demonstrate your understanding of Python modules, including module creation, state management, and the difference between single-phase and multi-phase initialization. #### Background: You are tasked with creating a custom Python module, `my_module`, which will be implemented using C extensions. This mo...
import ctypes, sys from collections.abc import Callable # Define a function pointer type for PyObject* functions PyObjectFuncType = ctypes.CFUNCTYPE(ctypes.py_object, ctypes.py_object, ctypes.py_object) class MyModuleWrapper: def __init__(self, init_func: Callable, incre_func: Callable): self.state = 0 ...
def test_single_phase_increment(): assert my_module_single.increment(None, None) == 1 assert my_module_single.increment(None, None) == 2 def test_multi_phase_increment(): assert my_module_multi.increment(None, None) == 1 assert my_module_multi.increment(None, None) == 2
[]
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "# Single-phase Initialization\nfrom distutils.core import setup, Extension\n\ndef create_single_phase_module():\n module = Extension('my_module_single', sources = ['...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00010343", "row_id": 10343, "seed_ids": "[57]" }
0.455307
Docs: Python310_10343
I
[ "single_phase_init", "multi_phase_create", "multi_phase_exec", "PyInit_my_module_single" ]
4
[ [ "PyInit_my_module_single", "single_phase_init" ] ]
1
[]
false
[ "MyModuleWrapper" ]
true
pytest
false
[]
true
19324f8ac86b0dc8a7efb6f3e5ac77a296508852
4f584a0d2127794b77130c1f17b1f951473a3930
v1.0
instruct
Docs
Docs: Python310_10346_I
### Understanding Context Variables and Asynchronous Context Management #### Problem Statement You are tasked with creating a logging system for an asynchronous web server. The logging system should use context variables to store and access the request ID and user ID for each request, ensuring that this information i...
import asyncio import contextvars from random import randint class RequestContext: request_id: contextvars.ContextVar[str] = contextvars.ContextVar('request_id', default=None) user_id: contextvars.ContextVar[str] = contextvars.ContextVar('user_id', default=None) @staticmethod def set_request_context(r...
import asyncio import pytest from solution import RequestContext, handle_request, log_request @pytest.mark.asyncio async def test_request_context(): RequestContext.set_request_context('test_req', 'test_user') assert RequestContext.request_id.get() == 'test_req' assert RequestContext.user_id.get() == 'test_...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport contextvars\nfrom random import randint\n\nclass RequestContext:\n request_id: contextvars.ContextVar[str] = contextvars.ContextVar('request_i...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00010346", "row_id": 10346, "seed_ids": "[392]" }
0.453595
Docs: Python310_10346
I
[ "log_request", "handle_request", "main" ]
3
[ [ "handle_request", "log_request" ] ]
1
[]
false
[ "RequestContext" ]
true
pytest
true
[]
true
4029eb0b9dd74465f9de5ad039e0b38896cb8b61
4390d09909a0438aef57116797408b525771c08a
v1.0
instruct
Docs
Docs: Python310_10387_I
### Functional Programming Challenge in Python #### Objective: Demonstrate your understanding of functional programming concepts and techniques using Python. #### Problem Statement: You are required to implement a function that processes a list of numbers and returns a transformed version of this list using functiona...
from math import factorial from functools import reduce from typing import List def is_prime(n: int) -> bool: """Check if a number is prime.""" if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n %...
from solution import process_numbers def test_process_numbers_example1(): numbers = [10, 7, 11, 13, 4, 6] assert process_numbers(numbers) == 6227020800 + 39916800 + 5040 def test_process_numbers_example2(): numbers = [1, 2, 3] assert process_numbers(numbers) == 2 + 6 def test_process_numbers_all_prim...
[ { "docstring": "Check if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Process numbers by filtering primes, mapping to factorials, and reducing by summing the factorials.", "function_declaration": ...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from functools import reduce\nfrom math import factorial\nfrom sympy import isprime\n\ndef process_numbers(numbers):\n \"\"\"\n Processes a list of numbers accord...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010387", "row_id": 10387, "seed_ids": "[73]" }
0.70973
Docs: Python310_10387
I
[ "is_prime", "process_numbers" ]
2
[ [ "process_numbers", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
947229bd30e0d4274d11cd1b5c656269306a09a1
af72c41e3f73473b395dab17f876a1ea0e6ca6c4
v1.0
instruct
Docs
Docs: Python310_10420_I
<|Analysis Begin|> The provided documentation describes the `lzma` module in Python, which is used for data compression utilizing the LZMA algorithm. Key functionalities include: 1. **Reading and writing compressed files** through the `lzma.open` function or using the `LZMAFile` class. 2. **Compressing and decompress...
import lzma def compress_data(data: bytes) -> bytes: """ Compress the input data using the default .xz format. Parameters: data (bytes): The data to be compressed. Returns: bytes: The compressed data. """ return lzma.compress(data) def decompress_data(compressed_data: bytes) ...
import pytest import os from solution import compress_data, decompress_data, compress_data_with_filters, file_compress, file_decompress def test_compress_decompress_data(): data = b'This is a test string for compression and decompression.' compressed_data = compress_data(data) decompressed_data = decompres...
[ { "docstring": "Compress the input data using the default .xz format.\n\nParameters:\ndata (bytes): The data to be compressed.\n\nReturns:\nbytes: The compressed data.", "function_declaration": "def compress_data(data):", "function_name": "compress_data", "parameter_list": "(data)" }, { "doc...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import lzma\n\ndef compress_data(data: bytes) -> bytes:\n \"\"\"\n Compress the input data using the default .xz format.\n \"\"\"\n return lzma.compress(dat...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010420", "row_id": 10420, "seed_ids": "[282]" }
0.543123
Docs: Python310_10420
I
[ "compress_data", "decompress_data", "compress_data_with_filters", "file_compress", "file_decompress" ]
5
[ [ "file_compress", "compress_data" ], [ "file_decompress", "decompress_data" ] ]
2
[]
false
[]
false
pytest
true
[]
true
0d01f2fa6a1e97f5211cd2a34fec14ad339e51ec
90304a5477b2214b72aad9370db64dbb04d75a09
v1.0
instruct
Docs
Docs: Python310_10444_I
### Asyncio Coding Assessment You are required to implement a function using Python's asyncio module which demonstrates the creation and management of multiple asynchronous tasks. The goal is to fetch data concurrently from multiple URLs, process this data, and handle any network timeouts gracefully. #### Function Sp...
import asyncio import random from typing import List async def fetch_data(url: str) -> str: """ Simulates fetching data from a URL. """ fetch_time = random.uniform(1, 5) # Simulate a delay between 1 to 5 seconds await asyncio.sleep(fetch_time) return f"data from {url}" async def process_data(...
import pytest import asyncio from solution import fetch_and_process @pytest.fixture def event_loop(): loop = asyncio.get_event_loop() yield loop loop.close() def test_fetch_and_process_all_success(): urls = ["http://example.com/1", "http://example.com/2", "http://example.com/3"] timeout = 6 ex...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\nfrom typing import List\n\nasync def fetch_data(url: str) -> str:\n \"\"\"\n Simulates fetching data from a URL.\n \"\"\"\n f...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00010444", "row_id": 10444, "seed_ids": "[360]" }
0.571228
Docs: Python310_10444
I
[ "fetch_data", "process_data", "fetch_and_process_url", "fetch_and_process" ]
4
[ [ "fetch_and_process", "fetch_and_process_url" ], [ "fetch_and_process_url", "fetch_data" ], [ "fetch_and_process_url", "process_data" ] ]
3
[ "process_data" ]
false
[]
false
pytest
true
[]
true
1ea7ad1d846a4f79604a8c89d473b2358b4acfbd
4bd96b011559bbc5269f73b02c91f01ddffae679
v1.0
instruct
Docs
Docs: Python310_10445_I
### Asynchronous File Processing with Platform Constraints **Objective:** You are required to implement an asynchronous file processing system that must take into consideration the platform-specific limitations of the asyncio module as provided in the documentation. The system you design should be capable of reading m...
import os import asyncio import platform async def process_file(input_path, output_path): """ Reads the content of the input file, processes the content by reversing each line, and writes the processed content to the output file. """ try: async with aiofiles.open(input_path, 'r') as f: ...
import pytest import shutil import os from solution import process_file, main @pytest.fixture(scope="module") def setup_test_files(): """ Setup test directories and files. """ input_dir = "test_input" output_dir = "test_output" os.makedirs(input_dir, exist_ok=True) os.makedirs(output_d...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport asyncio\nimport aiofiles\n\nasync def process_file(input_path, output_path):\n async with aiofiles.open(input_path, mode='r') as input_file:\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010445", "row_id": 10445, "seed_ids": "[370]" }
0.54471
Docs: Python310_10445
I
[ "process_file", "main", "process_file_with_semaphore" ]
3
[ [ "process_file_with_semaphore", "process_file" ] ]
1
[]
false
[]
false
pytest
true
[ "aiofiles" ]
false
de82406732c21f0933ae0302255fd6f3d8edec96
0cf2f4ce6f2d28465ad72e24b985d9bf84da8492
v1.0
instruct
Docs
Docs: Scikit_10461_I
### Coding Assessment: Implementing Out-of-Core Learning **Objective:** Your task is to design and implement an out-of-core learning system using scikit-learn that can handle large datasets which do not fit into memory. You will create a basic text classification model that uses incremental learning with the `SGDClass...
from typing import List, Tuple from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def stream_data(file_path: str, chunk_size: int) -> Tuple[List[str], List[str]]: """ Generator to stream data from a given file ...
import pytest from solution import stream_data, train_incremental_model, test_function def test_stream_data(): with open('temp_train_data.csv', 'w') as f: for i in range(100): f.write(f'label{i%2},text data {i}\n') stream = stream_data('temp_train_data.csv', 10) chunk = next(stream...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics impo...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00010461", "row_id": 10461, "seed_ids": "[63]" }
0.504686
Docs: Scikit_10461
I
[ "stream_data", "train_incremental_model", "test_function" ]
3
[ [ "train_incremental_model", "stream_data" ] ]
1
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
5a6fbcc52b349ad3f885ae0f9557854c02c73f63
38ee4d29f86c3e9783d32e3a3d2bedd3e8b7c7e1
v1.0
instruct
Docs
Docs: Python310_10569_I
### Secure Hash Function Task **Objective:** Your task is to write a Python function that takes a list of file paths and returns a dictionary containing the file path as the key and the SHA-256 hash of the file content as the value. Additionally, you need to implement functionalities to save these hash values to a JSO...
import hashlib import json from typing import List, Dict def calculate_file_hashes(file_paths: List[str]) -> Dict[str, str]: def calculate_hash(file_path: str) -> str: sha256 = hashlib.sha256() with open(file_path, 'rb') as f: while chunk := f.read(8192): sha256.update(c...
from solution import calculate_file_hashes, save_hashes_to_json, load_hashes_from_json, check_data_integrity import os import json def create_test_file(file_name, content): with open(file_name, 'w') as f: f.write(content) def remove_test_file(file_name): if os.path.exists(file_name): os.remove...
[ { "docstring": null, "function_declaration": "def calculate_file_hashes(file_paths):", "function_name": "calculate_file_hashes", "parameter_list": "(file_paths)" }, { "docstring": null, "function_declaration": "def save_hashes_to_json(hashes, file_name):", "function_name": "save_hash...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\nimport json\nfrom typing import List, Dict\n\ndef calculate_file_hashes(file_paths: List[str]) -> Dict[str, str]:\n \"\"\"\n Calculate SHA-256 has...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010569", "row_id": 10569, "seed_ids": "[225]" }
0.803345
Docs: Python310_10569
I
[ "calculate_file_hashes", "save_hashes_to_json", "load_hashes_from_json", "check_data_integrity" ]
4
[ [ "check_data_integrity", "calculate_file_hashes" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5427cb5912ffda5f9ab5e38f9148471342a37c55
428f7bebe4a63ec4d9871e7669df79958e8785e1
v1.0
instruct
Docs
Docs: Pytorch_10613_I
#### Objective: Implement a simple distributed training example using PyTorch's Distributed RPC Framework. You will create a setup where one worker will act as the parameter server, and multiple other workers will act as trainers that send gradient updates to the parameter server. #### Task: 1. **Initialize the Distri...
import os import torch import torch.distributed.rpc as rpc import torch.nn as nn import torch.optim as optim # Define the model class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.linear = nn.Linear(10, 1) def forward(self, x): return self.linear...
import multiprocessing import os def test_distributed_training(): # This test will be run by spawning multiple processes to simulate different workers world_size = 3 def run_worker(rank): os.environ['RANK'] = str(rank) main() processes = [] for rank in range(world_size): ...
[]
[ 0, 0, 0, 0, 0, 1, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport torch\nimport torch.distributed.rpc as rpc\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.distributed.optim import DistributedOptimiz...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00010613", "row_id": 10613, "seed_ids": "[36]" }
0.444913
Docs: Pytorch_10613
I
[ "init_rpc", "parameter_server", "trainer", "main" ]
4
[ [ "parameter_server", "init_rpc" ], [ "trainer", "init_rpc" ] ]
2
[]
false
[ "SimpleModel" ]
true
pytest
false
[ "torch" ]
false
cb9c9a1eea1fba34234615e40f164419d7f65f7e
598ac5b8cf8cdc9a05cd950862807415b7e15589
v1.0
instruct
Docs
Docs: Python310_10665_I
**Coding Assessment Question: Persistent User Profiles with Shelve** ### Objective Write a Python program to manage persistent user profiles using the `shelve` module. Each profile should contain a username, email, and a list of interests. The program should support adding new profiles, updating interests, retrieving...
import shelve def add_profile(shelf): username = input("Enter username: ").strip() if not username.isalnum(): print("Username must be alphanumeric.") return if username in shelf: print("Username already exists.") return email = input("Enter email: ").strip() int...
import os import shelve import pytest TEST_DB = 'test_shelve.db' # Helper functions to mimic inputs for unit tests def set_input(monkeypatch, inputs): monkeypatch.setattr('builtins.input', lambda _: inputs.pop(0)) # Test cases def test_add_profile(monkeypatch): inputs = ["testuser", "test@user.com", "reading...
[ { "docstring": null, "function_declaration": "def add_profile(shelf):", "function_name": "add_profile", "parameter_list": "(shelf)" }, { "docstring": null, "function_declaration": "def update_interests(shelf):", "function_name": "update_interests", "parameter_list": "(shelf)" }...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import shelve\n\ndef manage_user_profiles(filename: str) -> None:\n def add_new_profile(shelf):\n username = input(\"Enter username: \")\n email = inpu...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010665", "row_id": 10665, "seed_ids": "[376]" }
0.354178
Docs: Python310_10665
I
[ "add_profile", "update_interests", "retrieve_profile", "delete_profile", "manage_user_profiles" ]
5
[ [ "manage_user_profiles", "add_profile" ], [ "manage_user_profiles", "delete_profile" ], [ "manage_user_profiles", "retrieve_profile" ], [ "manage_user_profiles", "update_interests" ] ]
4
[]
false
[]
false
pytest
false
[]
true
d5b3db2ba8285f85ed5db99b63cbe5657b23a07e
194b4fa37bc58ef5b09a93f0a7d87434ccd82b98
v1.0
instruct
Docs
Docs: Pytorch_10753_I
#### Title: Implement a Distributed Counter Using PyTorch RPC and RRef #### Objective: Implement a distributed counter using PyTorch's RPC framework and Remote References (RRef). The counter should be shared across multiple workers, and each worker should be able to increment and retrieve the counter's value. #### Pr...
import torch import torch.distributed.rpc as rpc from torch.distributed.rpc import RRef class DistributedCounter: def __init__(self): self.counter = 0 def increment(self, n: int) -> None: self.counter += n def get_value(self) -> int: return self.counter def create_counter(): ...
import pytest from multiprocessing import Process import os def test_distributed_counter(): def run_master(): import sys sys.argv = ['master'] from solution import run_master as master_main master_main() def run_worker(worker_id): import sys sys.argv = [str(work...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.distributed.rpc as rpc\nfrom torch.distributed.rpc import RRef\nimport threading\n\nclass DistributedCounter:\n def __init__(self):\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010753", "row_id": 10753, "seed_ids": "[158]" }
0.433689
Docs: Pytorch_10753
I
[ "create_counter", "increment_counter", "get_counter_value", "run_master", "run_worker" ]
5
[ [ "run_master", "create_counter" ], [ "run_master", "get_counter_value" ], [ "run_master", "increment_counter" ] ]
3
[]
false
[ "DistributedCounter" ]
true
pytest
true
[ "torch" ]
false
378ede7958ff03b7b5394ab84866eb7f502d9789
59363883b68689b2293a9df7fbbfde8dcd966d36
v1.0
instruct
Docs
Docs: Pytorch_10766_I
### Asynchronous File Reading with PyTorch Futures **Problem Description:** You are tasked to implement a utility function that reads multiple text files asynchronously and processes their contents. You must use the `torch.futures.Future` class to handle asynchronous operations and the helper functions `collect_all` ...
import torch from torch.futures import Future, collect_all, wait_all import asyncio async def read_file_async(file_path): """ Asynchronously read the contents of a single text file. """ loop = asyncio.get_event_loop() with open(file_path, 'r') as file: content = await loop.run_in_executor(N...
import pytest import os from solution import async_file_read @pytest.fixture def setup_test_files(tmp_path): file1 = tmp_path / "file1.txt" file1.write_text("Hello") file2 = tmp_path / "file2.txt" file2.write_text("World") return [str(file1), str(file2)] def test_async_file_read(setup_test_files):...
[ { "docstring": "Asynchronously read the contents of multiple text files.\n\nParameters:\n----------\nfile_paths : List[str]\n A list of file paths to read.\n\nReturns:\n-------\nList[str]\n A list containing the contents of each file.", "function_declaration": "def async_file_read(file_paths):", "...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.futures import Future, collect_all, wait_all\nimport asyncio\nimport aiofiles\n\nasync def read_file_async(file_path):\n async with aiofiles...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00010766", "row_id": 10766, "seed_ids": "[53]" }
0.508973
Docs: Pytorch_10766
I
[ "read_file_async", "async_file_read" ]
2
[ [ "async_file_read", "read_file_async" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
239ea591618bffc399bdfc5a493ec1c0cf9ef7c5
5da7a3d407569d65e9c7bcc7a2b59eb7ccc6f3cf
v1.0
instruct
Docs
Docs: Scikit_10827_I
**Problem Statement:** You are provided with a dataset of points in a two-dimensional space and their respective class labels. Your task is to implement a nearest neighbors classifier using scikit-learn to predict the class labels for a new set of points. In addition, you need to explore the impact of different neares...
import numpy as np from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from time import time import random def nearest_neighbors_classifier(X_train, y_train, X_test, n_neighbors, algorithm): """ Implements a nearest neighbors classifier with specified algorit...
import pytest import numpy as np from solution import nearest_neighbors_classifier def test_nearest_neighbors_classifier_brute(): np.random.seed(0) X_train = np.random.rand(100, 2) * 100 y_train = np.random.randint(0, 3, 100) X_test = np.random.rand(10, 2) * 100 result = nearest_neighbors_classifie...
[]
[ 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 numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom time import time\nimport random\n\nde...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00010827", "row_id": 10827, "seed_ids": "[52]" }
0.655257
Docs: Scikit_10827
I
[ "nearest_neighbors_classifier", "evaluate_algorithms" ]
2
[ [ "evaluate_algorithms", "nearest_neighbors_classifier" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
6d637c03f280594ab5101d39770bed4b9f4d9f2e
e9b703312d1ef67587e0d62bf4d09e24d8e279de
v1.0
instruct
Docs
Docs: Pytorch_10854_I
### Advanced PyTorch Optimization using MPS Environment Variables In this assessment, you are required to write a Python script that demonstrates the following capabilities using PyTorch with Metal Performance Shaders (MPS) on a macOS system: 1. **Model Training with Environment Variable Configurations**: Set up a si...
import os import torch import torch.nn as nn import torch.optim as optim def set_mps_environment_vars(): """ Sets specific environment variables for optimizing PyTorch with MPS backend. """ os.environ['PYTORCH_MPS_HIGH_WATERMARK_RATIO'] = '1.5' os.environ['PYTORCH_MPS_LOW_WATERMARK_RATIO'] = '1.2' ...
from solution import set_mps_environment_vars def test_set_mps_environment_vars(): set_mps_environment_vars() assert os.environ['PYTORCH_MPS_HIGH_WATERMARK_RATIO'] == '1.5' assert os.environ['PYTORCH_MPS_LOW_WATERMARK_RATIO'] == '1.2' assert os.environ['PYTORCH_DEBUG_MPS_ALLOCATOR'] == '1' assert o...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\ndef set_mps_environment_vars():\n \"\"\"\n Set PyTorch environment variables for MP...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00010854", "row_id": 10854, "seed_ids": "[64]" }
0.461003
Docs: Pytorch_10854
I
[ "set_mps_environment_vars", "train_model" ]
2
[ [ "train_model", "set_mps_environment_vars" ] ]
1
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
1a3696914be86879800fab183ff681024db45f69
79ad80e16c2642ff688f98d564bf4f598871dbc3