version
stringclasses
1 value
style
stringclasses
2 values
subset
stringclasses
12 values
question_id
stringlengths
9
23
question
stringlengths
27
8.13k
solution
stringlengths
99
5.97k
test
stringlengths
105
4.45k
test_info
listlengths
0
13
gpt_pass_sequence
listlengths
1
10
gpt_pass_trial_num
int64
1
10
gpt_difficulty
stringclasses
3 values
gpt_pass_percentage
float64
0.1
1
trials
dict
chosen_trial
stringclasses
10 values
metadata
dict
benchmark_similarity
float64
0.16
0.93
benchmark_instruction
stringclasses
1 value
benchmark_task_id
stringclasses
1 value
filter_reason
stringclasses
1 value
base_id
stringlengths
7
21
variant
stringclasses
2 values
top_function_names
listlengths
2
13
n_top_functions
int64
2
13
helper_call_edges
listlengths
1
16
n_helper_call_edges
int64
1
16
harness_functions
listlengths
0
3
structural_wrapper
bool
1 class
class_names
listlengths
0
5
has_class
bool
2 classes
test_kind
stringclasses
1 value
test_has_solution_import
bool
2 classes
third_party_imports
listlengths
0
5
stdlib_only
bool
2 classes
question_norm_sha1
stringlengths
40
40
solution_ast_sha1
stringlengths
40
40
v1.0
complete
Docs
Docs: Python310_7904_C
import asyncio import logging import random 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): if n <= 1: return n else: ...
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": "#### Problem Statement\n\nYou 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 exte...
0.554687
Docs: Python310_7904
C
[ "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
cd5b55055cd6ad53b2b457de32322695b858037e
ca019dfddb3c8ab0ddd20420eb577c2da9448b4b
v1.0
complete
Docs
Docs: Python310_7713_C
import asyncio import contextvars from contextvars import ContextVar, copy_context # Initialize a ContextVar with a default value of 0 counter: ContextVar[int] = ContextVar('counter', default=0) def increment(): """Increment the context counter by 1.""" # Implementation here def get_counter_value(): """R...
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": "#### Objective:\nImplement 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 ...
0.525836
Docs: Python310_7713
C
[ "increment", "get_counter_value", "reset_counter", "increment_counter", "main" ]
5
[ [ "increment_counter", "increment" ] ]
1
[]
false
[]
false
pytest
false
[]
true
609f0b24a2e2aaf37018f876e25d5d05c8d32c2d
dd4b64a80c911d953e22a0942b0b736db43d3c23
v1.0
complete
Docs
Docs: Python310_8254_C
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. """ def get_config(): """ Retrieves the current configuration. """ def process...
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": "### Contextual Data Management in Asynchronous Programming\n\nYou 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 manag...
0.519624
Docs: Python310_8254
C
[ "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
6ca38e86fc98c1e49ab65ef056801b3d0f8ed620
3c655f0f8fd966416cffc5f7296f4ed936a883bf
v1.0
complete
Docs
Docs: Python310_6312_C
import hashlib def hash_file(file_path: str, algorithm: str = 'sha256') -> str: """ Hash the contents of a file using the specified hashing algorithm. Parameters: - file_path (str): The path to the file that needs to be hashed. - algorithm (str): The name of the hashing algorithm to use (default i...
import hashlib def hash_file(file_path: str, algorithm: str = 'sha256') -> str: """ Hash the contents of a file using the specified hashing algorithm. Parameters: - file_path (str): The path to the file that needs to be hashed. - algorithm (str): The name of the hashing algorithm to use (defau...
from solution import hash_file, verify_hash import hashlib import pytest def test_hash_file_sha256(tmp_path): # Create a temporary file test_file = tmp_path / "test.txt" test_file.write_text("This is a test.") # Expected hash using sha256 expected_hash = hashlib.sha256(b"This is a test.").hexd...
[ { "docstring": "Hash the contents of a file using the specified hashing algorithm.\n\nParameters:\n- file_path (str): The path to the file that needs to be hashed.\n- algorithm (str): The name of the hashing algorithm to use (default is 'sha256').\n\nReturns:\n- str: A hexadecimal string representing the hash o...
[ 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\n\ndef hash_file(file_path: str, algorithm: str = 'sha256') -> str:\n \"\"\"\n Returns the hash of the contents of the specified file using the giv...
trial_gpt4o_2
{ "original_instruction": "### Hashlib Coding Assessment Question\n\n#### Objective:\nYou are tasked with creating a Python utility that uses the `hashlib` module to hash files and verify their integrity. This exercise will assess your ability to work with different hashing algorithms and methods provided by the `has...
0.744117
Docs: Python310_6312
C
[ "hash_file", "verify_hash" ]
2
[ [ "verify_hash", "hash_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6010331817c3021dbb1a39b2a692de8144894fad
8fc71ea78761719c0eb46937cc763aca7f71c03f
v1.0
complete
Docs
Docs: Python310_7254_C
import asyncio import socket async def handle_client(client_socket, clients): """ Handle communication with a connected client. This function reads messages from the client and broadcasts them to all other connected clients. """ pass async def start_chat_server(host: str, port: int): ...
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": "#### Objective:\nDemonstrate your understanding of `asyncio` for asynchronous operations and `socket` for low-level networking by designing and implementing a simple asynchronous chat server and client.\n\n#### Task:\n\n1. **Chat Server**:\n - Implement an asynchronous chat server using t...
0.620837
Docs: Python310_7254
C
[ "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
50fce87602d5ea6ac6c54a98f2795a201336607d
beb292ffed62f25fd2d4dcf49a4754d46eceeb7a
v1.0
complete
Docs
Docs: Python310_8496_C
import traceback def custom_traceback_formatter() -> str: """ Captures an exception, extracts its traceback, and returns a formatted string of the entire traceback using the traceback module. >>> custom_traceback_formatter() Traceback (most recent call last): ... ValueError: This is a ...
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": "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.\n\n### Function Signature\n```python\ndef custom_traceback_formatter() -> str:\n```\n\n### ...
0.524949
Docs: Python310_8496
C
[ "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
abcf93edc2ce13c0b94123f504075013aa82f51c
49226665da813980a1b6b5306b806f9b0b586940
v1.0
complete
Docs
Docs: Python310_7512_C
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 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": "### Python Coding Assessment Question\n\n**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 ...
0.497466
Docs: Python310_7512
C
[ "process_chunk", "process_data_concurrently" ]
2
[ [ "process_data_concurrently", "process_chunk" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ed59b6299fd459d6cc4c6f29f910f8f6b2cd01c4
bc7d96632f99f2040c5c757908b7dbb7f1907197
v1.0
complete
Docs
Docs: Seaborn_7746_C
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. Parameters: file_path (str): Path to the CSV file. Returns: pd.DataFrame: DataFrame containing the loaded data. """ pass def create_scatter_plot(data...
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": "**Question**: Exploring Seaborn Styles and Plotting Functions\n\nYou 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 illustr...
0.747012
Docs: Seaborn_7746
C
[ "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
6b631fb5b28aadc35fd479bf2b57b62cf2befa54
85fd12c3d5c75161c9c9f6aabffa97e943ae205d
v1.0
complete
Docs
Docs: Python310_6357_C
import calendar from typing import List def filter_calendar_events(year: int, month: int, filter_criteria: str) -> List[int]: """ Filter specific days from a given month based on certain criteria such as weekdays, weekends, or prime days. Args: year (int): The year for which the calendar is to be gen...
import calendar def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def filter_calendar_events(ye...
from solution import filter_calendar_events def test_filter_calendar_events_weekdays(): assert filter_calendar_events(2023, 10, 'weekdays') == [2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 16, 17, 18, 19, 20, 23, 24, 25, 26, 27, 30, 31] def test_filter_calendar_events_weekends(): assert filter_calendar_events(2023, 10, ...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def filter_calendar_events(year, month, filter_criteria):", "function_name": "filter_calendar_events", "parameter...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import calendar\n\ndef is_prime(n):\n \"\"\"Check if a number is a prime number.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n ...
trial_gpt4o_2
{ "original_instruction": "**Question: Custom Calendar Filter**\n\nYou are required to create a function named `filter_calendar_events` that filters out specific days from a given month based on certain criteria. The function will use the `calendar` module to generate the days of the month and filter out days based o...
0.695892
Docs: Python310_6357
C
[ "is_prime", "filter_calendar_events" ]
2
[ [ "filter_calendar_events", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1502e02da121995fe30202607320574f930afe7e
74f1dbce27860cdc5ba348501c0f24593bd3c0e9
v1.0
complete
Docs
Docs: Scikit_8162_C
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 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": "Implementing Out-of-Core Learning for Text Classification\n\n#### Objective\nDesign 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....
0.557998
Docs: Scikit_8162
C
[ "stream_data", "train_incremental_model" ]
2
[ [ "train_incremental_model", "stream_data" ] ]
1
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
78d5edc577d4426df4b4bc8d72304f09d443c40e
91fe6add540b5438f0d4f508a501a05d11ee4108
v1.0
complete
Docs
Docs: Scikit_7554_C
import numpy as np from typing import Tuple def pls_canonical(X: np.ndarray, Y: np.ndarray, n_components: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """ Perform Partial Least Squares Canonical (PLSCanonical) decomposition on two matrices X and Y using n_components components. Param...
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": "#### Objective:\nImplement a simplified version of the `PLSCanonical` algorithm described in the scikit-learn cross decomposition module.\n\n#### Problem Statement:\nYou are required to create a function `pls_canonical(X, Y, n_components)` that performs Partial Least Squares Canonical (PLSC...
0.654247
Docs: Scikit_7554
C
[ "nipals", "pls_canonical" ]
2
[ [ "pls_canonical", "nipals" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy" ]
false
f5dbc22903a0e8cfe00fbe9575fc8ded5415e0f8
fef461a63f8745468dae62e9e7301046ae1edf9d
v1.0
complete
Docs
Docs: Python310_6474_C
import sqlite3 from typing import List, Tuple def create_database(): """Create a database file named books.db and a table called book with the following columns: - title (TEXT) - author (TEXT) - published_year (INTEGER) - rating (REAL)""" pass def insert_data(): """Insert the following boo...
import sqlite3 from typing import List, Tuple # Step 1: Create a database and table def create_database(): connection = sqlite3.connect('books.db') cursor = connection.cursor() cursor.execute('''CREATE TABLE IF NOT EXISTS book ( title TEXT, author TEXT, published_year INTEGER, ...
from solution import create_database, insert_data, get_books_by_year, update_book_rating, Book, store_book, retrieve_books def test_database_creation(): create_database() connection = sqlite3.connect('books.db') cursor = connection.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE type='tab...
[]
[ 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 sqlite3\nfrom typing import List, Tuple\n\n# Step 1: Create a database and table\ndef create_database():\n conn = sqlite3.connect(\"books.db\")\n cursor = ...
trial_gpt4o_2
{ "original_instruction": "### SQLite Database Tasks with `sqlite3` Module\n\nIn this assessment, you will showcase your proficiency in using Python's `sqlite3` module to interact with an SQLite database. You will perform a series of operations including creating a database, managing transactions, handling custom dat...
0.59099
Docs: Python310_6474
C
[ "create_database", "insert_data", "get_books_by_year", "update_book_rating", "adapt_book", "convert_book", "store_book", "retrieve_books" ]
8
[ [ "retrieve_books", "adapt_book" ], [ "retrieve_books", "convert_book" ], [ "store_book", "adapt_book" ], [ "store_book", "convert_book" ] ]
4
[]
false
[ "Book" ]
true
pytest
true
[]
true
3c5cdcc13631209317ae5927d10dc54b65705c48
c44b2e2579a5a1191dbd5fba2a9723fc02c74ed0
v1.0
complete
Docs
Docs: Python310_7923_C
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. >>> person = Perso...
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": "### Question: Persistence Layer with Python Serialization and SQLite Database\n\nYou 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.\n\n#### Requir...
0.55748
Docs: Python310_7923
C
[ "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
0095b13a21ebb723428b2b44cdc2a3a7ed9f9030
76d177133d82940cee4de296e7d002996d638f57
v1.0
complete
Docs
Docs: Python310_7911_C
import readline import atexit import os COMMANDS = ["start", "stop", "pause", "resume", "status"] def init_history(histfile): """ Initialize history from a specified history file. Parameter: histfile (str): Path to the history file. Example: >>> init_history("~/.custom_python_history") "...
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": "**Custom Interactive Python Shell with Enhanced Readline Features**\n\nYou are tasked with creating your own custom interactive Python shell utilizing the \"readline\" module. Your shell should support the following features:\n\n1. **History Management**: \n - Load history from a file dur...
0.372414
Docs: Python310_7911
C
[ "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
a7058bbad4ce2e6f1a15f51d79e6df4308720b06
b0ec2ad844286f6ba1bf7918b825d47202866395
v1.0
complete
Docs
Docs: Python310_7473_C
import types from types import SimpleNamespace def create_dynamic_person_class(): """ Create a dynamic class 'DynamicPerson' with the required attributes and methods. """ pass def test_dynamic_person_class(): """ Create instances of 'DynamicPerson' and demonstrate the required functionality. """ pass ...
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": "**Question: Implementing a Dynamic Class with Special Attributes**\n\nObjective:\nYou 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 demonstr...
0.445324
Docs: Python310_7473
C
[ "create_dynamic_person_class", "test_dynamic_person_class" ]
2
[ [ "test_dynamic_person_class", "create_dynamic_person_class" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9c92219abc63e5285944777decd5010303c2d8c7
49c3ad0ccc19e54d3dc0361fcc6a1a7427120f52
v1.0
complete
Docs
Docs: Python310_7501_C
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. >>> h = create_hmac(b'secret_key', b'hello', 'sha256') >>> isinstance(h, hmac.HMAC) True """ p...
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": "**Question: HMAC Message Authentication**\n\nYou 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, u...
0.824912
Docs: Python310_7501
C
[ "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
b51717efdcb972de3ce2f04da8c9ec48cbd54966
579054e7eebfadc62861397c692c623abb271beb
v1.0
complete
Docs
Docs: Python310_6090_C
from typing import List, Union, Tuple import math def gcd(a: int, b: int) -> int: ... def lcm(a: int, b: int) -> int: ... def analyze_numbers(numbers: List[Union[int, float]]) -> Tuple[float, float, Tuple[int, int], float, bool]: """ Analyze a list of numbers to compute various statistical result...
from typing import List, Union, Tuple import math from functools import reduce import operator def gcd(a, b): while b: a, b = b, a % b return abs(a) def lcm(a, b): return abs(a * b) // gcd(a, b) if a and b else 0 def analyze_numbers(numbers: List[Union[int, float]]) -> Tuple[float, float, Tup...
from solution import analyze_numbers import math def test_single_element(): result = analyze_numbers([5]) expected_sum = 5.0 expected_norm = 5.0 expected_gcd_lcm = (5, 5) expected_rem = math.remainder(5, math.pi) expected_close_to_zero = False assert result == (expected_sum, expected_norm, ...
[ { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": null, "function_dec...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Union, Tuple\nimport math\nfrom functools import reduce\nimport operator\n\ndef gcd(a, b):\n while b:\n a, b = b, a % b\n return a...
trial_gpt4o_0
{ "original_instruction": "You are required to implement a function `analyze_numbers(numbers: List[Union[int, float]]) -> Tuple[float, float, Tuple[int, int], float, bool]`. The function should perform various mathematical operations and return a tuple containing the following five elements based on the given list of...
0.573587
Docs: Python310_6090
C
[ "gcd", "lcm", "analyze_numbers" ]
3
[ [ "analyze_numbers", "gcd" ], [ "analyze_numbers", "lcm" ], [ "lcm", "gcd" ] ]
3
[]
false
[]
false
pytest
true
[]
true
746d97b8692c2183d19d38ab141523b3ceeb72f3
79da433095ae71c46a423445eaa8d22bf94b73c5
v1.0
complete
Docs
Docs: Python310_8537_C
import os import readline import atexit def load_history(history_file: str) -> None: """ Load command history from history_file if it exists. """ pass def save_history(history_file: str, max_commands: int) -> None: """ Save command history to history_file (max length max_commands). """ ...
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": "### Question: Implementing a Custom Interactive Shell with `readline`\n\nIn this task, you are required to implement a custom interactive shell in Python using the `readline` module. This shell should support:\n1. Custom history management.\n2. Custom word completion.\n3. Saving the session...
0.404568
Docs: Python310_8537
C
[ "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
1a148cb448465d41f2b2eda9f73d87fd304b1746
1eca9b7712dc54d5c80fe237865209dcb0dec905
v1.0
complete
Docs
Docs: Python310_8020_C
import timeit def compare_execution_times(n: int) -> str: """ Compare the execution times of summing numbers using a loop versus using a formula. Parameters: n (int): The upper limit of the range to sum. Returns: str: A report indicating which method is faster and by how much. >>> compar...
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": "### Timeit Module Exercise: Measuring and Optimizing Code Performance\n\n#### Objective\nWrite 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.\...
0.543203
Docs: Python310_8020
C
[ "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
973918d24765ce539e2a64270cb20eee0318af78
74fb80b34f808c93247715ad723837934264a141
v1.0
complete
Docs
Docs: Pytorch_8116_C
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 # Define a simple model class SimpleModelPart1(nn.Module): def __init__(self): super(SimpleModelPart1, self).__init__() ...
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": "**Distributed Training with RPC and Autograd in PyTorch**\n\n**Objective:**\nImplement 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 m...
0.494756
Docs: Pytorch_8116
C
[ "remote_forward", "run_worker" ]
2
[ [ "run_worker", "remote_forward" ] ]
1
[]
false
[ "SimpleModelPart1", "SimpleModelPart2" ]
true
pytest
true
[ "torch" ]
false
601162826da4aac1ed6cfc6af06bc968af78a296
c6080dd1dd1f8a631bae75f3804a9d5ea0dec548
v1.0
complete
Docs
Docs: Seaborn_8710_C
import seaborn as sns import matplotlib.pyplot as plt def load_penguins_dataset(): """ Load the seaborn penguins dataset. Returns: DataFrame: Contains the penguins dataset. """ return sns.load_dataset("penguins") def create_ecdf_plots(): """ Create and display ECDF plots for the flipper le...
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": "**Coding Assessment Question: Seaborn ECDF Plot**\n\n**Objective:**\nYour task is to load a dataset and create specific ECDF plots using Seaborn, demonstrating your comprehension of fundamental and advanced concepts of this package.\n\n**Problem Statement:**\n\n1. Load the 'penguins' datase...
0.731
Docs: Seaborn_8710
C
[ "load_penguins_dataset", "create_ecdf_plots" ]
2
[ [ "create_ecdf_plots", "load_penguins_dataset" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "seaborn" ]
false
824a413a6238613b328f669604a03186919a6668
21d7c61b7d2bdc85195771391171e06dad7448fa
v1.0
complete
Docs
Docs: Python310_8101_C
def faulty_factorial(n: int) -> int: """Intentionally faulty implementation of factorial to demonstrate debugging. """ if n == 0: return 1 else: return n * faulty_factorial(n - 1) def correct_factorial(n: int) -> int: """Correct implementation of factorial after debugging the faulty...
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": "### Advanced Python Debugging and Profiling Assignment\n\n**Objective:**\n\nYou 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` mo...
0.675006
Docs: Python310_8101
C
[ "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
5b92d77d5fc100d8fb520838888d35d025dc97ff
0fe4cc48ea626a81b3e510ea7e4a1211c85d124e
v1.0
complete
Docs
Docs: Pandas_8032_C
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. >>> df = pd.DataFrame({'A': range(100), 'B': range(100, 200)}) >>> get_memory_usage(df) > 0 True """ ...
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": "Advanced DataFrame Operations and Memory Management\n\n#### Objective:\nYou 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).\n\n#### Problem State...
0.601105
Docs: Pandas_8032
C
[ "get_memory_usage", "format_bytes", "apply_transformation", "check_condition" ]
4
[ [ "get_memory_usage", "format_bytes" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "pandas" ]
false
130b8fa538f52ec897f98418ace6e7b9770adf63
676d7be053ea1219321db30849126b1003216540
v1.0
complete
Docs
Docs: Python310_8331_C
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() -> email.policy.Policy: """ Creates and returns a custom email policy that: - Has a maximum line length of 100 c...
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": "### Email Policy Customization and Application\n\nThe `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 ...
0.633678
Docs: Python310_8331
C
[ "create_custom_policy", "parse_and_modify_email" ]
2
[ [ "parse_and_modify_email", "create_custom_policy" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5f092bd01cd937b6f4cd64a929226f6b48fe9e11
cf427e04c3f5d52f68a3adc612b31ebf9b7d17d6
v1.0
complete
Docs
Docs: Python310_7261_C
import asyncio from asyncio import Queue, LifoQueue, PriorityQueue, QueueFull, QueueEmpty async def worker(name, queue): """ Worker function to process tasks from the queue """ # Implement the worker function here async def async_task_processor(task_list, queue_type, maxsize): """ Implement an asynch...
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": "#### Objective:\nImplement 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.\n\n#### Problem Statement:\nYou are ...
0.557296
Docs: Python310_7261
C
[ "worker", "async_task_processor" ]
2
[ [ "async_task_processor", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a7e00c89af1510e4acedb7396c5efa1edfa349ad
5c5a4914fb56f4f681bbbb5f9421159bfc0d2739
v1.0
complete
Docs
Docs: Python310_8485_C
import contextvars # Declare the context variable for log level log_level_var = contextvars.ContextVar('log_level', default='INFO') def set_log_level(level: str) -> None: """ Set the log level for the current context. Parameters: - level: A string representing the log level (e.g., "DEBUG", "INFO", "W...
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": "**Title: Managing Contextual State in Asynchronous Tasks**\n\n#### Objective:\nDesign 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...
0.5638
Docs: Python310_8485
C
[ "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
66d861a76d452a6a514a010070a29e32f9cb9a53
c72124fd39602a2d134ef9353eab1017d67ba15d
v1.0
complete
Docs
Docs: Python310_6961_C
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: """ Modifies certain elemen...
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": "**XML Document Traversal and Modification Using `xml.dom`**\n\nGiven 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.\n\n### Function Signature...
0.594496
Docs: Python310_6961
C
[ "transform_xml_document", "change_tag" ]
2
[ [ "transform_xml_document", "change_tag" ] ]
1
[]
false
[ "XMLTransformationError" ]
true
pytest
true
[]
true
f66871cd3e6c5683498bd9c0910a29ca97719772
f26905105f6bc200d6a7394dbeee0ca680a4a687
v1.0
complete
Docs
Docs: Python310_7711_C
import struct def serialize_data(data, version=2): """ Serialize a Python object to a byte string. Parameters: - data: A Python object of types int, float, str, list, or dict. - version: An optional integer specifying the serialization protocol version. Returns: - A serialized byte s...
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": "### Serialization and Deserialization with Custom Constraints\n\nIn 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, ensurin...
0.583801
Docs: Python310_7711
C
[ "_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
b21bf28ad0841f3f14cf99bc05f350775b6530e0
569c710d45a2503703941c34236bdc855b828b8a
v1.0
complete
Docs
Docs: Python310_8718_C
import mailcap import re def process_mime_type(MIMEtype: str, filename: str = '/dev/null', plist: list = []) -> tuple: """ Processes the given MIME type and returns the appropriate command and mailcap entry if found. Parameters: - MIMEtype: str - The MIME type to be processed. - filename: str - Th...
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": "**Question: MIME Type Handling with Mailcap**\n\nYou 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.\n...
0.544997
Docs: Python310_8718
C
[ "sanitize_filename", "sanitize_plist", "process_mime_type" ]
3
[ [ "process_mime_type", "sanitize_filename" ], [ "process_mime_type", "sanitize_plist" ] ]
2
[]
false
[]
false
pytest
true
[]
true
604d6bd260a214cec54fd9292bc874cfcaefa1ef
2aa5e1472c0e7e48cf438695b6e822ff4c392321
v1.0
complete
Docs
Docs: Python310_8570_C
import signal import time def periodic_task_runner(): """ Performs a periodic task every few seconds and handles an external termination signal to gracefully stop the task. """ # Your implementation here Unit Test: import os import signal import time from multiprocessing import Process from sol...
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": "### Custom Signal Handling and Alarm Management\n\n#### Objective:\nImplement 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.\n\n...
0.681808
Docs: Python310_8570
C
[ "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
c54c21f52506c4de7a9022af685cd6fb9375614c
1a5a603a117e42349c3bcf58eb2a2fc0cb83f116
v1.0
complete
Docs
Docs: Scikit_8293_C
import numpy as np from sklearn.svm import SVC def polynomial_kernel(X: np.ndarray, Y: np.ndarray, degree: int, gamma: float, coef0: float) -> np.ndarray: """ Computes the polynomial kernel between matrices X and Y. Parameters: - X (np.ndarray): Input matrix X. - Y (np.ndarray): Input matrix Y...
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": "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.\n\n### Requirements\n\n1. Implement ...
0.597524
Docs: Scikit_8293
C
[ "polynomial_kernel", "kernel_svm_prediction" ]
2
[ [ "kernel_svm_prediction", "polynomial_kernel" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
66d286cbcc1ec34e303373d1479ca7cadfde87ea
bb8facf32d06e8511547c41479684ae1eb065e32
v1.0
complete
Docs
Docs: Pytorch_8901_C
import os import torch import torch.nn as nn def configure_mps_environment(): """Configures MPS environment variables for optimization and logging.""" # Set environment variables as per requirements def create_and_run_model(): """Creates a simple model to perform matrix multiplication and prints the outpu...
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": "### PyTorch MPS Environment Configuration Task\n\nYou 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. Specif...
0.542524
Docs: Pytorch_8901
C
[ "configure_mps_environment", "create_and_run_model" ]
2
[ [ "create_and_run_model", "configure_mps_environment" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
2a4591e26fdf8d92a83a0002a9e9cc4d32e66ef0
5d80672f4cce218960ef782a29f765498d997128
v1.0
complete
Docs
Docs: Python310_8500_C
import unittest from unittest.mock import patch, Mock, call import requests def fetch_data_and_process(url): """ Fetch data from the provided URL, process it, and save it. Raises HTTPError if the fetch fails. """ pass def process_data(data): """ Process the data and return processed data. """ ...
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": "**Python Coding Assessment Question: Using `unittest.mock` to Test Functionality**\n\n### Objective\nCreate 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 testin...
0.704031
Docs: Python310_8500
C
[ "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
54995b72fdf098b2396a6372373d3c3c0fd627a4
4af45369b4dcafd95e9fbd894f95efec27bf7b65
v1.0
complete
Docs
Docs: Python310_7606_C
import asyncio async def start_server(host: str, port: int): """Starts the TCP server at the specified host and port, listens for incoming connections and creates a new asyncio task for each client. """ pass # TODO: Implement the server initialization logic here async def handle_client(reader: asynci...
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": "### Advanced Python Asynchronous Programming Assessment\n\n**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.\n\n---\n\n#### Question:\n\nYou are tasked with...
0.554919
Docs: Python310_7606
C
[ "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
fb61b1c8d18b77583478b127d8f4fa9b58bc16d4
7d85758232fab68b9ec5938c16e2b3f979234e92
v1.0
complete
Docs
Docs: Python310_9155_C
import math import statistics def analyze_numbers(data: list) -> dict: """ Perform a series of mathematical and statistical operations on a list of integers. 1. Prime Check: - Determine if each number in the list is a prime number. 2. Statistical Analysis: - Calculate the mean and va...
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": "### Advanced Coding Assessment Question\n\n#### Objective:\nImplement a function that accepts a list of integers and performs a series of mathematical and statistical operations as defined below.\n\n#### Problem Statement:\n\nYou are provided with a list of integers. Implement a function `a...
0.630702
Docs: Python310_9155
C
[ "is_prime", "analyze_numbers" ]
2
[ [ "analyze_numbers", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b3b3fbd42fb617bd90d94dcba45699a072c4b7f1
0e7b26ec25ff4b7135a96ad8c7849fa354ace053
v1.0
complete
Docs
Docs: Python310_6876_C
from datetime import datetime, timedelta, timezone def generate_event_summary(events, timezone_str): """ Generate summary of events with adjusted times for a specific timezone. Args: events (list): List of events where each event is a tuple (event_name, start_datetime, end_datetime). ...
from datetime import datetime, timedelta, timezone def convert_to_timezone(dt_str, tz_str): dt = datetime.fromisoformat(dt_str.replace("Z", "+00:00")) sign = 1 if tz_str[3] == '+' else -1 hours_offset = int(tz_str[4:6]) minutes_offset = int(tz_str[7:9]) offset = timedelta(hours=hours_offset, minute...
def test_generate_event_summary(): events = [ ("Meeting", "2023-03-15T14:00:00Z", "2023-03-15T15:30:00Z"), ("Conference", "2023-04-20T08:00:00Z", "2023-04-20T11:00:00Z"), ("Webinar", "2023-05-01T12:00:00Z", "2023-05-01T13:45:00Z") ] timezone_str = "UTC-04:00" expected = { ...
[ { "docstring": null, "function_declaration": "def convert_to_timezone(dt_str, tz_str):", "function_name": "convert_to_timezone", "parameter_list": "(dt_str, tz_str)" }, { "docstring": null, "function_declaration": "def calculate_duration(start_str, end_str):", "function_name": "calcu...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from datetime import datetime, timedelta, timezone\nimport re\n\ndef generate_event_summary(events, timezone_str):\n \"\"\"\n Generates a summary of events with t...
trial_gpt4o_2
{ "original_instruction": "**Problem Statement**\n\nYou are tasked with creating a Python function to manage a schedule of events that span different time zones. You need to account for the varying offsets from UTC and daylight saving adjustments. \n\nWrite a function `generate_event_summary(events, timezone_str)` th...
0.677361
Docs: Python310_6876
C
[ "convert_to_timezone", "calculate_duration", "generate_event_summary" ]
3
[ [ "generate_event_summary", "calculate_duration" ], [ "generate_event_summary", "convert_to_timezone" ] ]
2
[]
false
[]
false
pytest
false
[]
true
3bc206f97defa38ee8b96852a6dcda7fb2530adc
6490ceb35516bd7a4f1c1fd7df894b442fe3c869
v1.0
complete
Docs
Docs: Python310_8364_C
import webbrowser import datetime import time import threading import re from typing import List, Tuple def schedule_browser_openings(schedule: List[Tuple[str, str]]) -> None: """ Processes a schedule of URLs to be opened at specific times using the webbrowser module. Args: schedule (List[Tuple[st...
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": "### Question: Implement a Web Browser Controller for Scheduled URL Openings\n\n**Objective**: \nYour 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 us...
0.681296
Docs: Python310_8364
C
[ "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
411088f507300d849af4c1a6e783d9ec5334e9d1
1b6878bc121cf5359eed8860b133f9bfdc9242dd
v1.0
complete
Docs
Docs: Seaborn_8319_C
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. Returns: data (numpy.ndarray): Generated dataset with shape (100, 4) """ ...
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": "**Question: Advanced Seaborn Aesthetics**\n\nAs 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 effe...
0.744287
Docs: Seaborn_8319
C
[ "generate_data", "sinplot", "advanced_visualizer" ]
3
[ [ "advanced_visualizer", "sinplot" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "seaborn" ]
false
4d839e3fd91b3218e9cd7b2a56148324987a64a1
83eb75c66d241bc4798da7befc317959e083cd93
v1.0
complete
Docs
Docs: Python310_8898_C
import unittest 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...
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": "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 ...
0.65184
Docs: Python310_8898
C
[ "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
92bdbc8338576b4001d7df7bbab7db69544b8b4a
6b72367895bc87b5351132e859d215ee35c38826
v1.0
complete
Docs
Docs: Python310_9118_C
from typing import Iterator, Dict, List, Tuple def read_lines(file_path: str) -> Iterator[str]: """ Generator that reads lines from a file. """ # Implement this function def process_lines(lines: Iterator[str]) -> Iterator[str]: """ Generator that processes lines. Strips leading/trailin...
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": "### **Question: Implementing a Functional Pipeline with Iterators and Generators**\n\nYou 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[...
0.701843
Docs: Python310_9118
C
[ "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
d6f16c709ec79106b4aeb9ed8d815a61c2c80b9b
b214f55baaf77edc5bc4abf20dbad6d298a45794
v1.0
complete
Docs
Docs: Python310_9099_C
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 ...
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": "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 o...
0.613633
Docs: Python310_9099
C
[ "is_prime", "parallel_prime_check" ]
2
[ [ "parallel_prime_check", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b845c74e2b183a44b358a5d25c2ba8f21f601b32
9121101239d905d44ac9b0755794ff855a293c08
v1.0
complete
Docs
Docs: Python310_8804_C
import asyncio from typing import List, Dict async def count_async_in_file(file_path: str) -> int: """Count the number of lines in a file that contain the word 'async'.""" count = 0 async with aiofiles.open(file_path, 'r') as f: async for line in f: if 'async' in line: c...
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": "### Asynchronous File Processing with Platform Considerations\n\n#### Background:\nYou 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 d...
0.631951
Docs: Python310_8804
C
[ "count_async_in_file", "process_files" ]
2
[ [ "process_files", "count_async_in_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f1efcb6da7e3680083bf54bf463e9dd3d1443ea7
8cffd1852c98939bf0c55a7636a97555ba53d2af
v1.0
complete
Docs
Docs: Scikit_8417_C
import numpy as np from sklearn.datasets import load_digits from sklearn.decomposition import NMF def load_and_prepare_data(): """ Load the "digits" dataset using sklearn.datasets.load_digits. >>> X = load_and_prepare_data() >>> isinstance(X, np.ndarray) True """ X, _ = load_digits(return_...
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": "**Problem Description:**\n\nYou are given a dataset and required to implement and optimize a machine learning model using scikit-learn. Your task involves:\n1. Loading and preparing the data.\n2. Implementing a machine learning model.\n3. Profiling the existing implementation to identify bo...
0.521023
Docs: Scikit_8417
C
[ "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
b119d38a7aa3cb062f50e1cfb5eeb84cd1c8a8fe
f97785cfa743eea64ba97c659218109eb23335da
v1.0
complete
Docs
Docs: Python310_7740_C
from datetime import date, time, datetime, timezone def create_date(year, month, day): """ Create a date object with given year, month, and day. >>> d = create_date(2023, 10, 5) >>> d.year 2023 >>> d.month 10 >>> d.day 5 """ pass def create_time(hour, minute, second, micros...
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": "### Advanced Python DateTime API Integration\n\nYou 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 implement...
0.709702
Docs: Python310_7740
C
[ "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
c402030146830dc55f76a83905004d73d5403ca8
66830db1d0f352368635f617e0bb066d51086f8b
v1.0
complete
Docs
Docs: Python310_8715_C
import uuid from typing import List def generate_uuids(): """ Generate and manipulate UUIDs according to specified criteria. 1. Generate 10 UUIDs using uuid4() and store them in a list. 2. Generate 1 UUID using uuid1(), ensuring it is multiprocessing-safe. 3. Convert the list of 10 UUIDs to their integ...
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": "**Objective:**\n\nImplement a Python program that generates and manipulates UUIDs using the `uuid` module according to specified criteria.\n\n#### Problem Statement:\n\n1. **UUID Generation:**\n - Generate 10 UUIDs using `uuid4()` and store them in a list.\n - Generate 1 UUID using `uui...
0.512257
Docs: Python310_8715
C
[ "generate_uuids", "validate_uuids" ]
2
[ [ "generate_uuids", "validate_uuids" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2dcc81d5f12e53c91a08d724e28a01e2f5a5f149
d5393a9e3244c5a873166a6e90a2efe79c501d8f
v1.0
complete
Docs
Docs: Python310_9792_C
import asyncio async def run_commands(commands: list[str]) -> dict[str, tuple[str, int]]: """Run a list of shell commands concurrently and return a dictionary with the command as the key and a tuple containing the standard output and the return code as the value. >>> import asyncio >>> commands = ["echo '...
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": "### Coding Challenge:\n\n#### Objective:\nEvaluate your ability to use Python's `asyncio` library to manage subprocesses.\n\n#### Task:\nYou are required to write an asynchronous Python function that takes a list of shell commands and runs them concurrently. The function should return a dic...
0.653266
Docs: Python310_9792
C
[ "run_command", "run_commands" ]
2
[ [ "run_commands", "run_command" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e9ddf5c38bd0a714670f6b1d3b2d1c7a70f9cab6
efb5c9aecb7687f72a01237e57aeec67f7d3817e
v1.0
complete
Docs
Docs: Pytorch_9618_C
import torch import torch.nn as nn import torch.optim as optim from torch.autograd import profiler def init_profiling_hook(): """Initialize a global profiling hook to monitor the execution time of PyTorch operations.""" pass # Define a simple neural network class SimpleNN(nn.Module): def __init__(self): ...
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": "### PyTorch Profiling Hooks Implementation\n\n#### Objective:\nImplement 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.\n\n#### Problem Sta...
0.621354
Docs: Pytorch_9618
C
[ "init_profiling_hook", "run_training_with_profiling" ]
2
[ [ "run_training_with_profiling", "init_profiling_hook" ] ]
1
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
8a17cbdadc793fc07ad521732692ae000cad2733
1afcd655d5209875df55da849cb22b286c9d2905
v1.0
complete
Docs
Docs: Pytorch_9346_C
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' def run_benchmark(): """ Run the benchmark on the given model using the provided command. """ ...
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": "#### Objective\nThe 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.\n\n#### Problem Statement\nYou are given a PyTorch model...
0.509709
Docs: Pytorch_9346
C
[ "run_benchmark", "analyze_profiling_logs", "profile_model" ]
3
[ [ "profile_model", "analyze_profiling_logs" ], [ "profile_model", "run_benchmark" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b2de53851c2ad6e6650e1323666f7d382e3c8fd0
e210d1f27a0c7445a83f4c8dbf2c00b9ef6b2468
v1.0
complete
Docs
Docs: Pytorch_9474_C
import torch import torch.nn as nn def check_mps_availability() -> bool: """ Checks if the MPS backend is available. >>> check_mps_availability() True # or False """ pass def tensor_operations_on_mps() -> torch.Tensor: """ Performs simple tensor operations on MPS. - Creates a tenso...
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": "**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.\n\n**Question:**\n\nYou are tasked with verifying the availability of the MPS backend in PyTorch...
0.553664
Docs: Pytorch_9474
C
[ "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
9593b531d62331a34ab2ffe1d322df94288cc4cd
bcff8316a004cc5772a039c966e97253f899dec5
v1.0
complete
Docs
Docs: Python310_9427_C
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_...
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": "### Memory Leak Analysis with tracemalloc\n\n#### Objective\nIn 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 i...
0.457629
Docs: Python310_9427
C
[ "computation_function", "analyze_memory_leak" ]
2
[ [ "analyze_memory_leak", "computation_function" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ac78d1f52e81175d925f76a9faeb216de92bbae7
323c52564513b69c9cda57fa53e6247ab98175a6
v1.0
complete
Docs
Docs: Pytorch_8988_C
import torch from torch.func import grad, vmap def squared_error(tensor1, tensor2): """ Computes the element-wise squared error between two tensors. >>> tensor1 = torch.tensor([1.0, 2.0, 3.0]) >>> tensor2 = torch.tensor([4.0, 5.0, 6.0]) >>> squared_error(tensor1, tensor2) tensor([9., 9., 9.]) ...
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": "### PyTorch Function Transformation Assessment\n\n#### Objective:\nDemonstrate your understanding of PyTorch's `torch.func` module by implementing and transforming a function using function transforms while adhering to the constraints provided.\n\n#### Problem Statement:\nYou are required t...
0.566739
Docs: Pytorch_8988
C
[ "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
5665077c738775c359b0a391b88dcfaf65a745d8
a5455181cb05caaa7ef786d302aba8cb769456e4
v1.0
complete
Docs
Docs: Scikit_8888_C
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 ...
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": "### Anomaly Detection with Scikit-Learn\n\n**Objective:**\nImplement 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 `Ellipt...
0.674928
Docs: Scikit_8888
C
[ "generate_synthetic_data", "anomaly_detection_comparison", "evaluate_performance" ]
3
[ [ "anomaly_detection_comparison", "evaluate_performance" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
d9cd4714123e872d8f720ff0a251ca49edb34be7
4427715ef5efddd4027f188b35f67280560e3cc6
v1.0
complete
Docs
Docs: Pytorch_9485_C
import torch from typing import Optional def multi_headed_attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, num_heads: int, mask: Optional[torch.Tensor] = None) -> torch.Tensor: """ Perform multi-headed attention using the given queries, keys, and values. Args: query (torch.Tensor...
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": "#### Objective\nImplement a custom multi-headed attention mechanism using PyTorch's `torch.nn.attention.flex_attention` and `BlockMask` utilities.\n\n#### Problem Statement\nYou are required to implement a function `multi_headed_attention` that performs multi-headed attention on a given set...
0.493565
Docs: Pytorch_9485
C
[ "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
ce49118cd9923a85887e1fea44bd9f033e9caf2b
49038e02ec15419092d6c874e68cad96c1bb1fd1
v1.0
complete
Docs
Docs: Python310_10115_C
import asyncio async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): """ Handle communication with a single client. """ pass async def broadcast(message: str, writer: asyncio.StreamWriter): """ Send a message to all connected clients except the sender. """ ...
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": "**Question: Implement a Concurrent Chat Server Using asyncio**\n\nYou 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.\n\n### Requ...
0.571523
Docs: Python310_10115
C
[ "handle_client", "broadcast", "chat_server", "main" ]
4
[ [ "chat_server", "handle_client" ], [ "handle_client", "broadcast" ] ]
2
[]
false
[]
false
pytest
true
[]
true
aeaa4d9855ec5ae5fb3b1e52734f69dedb1c3f14
d2c4b38e14222c67d98bc2e0fd997d3cbea23775
v1.0
complete
Docs
Docs: Pytorch_10153_C
import torch from torch.nn.attention.flex_attention import create_block_mask, create_mask, or_masks def custom_block_attention_mask(block_size: int, sequence_length: int) -> torch.Tensor: """ Create a custom block attention mask for a transformer model. The mask will block regions in blocks of the given block_...
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": "Advanced Mask Manipulation in Attention Mechanisms\n\nOne 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 ...
0.384486
Docs: Pytorch_10153
C
[ "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
041246982a38a13d490352f93e136099d3cce642
fb6cc6d78149559322eb4dba817c39a1e4fa85a3
v1.0
complete
Docs
Docs: Pandas_9418_C
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.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": "### Coding Assessment: Working with PyArrow and pandas\n\n#### Objective:\nDemonstrate understanding and application of integrating PyArrow with pandas for efficient data manipulation and I/O operations.\n\n#### Problem Statement:\n\nYou are provided with a CSV file named `data.csv` which c...
0.643371
Docs: Pandas_9418
C
[ "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
bed20d2521079a06d9f27f3d7b7b80a71f1d237f
e911fa57c999ce18a660e6ec7c72d4628fb46d2e
v1.0
complete
Docs
Docs: Pytorch_9878_C
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...
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": "#### Objective\nImplement a neural network training loop using PyTorch's Automatic Mixed Precision (AMP) functionalities to improve performance and stability. \n\n#### Problem Statement\nYou are provided with a simple convolutional neural network (CNN) and a dummy dataset. Your task is to w...
0.655017
Docs: Pytorch_9878
C
[ "get_dataloader", "train_model" ]
2
[ [ "train_model", "get_dataloader" ] ]
1
[]
false
[ "SimpleCNN" ]
true
pytest
false
[ "torch" ]
false
e425e0acf1ed4da7269dd5509de2b395007eeec2
1cc442182375d7f0ab44e23814cae7a6b77fc931
v1.0
complete
Docs
Docs: Python310_10041_C
import getpass import hashlib # Predefined credentials (username: hashed_password) credentials = { 'user1': '5e884898da28047151d0e56f8dc629...', 'user2': 'ee26b0dd4af7e749aa1a8ee3c10ae9...' } def hash_password(password): """ Hash the given password using SHA-256 and return the hexadecimal digest. ...
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": "**Question: Secure User Authentication System**\n\nYou 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 use...
0.616082
Docs: Python310_10041
C
[ "hash_password", "check_password", "authenticate_user" ]
3
[ [ "authenticate_user", "check_password" ], [ "check_password", "hash_password" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e9867e273abc801fdb842088c8b18af867729992
24964082d1b746e4c73d1887b6cc4cbdbde0576a
v1.0
complete
Docs
Docs: Pytorch_9115_C
import torch import torch.nn.functional as F from typing import Optional def scaled_dot_product_attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor: """ Compute the scaled dot-product attention. Args: - query: A tensor of shap...
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": "**Attention Mechanism Implementation in PyTorch**\n\nYou 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.\n\n### Task Description\n\nImple...
0.554615
Docs: Pytorch_9115
C
[ "scaled_dot_product_attention", "multi_head_attention" ]
2
[ [ "multi_head_attention", "scaled_dot_product_attention" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
3c380a29af3a5c1ae4030962ab3098ff094a4031
6ede2a89ef85117ef6638be3823a8ac944f0935c
v1.0
complete
Docs
Docs: Python310_9845_C
import asyncio 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 successfully w...
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": "### Asynchronous Web Scraper with Timeout\n\n#### Problem Statement\n\nYou 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 an...
0.607445
Docs: Python310_9845
C
[ "fetch_with_timeout", "fetch_all", "main" ]
3
[ [ "fetch_all", "fetch_with_timeout" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
5ae18fb27f4cd3e34e2faa1d618723dffb4eaf27
31350656294def26bb239caaf367e72db0da93d0
v1.0
complete
Docs
Docs: Python310_9683_C
c #include <Python.h> // Function to safely assign source object to target void safe_assign_object(PyObject **target, PyObject *source) { /** * Function to safely assign a source Python object to a target Python object reference * * Example usage: * PyObject* target = NULL; * PyObject* so...
# 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": "Implementing Safe Reference Counting in a Python C Extension\n\n**Objective:** \nDesign and implement a small part of a Python C extension that demonstrates proper reference counting using the functions provided in the Python C API.\n\n**Problem Statement:**\n\nYou are tasked with implemen...
0.415197
Docs: Python310_9683
C
[ "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
547c53357bbda6b921fcf7aec60e077b8168cf6d
6cb46af28ffec21039da9b1f3135beb54c000920
v1.0
complete
Docs
Docs: Scikit_9078_C
import numpy as np import matplotlib.pyplot as plt from sklearn.neighbors import KernelDensity def generate_dataset(): """Generate a dataset of 2D points with two clusters. Returns: np.ndarray: The generated dataset. """ np.random.seed(0) X = np.vstack([np.random.normal(loc=-1, scale=1, siz...
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": "#### Problem Statement\n\nYou 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 ...
0.619369
Docs: Scikit_9078
C
[ "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
8ddc4f0aa71a872188c07bbff245ae4c36a24403
98df83d671f9792dbb2b166d677d8b284e86b59a
v1.0
complete
Docs
Docs: Python310_7967_C
import os import hashlib import hmac def hash_file(filepath: str, algorithm: str='sha256') -> str: """ Hashes the content of a file using the specified algorithm. Args: filepath (str): Path to the file to be hashed. algorithm (str): Hashing algorithm to use ('sha256', 'sha512', 'blake2b'). ...
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": "### Advanced Cryptographic Hashing and HMAC Implementation\n\n#### Problem Statement\n\nYou are tasked with implementing a secure file manipulation pipeline involving hashing and authentication processes. Your solution must include the following functionalities:\n\n1. **File Hashing**:\n ...
0.776909
Docs: Python310_7967
C
[ "hash_file", "generate_hmac", "verify_hmac" ]
3
[ [ "verify_hmac", "generate_hmac" ] ]
1
[]
false
[]
false
pytest
true
[]
true
be39a9ea5179fabeedc1ab300f8ce256d9ad493d
d05b7c6d5e0abe978c9921f2151c8597fd3261fe
v1.0
complete
Docs
Docs: Python310_8592_C
import functools from functools import partial @functools.cache def cached_factorial(n): """ Calculate the factorial of n using recursion with caching. >>> cached_factorial(0) == 1 >>> cached_factorial(5) == 120 >>> cached_factorial(10) == 3628800 >>> cached_factorial(15) == 1307674368000 "...
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": "#### Objective\n\nImplement 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.partia...
0.623704
Docs: Python310_8592
C
[ "cached_factorial", "evaluate_performance" ]
2
[ [ "evaluate_performance", "cached_factorial" ] ]
1
[]
false
[ "FactorialCalculator" ]
true
pytest
true
[]
true
81c3fe23aeb2685398c14bfbd390734caed2ce72
f66b3e21afb04070ad456b5a2d9c5d69345698f6
v1.0
complete
Docs
Docs: Python310_9677_C
import os import syslog def get_file_info(filepath: str) -> dict: """ Retrieves the size, permissions, and owner of the specified file. >>> get_file_info('/path/to/file') {'size': 1024, 'permissions': '0755', 'owner': 1000} """ pass def modify_file(filepath: str, permissions: str, size: int) -...
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": "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:\n1. Retrieving the current size, permissions, and owner of a specified file.\n2. Changing the file's permissions ...
0.48226
Docs: Python310_9677
C
[ "get_file_info", "modify_file", "log_operation" ]
3
[ [ "get_file_info", "log_operation" ], [ "modify_file", "log_operation" ] ]
2
[]
false
[]
false
pytest
true
[]
true
6808b79e5db348b8c30b5f287387afe5303256fb
ff570c04576dcd573d60a1301357c046386781a3
v1.0
complete
Docs
Docs: Scikit_10461_C
from typing import List, Tuple def stream_data(file_path: str, chunk_size: int) -> Tuple[List[str], List[str]]: """ Generator to stream data from a given file in chunks. Args: - file_path (str): Path to the data file. - chunk_size (int): Number of lines to read at once. Yields: - Tuple[Lis...
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": "### Coding Assessment: Implementing Out-of-Core Learning\n\n**Objective:**\nYour 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 increme...
0.605082
Docs: Scikit_10461
C
[ "stream_data", "train_incremental_model", "test_function" ]
3
[ [ "train_incremental_model", "stream_data" ] ]
1
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
bae22bf61b549a9b335b2f96510c945e9fa3fd20
38ee4d29f86c3e9783d32e3a3d2bedd3e8b7c7e1
v1.0
complete
Docs
Docs: Python310_9922_C
import itertools def temperature_generator(city_temperatures): """ Generator function that yields tuples of (city, average temperature). Example: city_temperatures = [ ("New York", [75, 80, 82, 78, 76, 77, 79]), ("Los Angeles", [85, 87, 89, 90, 84, 83, 88]), ("Chicago", [70...
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": "**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.\n\n**Question**:\n\nYou are given a list of tuples, where each tuple represents a city's name and its corre...
0.635894
Docs: Python310_9922
C
[ "temperature_generator", "highest_temperature_city", "top_cities" ]
3
[ [ "highest_temperature_city", "temperature_generator" ], [ "top_cities", "temperature_generator" ] ]
2
[]
false
[]
false
pytest
true
[]
true
dd472f149dbb88160022e92e66c3681a8e1c3903
88d3d710543bbda5133f52cdf5f6ba44c7c39688
v1.0
complete
Docs
Docs: Python310_10343_C
c #include <Python.h> // Define a static variable to hold the state for single-phase initialization static int single_phase_state = 0; // Define a struct to hold the module-specific state for multi-phase initialization typedef struct { int counter; } ModuleState; // Helper function to get the state static ModuleS...
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": "**Objective:** \nDemonstrate your understanding of Python modules, including module creation, state management, and the difference between single-phase and multi-phase initialization.\n\n#### Background:\nYou are tasked with creating a custom Python module, `my_module`, which will be implem...
0.428626
Docs: Python310_10343
C
[ "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
4c84074938e203794f96352a91c421b772b51415
4f584a0d2127794b77130c1f17b1f951473a3930
v1.0
complete
Docs
Docs: Python310_10387_C
from typing import List from math import factorial from functools import reduce def is_prime(n: int) -> bool: """Check if a number is prime""" ... def process_numbers(numbers: List[int]) -> int: """Process a list of numbers using functional programming principles: filter primes, map to factorials, and red...
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": "### Functional Programming Challenge in Python\n\n#### Objective:\nDemonstrate your understanding of functional programming concepts and techniques using Python.\n\n#### Problem Statement:\nYou are required to implement a function that processes a list of numbers and returns a transformed v...
0.68896
Docs: Python310_10387
C
[ "is_prime", "process_numbers" ]
2
[ [ "process_numbers", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5e57b6e722fc5c038dfc8a1182ac2f9d1d074fe1
af72c41e3f73473b395dab17f876a1ea0e6ca6c4
v1.0
complete
Docs
Docs: Scikit_10874_C
from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.svm import LinearSVC from sklearn.multiclass import OneVsRestClassifier from sklearn.pipeline import make_pipeline from sklearn.metrics import classification_report from sklearn.model_selection impor...
from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.svm import LinearSVC from sklearn.multiclass import OneVsRestClassifier from sklearn.pipeline import make_pipeline from sklearn.metrics import classification_report from sklearn.model_selection impor...
import pytest from solution import load_and_preprocess_data, create_pipeline, train_and_evaluate def test_data_loading(): categories = ['alt.atheism', 'comp.graphics', 'sci.space', 'talk.politics.guns'] train_data, test_data = load_and_preprocess_data(categories) assert len(train_data.data) > 0 assert ...
[]
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn.datasets import fetch_20newsgroups\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.svm import LinearSVC\nfrom sklearn.multiclass...
trial_gpt4o_0
{ "original_instruction": "## Coding Assessment Question\n\n### Objective\nTo assess your understanding of scikit-learn, specifically focusing on handling multi-label classifications using the `OneVsRestClassifier`.\n\n### Problem Statement\nGiven a text dataset, your task is to implement a pipeline to classify text ...
0.57622
Docs: Scikit_10874
C
[ "load_and_preprocess_data", "create_pipeline", "train_and_evaluate" ]
3
[ [ "train_and_evaluate", "create_pipeline" ], [ "train_and_evaluate", "load_and_preprocess_data" ] ]
2
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
355fa0a8cc7a8cc524c7cd87cdb1fb3be0cb5d27
e5fe87284c648af0d29c0f2cbcb8c059ef303d69
v1.0
complete
Docs
Docs: Scikit_8981_C
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. ...
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": "### Question: Implementing and Analyzing Kernel Density Estimation (KDE)\n\n**Objective:**\n\nIn 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 wil...
0.615229
Docs: Scikit_8981
C
[ "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
96f9970d196796bb21b15e2eedf0c7ca68429024
40719a9b98e8b8371b7ffdbf877672f868c86ae7
v1.0
complete
Docs
Docs: Python310_10569_C
import hashlib import json from typing import List, Dict def calculate_file_hashes(file_paths: List[str]) -> Dict[str, str]: """ Calculate SHA-256 hashes for the content of the given files. Args: file_paths (List[str]): A list of file paths to calculate hash values for. Returns: Dict...
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": "### Secure Hash Function Task\n\n**Objective:**\nYour 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...
0.814224
Docs: Python310_10569
C
[ "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
cac4449c88c7d1c2abb4d53f655407dd9309c336
428f7bebe4a63ec4d9871e7669df79958e8785e1
v1.0
complete
Docs
Docs: Python310_10444_C
import asyncio from typing import List async def fetch_and_process(urls: List[str], timeout: int) -> List[str]: """ Function to concurrently fetch data from a list of URLs and process the data. Args: urls (List[str]): List of URLs to fetch data from. timeout (int): Timeout in seconds for each ...
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": "### Asyncio Coding Assessment\n\nYou 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 timeout...
0.536014
Docs: Python310_10444
C
[ "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
8fa2c31100d98e6fee11e7609631f1a998ca8bd8
4bd96b011559bbc5269f73b02c91f01ddffae679
v1.0
complete
Docs
Docs: Pytorch_10766_C
import torch from torch.futures import Future, collect_all, wait_all import asyncio def async_file_read(file_paths): """ Asynchronously read the contents of multiple text files. Parameters: ---------- file_paths : List[str] A list of file paths to read. Returns: ------- Li...
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": "### Asynchronous File Reading with PyTorch Futures\n\n**Problem Description:**\n\nYou 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 th...
0.455336
Docs: Pytorch_10766
C
[ "read_file_async", "async_file_read" ]
2
[ [ "async_file_read", "read_file_async" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
5d96e31a188ce276d30c530fcdf4a637025effc2
5da7a3d407569d65e9c7bcc7a2b59eb7ccc6f3cf
v1.0
complete
Docs
Docs: Python310_10445_C
import os import asyncio 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. Args: input_path (str): Path to the input file. output_path (str): Path...
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": "### Asynchronous File Processing with Platform Constraints\n\n**Objective:**\nYou 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 desig...
0.598395
Docs: Python310_10445
C
[ "process_file", "main", "process_file_with_semaphore" ]
3
[ [ "process_file_with_semaphore", "process_file" ] ]
1
[]
false
[]
false
pytest
true
[ "aiofiles" ]
false
78fd68859ce5838242b67902145155c3dbb63d0e
0cf2f4ce6f2d28465ad72e24b985d9bf84da8492
v1.0
complete
Docs
Docs: Pytorch_11036_C
import torch def check_mps_availability(): """ Returns: True if MPS is available, else False """ # Implementation here def perform_mps_tensor_operations(n): """ Args: n (int): The size of the tensor to create Returns: torch.Tensor: The resultant tensor on MPS device after multipli...
import torch def check_mps_availability(): """ Returns: True if MPS is available, else False """ if not torch.backends.mps.is_available(): return False return True def perform_mps_tensor_operations(n): """ Args: n (int): The size of the tensor to create Returns: torch....
import pytest import torch from solution import check_mps_availability, perform_mps_tensor_operations, compare_cpu_mps def test_check_mps_availability(): # This test depends on the actual availability of MPS backend which might not be available in the testing environment. assert isinstance(check_mps_availabili...
[ { "docstring": "Returns: True if MPS is available, else False", "function_declaration": "def check_mps_availability():", "function_name": "check_mps_availability", "parameter_list": "()" }, { "docstring": "Args:\nn (int): The size of the tensor to create\n\nReturns:\ntorch.Tensor: The result...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\n\ndef check_mps_availability():\n \"\"\"\n Returns: True if MPS is available, else False\n \"\"\"\n if not torch.backends.mps.is_available():\...
trial_gpt4o_0
{ "original_instruction": "### MPS Backend with PyTorch\n\nIn this task, you will demonstrate your understanding of utilizing the MPS backend for GPU computations in PyTorch. You will need to implement functions that verify the availability of the MPS device, perform tensor operations on the MPS device, and compare t...
0.499561
Docs: Pytorch_11036
C
[ "check_mps_availability", "perform_mps_tensor_operations", "compare_cpu_mps" ]
3
[ [ "compare_cpu_mps", "check_mps_availability" ], [ "perform_mps_tensor_operations", "check_mps_availability" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
c003594a4c4e32e4bad6b9398b4be548e92c775b
29ceb194c55c88abd06ca83ca1909b42cd3c87bf
v1.0
complete
Docs
Docs: Python310_11267_C
import asyncio import random from typing import List async def async_task_scheduler(n: int) -> List[str]: """Schedules and manages multiple asynchronous tasks using asyncio futures. Args: n (int): Number of asynchronous tasks to schedule. Returns: List[str]: A list of strings, where each stri...
import asyncio import random from typing import List async def simulate_task(fut: asyncio.Future, delay: int, result: str) -> None: await asyncio.sleep(delay) fut.set_result(result) async def async_task_scheduler(n: int) -> List[str]: loop = asyncio.get_running_loop() futures = [] for i in ra...
import pytest import asyncio from unittest.mock import patch from solution import async_task_scheduler @pytest.mark.asyncio async def test_async_task_scheduler(): # Test the function with a defined number of tasks n = 5 results = await async_task_scheduler(n) assert len(results) == n for i in rang...
[]
[ 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 simulate_task(fut: asyncio.Future, delay: int, result: str) -> None:\n await asyncio.sleep(delay)...
trial_gpt4o_2
{ "original_instruction": "**Objective:**\nImplement a function using `asyncio` futures to simulate an asynchronous task scheduler.\n\n**Problem Statement:**\n\nYou need to write a function `async_task_scheduler` that schedules and manages multiple asynchronous tasks using `asyncio` futures. Each task should simulate...
0.585632
Docs: Python310_11267
C
[ "simulate_task", "async_task_scheduler" ]
2
[ [ "async_task_scheduler", "simulate_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c4ce8b477a4a6e9cd7da4ddb05f21249890e42a3
7bca226875f753ed3374df0b80fc8dcf5acb3e67
v1.0
complete
Docs
Docs: Python310_9993_C
def secure_extract_tar(tar_path: str, extract_path: str) -> None: """ Securely extract files from a tar archive to the given directory. Args: tar_path (str): The path to the tar archive file to extract. extract_path (str): The destination directory where the files will be extracted. ...
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": "Securely Extracting Files from a Tar Archive\n\nYou 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 arc...
0.670614
Docs: Python310_9993
C
[ "is_within_directory", "secure_extract_tar" ]
2
[ [ "secure_extract_tar", "is_within_directory" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b51978efd91a54a77551e07ef80543ca6db8932f
d21c4b91e6772c17e7446c87135a9f324f6ba2f5
v1.0
complete
Docs
Docs: Python310_10239_C
import asyncio from typing import List, Tuple async def task_dispatcher(tasks: List[Tuple[int, str]], num_workers: int) -> None: """ Asynchronous Task Dispatcher using `asyncio.Queue` This function manages and processes tasks concurrently using multiple worker tasks. Each task consists of a priority numbe...
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": "### Asynchronous Task Dispatcher using `asyncio.Queue`\n\n#### Problem Statement:\nYou 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 pri...
0.608529
Docs: Python310_10239
C
[ "worker", "task_dispatcher" ]
2
[ [ "task_dispatcher", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
578aa7ae6040c0953c06e106dc869a741ab478a5
019e1af6db06bae8a20a5bee4b9cd308adfb4390
v1.0
complete
Docs
Docs: Python310_9377_C
import asyncio async def handle_client(reader, writer): """ Handle a client connection, receive messages, simulate a delay, and echo the message back. """ pass async def run_server(host, port): """ Start an asyncio server that listens on the given host and port. Accepts connections and han...
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": "### Question\n\n**Title: Implement a Custom Asynchronous Server-Client Model using asyncio**\n\n**Difficulty: Advanced**\n\n**Objective:**\nYour task is to implement a custom server-client model using the `asyncio` module in Python. The server will handle multiple clients concurrently, echo...
0.653393
Docs: Python310_9377
C
[ "handle_client", "run_server", "run_client" ]
3
[ [ "run_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8b7b91ec5b343d14cbe58c0946c5dc6b05b85b78
16ca23cb4e887f2bb0581743401d6d4ec80ec46e
v1.0
complete
Docs
Docs: Python310_11194_C
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor def compute_sum_of_squares(numbers: list[int]) -> int: """ Compute the sum of the squares of each number in the list using both thread-based and process-based parallelism. >>> compute_sum_of_squares([1, 2, 3, 4, 5]) 55 >>> comp...
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor def compute_square(n): return n * n def sum_chunk(chunk): return sum(chunk) def compute_sum_of_squares(numbers): # Step 1: Use ThreadPoolExecutor to compute squares of each number with ThreadPoolExecutor() as executor: squ...
from solution import compute_sum_of_squares def test_compute_sum_of_squares_small_list(): numbers = [1, 2, 3, 4, 5] assert compute_sum_of_squares(numbers) == 55 def test_compute_sum_of_squares_large_list(): numbers = list(range(1000)) expected_sum = sum(x * x for x in numbers) assert compute_sum_o...
[ { "docstring": null, "function_declaration": "def compute_square(n):", "function_name": "compute_square", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def sum_chunk(chunk):", "function_name": "sum_chunk", "parameter_list": "(chunk)" }, { "docst...
[ 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 ThreadPoolExecutor, ProcessPoolExecutor\nimport math\n\ndef chunked_iterable(iterable, size):\n \"\"\"Helper function to split an iter...
trial_gpt4o_1
{ "original_instruction": "Your task is to implement a program that demonstrates the use of both thread-based and process-based parallelism to perform a computation-intensive task efficiently.\n\n#### Problem Statement\n\nYou are given a large list of numbers, which you need to process in two steps:\n1. **Step 1 - Th...
0.642062
Docs: Python310_11194
C
[ "compute_square", "sum_chunk", "compute_sum_of_squares" ]
3
[ [ "compute_sum_of_squares", "compute_square" ], [ "compute_sum_of_squares", "sum_chunk" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b75fdebdbea39ce1c80d4cdd428be8b61ffbe144
94998b4ccabb60ced2eea8b18d9ece6077a7bb50
v1.0
complete
Docs
Docs: Pytorch_10613_C
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 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": "#### Objective:\nImplement 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.\n\n#### ...
0.548369
Docs: Pytorch_10613
C
[ "init_rpc", "parameter_server", "trainer", "main" ]
4
[ [ "parameter_server", "init_rpc" ], [ "trainer", "init_rpc" ] ]
2
[]
false
[ "SimpleModel" ]
true
pytest
false
[ "torch" ]
false
efffff5af1a84ae56d7a0e0815b3e943d42b2d7b
598ac5b8cf8cdc9a05cd950862807415b7e15589
v1.0
complete
Docs
Docs: Python310_10112_C
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]: """ Process multiple asynchronous ...
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": "**Coding Assessment Question**\n\n### Objective:\nCreate an asynchronous Python program to manage multiple tasks and demonstrate an understanding of asyncio's concurrency, timeouts, and task cancellation handling.\n\n### Requirements:\nImplement an asynchronous function `process_tasks` that...
0.617807
Docs: Python310_10112
C
[ "worker", "process_tasks" ]
2
[ [ "process_tasks", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eae57f6b8a6628a3b800dc8f6dcc034869a6db4a
42abfdeee8d33687f92ff94abc17864f6abbd690
v1.0
complete
Docs
Docs: Python310_11345_C
from typing import List def process_item(data: int) -> int: """ Multiplies the input data by 2 and simulates a time-consuming task. >>> process_item(2) 4 >>> process_item(5) 10 >>> process_item(0) 0 >>> process_item(-3) -6 """ def process_data_in_parallel(data_list: List[int]) ...
from typing import List import time from concurrent.futures import ThreadPoolExecutor def process_item(data: int) -> int: """ Multiplies the input data by 2 and simulates a time-consuming task by sleeping for 1 second. """ time.sleep(1) # Simulating time-consuming task return data * 2 def process...
from solution import process_item, process_data_in_parallel def test_process_item(): assert process_item(2) == 4 assert process_item(5) == 10 assert process_item(0) == 0 assert process_item(-3) == -6 def test_process_data_in_parallel(): # Test with a list of positive integers assert process_da...
[ { "docstring": "Multiplies the input data by 2 and simulates a time-consuming task by sleeping for 1 second.", "function_declaration": "def process_item(data):", "function_name": "process_item", "parameter_list": "(data)" }, { "docstring": "Processes a list of integers in parallel using Thre...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef process_item(data: int) -> int:\n \"\"\"\n Multiplies the input dat...
trial_gpt4o_2
{ "original_instruction": "Title: Parallel Data Processing using Concurrent Execution\n\n## Background\n\nYou are tasked with designing a data processing system that efficiently handles large datasets by utilizing concurrent execution. You will implement a program that processes data in parallel using the provided `c...
0.696565
Docs: Python310_11345
C
[ "process_item", "process_data_in_parallel" ]
2
[ [ "process_data_in_parallel", "process_item" ] ]
1
[]
false
[]
false
pytest
true
[]
true
edb7db8b14163e4d5573c59a2d5fb880ea02554a
de02822604352a1e7fd8885c65e0066d5e966f8e
v1.0
complete
Docs
Docs: Python310_11364_C
import cProfile import pstats from typing import List def calculate_prime_factors(n: int) -> List[int]: """Returns a list of prime factors of the given integer n. >>> calculate_prime_factors(30) [2, 3, 5] >>> calculate_prime_factors(19) [19] >>> calculate_prime_factors(100) [2, 2, 5, 5] ...
import cProfile import pstats from typing import List def calculate_prime_factors(n: int) -> List[int]: """ Returns a list of prime factors of the given integer n. """ i = 2 factors = [] # Check for the number of times 2 divides n while n % i == 0: factors.append(i) n = n //...
from solution import calculate_prime_factors def test_calculate_prime_factors(): assert calculate_prime_factors(30) == [2, 3, 5] assert calculate_prime_factors(987654321) == [3, 3, 17, 17, 379721] assert calculate_prime_factors(19) == [19] assert calculate_prime_factors(100) == [2, 2, 5, 5] assert ...
[ { "docstring": "Returns a list of prime factors of the given integer n.", "function_declaration": "def calculate_prime_factors(n):", "function_name": "calculate_prime_factors", "parameter_list": "(n)" }, { "docstring": "Profiles the calculate_prime_factors function with the input value 98765...
[ 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 cProfile\nimport pstats\nfrom typing import List\n\ndef calculate_prime_factors(n: int) -> List[int]:\n \"\"\"\n Returns all prime factors of a given integ...
trial_gpt4o_2
{ "original_instruction": "**Question: Profiling Python Functions with cProfile**\n\nIn this assessment, you will demonstrate your understanding of the `cProfile` module by profiling a Python script and analyzing its performance data.\n\n### Task\n\n1. **Profile a Function**\n Write a Python function `calculate_pri...
0.574381
Docs: Python310_11364
C
[ "calculate_prime_factors", "profile_function", "analyze_profiling_result" ]
3
[ [ "profile_function", "calculate_prime_factors" ] ]
1
[]
false
[]
false
pytest
true
[]
true
66c57a06d5711dff473ba35bd94309cf7ecd2530
5c32ef7efd27a23642002ba2c2479afe4d1da035
v1.0
complete
Docs
Docs: Python310_10864_C
import sys def celsius_to_fahrenheit(celsius: float) -> float: pass def fahrenheit_to_celsius(fahrenheit: float) -> float: pass def celsius_to_kelvin(celsius: float) -> float: pass def kelvin_to_celsius(kelvin: float) -> float: pass def fahrenheit_to_kelvin(fahrenheit: float) -> float: pass de...
import sys def celsius_to_fahrenheit(celsius: float) -> float: return celsius * 9/5 + 32 def fahrenheit_to_celsius(fahrenheit: float) -> float: return (fahrenheit - 32) * 5/9 def celsius_to_kelvin(celsius: float) -> float: return celsius + 273.15 def kelvin_to_celsius(kelvin: float) -> float: return...
from solution import ( celsius_to_fahrenheit, fahrenheit_to_celsius, celsius_to_kelvin, kelvin_to_celsius, fahrenheit_to_kelvin, kelvin_to_fahrenheit, ) def test_celsius_to_fahrenheit(): assert celsius_to_fahrenheit(0) == 32 assert celsius_to_fahrenheit(100) == 212 def test_fahrenheit...
[ { "docstring": null, "function_declaration": "def celsius_to_fahrenheit(celsius):", "function_name": "celsius_to_fahrenheit", "parameter_list": "(celsius)" }, { "docstring": null, "function_declaration": "def fahrenheit_to_celsius(fahrenheit):", "function_name": "fahrenheit_to_celsiu...
[ 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\n\ndef celsius_to_fahrenheit(celsius: float) -> float:\n return celsius * 9 / 5 + 32\n \ndef fahrenheit_to_celsius(fahrenheit: float) -> float:\n re...
trial_gpt4o_6
{ "original_instruction": "#### Objective:\nDemonstrate your understanding of Python's `__main__` special name, writing idiomatic script code that can be used both as a standalone script and as an importable module.\n\n#### Problem Statement:\nYou are tasked with creating a Python module named `converter.py` that inc...
0.544769
Docs: Python310_10864
C
[ "celsius_to_fahrenheit", "fahrenheit_to_celsius", "celsius_to_kelvin", "kelvin_to_celsius", "fahrenheit_to_kelvin", "kelvin_to_fahrenheit", "main" ]
7
[ [ "fahrenheit_to_kelvin", "celsius_to_kelvin" ], [ "fahrenheit_to_kelvin", "fahrenheit_to_celsius" ], [ "kelvin_to_fahrenheit", "celsius_to_fahrenheit" ], [ "kelvin_to_fahrenheit", "kelvin_to_celsius" ] ]
4
[]
false
[]
false
pytest
true
[]
true
e4387c4b3ab52a5bf5fd7f9dfd4f8f9e4e607b61
da0bc10a48747c227fe6accfae38c7df6394eace
v1.0
complete
Docs
Docs: Python310_10665_C
import shelve def add_profile(shelf): """Add a new profile to the 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 emai...
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": "**Coding Assessment Question: Persistent User Profiles with Shelve**\n\n### Objective\n\nWrite 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 profile...
0.412592
Docs: Python310_10665
C
[ "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
f4ed00335ddf1b93e2ec933efa8ac423aacd792c
194b4fa37bc58ef5b09a93f0a7d87434ccd82b98
v1.0
complete
Docs
Docs: Pytorch_11627_C
import torch def dynamic_operations(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: """ Perform a concatenation of two tensors followed by a conditional operation. Args: - x (torch.Tensor): Input tensor 1. - y (torch.Tensor): Input tensor 2. Returns: - torch.Tensor: Result tensor after...
import torch import torch._dynamo def dynamic_operations(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: """ Perform a concatenation of two tensors followed by a conditional operation. Args: - x (torch.Tensor): Input tensor 1. - y (torch.Tensor): Input tensor 2. Returns: - torch.Tensor...
import pytest import torch from solution import dynamic_operations, verify_dynamic_shapes def test_dynamic_operations_concat_greater_than_two_rows(): x = torch.randn(2, 2) y = torch.randn(1, 2) result = dynamic_operations(x, y) expected = torch.cat([x, y]).mul(2) assert torch.equal(result, expected...
[ { "docstring": "Perform a concatenation of two tensors followed by a conditional operation.\n\nArgs:\n- x (torch.Tensor): Input tensor 1.\n- y (torch.Tensor): Input tensor 2.\n\nReturns:\n- torch.Tensor: Result tensor after conditional operations.", "function_declaration": "def dynamic_operations(x, y):", ...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\n\ndef dynamic_operations(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Perform a concatenation of two tensors followed by a conditio...
trial_gpt4o_8
{ "original_instruction": "### Problem: Implementing and Testing Dynamic Shapes in PyTorch\n\n#### Objective:\nYou are asked to implement a function that performs operations on dynamically shaped tensors and another function that verifies the correct functioning of dynamic shape handling using guards and symbolic siz...
0.465725
Docs: Pytorch_11627
C
[ "dynamic_operations", "verify_dynamic_shapes" ]
2
[ [ "verify_dynamic_shapes", "dynamic_operations" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
63ef751f864d2a4007c9d57d32ec4347e97f4685
5262ea54220c23aaa779848b458baed36489250f
v1.0
complete
Docs
Docs: Pytorch_10753_C
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: """ Increment the counter by n. """ self.counter += n def get_value(self) -> int: """...
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": "#### Title: Implement a Distributed Counter Using PyTorch RPC and RRef\n\n#### Objective:\nImplement 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 retrie...
0.459865
Docs: Pytorch_10753
C
[ "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
9ab67e49063985610ee111676ad51f9953a11cc5
59363883b68689b2293a9df7fbbfde8dcd966d36
v1.0
complete
Docs
Docs: Pytorch_10854_C
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' ...
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": "### Advanced PyTorch Optimization using MPS Environment Variables\n\nIn 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:\n\n1. **Model Training with Environment Varia...
0.45523
Docs: Pytorch_10854
C
[ "set_mps_environment_vars", "train_model" ]
2
[ [ "train_model", "set_mps_environment_vars" ] ]
1
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
ef196ff73504c6fca256b6ef3f5580fa9d7cb34b
79ad80e16c2642ff688f98d564bf4f598871dbc3
v1.0
complete
Docs
Docs: Python310_11573_C
def generate_squares(n: int): """ A generator function that yields the square of numbers from 1 to n. Parameters: n (int): The number of terms to generate. Yields: int: The square of the current number in the sequence. """ # Implement the generator logic here def sum_of_squares(n: int...
def generate_squares(n): """ A generator function that yields the square of numbers from 1 to n. Parameters: n (int): The number of terms to generate. Yields: int: The square of the current number in the sequence. """ for i in range(1, n + 1): yield i ** 2 def sum_of_squares(n...
from solution import generate_squares, sum_of_squares def test_generate_squares(): assert list(generate_squares(1)) == [1] assert list(generate_squares(2)) == [1, 4] assert list(generate_squares(3)) == [1, 4, 9] assert list(generate_squares(5)) == [1, 4, 9, 16, 25] def test_sum_of_squares(): asser...
[ { "docstring": "A generator function that yields the square of numbers from 1 to n.\n\nParameters:\nn (int): The number of terms to generate.\n\nYields:\nint: The square of the current number in the sequence.", "function_declaration": "def generate_squares(n):", "function_name": "generate_squares", ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def generate_squares(n):\n \"\"\"\n A generator function that yields the square of numbers from 1 to n.\n\n Parameters:\n n (int): The number of terms to ge...
trial_gpt4o_0
{ "original_instruction": "#### Objective\nThe goal of this assessment is to evaluate your understanding of Python generators and your ability to manipulate them effectively.\n\n#### Task\nImplement a function `sum_of_squares(n)` that generates and returns the sum of the squares of the first `n` natural numbers using...
0.737465
Docs: Python310_11573
C
[ "generate_squares", "sum_of_squares" ]
2
[ [ "sum_of_squares", "generate_squares" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0019ca901137765475e45a31014a670f08e594ed
43c0db126c2b4e69ce7a7e8adfaa5779ef6d25a2
v1.0
complete
Docs
Docs: Python310_11272_C
import asyncio from typing import List async def fetch_and_process_data(urls: List[str], timeout: float) -> None: """ Fetches data asynchronously from multiple URLs and processes them with appropriate exception handling. Args: - urls (List[str]): A list of URLs to fetch data from. - timeout (float...
import asyncio from typing import List async def fetch_data(url: str, timeout: float): try: await asyncio.sleep(timeout) print(f"Fetched data from {url}") except asyncio.TimeoutError: print(f"TimeoutError: Fetching data from {url} timed out.") except asyncio.CancelledError: ...
import asyncio import pytest from solution import fetch_and_process_data @pytest.mark.asyncio async def test_fetch_and_process_data_timeout(): urls = ["http://example.com/data1", "http://example.com/data2"] timeout = 0.5 # Simulate a timeout for asyncio.sleep await fetch_and_process_data(urls, timeout) @...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List\n\nasync def fetch_data(url: str, timeout: float):\n try:\n await asyncio.sleep(timeout)\n print(f\"Fetched dat...
trial_gpt4o_0
{ "original_instruction": "### Asynchronous Task and Exception Handling\n\n**Objective:**\n\nImplement an asynchronous function that performs multiple I/O operations and demonstrates comprehensive exception handling using the asyncio exceptions discussed above.\n\n**Task Description:**\n\nWrite an asynchronous functi...
0.53451
Docs: Python310_11272
C
[ "fetch_data", "fetch_and_process_data" ]
2
[ [ "fetch_and_process_data", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[]
true
87e7b833b6bbf0f0e7894d869b8ec2685198cbc1
c58a93febbe904592006b70c26fdd2d90df6321f
v1.0
complete
Docs
Docs: Python310_10420_C
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. """ pass def decompress_data(compressed_data: bytes) -> bytes: """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": "<|Analysis Begin|>\n\nThe provided documentation describes the `lzma` module in Python, which is used for data compression utilizing the LZMA algorithm. Key functionalities include:\n\n1. **Reading and writing compressed files** through the `lzma.open` function or using the `LZMAFile` class...
0.699446
Docs: Python310_10420
C
[ "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
51b1063f9814f15cb6e66f20a1717bbecd7c6653
90304a5477b2214b72aad9370db64dbb04d75a09
v1.0
complete
Docs
Docs: Python310_10972_C
import sys import getopt def parse_arguments(args: list) -> dict: """ Parse command line arguments. :param args: List of command-line arguments (excluding the script name). :return: Dictionary with parsed options. >>> parse_arguments(["-i", "input.txt", "-o", "output.txt", "-v"]) {'input': 'i...
import sys import getopt def parse_arguments(args): """ Parse command line arguments. :param args: List of command-line arguments (excluding the script name). :return: Dictionary with parsed options. """ options = { 'input': None, 'output': None, 'verbose': False, ...
import sys import pytest from solution import parse_arguments, print_usage def test_parse_arguments_with_all_options(): args = ["-i", "input.txt", "-o", "output.txt", "-v"] expected_output = { 'input': 'input.txt', 'output': 'output.txt', 'verbose': True, 'help': False } ...
[ { "docstring": "Parse command line arguments.\n\n:param args: List of command-line arguments (excluding the script name).\n:return: Dictionary with parsed options.", "function_declaration": "def parse_arguments(args):", "function_name": "parse_arguments", "parameter_list": "(args)" }, { "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 sys\nimport getopt\n\ndef parse_arguments(args):\n \"\"\"\n Parse command line arguments.\n\n :param args: List of command-line arguments (excluding the...
trial_gpt4o_0
{ "original_instruction": "**Command Line Argument Parser for a File Processor**\n\nYou are tasked with developing a command-line argument parser for a Python script that processes files. The script should accept the following options:\n\n1. **-i or --input**: Specifies the input file path (required).\n2. **-o or --o...
0.475695
Docs: Python310_10972
C
[ "parse_arguments", "print_usage" ]
2
[ [ "parse_arguments", "print_usage" ] ]
1
[]
false
[]
false
pytest
true
[]
true
298fa2fa14ac5fd78aac66779220d93c6d3e1c44
b452f297922f8ff1f64d4d09aea019f53175cf34
v1.0
complete
Docs
Docs: Python310_11289_C
def is_valid_float(num_str: str) -> bool: """ Check if the given string can be converted to a valid float. Input: num_str (str): A numeric string. Output: bool: True if valid float, False otherwise. """ pass def convert_to_float_object(num_str: str) -> float: """ Convert a valid numeric...
def is_valid_float(num_str: str) -> bool: """ Check if the given string can be converted to a valid float. Input: num_str (str): A numeric string. Output: bool: True if valid float, False otherwise. """ try: float(num_str) return True except ValueError: return False ...
from solution import is_valid_float, convert_to_float_object, float_info def test_is_valid_float(): assert is_valid_float("12.34") == True assert is_valid_float("0.001") == True assert is_valid_float("-123.456") == True assert is_valid_float("abc") == False assert is_valid_float("") == False as...
[ { "docstring": "Check if the given string can be converted to a valid float.\nInput: num_str (str): A numeric string.\nOutput: bool: True if valid float, False otherwise.", "function_declaration": "def is_valid_float(num_str):", "function_name": "is_valid_float", "parameter_list": "(num_str)" }, ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_valid_float(num_str: str) -> bool:\n \"\"\"\n Check if the given string can be converted to a valid float.\n Input: num_str (str): A numeric string.\n ...
trial_gpt4o_2
{ "original_instruction": "#### Objective:\nThe goal of this exercise is to create a series of functions that interact with floating-point objects in Python, utilizing provided C-API functions (simulated in the task) to manage and manipulate these objects effectively.\n\n#### Problem Statement:\nImplement a function ...
0.594172
Docs: Python310_11289
C
[ "is_valid_float", "convert_to_float_object", "float_info" ]
3
[ [ "convert_to_float_object", "is_valid_float" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e2a09e858a89168f0dc327ceebc6f7ffde7596f0
5836a834958580dad6d53a08ebffda9de68f86d2
v1.0
complete
Docs
Docs: Python310_11292_C
import asyncio from typing import List, Tuple, Any async def schedule_tasks(tasks: List[Tuple[str, Any]], timeout=None) -> List[Tuple[str, Any]]: """ Schedule multiple tasks concurrently and return their results. Args: tasks (List[Tuple[str, Any]]): A list of tuples where each tuple contains ...
import asyncio from typing import List, Tuple, Any async def run_task(coro, name, timeout=None): try: result = await asyncio.wait_for(coro, timeout) return (name, result) except asyncio.TimeoutError: return (name, "Timeout") async def schedule_tasks(tasks: List[Tuple[str, Any]], timeou...
import asyncio from solution import run_task, schedule_tasks async def task_duration(duration, result): await asyncio.sleep(duration) return result def test_run_task_complete(): coro = task_duration(1, "Completed") name = "Test_Task_Complete" result = asyncio.run(run_task(coro, name, timeout=3)) ...
[ { "docstring": null, "function_declaration": "def main():", "function_name": "main", "parameter_list": "()" } ]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def run_task(coro, name, timeout=None):\n \"\"\"\n Runs a single task and returns its result or timeout message.\n \"\"\"\n try:\n ...
trial_gpt4o_2
{ "original_instruction": "#### Task\n\nYou are tasked with implementing a simplified **asyncio-based task scheduler**. This scheduler should be capable of scheduling multiple tasks concurrently, handling task timeouts, and managing task cancellations. \n\nImplement the following three functions:\n\n1. **`async def s...
0.680446
Docs: Python310_11292
C
[ "run_task", "schedule_tasks", "main" ]
3
[ [ "schedule_tasks", "run_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
761a447b16f08090564021cdbe04b44b60f51990
e68a5344aac7b9887d219fa561230d5c668bcca1
v1.0
complete
Docs
Docs: Python310_11549_C
import asyncio from typing import List, Tuple async def fetch_data_in_parallel(sources: List[Tuple[str, int]]) -> List[str]: """ Fetches data from multiple sources in parallel and returns the results as they are fetched. Args: sources (List[Tuple[str, int]]): A list of tuples where each tuple contains...
import asyncio from typing import List, Tuple async def fetch_single_source(data: str, delay: int) -> str: """ Fetches data after a delay. """ await asyncio.sleep(delay) print(f"{data} fetched in {delay} seconds") return data async def fetch_data_in_parallel(sources: List[Tuple[str, int]]) -> ...
import asyncio from solution import fetch_data_in_parallel def test_fetch_data_in_parallel(): sources = [('data1', 2), ('data2', 3), ('data3', 1)] results = asyncio.run(fetch_data_in_parallel(sources)) assert results == ['data3', 'data1', 'data2'] def test_fetch_zero_delay(): sources = [('data1', 0), ...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1 ]
8
easy
1
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def fetch_data(source: Tuple[str, int]) -> str:\n data, delay = source\n await as...
trial_gpt4o_5
{ "original_instruction": "### Asyncio Futures: Task Scheduling and Management\n\nYou are tasked with creating a function that handles multiple asynchronous operations using `asyncio.Future` objects. The function will simulate fetching data from different sources, each with varying delay times. Your goal is to start ...
0.578508
Docs: Python310_11549
C
[ "fetch_single_source", "fetch_data_in_parallel" ]
2
[ [ "fetch_data_in_parallel", "fetch_single_source" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4b6941ea99b760d968ca9a4c72371e265f5038f0
06a568fee1d7095e740e7b086d7465f0bbf1a336
v1.0
complete
Docs
Docs: Python310_11686_C
def sample_function(): """ This function runs a sample computation (Fibonacci sequence calculation) to be used for profiling. """ import time def fibonacci(n): if n < 0: raise ValueError("Input should be a non-negative integer") elif n == 0: return 0 ...
def sample_function(): import time def fibonacci(n): if n < 0: raise ValueError("Input should be a non-negative integer") elif n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) start_time = tim...
def test_profile_function(): profile_function() # We can't assert specific values in the test for profiling output, # as the output depends on runtime, environment, and is meant for human analysis. # The aim here is to ensure that `profile_function` runs without errors.
[ { "docstring": null, "function_declaration": "def sample_function():", "function_name": "sample_function", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def profile_function():", "function_name": "profile_function", "parameter_list": "()" }, { "d...
[ 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": "def sample_function():\n import time\n def fibonacci(n):\n if n < 0:\n raise ValueError(\"Input should be a non-negative integer\")\n eli...
trial_gpt4o_5
{ "original_instruction": "### Profiling Functions in Python\n\nIn this assessment, you will demonstrate your understanding of Python's `cProfile` and `pstats` modules by profiling a provided function and analyzing the results.\n\n#### Objective\nYou need to:\n1. Profile a given function using the `cProfile` module.\...
0.539872
Docs: Python310_11686
C
[ "sample_function", "profile_function" ]
2
[ [ "profile_function", "sample_function" ] ]
1
[]
false
[]
false
pytest
false
[]
true
1e5970e0a9d08b7b7d8cb08db0448708181b8a29
8689f0ed0c9f0be354a9943d5ffe006a717748f2
v1.0
complete
Docs
Docs: Python310_10346_C
import asyncio import contextvars from random import randint class RequestContext: """Class to handle creation and management of context variables for request_id and user_id.""" request_id: contextvars.ContextVar[str] = contextvars.ContextVar('request_id', default=None) user_id: contextvars.ContextVar[str...
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": "### Understanding Context Variables and Asynchronous Context Management\n\n#### Problem Statement\n\nYou 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,...
0.510705
Docs: Python310_10346
C
[ "log_request", "handle_request", "main" ]
3
[ [ "handle_request", "log_request" ] ]
1
[]
false
[ "RequestContext" ]
true
pytest
true
[]
true
acaf5a5cdcc01170ef558112786b6b2a8b9176e4
4390d09909a0438aef57116797408b525771c08a
v1.0
complete
Docs
Docs: Seaborn_11550_C
import seaborn as sns import matplotlib.pyplot as plt def create_custom_palette(): """ Creates a custom seaborn color palette by combining predefined palettes. Returns: custom_palette (list): List of colors in the palette. """ # Implement this function to combine predefined seaborn pal...
import seaborn as sns import matplotlib.pyplot as plt def create_custom_palette(): """ Creates a custom seaborn color palette by combining predefined palettes. Returns: custom_palette (list): List of colors in the palette. """ palette1 = sns.color_palette("Set3", 3) palette2 = sns....
from solution import create_custom_palette, plot_with_custom_palette, convert_palette_to_hex import seaborn as sns import matplotlib.pyplot as plt def test_create_custom_palette(): palette = create_custom_palette() assert isinstance(palette, list) assert len(palette) == 5 # Should create a palette with ex...
[ { "docstring": "Creates a custom seaborn color palette by combining predefined palettes.\n\nReturns:\n custom_palette (list): List of colors in the palette.", "function_declaration": "def create_custom_palette():", "function_name": "create_custom_palette", "parameter_list": "()" }, { "doc...
[ 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 seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef create_custom_palette():\n \"\"\"\n Creates a custom seaborn color palette by combining elements fro...
trial_gpt4o_6
{ "original_instruction": "### Question: Advanced Color Palettes with Seaborn\n\n**Objective**: \nDemonstrate your understanding of seaborn color palettes by generating various types of color palettes and utilizing them in plots.\n\n**Task**:\n1. Implement a function `create_custom_palette()` that returns a customize...
0.758851
Docs: Seaborn_11550
C
[ "create_custom_palette", "plot_with_custom_palette", "convert_palette_to_hex" ]
3
[ [ "plot_with_custom_palette", "create_custom_palette" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "seaborn" ]
false
729d67d59e69fc937fad60eaf32a6295b0867237
09cf66b9ea6bce1c3dcbcc0fb0c0cd460af25a72