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_12094_C
import random import timeit def merge_sort(arr): """Implements the merge sort algorithm.""" pass def quick_sort(arr): """Implements the quick sort algorithm.""" pass def generate_random_list(size, min_value, max_value): """Generates a list of random integers.""" pass def main(): """Runs ...
import random import timeit def merge_sort(arr): """Implements the merge sort algorithm.""" if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right) def merge(left, right): result = [] i = j = 0 ...
from solution import merge_sort, quick_sort, generate_random_list def test_merge_sort_empty_list(): assert merge_sort([]) == [] def test_merge_sort_single_element(): assert merge_sort([1]) == [1] def test_merge_sort_multiple_elements(): assert merge_sort([3, 1, 4, 1, 5, 9, 2, 6, 5]) == [1, 1, 2, 3, 4, 5,...
[ { "docstring": "Implements the merge sort algorithm.", "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge(left, right):", "function_name": "merge", "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 random\nimport timeit\n\ndef merge_sort(arr):\n if len(arr) <= 1:\n return arr\n\n def merge(left, right):\n sorted_arr = []\n left_id...
trial_gpt4o_2
{ "original_instruction": "**Coding Assessment Question: Performance Evaluation of Sorting Algorithms**\n\n**Objective:**\nThe objective of this task is for you to implement and compare the performance of two different sorting algorithms: Merge Sort and Quick Sort. You will use Python's `timeit` module to measure and...
0.658294
Docs: Python310_12094
C
[ "merge_sort", "merge", "quick_sort", "generate_random_list", "main" ]
5
[ [ "merge_sort", "merge" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ffe4610e1ee78933b350c3dd5997d58eec6c90f6
d4a66fd14f37fce0439fbd65ba2272fa417ec35b
v1.0
complete
Docs
Docs: Python310_11771_C
import tkinter as tk from tkinter import font def apply_font(sample_text, font_family, font_size, font_weight, font_style): """ Apply the selected font settings to the sample text area. This function takes the sample text widget, the selected font family, size, weight (bold/normal), and style (italic/roman...
import tkinter as tk from tkinter import font def apply_font(sample_text, font_family, font_size, font_weight, font_style): try: size = int(font_size.get()) except ValueError: size = 10 # default font size font_conf = { "family": font_family.get(), "size": size, "we...
import pytest from unittest.mock import MagicMock, patch import tkinter as tk from tkinter import font from solution import apply_font @pytest.fixture def mocked_widgets(): sample_text = MagicMock() font_family = MagicMock() font_family.get.return_value = "Courier" font_size = MagicMock() font_size...
[ { "docstring": null, "function_declaration": "def apply_font(sample_text, font_family, font_size, font_weight, font_style):", "function_name": "apply_font", "parameter_list": "(sample_text, font_family, font_size, font_weight, font_style)" }, { "docstring": null, "function_declaration": ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import tkinter as tk\nfrom tkinter import font\n\ndef apply_font_settings(display_label, font_settings):\n \"\"\"\n Apply the font settings to the display label.\...
trial_gpt4o_9
{ "original_instruction": "You are tasked with creating a Python GUI application using the `tkinter.font` module to handle font customization. Your application should allow users to select a font family, size, weight, and style for a text display. You need to implement the following features:\n\n1. A drop-down menu f...
0.352833
Docs: Python310_11771
C
[ "apply_font", "setup_app" ]
2
[ [ "setup_app", "apply_font" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bd218276e880d7fee297e54fb3e55b4fec56ecce
e72d037601396c63369f16fe38e24ec174146140
v1.0
complete
Docs
Docs: Scikit_11512_C
import numpy as np def manhattan_distance(a: np.ndarray, b: np.ndarray) -> float: """ Returns the Manhattan distance between two 1D numpy arrays a and b. >>> manhattan_distance(np.array([1, 2]), np.array([3, 4])) 4 >>> manhattan_distance(np.array([2, 3]), np.array([2, 3])) 0 """ def linear...
import numpy as np def manhattan_distance(a, b): """ Returns the Manhattan distance between two 1D numpy arrays a and b. """ return np.sum(np.abs(a - b)) def linear_kernel(a, b): """ Returns the linear kernel (dot product) between two 1D numpy arrays a and b. """ return np.dot(a, b) ...
import numpy as np import pytest from sklearn.metrics import pairwise_distances from sklearn.metrics.pairwise import pairwise_kernels from solution import manhattan_distance, linear_kernel, pairwise_manhattan_distances, pairwise_linear_kernels # Example dataset X = np.array([[2, 3], [3, 5], [5, 8], [1, 0], [2, 1]]) d...
[ { "docstring": "Returns the Manhattan distance between two 1D numpy arrays a and b.", "function_declaration": "def manhattan_distance(a, b):", "function_name": "manhattan_distance", "parameter_list": "(a, b)" }, { "docstring": "Returns the linear kernel (dot product) between two 1D numpy arr...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef manhattan_distance(a, b):\n \"\"\"\n Computes the Manhattan distance between two 1D numpy arrays a and b.\n \"\"\"\n return np.sum...
trial_gpt4o_1
{ "original_instruction": "**Custom Distance Metric and Kernel Matrix Calculation**\n\n### Objective:\nImplement a custom Manhattan distance metric and a custom Linear kernel function, then compute the pairwise distance and kernel matrices for given datasets and verify these calculations against scikit-learn's built-...
0.625932
Docs: Scikit_11512
C
[ "manhattan_distance", "linear_kernel", "pairwise_manhattan_distances", "pairwise_linear_kernels" ]
4
[ [ "pairwise_linear_kernels", "linear_kernel" ], [ "pairwise_manhattan_distances", "manhattan_distance" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
d30d31c4610eb5eae737cde7dec7251dcd9809ff
eb71092f05b33dfc948ac455d27688ea9ca450f7
v1.0
complete
Docs
Docs: Pytorch_11493_C
import torch import matplotlib.pyplot as plt from typing import List def apply_window_and_fft(signal: torch.Tensor, window_function: str) -> torch.Tensor: """ Applies a specified window function to the input signal and performs a Fast Fourier Transform (FFT). Args: signal (torch.Tensor): 1D in...
import torch import torch.fft import matplotlib.pyplot as plt import numpy as np def apply_window_and_fft(signal: torch.Tensor, window_function: str) -> torch.Tensor: """ Applies a specified window function to the input signal and performs a Fast Fourier Transform (FFT). Args: signal (torch.Te...
import torch from solution import apply_window_and_fft def test_apply_window_and_fft_hann(): signal = torch.sin(torch.linspace(0, 2 * torch.pi * 5, 500)) spectrum = apply_window_and_fft(signal, 'hann') assert len(spectrum) == len(signal) assert torch.max(spectrum).item() > 0 def test_apply_window_and_...
[ { "docstring": "Applies a specified window function to the input signal and performs a Fast Fourier Transform (FFT).\n\nArgs:\n signal (torch.Tensor): 1D input signal tensor.\n window_function (str): Name of the window function.\n\nReturns:\n torch.Tensor: Magnitude spectrum of the transformed signal."...
[ 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\nimport torch.fft\nimport matplotlib.pyplot as plt\nfrom typing import List\n\ndef apply_window_and_fft(signal: torch.Tensor, window_function: str) -> torc...
trial_gpt4o_2
{ "original_instruction": "**Problem Statement:**\n\nYou are given a 1D signal represented as a PyTorch tensor. Your task is to apply different window functions from the `torch.signal.windows` module to this signal and analyze their effects on the signal by performing a Fast Fourier Transform (FFT). After applying ea...
0.646534
Docs: Pytorch_11493
C
[ "apply_window_and_fft", "compare_window_functions" ]
2
[ [ "compare_window_functions", "apply_window_and_fft" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "torch" ]
false
e933ae8ec40792d0904611b0d6982ec26f38f405
e9de144f0826afc5c7049da32e4284c52f4dc5c2
v1.0
complete
Docs
Docs: Flask_12044_C
import os import secrets import subprocess def build_application(): """ Builds the Flask application into a distribution file using the build tool. """ # Add code here to build the application def initialize_database(): """ Initializes the database for the Flask application. """ # Add ...
import os import secrets import subprocess def build_application(): """ Builds the Flask application into a distribution file using the build tool. """ subprocess.run(['pip', 'install', 'build'], check=True) subprocess.run(['python', '-m', 'build'], check=True) print("Application built successf...
import os import secrets from solution import configure_application, build_application, initialize_database, run_application from unittest.mock import patch, mock_open, call def test_generate_secret_key(): secret_key = secrets.token_urlsafe(32) assert len(secret_key) > 0 @patch('builtins.open', new_callable=m...
[ { "docstring": "Builds the Flask application into a distribution file using the build tool.", "function_declaration": "def build_application():", "function_name": "build_application", "parameter_list": "()" }, { "docstring": "Initializes the database for the Flask application.", "functio...
[ 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 os\nimport subprocess\nimport secrets\n\ndef build_application():\n \"\"\"\n Build the Flask application to create a .whl distribution file.\n \"\"\"\n ...
trial_gpt4o_3
{ "original_instruction": "### Flask Deployment Challenge\n\nYou have developed a simple Flask application and now it's time to deploy it to a production environment. Your task is to write a script that handles the following deployment steps:\n\n1. **Build the Application**:\n - Create a distribution (`.whl`) file ...
0.561978
Docs: Flask_12044
C
[ "build_application", "initialize_database", "configure_application", "run_application", "deploy" ]
5
[ [ "deploy", "build_application" ], [ "deploy", "configure_application" ], [ "deploy", "initialize_database" ], [ "deploy", "run_application" ] ]
4
[]
false
[]
false
pytest
true
[]
true
2a514f74445cd57a7af6c75990c5d0684c29973a
89759dfb6c47503b6299bf450b9579fc4b721d74
v1.0
complete
Docs
Docs: Python310_11755_C
def custom_encode(input_string: str, quotetabs: bool = False, header: bool = False) -> str: """ Encode a plain input string into a quoted-printable format with the following constraints: - Non-printable characters (ASCII code < 32 and > 126) should be represented in the form `=XY`, where `XY` is the hexade...
def _to_hex(value: int) -> str: return f'={value:02X}' def custom_encode(input_string: str, quotetabs: bool = False, header: bool = False) -> str: encoded_chars = [] for char in input_string: ascii_code = ord(char) if header and char == ' ': encoded_chars.append('_') eli...
from solution import custom_encode, custom_decode def test_custom_encode_basic(): assert custom_encode("Hello World!") == 'Hello World!' def test_custom_encode_non_printable(): assert custom_encode("Hello\nWorld!") == 'Hello=0AWorld!' def test_custom_encode_space_end_line(): assert custom_encode("Hello W...
[ { "docstring": null, "function_declaration": "def _to_hex(value):", "function_name": "_to_hex", "parameter_list": "(value)" }, { "docstring": null, "function_declaration": "def custom_encode(input_string, quotetabs=False, header=False):", "function_name": "custom_encode", "parame...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def custom_encode(input_string: str, quotetabs: bool = False, header: bool = False) -> str:\n encoded_chars = []\n for i, char in enumerate(input_string):\n ...
trial_gpt4o_2
{ "original_instruction": "### Quoted-Printable Encoding/Decoding Challenge\n\nYou are provided with several utility functions within the `quopri` module in Python, which helps encode and decode MIME quoted-printable data. Your task is to implement a custom encoder and decoder for quoted-printable data with the follo...
0.656188
Docs: Python310_11755
C
[ "_to_hex", "custom_encode", "custom_decode" ]
3
[ [ "custom_encode", "_to_hex" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1976734fdccb88d1bf44b8e005f7b161c7cc3553
0601c7389ed968a1c63a2fa155bf18e8b4b1587f
v1.0
complete
Docs
Docs: Python310_11827_C
from typing import Type, List import warnings def custom_warn(message: str, category: Type[Warning], stacklevel: int = 1) -> None: """ Issues a warning with the specified message, category, and stacklevel. >>> with warnings.catch_warnings(record=True) as w: ... warnings.simplefilter("always") ....
import warnings from typing import Type, List def custom_warn(message: str, category: Type[Warning], stacklevel: int = 1) -> None: """ Issues a warning with the specified message, category, and stacklevel. """ warnings.warn(message, category, stacklevel=stacklevel) class SuppressWarnings: """ ...
from solution import custom_warn, SuppressWarnings, test_warnings def test_custom_warn(): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") custom_warn("Test deprecation warning.", DeprecationWarning, stacklevel=2) assert len(w) == 1 assert issubclass(w...
[]
[ 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 warnings\nfrom typing import Type, List\n\ndef custom_warn(message: str, category: Type[Warning], stacklevel: int = 1) -> None:\n \"\"\"\n Issues a warning...
trial_gpt4o_0
{ "original_instruction": "You are working on a Python project that involves updating an old codebase. This codebase uses several deprecated methods and you need to ensure that all deprecations are handled properly without overwhelming the standard output with warning messages during execution. You also need to ensur...
0.557481
Docs: Python310_11827
C
[ "custom_warn", "test_warnings" ]
2
[ [ "test_warnings", "custom_warn" ] ]
1
[]
false
[ "SuppressWarnings" ]
true
pytest
true
[]
true
2e4a46ba96bc1a6b044d24db2eca2d8de3c6252d
d2eeaaa5099c9d392b0bf16fbc127a5e323f5197
v1.0
complete
Docs
Docs: Python310_11878_C
import multiprocessing from typing import List def compute_determinant(matrix: List[List[int]]) -> int: """ Computes the determinant of a 2x2 matrix. Parameters: matrix (List[List[int]]): A 2x2 matrix represented as a list of two lists, each containing two int...
import multiprocessing from typing import List def compute_determinant(matrix: List[List[int]]) -> int: """ Computes the determinant of a 2x2 matrix. Parameters: matrix (List[List[int]]): A 2x2 matrix represented as a list of two lists, each containing two int...
import pytest from multiprocessing import Queue from solution import compute_determinant, worker def test_compute_determinant(): assert compute_determinant([[1, 2], [3, 4]]) == -2 assert compute_determinant([[2, 0], [1, 2]]) == 4 assert compute_determinant([[0, 1], [1, 0]]) == -1 assert compute_determi...
[ { "docstring": "Computes the determinant of a 2x2 matrix.\n\nParameters:\n matrix (List[List[int]]): A 2x2 matrix represented as a list of two lists,\n each containing two integers.\n\nReturns:\n int: The determinant of the matrix.", "function_declaration": "def compute_de...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import multiprocessing\nfrom typing import List\n\ndef compute_determinant(matrix: List[List[int]]) -> int:\n \"\"\"\n Calculate the determinant of a 2x2 matrix.\...
trial_gpt4o_5
{ "original_instruction": "You are tasked to design and implement a Python program that calculates the determinants of multiple 2x2 matrices using multiple processes to expedite the computation. The goal is to demonstrate proficiency in creating and managing processes, sharing data between them, and coordinating thei...
0.559886
Docs: Python310_11878
C
[ "compute_determinant", "worker", "calculate_determinants" ]
3
[ [ "worker", "compute_determinant" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f902b1229f7d57602414856850f5cc18d2ccc89f
86242b9285da78abd3e0237008bade0e926160f8
v1.0
complete
Docs
Docs: Python310_11920_C
import glob from typing import List def list_all_files_with_pattern(root_dir: str, pattern: str) -> List[str]: """ Returns a list of all files in the root_dir that match the specified pattern. >>> root_dir = '/path/to/your/root' >>> pattern = '*.txt' >>> list_all_files_with_pattern(root_dir, patte...
import glob from typing import List def list_all_files_with_pattern(root_dir: str, pattern: str) -> List[str]: """ Returns a list of all files in the root_dir that match the specified pattern. """ return glob.glob(f"{root_dir}/**/{pattern}", recursive=True) def count_files_with_pattern(root_dir: str, ...
import os import tempfile from solution import list_all_files_with_pattern, count_files_with_pattern, escape_and_list_files_with_pattern def test_list_all_files_with_pattern(): with tempfile.TemporaryDirectory() as root_dir: # Create some test files open(os.path.join(root_dir, 'file1.txt'), 'w').cl...
[ { "docstring": "Returns a list of all files in the root_dir that match the specified pattern.", "function_declaration": "def list_all_files_with_pattern(root_dir, pattern):", "function_name": "list_all_files_with_pattern", "parameter_list": "(root_dir, pattern)" }, { "docstring": "Returns th...
[ 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 glob\nimport os\nfrom typing import List\n\ndef list_all_files_with_pattern(root_dir: str, pattern: str) -> List[str]:\n \"\"\"\n Returns a list of all fil...
trial_gpt4o_8
{ "original_instruction": "**Objective**: Demonstrate your understanding of the `glob` module by writing functions that make use of its capabilities.\n\n**Problem Statement**:\n\nYou are given a root directory path `\"root_dir\"` and different file patterns. Your task is to implement three functions:\n\n1. `list_all_...
0.746014
Docs: Python310_11920
C
[ "list_all_files_with_pattern", "count_files_with_pattern", "escape_and_list_files_with_pattern" ]
3
[ [ "count_files_with_pattern", "list_all_files_with_pattern" ] ]
1
[]
false
[]
false
pytest
true
[]
true
11d980b0c539bacf19568de68852de00ebe451a8
cc4d8b1207ff3d887572ca90c0f6aa582a2f24ae
v1.0
complete
Docs
Docs: Python310_11664_C
import asyncio async def run_server_client_interaction(port: int, message: str, client_count: int): """Simulates a basic server-client interaction using asyncio. Parameters: port (int): The port number on which the server will listen for incoming connections. message (str): The message that each c...
import asyncio async def handle_client(reader, writer): # Read the data sent by the client data = await reader.read(100) message = data.decode() # Simulate processing time await asyncio.sleep(2) # Send a response back to the client writer.write(data) await writer.drain() ...
import asyncio import pytest from solution import run_server_client_interaction @pytest.mark.asyncio async def test_single_client(): port = 8888 message = "Hello Server" client_count = 1 responses = await run_server_client_interaction(port, message, client_count) assert len(responses) == client_cou...
[]
[ 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 data = await reader.read(100)\n message = data.decode()\n print(f\"Received {message!r} from {writ...
trial_gpt4o_1
{ "original_instruction": "**Objective:**\nTo assess the student's understanding of asyncio task management, task synchronization, and exception handling.\n\n**Problem Statement:**\n\nYou are required to write an asyncio-based function that simulates a basic server-client interaction using TCP connections. The server...
0.564758
Docs: Python310_11664
C
[ "handle_client", "run_server", "client", "run_server_client_interaction" ]
4
[ [ "run_server", "handle_client" ], [ "run_server_client_interaction", "client" ], [ "run_server_client_interaction", "run_server" ] ]
3
[]
false
[]
false
pytest
true
[]
true
8b01f149dae91bc96acc29daee11d1090afb4064
3a558ac5ee44ec612251af734b11126e7b71038b
v1.0
complete
Docs
Docs: Python310_11095_C
import asyncio import contextvars client_addr_var = contextvars.ContextVar('client_addr') def render_goodbye() -> bytes: """ Get the client's address from the context variable and return a goodbye message. Returns: bytes: Goodbye message encoded in bytes. """ pass async def handle_reques...
import asyncio import contextvars client_addr_var = contextvars.ContextVar('client_addr') def render_goodbye() -> bytes: """ Get the client's address from the context variable and return a goodbye message. Returns: bytes: Goodbye message encoded in bytes. """ client_addr = client_addr...
import pytest import contextvars from solution import render_goodbye, handle_request, client_addr_var import asyncio from asyncio import StreamReader, StreamWriter def test_render_goodbye(): addr = ("127.0.0.1", 8081) token = client_addr_var.set(addr) greet_message = render_goodbye() assert g...
[ { "docstring": "Get the client's address from the context variable and return a goodbye message.\n\nReturns:\n bytes: Goodbye message encoded in bytes.", "function_declaration": "def render_goodbye():", "function_name": "render_goodbye", "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 asyncio\nimport contextvars\n\nclient_addr_var = contextvars.ContextVar('client_addr')\n\ndef render_goodbye() -> bytes:\n \"\"\"\n Get the client's addres...
trial_gpt4o_1
{ "original_instruction": "### Context Management in Asynchronous Programming\n\n**Objective**:\n\nWrite a function and a test suite to simulate an async server handling multiple clients using context variables to maintain client-specific state without interference.\n\n**Background**:\n\nYou are to implement a simple...
0.619089
Docs: Python310_11095
C
[ "render_goodbye", "handle_request", "main" ]
3
[ [ "handle_request", "render_goodbye" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5799e313302959474db9ffc377472ba9bf4533c9
c0df2d2af19e061ef66b2fef896415ba8e60e123
v1.0
complete
Docs
Docs: Python310_12176_C
def main_function(): """ Main function showcasing the complex call scenario. >>> main_function() """ try: func_a() except Exception as e: print("Exception in main_function:", e) def func_a(): """ Function A calling func_b and func_d. """ func_b() func_d() def func_b...
def main_function(): try: func_a() except Exception as e: print("Exception in main_function:", e) def func_a(): func_b() func_d() def func_b(): for i in range(3): try: func_c(i) except ValueError as e: print(f"Exception caught in func_b: {e}"...
def test_func_c_raises(): """ Test that func_c raises a ValueError when x is even. """ try: func_c(2) except ValueError as e: assert str(e) == "Intentional Error: 2 is even" def test_func_c_no_exception(): """ Test that func_c does not raise an error when x is odd. "...
[ { "docstring": null, "function_declaration": "def main_function():", "function_name": "main_function", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def func_a():", "function_name": "func_a", "parameter_list": "()" }, { "docstring": null, "fu...
[ 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": "# complex_call_scenario.py\n\ndef main_function():\n try:\n func_a()\n except Exception as e:\n print(\"Exception in main_function:\", e)\n\ndef fun...
trial_gpt4o_4
{ "original_instruction": "#### Objective:\nYou are tasked with creating a Python script that simulates a complex function call scenario. Additionally, you need to write a SystemTap script that traces and outputs the function call and return hierarchy for your Python script.\n\n#### Requirements:\n\n1. **Python Scrip...
0.549238
Docs: Python310_12176
C
[ "main_function", "func_a", "func_b", "func_c", "func_d", "func_e", "func_f" ]
7
[ [ "func_a", "func_b" ], [ "func_a", "func_d" ], [ "func_b", "func_c" ], [ "func_d", "func_e" ], [ "func_d", "func_f" ], [ "main_function", "func_a" ] ]
6
[]
false
[]
false
pytest
false
[]
true
d4f90cd0f8e8d6c0af5d16754849972edbeefe0a
cc36087d54db4cb259253f0dd63c0be973286bca
v1.0
complete
Docs
Docs: Python310_12269_C
import asyncio async def process_files(file_paths, timeout): """ Process multiple files concurrently by reading their content, turning all text to uppercase, and writing back to the files. Args: - file_paths (list of str): A list of file paths to process. - timeout (float): The maximum amo...
import asyncio import os async def process_file(file_path, timeout): try: # Read file contents async with aiofiles.open(file_path, 'r') as f: content = await f.read() # Simulate processing delay await asyncio.sleep(0.1) # Simulate processing time # Con...
import asyncio import os import pytest from solution import process_files @pytest.fixture def setup_files(tmp_path): file1 = tmp_path / "file1.txt" file2 = tmp_path / "file2.txt" file3 = tmp_path / "file3.txt" file1.write_text("hello world") file2.write_text("asyncio is fun!") file3.write_...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiofiles\n\nasync def process_file(file_path, timeout):\n try:\n async with aiofiles.open(file_path, mode='r') as f:\n conte...
trial_gpt4o_9
{ "original_instruction": "### Asynchronous File Processing with Timeout and Shielding\n\n**Problem Statement:**\n\nYou are tasked with creating an asynchronous file processing system. The system will read multiple files concurrently, process their contents (in this case, converting all text to uppercase), and save t...
0.594335
Docs: Python310_12269
C
[ "process_file", "shield_file_processing", "process_files" ]
3
[ [ "process_files", "shield_file_processing" ], [ "shield_file_processing", "process_file" ] ]
2
[]
false
[]
false
pytest
true
[]
true
8a7c48063fd82da0fae7ba0b815aaba6e0b39f61
9bbd2a6a690fe5fee51231bd528f44e061069d5e
v1.0
complete
Docs
Docs: Python310_12882_C
import asyncio async def async_even_generator(limit): """ Asynchronous generator function that yields even numbers up to the specified limit. """ def collect_even_numbers(n): """ Synchronous function that collects all even numbers up to n using the async_even_generator. """ # Example Usag...
import asyncio async def async_even_generator(limit): """ Asynchronous generator function that yields even numbers up to the specified limit. """ for number in range(0, limit + 1, 2): await asyncio.sleep(0) # Simulate asynchronous behavior yield number def collect_even_numbers(n): ...
from solution import collect_even_numbers def test_collect_even_numbers(): # Test with a small limit assert collect_even_numbers(10) == [0, 2, 4, 6, 8, 10] # Test with a limit that is not an even number assert collect_even_numbers(15) == [0, 2, 4, 6, 8, 10, 12, 14] # Test with zero as lim...
[ { "docstring": "Synchronous function that collects all even numbers up to n using the async_even_generator.", "function_declaration": "def collect_even_numbers(n):", "function_name": "collect_even_numbers", "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 asyncio\n\nasync def async_even_generator(limit):\n for num in range(0, limit + 1, 2):\n yield num\n await asyncio.sleep(0) # Simulates an asyn...
trial_gpt4o_2
{ "original_instruction": "### Asynchronous Iterator Challenge\n\n#### Objective\nImplement a function `async_even_generator()` that provides an asynchronous iterator. The iterator should generate even numbers up to a given limit asynchronously. Additionally, implement a synchronous function `collect_even_numbers(n)`...
0.650786
Docs: Python310_12882
C
[ "async_even_generator", "collect_even_numbers" ]
2
[ [ "collect_even_numbers", "async_even_generator" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6b3b9a29e44c8768acf6a9916e901c8bf5435391
9a535bbb57402371f4597d41e30d6df82646c46e
v1.0
complete
Docs
Docs: Python310_11017_C
import sys import termios import tty import time import signal def enable_raw_mode(fd: int) -> None: """ Sets the terminal to raw mode. :param fd: File descriptor of the terminal """ pass def enable_cbreak_mode(fd: int) -> None: """ Sets the terminal to cbreak (canonical) mode. ...
import sys import termios import tty import time import signal def enable_raw_mode(fd: int) -> None: """ Sets the terminal to raw mode. :param fd: File descriptor of the terminal """ tty.setraw(fd) def enable_cbreak_mode(fd: int) -> None: """ Sets the terminal to cbreak (canonical) mo...
# Due to the interactive nature of terminal control and its requirement for manual interruption, # writing unit tests for the above behavior requires mocking and isn't feasible as traditional unit tests. # Therefore, we'll create pseudo-tests using mocks for demonstration, but in practice, # these would be confirmed ma...
[ { "docstring": "Sets the terminal to raw mode.\n\n:param fd: File descriptor of the terminal", "function_declaration": "def enable_raw_mode(fd):", "function_name": "enable_raw_mode", "parameter_list": "(fd)" }, { "docstring": "Sets the terminal to cbreak (canonical) mode.\n\n:param fd: File ...
[ 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\nimport termios\nimport tty\nimport time\nimport signal\n\ndef enable_raw_mode(fd: int) -> None:\n tty.setraw(fd)\n\ndef enable_cbreak_mode(fd: int) -> No...
trial_gpt4o_4
{ "original_instruction": "### Terminal Control with Python's `tty` Module\n\nYou are tasked with designing a small command-line tool in Python to interactively toggle the terminal mode between `raw` and `cbreak`. \n\n#### Requirements:\n1. **Functions to Implement:**\n - `enable_raw_mode(fd: int) -> None`: This f...
0.361755
Docs: Python310_11017
C
[ "enable_raw_mode", "enable_cbreak_mode", "reset_terminal_mode", "toggle_modes" ]
4
[ [ "toggle_modes", "enable_cbreak_mode" ], [ "toggle_modes", "enable_raw_mode" ], [ "toggle_modes", "reset_terminal_mode" ] ]
3
[]
false
[]
false
pytest
true
[]
true
0124748bc9c07833a64abfc4257212ae88096fb4
031bcc1b7c7d04f47b1f3ee775a9b97ffcbad655
v1.0
complete
Docs
Docs: Python310_12135_C
import cgi import cgitb import re import os cgitb.enable() # This line helps with debugging. UPLOAD_DIR = "uploads/" def validate_username(username): """ Ensure the username is alphanumeric and length is between 3 and 20 characters. >>> validate_username("ValidUser123") True >>> validate_username("u...
#!/usr/bin/env python3 import cgi import cgitb import re import os cgitb.enable() # This line helps with debugging. UPLOAD_DIR = "uploads/" def validate_username(username): # Ensure the username is alphanumeric and length is between 3 and 20 characters. return re.match(r'^[a-zA-Z0-9]{3,20}$', username) de...
import pytest import os from solution import validate_username, is_username_unique, save_username def setup_module(module): # Setup code (similar to a fixture in pytest) if os.path.exists("usernames.txt"): os.remove("usernames.txt") def teardown_module(module): if os.path.exists("usernames.txt"): ...
[ { "docstring": null, "function_declaration": "def validate_username(username):", "function_name": "validate_username", "parameter_list": "(username)" }, { "docstring": null, "function_declaration": "def is_username_unique(username, datafile='usernames.txt'):", "function_name": "is_us...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "#!/usr/bin/env python3\n\nimport cgi\nimport cgitb\nimport re\nimport os\n\ncgitb.enable() # This line helps with debugging.\n\nUPLOAD_DIR = \"uploads/\"\n\ndef valida...
trial_gpt4o_0
{ "original_instruction": "**Problem Statement: Building a Secure CGI Script for User Registration**\n\nYou are tasked with creating a CGI script for a user registration form. The form is expected to gather the following details from the users:\n1. Username (must be unique)\n2. Email\n3. Password\n4. Profile Picture ...
0.475919
Docs: Python310_12135
C
[ "validate_username", "is_username_unique", "save_username", "handle_form_submission", "generate_html_response", "main" ]
6
[ [ "handle_form_submission", "is_username_unique" ], [ "handle_form_submission", "save_username" ], [ "handle_form_submission", "validate_username" ] ]
3
[]
false
[]
false
pytest
true
[]
true
850952d1029621ca488fee9d6014544518355d59
8d2675f4d9233aea73371a8904fafd022907f784
v1.0
complete
Docs
Docs: Pytorch_12226_C
import torch import numpy as np import random from torch.utils.data import DataLoader, TensorDataset def seed_all(seed): """ Set seeds for reproducibility in PyTorch, NumPy and Python's random module. """ torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) torch.backends.cudnn.be...
import torch import numpy as np import random from torch.utils.data import DataLoader, TensorDataset def seed_all(seed): torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True def seed_worker(worker_id): w...
from solution import reproducible_pytorch_app def test_tensor_size_5(): reproducible_pytorch_app(5) def test_tensor_size_10(): reproducible_pytorch_app(10) def test_reproducibility_check(): seed = 0 torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) torch.backends.cudnn.benchm...
[ { "docstring": null, "function_declaration": "def seed_all(seed):", "function_name": "seed_all", "parameter_list": "(seed)" }, { "docstring": null, "function_declaration": "def seed_worker(worker_id):", "function_name": "seed_worker", "parameter_list": "(worker_id)" }, { ...
[ 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 numpy as np\nimport random\nfrom torch.utils.data import DataLoader, TensorDataset\n\ndef seed_all(seed):\n torch.manual_seed(seed)\n np.rand...
trial_gpt4o_1
{ "original_instruction": "#### Objective\nYour task is to create a PyTorch-based application that demonstrates understanding and implementation of reproducibility in every step. This will test your knowledge of handling randomness and ensuring consistent results across multiple runs.\n\n#### Problem Statement\nCreat...
0.64646
Docs: Pytorch_12226
C
[ "seed_all", "seed_worker", "reproducible_pytorch_app" ]
3
[ [ "reproducible_pytorch_app", "seed_all" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "torch" ]
false
f0afb01753aac334603cab85fce82c58b27201be
230943a6798cb79c26a405538c273ef32360728a
v1.0
complete
Docs
Docs: Scikit_10827_C
import numpy as np from sklearn.neighbors import KNeighborsClassifier def nearest_neighbors_classifier(X_train, y_train, X_test, n_neighbors, algorithm): """ Implements a nearest neighbors classifier with specified algorithm. Args: X_train (numpy.ndarray): A 2D array of shape (n_samples, 2) represent...
import numpy as np from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from time import time import random def nearest_neighbors_classifier(X_train, y_train, X_test, n_neighbors, algorithm): """ Implements a nearest neighbors classifier with specified algorit...
import pytest import numpy as np from solution import nearest_neighbors_classifier def test_nearest_neighbors_classifier_brute(): np.random.seed(0) X_train = np.random.rand(100, 2) * 100 y_train = np.random.randint(0, 3, 100) X_test = np.random.rand(10, 2) * 100 result = nearest_neighbors_classifie...
[]
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom time import time\nimport random\n\nde...
trial_gpt4o_0
{ "original_instruction": "**Problem Statement:**\n\nYou are provided with a dataset of points in a two-dimensional space and their respective class labels. Your task is to implement a nearest neighbors classifier using scikit-learn to predict the class labels for a new set of points. In addition, you need to explore...
0.627226
Docs: Scikit_10827
C
[ "nearest_neighbors_classifier", "evaluate_algorithms" ]
2
[ [ "evaluate_algorithms", "nearest_neighbors_classifier" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
192c31541b8489c9a6151eaf194b6ff130c95dc1
e9b703312d1ef67587e0d62bf4d09e24d8e279de
v1.0
complete
Docs
Docs: Python310_12149_C
from unittest.mock import patch def process_and_save_data(data): """ This function processes the input data (a dictionary), performs some calculations, and then saves the processed data using external services. Args: - data (dict): A dictionary containing raw data. Returns: - bool: True i...
def save_to_database(value): # Imagine this is an external service that saves data to a database pass def log(message): # Imagine this is an external service for logging messages pass def process_and_save_data(data): """ This function processes the input data (a dictionary), performs some calc...
from unittest.mock import patch from solution import process_and_save_data def test_successful_saving(): with patch('solution.save_to_database') as mock_save, \ patch('solution.log') as mock_log: mock_save.return_value = True result = process_and_save_data({'value': 5}) mock_save.a...
[ { "docstring": null, "function_declaration": "def save_to_database(value):", "function_name": "save_to_database", "parameter_list": "(value)" }, { "docstring": null, "function_declaration": "def log(message):", "function_name": "log", "parameter_list": "(message)" }, { "d...
[ 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 save_to_database(value):\n # Imagine this is an external service that saves data to a database\n pass\n\ndef log(message):\n # Imagine this is an external ...
trial_gpt4o_0
{ "original_instruction": "#### Objective:\nThe goal is to assess your ability to use the `unittest.mock` module for creating and using mock objects and making assertions about their interactions.\n\n#### Problem Statement:\n\nYou are developing a data processing pipeline for a software system, and you need to write ...
0.61523
Docs: Python310_12149
C
[ "save_to_database", "log", "process_and_save_data" ]
3
[ [ "process_and_save_data", "log" ], [ "process_and_save_data", "save_to_database" ] ]
2
[]
false
[]
false
pytest
true
[]
true
01f1e8002f31c06bc6f298d15ceb34c585d42ba3
9bc6c7d169240b032e6107d3ba069f887da08521
v1.0
complete
Docs
Docs: Python310_12443_C
import asyncio async def perform_task(task_id: int, duration: float) -> int: """ Simulates an asynchronous task with given task_id and duration. Args: task_id (int): The ID of the task. duration (float): The duration for which the task will run. Returns: int: The task_id upon comp...
import asyncio async def perform_task(task_id: int, duration: float) -> int: """ Simulates an asynchronous task with given task_id and duration. Args: task_id (int): The ID of the task. duration (float): The duration for which the task will run. Returns: int: The task_id upon comp...
from solution import run_task_manager import pytest def test_run_task_manager(): tasks = [(1, 1), (2, 2), (3, 0.5)] results = run_task_manager(tasks) # Since asyncio.gather keeps the order of the tasks as in the input # we expect results to be in order of task IDs assert results == [1, 2,...
[ { "docstring": "Runs the asynchronous task manager.\n\nArgs:\ntasks (list of tuples): Each tuple contains task_id and duration.\n\nReturns:\nlist of int: The task_ids of all completed tasks.", "function_declaration": "def run_task_manager(tasks):", "function_name": "run_task_manager", "parameter_lis...
[ 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 perform_task(task_id: int, duration: float) -> int:\n \"\"\"\n Simulates an asynchronous I/O operation.\n \n Args:\n task_id ...
trial_gpt4o_2
{ "original_instruction": "### Question: Building an Asynchronous Task Manager\n\nYou are tasked with building an asynchronous task manager using Python's `asyncio` library. Your manager will handle multiple tasks that simulate asynchronous I/O operations such as network requests or database queries. The goal is to i...
0.629395
Docs: Python310_12443
C
[ "perform_task", "task_manager", "run_task_manager" ]
3
[ [ "run_task_manager", "task_manager" ], [ "task_manager", "perform_task" ] ]
2
[]
false
[]
false
pytest
true
[]
true
217b7eeccb2dde381e75fc9cede9c631ab814efb
2ad31c6cebca41eff6a68bc85b68a9d9d62f9e84
v1.0
complete
Docs
Docs: Python310_12828_C
import asyncio import socket async def handle_client(client_socket): """ Handle client connections and respond with appropriate HTTP response. Args: client_socket (socket): The client's socket instance. """ pass async def run_server(host, port): """Run an asynchronous web server that handles ...
import asyncio import socket async def handle_client(client_socket): request = await asyncio.get_event_loop().sock_recv(client_socket, 1024) request_line = request.decode().splitlines()[0] method, path, _ = request_line.split() if method != 'GET': response = 'HTTP/1.1 405 Method Not Allowed\r\...
import asyncio import socket import pytest from solution import run_server @pytest.mark.asyncio async def test_server_responds_with_hello_world(): port = 9000 server_task = asyncio.create_task(run_server('127.0.0.1', port)) await asyncio.sleep(1) # Allow server some time to start reader, writer = aw...
[]
[ 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 socket\n\nasync def handle_client(client_socket):\n request = await asyncio.to_thread(client_socket.recv, 1024)\n request_line = request.de...
trial_gpt4o_2
{ "original_instruction": "**Networking and Interprocess Communication — Asynchronous Web Server**\n\n**Question:**\n\nYou are to implement a simple asynchronous web server using the `asyncio` and `socket` modules in Python. This server will accept incoming HTTP GET requests and respond with a simple HTML message. En...
0.620777
Docs: Python310_12828
C
[ "handle_client", "run_server" ]
2
[ [ "run_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7e81e5e733ecf9632a394d34162ed75a4888d6eb
c0d402724137016fe900f5f58e814991c7722c7d
v1.0
complete
Docs
Docs: Python310_12927_C
import asyncio async def delayed_result(delay: int, value: any) -> any: """Returns the value after a specified delay. >>> await delayed_result(1, 42) == 42 """ pass async def run_tasks(tasks: list[tuple[int, any]]) -> list[any]: """Runs multiple `delayed_result` tasks and returns their results. ...
import asyncio async def delayed_result(delay: int, value: any) -> any: """ Returns the value after a specified delay. Args: delay: The wait time in seconds. value: The value to be returned after the delay. """ await asyncio.sleep(delay) return value async def run_tasks(tasks:...
import pytest import asyncio from solution import delayed_result, run_tasks @pytest.mark.asyncio async def test_delayed_result(): result = await delayed_result(1, 42) assert result == 42 @pytest.mark.asyncio async def test_run_tasks(): tasks = [(1, 'task1'), (2, 'task2'), (3, 'task3')] results = await...
[ { "docstring": "Main function to create and run tasks.", "function_declaration": "def main():", "function_name": "main", "parameter_list": "()" } ]
[ 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 asyncio\n\nasync def delayed_result(delay, value):\n \"\"\"\n Returns the value after a specified delay.\n \"\"\"\n await asyncio.sleep(delay)\n r...
trial_gpt4o_2
{ "original_instruction": "### **Asyncio Futures Simulation with Task Management**\n\nIn this assessment, you are tasked with demonstrating your understanding of `asyncio` futures by implementing a simple asynchronous task management system using `asyncio.Future`.\n\n**Instructions**:\n1. **Create a Function `delayed...
0.722261
Docs: Python310_12927
C
[ "delayed_result", "run_tasks", "main" ]
3
[ [ "run_tasks", "delayed_result" ] ]
1
[]
false
[]
false
pytest
true
[]
true
70ecdb36af78d6a970a9b79861f2b95574f8b13c
12978364a937612b3338e9250709adf77c81e534
v1.0
complete
Docs
Docs: Python310_12791_C
from concurrent.futures import ThreadPoolExecutor from typing import List def parallel_square(numbers: List[int]) -> List[int]: """ Compute the squares of a list of integers concurrently using ThreadPoolExecutor. >>> parallel_square([1, 2, 3, 4, 5]) [1, 4, 9, 16, 25] >>> parallel_square([-1, -2, -3, -4...
from concurrent.futures import ThreadPoolExecutor from typing import List def square(n: int) -> int: return n * n def parallel_square(numbers: List[int]) -> List[int]: with ThreadPoolExecutor() as executor: results = list(executor.map(square, numbers)) return results
from solution import parallel_square def test_parallel_square_basic(): assert parallel_square([1, 2, 3, 4, 5]) == [1, 4, 9, 16, 25] def test_parallel_square_negative_numbers(): assert parallel_square([-1, -2, -3, -4, -5]) == [1, 4, 9, 16, 25] def test_parallel_square_mixed_numbers(): assert parallel_squa...
[ { "docstring": null, "function_declaration": "def square(n):", "function_name": "square", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def parallel_square(numbers):", "function_name": "parallel_square", "parameter_list": "(numbers)" } ]
[ 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 concurrent.futures import ThreadPoolExecutor\nfrom typing import List\n\ndef parallel_square(numbers: List[int]) -> List[int]:\n def square(n: int) -> int:\n ...
trial_gpt4o_2
{ "original_instruction": "## Coding Assessment Question\n\n### Context\nThe \"concurrent.futures\" module in Python allows for the execution of code in parallel using threads or processes. As a developer, you might need to perform multiple IO-bound or CPU-bound operations simultaneously to improve the performance of...
0.628382
Docs: Python310_12791
C
[ "square", "parallel_square" ]
2
[ [ "parallel_square", "square" ] ]
1
[]
false
[]
false
pytest
true
[]
true
43da4e4bb9c75fab1ab17e98a5a45a0d1d5d325e
cc4aac5b13e1beb91aebe072071f058acce6f0b7
v1.0
complete
Docs
Docs: Scikit_12537_C
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV from sklearn.metrics import make_scorer import numpy as np def custom_scorer(y_true, y_pred): """ Custom scoring function to calculate mean squared l...
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV from sklearn.metrics import make_scorer import numpy as np def custom_scorer(y_true, y_pred): """ Custom scoring function to calculate mean squared l...
from solution import custom_scorer, evaluate_model_with_custom_scorer, grid_search_with_custom_scorer import numpy as np def test_custom_scorer(): y_true = np.array([3, 5, 2.5, 7]) y_pred = np.array([2.5, 5, 4, 8]) expected_msle = np.mean((np.log1p(y_true) - np.log1p(y_pred)) ** 2) assert custom_scorer...
[ { "docstring": "Custom scoring function to calculate mean squared logarithmic error (MSLE).", "function_declaration": "def custom_scorer(y_true, y_pred):", "function_name": "custom_scorer", "parameter_list": "(y_true, y_pred)" }, { "docstring": "Evaluates a RandomForestRegressor model using ...
[ 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 sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\nfrom sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV\nfrom...
trial_gpt4o_1
{ "original_instruction": "### Custom Scoring Function and Model Evaluation with Cross-Validation\n\n#### Objective\nTo assess the students' understanding of custom scoring functions, cross-validation, and the use of advanced evaluation metrics in scikit-learn.\n\n#### Problem Statement\nYou are given a dataset `X` (...
0.753693
Docs: Scikit_12537
C
[ "custom_scorer", "evaluate_model_with_custom_scorer", "grid_search_with_custom_scorer" ]
3
[ [ "evaluate_model_with_custom_scorer", "custom_scorer" ], [ "grid_search_with_custom_scorer", "custom_scorer" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
8c48634f735dbef936fef6bd3b072024ff036d97
347f3eba35dfcdfbe2f85c294b26abe3be2d2da9
v1.0
complete
Docs
Docs: Python310_13193_C
import asyncio from typing import List, Tuple async def worker(name: str, queue: asyncio.PriorityQueue): while True: priority, task = await queue.get() print(f"Worker {name} is processing task: {task} with priority: {priority}") queue.task_done() await asyncio.sleep(0) # Simulating...
import asyncio from typing import List, Tuple async def worker(name: str, queue: asyncio.PriorityQueue): while True: priority, task = await queue.get() print(f"Worker {name} is processing task: {task} with priority: {priority}") queue.task_done() await asyncio.sleep(0) # Simulating...
import asyncio import pytest from solution import manage_tasks @pytest.mark.asyncio async def test_manage_tasks_order(): tasks = [(3, "Low priority task"), (1, "High priority task"), (2, "Medium priority task")] async def run_and_capture_output(): output = [] def mock_print(*args): ...
[]
[ 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\n\nasync def worker(worker_id: int, queue: asyncio.PriorityQueue):\n while True:\n priority, task = await queue...
trial_gpt4o_1
{ "original_instruction": "## Task\nImplement an asyncio-based task manager that handles tasks with different priorities using an `asyncio.PriorityQueue`. Your task manager should be capable of adding tasks with specified priorities, processing these tasks concurrently, and providing status updates.\n\n## Requirement...
0.600881
Docs: Python310_13193
C
[ "worker", "manage_tasks" ]
2
[ [ "manage_tasks", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bbbcbd443a53170402e184543091ed54cec8b9c7
79562b02afd9240556f7ab9e9edabf3a8b94933e
v1.0
complete
Docs
Docs: Pytorch_12633_C
import torch def check_simd_support(): """ Check if the machine supports AVX-512 or AMX instruction sets. Returns a dictionary with keys `avx512` and `amx` with corresponding boolean values. """ pass def optimized_matrix_multiplication(A, B): """ Perform matrix multiplication of two PyTor...
import subprocess import torch def check_simd_support(): def has_instruction(output, instruction): return instruction in output avx512_support = amx_support = False try: result = subprocess.check_output(['lscpu']).decode('utf-8') avx512_support = has_instruction(result, 'avx512')...
import torch from solution import check_simd_support, optimized_matrix_multiplication def test_check_simd_support_keys(): simd_support = check_simd_support() assert 'avx512' in simd_support assert 'amx' in simd_support assert isinstance(simd_support['avx512'], bool) assert isinstance(simd_support['...
[ { "docstring": null, "function_declaration": "def check_simd_support():", "function_name": "check_simd_support", "parameter_list": "()" }, { "docstring": "Perform matrix multiplication of two PyTorch tensors A and B.\nLeveraging any available SIMD instructions.", "function_declaration": ...
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport subprocess\n\ndef check_simd_support():\n \"\"\"\n Check if the machine supports AVX-512 or AMX instructions.\n Returns:\n A dictio...
trial_gpt4o_1
{ "original_instruction": "**Optimizing PyTorch Computation Using SIMD Instructions**\n\n### Objective:\nThe objective of this question is to assess your understanding of PyTorch and how to leverage SIMD instructions to optimize a computation task on x86 CPUs.\n\n### Problem Statement:\nYou are given a task to optimi...
0.561414
Docs: Pytorch_12633
C
[ "check_simd_support", "optimized_matrix_multiplication" ]
2
[ [ "optimized_matrix_multiplication", "check_simd_support" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
66635d16ee604c2281672885c0371ab30b03b2c3
f49e7042f439f9cef512ea92112f08a51caff300
v1.0
complete
Docs
Docs: Python310_12640_C
import imghdr def xyz_test(h, f): """ Test function for "xyz" format. """ if h[:3] == b'XYZ': return 'xyz' def add_xyz_test(): """ Adds the custom 'xyz' test to imghdr. """ imghdr.tests.append(xyz_test) def detect_image_type(file_path: str) -> str: """ Detects the type...
import imghdr def xyz_test(h, f): """ Test function for "xyz" format. """ if h[:3] == b'XYZ': return 'xyz' def add_xyz_test(): """ Adds the custom 'xyz' test to imghdr. """ imghdr.tests.append(xyz_test) def detect_image_type(file_path: str) -> str: """ Detects the type...
import os import pytest from solution import add_xyz_test, detect_image_type # Create test files for testing def setup_module(module): with open('test1.xyz', 'wb') as f: f.write(b'XYZcontent') with open('test2.png', 'wb') as f: f.write(b'\x89PNG\r\n\x1a\n') def teardown_module(module): os....
[ { "docstring": "Test function for \"xyz\" format.", "function_declaration": "def xyz_test(h, f):", "function_name": "xyz_test", "parameter_list": "(h, f)" }, { "docstring": "Adds the custom 'xyz' test to imghdr.", "function_declaration": "def add_xyz_test():", "function_name": "add_x...
[ 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 imghdr\n\ndef add_xyz_test():\n \"\"\"\n Adds a custom test to detect 'xyz' image format.\n \"\"\"\n def test_xyz(header, file):\n \"\"\"\n ...
trial_gpt4o_2
{ "original_instruction": "#### Objective\nWrite a function that extends the functionality of the `imghdr` module by adding a custom test to detect a specific image format that is not natively supported by `imghdr`.\n\n#### Problem Statement\nCreate a Python function that detects whether a file is of a custom image t...
0.529833
Docs: Python310_12640
C
[ "xyz_test", "add_xyz_test", "detect_image_type" ]
3
[ [ "add_xyz_test", "xyz_test" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f63b94d762bd4b05f944a054e5243998c65a99fb
bf842d10e4e48f8e65afbc05bee5d4982198a129
v1.0
complete
Docs
Docs: Python310_12559_C
def is_tuple(obj): """ Check if the object is a tuple. >>> is_tuple((1, 2, 3)) True >>> is_tuple([1, 2, 3]) False """ pass def is_exact_tuple(obj): """ Check if the object type is exactly tuple (not a subtype). >>> is_exact_tuple((1, 2, 3)) True >>> is_exact_tuple(MyTuple((1, 2...
def is_tuple(obj): """ Check if the object is a tuple. """ return isinstance(obj, tuple) def is_exact_tuple(obj): """ Check if the object type is exactly tuple (not a subtype). """ return type(obj) is tuple def create_and_populate_tuple(): """ Create a tuple of length 5, popula...
from solution import is_tuple, is_exact_tuple, create_and_populate_tuple, slice_tuple, Person def test_is_tuple(): assert is_tuple((1, 2, 3)) == True assert is_tuple([1, 2, 3]) == False def test_is_exact_tuple(): class MyTuple(tuple): pass assert is_exact_tuple((1, 2, 3)) == True assert i...
[]
[ 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 is_tuple(obj):\n \"\"\"\n Check if the object is a tuple.\n \"\"\"\n return isinstance(obj, tuple)\n\ndef is_exact_tuple(obj):\n \"\"\"\n Check if...
trial_gpt4o_0
{ "original_instruction": "### Python C API: Tuple and Struct Sequence Manipulation\n\nUsing the Python C API, write a Python program that accomplishes the following tasks:\n\n1. **Check Tuple Type**: \n Create a C function that checks whether a given Python object is a tuple and another that checks if it is exactl...
0.58518
Docs: Python310_12559
C
[ "is_tuple", "is_exact_tuple", "create_and_populate_tuple", "slice_tuple", "demonstrate" ]
5
[ [ "demonstrate", "create_and_populate_tuple" ], [ "demonstrate", "is_exact_tuple" ], [ "demonstrate", "is_tuple" ], [ "demonstrate", "slice_tuple" ] ]
4
[]
false
[ "Person" ]
true
pytest
true
[]
true
bb77592ca435c738ad9b74fc44b51576a765bddc
93e4de48c534e015ec11036eaf597a3dc108d7e1
v1.0
complete
Docs
Docs: Scikit_12534_C
def calculate_sparsity(X): """ Calculate the sparsity ratio of the input feature matrix X. Sparsity ratio is defined as the fraction of zero elements to the total elements. Parameters: X (np.ndarray): Input feature matrix Returns: float: Sparsity ratio """ # Implement the c...
import numpy as np import time from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def calculate_sparsity(X): """ Calculate the sparsity ratio of the input feature matrix X. Sparsity ratio is defined as the fraction of zero elements to the total elements. """ r...
import numpy as np from solution import calculate_sparsity, train_model, predict_performance, model_complexity_analysis, main def generate_dummy_data(n_samples=100, n_features=10): """ Generate dummy data for testing purposes. """ np.random.seed(42) X = np.random.randn(n_samples, n_features) y ...
[ { "docstring": "Calculate the sparsity ratio of the input feature matrix X.\nSparsity ratio is defined as the fraction of zero elements to the total elements.", "function_declaration": "def calculate_sparsity(X):", "function_name": "calculate_sparsity", "parameter_list": "(X)" }, { "docstrin...
[ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport time\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\nfrom scipy.sparse import csr_matrix\n\ndef ...
trial_gpt4o_4
{ "original_instruction": "### Question: Optimizing Machine Learning Model Performance\n\n#### Problem Statement:\nYou are given a high-dimensional dataset for a binary classification task. Your objective is to implement a machine learning pipeline using `scikit-learn` that:\n1. **Optimizes prediction latency** by ch...
0.577871
Docs: Scikit_12534
C
[ "calculate_sparsity", "train_model", "predict_performance", "model_complexity_analysis", "main" ]
5
[ [ "model_complexity_analysis", "predict_performance" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
322e4c99c336181bfecd442fcd93819a23a336f8
1ef958d27251a3b2f682664d83def2bc2448eddd
v1.0
complete
Docs
Docs: Python310_12942_C
import random import cProfile import pstats from pstats import SortKey def bubble_sort(arr): """Sort the array using bubble sort algorithm. >>> arr = [64, 34, 25, 12, 22, 11, 90] >>> bubble_sort(arr) >>> arr [11, 12, 22, 25, 34, 64, 90] """ # Your code here def merge_sort(arr): """Sort...
import random import cProfile import pstats from pstats import SortKey def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] def merge_sort(arr): if len(arr) > 1: mid = len(arr) ...
import random from solution import bubble_sort, merge_sort, profile_sorting_algorithms, analyze_profile_data def test_bubble_sort(): arr = [64, 34, 25, 12, 22, 11, 90] bubble_sort(arr) assert arr == [11, 12, 22, 25, 34, 64, 90] def test_merge_sort(): arr = [64, 34, 25, 12, 22, 11, 90] merge_sort(a...
[ { "docstring": null, "function_declaration": "def bubble_sort(arr):", "function_name": "bubble_sort", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def merge_sort(arr):", "function_name": "merge_sort", "parameter_list": "(arr)" }, { "docstring...
[ 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 random\nimport cProfile\nimport pstats\nfrom pstats import SortKey\n\ndef bubble_sort(arr):\n n = len(arr)\n for i in range(n):\n for j in range(0, ...
trial_gpt4o_0
{ "original_instruction": "### Objective:\nTo evaluate the understanding and application of Python’s profiling tools (`cProfile`, `profile`, and `pstats`) for analyzing program performance.\n\n### Problem Statement:\nWrite a Python script to profile the performance of different sorting algorithms. You need to impleme...
0.518576
Docs: Python310_12942
C
[ "bubble_sort", "merge_sort", "profile_sorting_algorithms", "analyze_profile_data" ]
4
[ [ "profile_sorting_algorithms", "bubble_sort" ], [ "profile_sorting_algorithms", "merge_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
66c3dab5f07a2adbe61279219602736ecd833ad7
d6282023dc888aef8d0d74160daa9072a45d195f
v1.0
complete
Docs
Docs: Scikit_11809_C
import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import silhouette_score, calinski_harabasz_score import pandas as pd def initialize_centroids(X, k, init='random'): """ Initialize centroids for K-Means clustering. Parameters: - X: np.ndarray, data points - k: int, number...
import numpy as np from sklearn.metrics import silhouette_score, calinski_harabasz_score import matplotlib.pyplot as plt from sklearn.datasets import make_blobs import pandas as pd def initialize_centroids(X, k, init='random'): """ Initialize centroids for K-Means clustering. Parameters: - X: np.n...
from solution import initialize_centroids, assign_clusters, compute_centroids, kmeans import numpy as np from sklearn.datasets import make_blobs from sklearn.metrics import silhouette_score, calinski_harabasz_score def test_initialize_centroids(): X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) centroids = init...
[ { "docstring": "Initialize centroids for K-Means clustering.\n\nParameters:\n- X: np.ndarray, data points\n- k: int, number of clusters\n- init: str, 'random' or 'kmeans++'\n\nReturns:\n- centroids: np.ndarray, initialized centroids", "function_declaration": "def initialize_centroids(X, k, init='random'):",...
[ 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 pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import silhouette_score, calinski_harabasz_score\nfrom sklearn.cluster im...
trial_gpt4o_1
{ "original_instruction": "### Question on Clustering with K-Means\n\n**Context:**\nYou are tasked to cluster data points using the K-Means clustering algorithm. To deepen your understanding, you will first implement the K-Means algorithm from scratch. Afterward, you will use sklearn's `KMeans` to cluster the same da...
0.804661
Docs: Scikit_11809
C
[ "initialize_centroids", "assign_clusters", "compute_centroids", "kmeans", "plot_clusters" ]
5
[ [ "kmeans", "assign_clusters" ], [ "kmeans", "compute_centroids" ], [ "kmeans", "initialize_centroids" ] ]
3
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "pandas", "sklearn" ]
false
d60616c62ef14f573d18d18620d122d1ad027d3c
00b79127f67fc703819677adc095466822ca4fb5
v1.0
complete
Docs
Docs: Python310_12857_C
import signal import sys def handle_sigint(signum, frame): """ Signal handler for SIGINT. """ pass def handle_sigalrm(signum, frame): """ Signal handler for SIGALRM. """ pass def handle_sigusr1(signum, frame): """ Signal handler for SIGUSR1. """ pass def setup_sig...
import signal import sys def handle_sigint(signum, frame): print("SIGINT received, exiting.") sys.exit(0) def handle_sigalrm(signum, frame): print("SIGALRM received, alarm triggered.") def handle_sigusr1(signum, frame): print("SIGUSR1 received.") def setup_signal_handlers(): signal.signal(si...
import signal import os import subprocess import time def test_handle_sigint(): process = subprocess.Popen(['python', 'solution.py'], stdout=subprocess.PIPE, text=True) # Give the process some time to start and pause waiting for signals time.sleep(2) process.send_signal(signal.SIGINT) stdout, _ = p...
[ { "docstring": null, "function_declaration": "def handle_sigint(signum, frame):", "function_name": "handle_sigint", "parameter_list": "(signum, frame)" }, { "docstring": null, "function_declaration": "def handle_sigalrm(signum, frame):", "function_name": "handle_sigalrm", "parame...
[ 0, 1, 0, 1, 1, 0, 1, 0, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import signal\nimport sys\n\ndef handle_sigint(signum, frame):\n print(\"SIGINT received, exiting.\")\n sys.exit(0)\n\ndef handle_sigalrm(signum, frame):\n pri...
trial_gpt4o_4
{ "original_instruction": "**Problem Statement:**\nWrite a Python program that sets up custom signal handlers for different types of signals. Your program should demonstrate the ability to:\n1. Set and handle the `SIGINT` signal (typically sent using Ctrl+C).\n2. Set and handle the `SIGALRM` signal using a timer.\n3....
0.544577
Docs: Python310_12857
C
[ "handle_sigint", "handle_sigalrm", "handle_sigusr1", "setup_signal_handlers", "main" ]
5
[ [ "setup_signal_handlers", "handle_sigalrm" ], [ "setup_signal_handlers", "handle_sigint" ], [ "setup_signal_handlers", "handle_sigusr1" ] ]
3
[]
false
[]
false
pytest
false
[]
true
82a38fb98074f11a93aefd9fbb861a199ecad2a5
49e2165e321dec29a46255c164a7907ca128a701
v1.0
complete
Docs
Docs: Python310_11503_C
import aiohttp import asyncio from typing import List, Callable async def fetch_and_process(urls: List[str], process_func: Callable[[str, str], str], output_file: str): """ Fetch data from multiple URLs asynchronously, process the content, and write to an output file. Args: urls (List[str]): The l...
import aiohttp import asyncio from typing import List, Callable async def fetch(url: str) -> str: """ Fetches the content of the given URL. Returns the content as a string, or raises an exception if the fetch fails. """ async with aiohttp.ClientSession() as session: try: async ...
import asyncio import pytest from solution import fetch_and_process async def sample_process_func(url, content): return f"Processed content from {url} with length {len(content)}" @pytest.mark.asyncio async def test_fetch_and_process(): urls = [ "https://httpbin.org/get", "https://httpbin.org/d...
[]
[ 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 aiohttp\nimport asyncio\nfrom typing import List, Callable\n\nasync def fetch(url: str, session: aiohttp.ClientSession) -> str:\n try:\n async with ses...
trial_gpt4o_1
{ "original_instruction": "### Problem Description\n\nYou are provided with a list of URLs that need to be fetched asynchronously. There is also a requirement to process the fetched data and save the results to a file. To handle this scenario, you need to implement an asynchronous function in Python using the asyncio...
0.559902
Docs: Python310_11503
C
[ "fetch", "fetch_and_process" ]
2
[ [ "fetch_and_process", "fetch" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
957b6d497af70828d1580bf3985b0b872fe36fb6
fa88a5cbc2cb495613ffc95f7090f821bbe0c6a9
v1.0
complete
Docs
Docs: Pandas_12454_C
import pandas as pd def calculate_operation_percentage(df: pd.DataFrame) -> dict: """ Calculate the percentage of time each machine was operational. Parameters: - df: pandas DataFrame with columns 'machine_id', 'time_period', and 'status' Returns: - A dictionary with machine_id as key...
import pandas as pd def calculate_operation_percentage(df): """ Calculate the percentage of time each machine was operational. Parameters: - df: pandas DataFrame with columns 'machine_id', 'time_period', and 'status' Returns: - A dictionary with machine_id as keys and their operation ...
from solution import calculate_operation_percentage, filter_machines import pandas as pd def test_calculate_operation_percentage(): data = { 'machine_id': [1, 1, 1, 2, 2, 2, 3, 3, 3], 'time_period': ['2021-Q1', '2021-Q2', '2021-Q3', '2021-Q1', '2021-Q2', '2021-Q3', '2021-Q1', '2021-Q2', '2021-Q3'],...
[ { "docstring": "Calculate the percentage of time each machine was operational.\n\nParameters:\n- df: pandas DataFrame with columns 'machine_id', 'time_period', and 'status'\n\nReturns:\n- A dictionary with machine_id as keys and their operation percentage as values", "function_declaration": "def calculate_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 pandas as pd\n\ndef calculate_operation_percentage(df):\n \"\"\"\n Calculates the percentage of time each machine was operational over all the time periods...
trial_gpt4o_2
{ "original_instruction": "You have been provided with a DataFrame that contains information about several machines and their status during different time periods. The DataFrame `df` has a nullable boolean column 'status' that indicates whether each machine was operating (`True`), not operating (`False`), or if the i...
0.655716
Docs: Pandas_12454
C
[ "calculate_operation_percentage", "filter_machines" ]
2
[ [ "filter_machines", "calculate_operation_percentage" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas" ]
false
5c2b76f98812d69f4602b16adc7c2cb74eb50e00
4f9c4524b3b82a1d7e4e47a3d5a0e5450e1cbf2e
v1.0
complete
Docs
Docs: Python310_12151_C
from typing import List, Dict import logging def is_prime(n: int) -> bool: """ Determines if a number is prime. """ if n < 2: return False if n == 2: return True if n % 2 == 0: return False sqrt_n = int(n ** 0.5) + 1 for i in range(3, sqrt_n, 2): if n % i...
from typing import List, Dict import concurrent.futures import logging def is_prime(n: int) -> bool: """ Determines if a number is prime. """ if n < 2: return False if n == 2: return True if n % 2 == 0: return False sqrt_n = int(n ** 0.5) + 1 for i in range(3, sq...
from solution import calculate_primes def test_calculate_primes_basic(): numbers = [2, 3, 4, 5, 6] result = calculate_primes(numbers) assert result == {2: True, 3: True, 4: False, 5: True, 6: False} def test_large_prime_number(): numbers = [99999941] # Known large prime number result = calculate_...
[ { "docstring": "Determines if a number is prime.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Calculate the primality of a list of numbers using concurrent processing.", "function_declaration": "def calculate_primes...
[ 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, Dict\n\ndef is_prime(n: int) -> bool:\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n re...
trial_gpt4o_1
{ "original_instruction": "**Objective:**\nImplement a Python function that uses concurrent processing to calculate a large number of prime numbers efficiently and correctly handles errors and timeouts.\n\n**Question:**\n\nWrite a function `calculate_primes(numbers, max_workers=4, timeout=None)` that takes a list of ...
0.619038
Docs: Python310_12151
C
[ "is_prime", "calculate_primes" ]
2
[ [ "calculate_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fd14344e243fbddec7bfe8cb62e2f781f86bb15f
2ac0c09ad0177707bec01ccf1db89fed511962f9
v1.0
complete
Docs
Docs: Python310_12624_C
import asyncio from typing import List, Dict async def process_logs(log_filenames: List[str]) -> Dict[str, int]: """ Asynchronous function to process log files and count word occurrences. Args: log_filenames (List[str]): List of log file names. Returns: Dict[str, int]: Dictionary with unique words...
import asyncio import re from typing import List, Dict def normalize_text(text: str) -> List[str]: # Remove punctuation and convert to lower case text = re.sub(r'[^\w\s]', '', text).lower() return text.split() async def count_words_in_file(filename: str) -> Dict[str, int]: word_count = {} async wi...
import pytest import asyncio from solution import process_logs @pytest.mark.asyncio async def test_process_logs_single_file(): result = await process_logs(['log1.txt']) expected = { "error": 1, "occurred": 1, "in": 1, "the": 1, "system": 1 } assert result == expe...
[ { "docstring": null, "function_declaration": "def normalize_text(text):", "function_name": "normalize_text", "parameter_list": "(text)" } ]
[ 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\nfrom typing import List, Dict\nimport re\nimport aiofiles\n\ndef normalize_text(text: str) -> List[str]:\n # Remove punctuation and convert to lower ...
trial_gpt4o_2
{ "original_instruction": "### Asynchronous File Processing with asyncio\n\nIn this challenge, you are required to use the asyncio library to implement an asynchronous function for processing log files. \n\n#### Objective:\n\nWrite an asynchronous function `process_logs(log_filenames: List[str]) -> Dict[str, int]` th...
0.648739
Docs: Python310_12624
C
[ "normalize_text", "count_words_in_file", "process_logs" ]
3
[ [ "count_words_in_file", "normalize_text" ], [ "process_logs", "count_words_in_file" ] ]
2
[]
false
[]
false
pytest
true
[]
true
9ffca0fb8de3c978e5967a35edd167ede1741601
329dc1038d10ef273aec0a1d3afab4c6b796f01d
v1.0
complete
Docs
Docs: Python310_13460_C
import codecs class ReverseIncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): """ Encode the input by reversing it. >>> encoder = ReverseIncrementalEncoder() >>> encoder.encode("Hello, ", final=False) '' >>> encoder.encode("World!", final=Tr...
import codecs class ReverseIncrementalEncoder(codecs.IncrementalEncoder): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.buffer = "" def encode(self, input, final=False): self.buffer += input if final: result = self.buffer[::-1] ...
import codecs from solution import register_reverse_codec, ReverseIncrementalEncoder, ReverseIncrementalDecoder def test_reverse_codec(): # Register the custom codec register_reverse_codec() # Fetch the incremental encoder and decoder encoder = codecs.getincrementalencoder('reverse_codec')() 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": "import codecs\n\nclass ReverseIncrementalEncoder(codecs.IncrementalEncoder):\n def encode(self, input, final=False):\n return input[::-1]\n\n def reset(sel...
trial_gpt4o_5
{ "original_instruction": "## Coding Assessment Question:\n\n### Objective:\nImplement an incremental encoder and decoder for a simple custom text codec that reverses the input text during encoding and restores it during decoding.\n\n### Problem Statement:\nYour task is to create a custom codec named `reverse_codec` ...
0.600372
Docs: Python310_13460
C
[ "reverse_codec_search", "register_reverse_codec" ]
2
[ [ "register_reverse_codec", "reverse_codec_search" ] ]
1
[]
false
[ "ReverseIncrementalEncoder", "ReverseIncrementalDecoder" ]
true
pytest
true
[]
true
0fe7667286d3cf6f619ed5f8e3eec3db79946bff
1a9215601faf22fcfb9ad921ec09fc799e3bb71c
v1.0
complete
Docs
Docs: Pandas_13417_C
import pandas as pd from typing import Callable import numpy as np def integrate_function(df: pd.DataFrame) -> pd.DataFrame: """ Perform numerical integration based on the DataFrame's contents. Optimized for performance using Cython and optionally Numba. >>> df = pd.DataFrame({ >>> "a": [0, 0], >>>...
import pandas as pd import numpy as np def linear(x): return x def quadratic(x): return x**2 def integrate_function(df): def integrate(a, b, N, func): dx = (b - a) / N total_sum = 0.0 for i in range(N): x = a + i*dx if func == "linear": tota...
import pandas as pd from solution import integrate_function def test_integrate_function(): df = pd.DataFrame({ "a": [0, 0], "b": [1, 2], "N": [1000, 2000], "func": ["linear", "quadratic"] }) result_df = integrate_function(df) # Expected values derived by analyt...
[ { "docstring": null, "function_declaration": "def linear(x):", "function_name": "linear", "parameter_list": "(x)" }, { "docstring": null, "function_declaration": "def quadratic(x):", "function_name": "quadratic", "parameter_list": "(x)" }, { "docstring": null, "functi...
[ 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 pandas as pd\nimport numpy as np\nfrom numba import jit\n\n# Define mathematical functions\ndef linear(x):\n return x\n\ndef quadratic(x):\n return x**2\n\...
trial_gpt4o_8
{ "original_instruction": "## Question: Optimizing DataFrame Computations with Cython and Numba\n\nYou are provided with a pandas DataFrame containing data about various mathematical functions and their parameters. Your task is to implement a function that performs numerical integration based on the DataFrame's conte...
0.607808
Docs: Pandas_13417
C
[ "linear", "quadratic", "integrate_function" ]
3
[ [ "integrate_function", "linear" ], [ "integrate_function", "quadratic" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "pandas" ]
false
23bf9e063b97426e4015f43f465faa7ae1997dfe
64db73fefd0ec4dbcccfb980d13b0330a3531428
v1.0
complete
Docs
Docs: Python310_13125_C
import asyncio import aiohttp import logging # Configure logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) async def fetch_content(url: str) -> str: """Fetch content from the given URL asynchronously.""" ... async def process_content(content: str) -> int: """Simulate p...
import asyncio import aiohttp import logging # Configure logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) async def fetch_content(url: str) -> str: """ Fetch content from the given URL asynchronously. """ try: async with aiohttp.ClientSession() as session: ...
import asyncio from solution import process_urls def test_process_urls_success(monkeypatch): urls = ["http://example.com", "http://example.org"] async def mock_fetch_content(url): return "content" async def mock_process_content(content): return len(content) monkeypatch.setatt...
[]
[ 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 asyncio\nimport aiohttp\nimport logging\n\n# Configure logging\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\nasync def fetch...
trial_gpt4o_0
{ "original_instruction": "### Advanced Asynchronous Programming with asyncio\n\n**Objective:** Implement an asynchronous function using Python's `asyncio` library that demonstrates the ability to manage multiple asynchronous tasks, handle potential pitfalls, and effectively use debugging and logging.\n\n#### Problem...
0.591584
Docs: Python310_13125
C
[ "fetch_content", "process_content", "process_single_url", "process_urls" ]
4
[ [ "process_single_url", "fetch_content" ], [ "process_single_url", "process_content" ], [ "process_urls", "process_single_url" ] ]
3
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
44b00686a2c21300e9b4f3e168850f0a59ffb247
6c5817cc9f7c35736e504ba58c65e6b0050bf3e6
v1.0
complete
Docs
Docs: Python310_13182_C
import itertools import functools class TemperatureStream: def __init__(self, temperatures): """ Initialize the temperature stream with a list of temperatures """ self.temperatures = temperatures self.index = 0 def __iter__(self): """ Return the iterator object itself """ ...
import itertools import functools class TemperatureStream: def __init__(self, temperatures): self.temperatures = temperatures self.index = 0 def __iter__(self): return self def __next__(self): if self.index >= len(self.temperatures): raise StopIteration ...
from solution import TemperatureStream, temperature_variation, max_24_hour_variation, average_temperature, analyze_temperature_readings def test_temperature_stream(): temps = [1, 2, 3, 4, 5] temp_stream = TemperatureStream(temps) assert list(temp_stream) == temps def test_temperature_variation(): temp...
[]
[ 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 itertools\nimport functools\n\nclass TemperatureStream:\n def __init__(self, temperatures):\n self.temperatures = temperatures\n self.index = 0\...
trial_gpt4o_2
{ "original_instruction": "### Question: Advanced Iterator and Generator Usage in Python\n\nImplement a custom iterator and a generator function, and then use them in combination with functions from the `itertools` and `functools` modules to solve the following problem:\n\n**Problem Statement:**\nYou are given a stre...
0.585645
Docs: Python310_13182
C
[ "temperature_variation", "max_24_hour_variation", "average_temperature", "analyze_temperature_readings" ]
4
[ [ "analyze_temperature_readings", "average_temperature" ], [ "analyze_temperature_readings", "max_24_hour_variation" ], [ "max_24_hour_variation", "temperature_variation" ] ]
3
[]
false
[ "TemperatureStream" ]
true
pytest
true
[]
true
e23d46b24736c38fb1256b96638e3813b6e4e3f3
0438e81e0ef3c5bf2cdd742f4d230d1d5b4e32a4
v1.0
complete
Docs
Docs: Pandas_12529_C
import pandas as pd def load_data(file_path): """ Load the data from the provided CSV file into a pandas DataFrame.""" pass def basic_data_exploration(df): """ Perform basic data exploration: display first 10 rows, summary statistics, and check for missing values. """ pass def handle_mis...
import pandas as pd import matplotlib.pyplot as plt def load_data(file_path): """ Load the data from the provided CSV file into a pandas DataFrame. """ return pd.read_csv(file_path) def basic_data_exploration(df): """ Perform basic data exploration: display first 10 rows, summary statistics, ...
import pandas as pd import pytest from solution import ( load_data, basic_data_exploration, handle_missing_values, create_goal_contribution, filter_appearances, average_goal_contribution_per_team, top_players_by_goal_contribution, nationality_with_most_players, plot_avg_goal_contribu...
[ { "docstring": "Load the data from the provided CSV file into a pandas DataFrame.", "function_declaration": "def load_data(file_path):", "function_name": "load_data", "parameter_list": "(file_path)" }, { "docstring": "Perform basic data exploration: display first 10 rows, summary statistics,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nimport matplotlib.pyplot as plt\n\ndef read_data(file_path):\n \"\"\"\n Reads data from a CSV file into a DataFrame.\n \"\"\"\n return ...
trial_gpt4o_9
{ "original_instruction": "Analyzing Soccer Player Statistics using Pandas\n\n**Objective:** \nTo assess your ability to manipulate and analyze data using the pandas library.\n\n**Problem Statement:**\n\nYou are provided with a CSV file that contains statistics of various soccer players. The CSV file has the followin...
0.739872
Docs: Pandas_12529
C
[ "load_data", "basic_data_exploration", "handle_missing_values", "create_goal_contribution", "filter_appearances", "average_goal_contribution_per_team", "top_players_by_goal_contribution", "nationality_with_most_players", "plot_avg_goal_contribution_per_position", "analyze_soccer_stats" ]
10
[ [ "analyze_soccer_stats", "average_goal_contribution_per_team" ], [ "analyze_soccer_stats", "basic_data_exploration" ], [ "analyze_soccer_stats", "create_goal_contribution" ], [ "analyze_soccer_stats", "filter_appearances" ], [ "analyze_soccer_stats", "handle_...
9
[]
false
[]
false
pytest
true
[ "matplotlib", "pandas" ]
false
431acd61a580e8017a2cd569bda4daf29e6bc090
f769b8ce9eb232803d07a9a97fd77c33e596e8e4
v1.0
complete
Docs
Docs: Python310_12689_C
import asyncio from typing import List, Tuple async def network_operation(task_id: int, delay: int) -> str: """ Simulates a network operation that takes `delay` seconds to complete. Args: - task_id (int): The ID of the task. - delay (int): The time in seconds that the task will take to complete. ...
import asyncio async def network_operation(task_id, delay): """ Simulates a network operation that takes `delay` seconds to complete. Args: - task_id (int): The ID of the task. - delay (int): The time in seconds that the task will take to complete. Returns: - str: A string message indicat...
import pytest import asyncio from solution import network_operation, manage_tasks def test_network_operation(): result = asyncio.run(network_operation(1, 1)) assert result == "Task 1 completed." @pytest.mark.asyncio async def test_manage_tasks_order(): task_details = [(1, 5), (2, 1), (3, 3)] result = ...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def network_operation(task_id, delay):\n \"\"\"\n Simulates a network operation that takes `delay` seconds to complete.\n\n Args:\n ...
trial_gpt4o_2
{ "original_instruction": "### Asyncio Task Management and Synchronization\n\n#### Background\nThe asyncio library in Python allows for writing concurrent code using the async/await syntax. It provides high-level APIs to run coroutines concurrently, manage network IO, and synchronize concurrent code. This assessment ...
0.631539
Docs: Python310_12689
C
[ "network_operation", "manage_tasks" ]
2
[ [ "manage_tasks", "network_operation" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d8dc6cded7b0aef5e8194186e2333cea42348795
173062ed49eab96a2a4e3c8cca0aef9bed531560
v1.0
complete
Docs
Docs: Python310_13740_C
import getpass def get_credentials(): """ Prompts the user for their username and password securely, then returns a tuple containing the entered username and password. """ def login_system(users): """ Accepts a dictionary of users with usernames as keys and passwords as values. Prompts...
import getpass def get_credentials(): """ Prompts the user for their username and password securely, then returns a tuple containing the entered username and password. """ username = input("Enter your username: ") password = getpass.getpass("Password: ") return (username, password) def lo...
from solution import login_system def test_login_system_valid_credentials(monkeypatch): users = { "alice": "password123", "bob": "secure456", "charlie": "passwd789" } inputs = iter(["alice", "password123"]) monkeypatch.setattr('builtins.input', lambda x: next(inputs)) m...
[ { "docstring": "Prompts the user for their username and password securely, \nthen returns a tuple containing the entered username and password.", "function_declaration": "def get_credentials():", "function_name": "get_credentials", "parameter_list": "()" }, { "docstring": "Accepts a dictiona...
[ 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 getpass\n\ndef get_credentials():\n \"\"\"\n Prompts the user for their username and password securely.\n Returns a tuple containing the entered usernam...
trial_gpt4o_1
{ "original_instruction": "### Secure Login System Implementation\n\n**Objective:**\nImplement a secure login system using the `getpass` module. The system should prompt the user for their username and password securely, verifying the credentials against a predefined set of users.\n\n**Task:**\n\n1. Implement a funct...
0.658391
Docs: Python310_13740
C
[ "get_credentials", "login_system" ]
2
[ [ "login_system", "get_credentials" ] ]
1
[]
false
[]
false
pytest
true
[]
true
62b550b2f0713916064480d183f4790d67e388d6
d60ce6f10f2319e09a73e140dcf4e889229ae8a8
v1.0
complete
Docs
Docs: Python310_13547_C
import asyncio async def execute_commands(commands: list) -> dict: """ Execute a list of shell commands concurrently and capture their outputs. Args: commands (list): A list of shell commands to be executed. Returns: dict: A dictionary where each key is a command string a...
import asyncio async def execute_command(command): process = await asyncio.create_subprocess_shell( command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, stderr = await process.communicate() return stdout.decode(), stderr.decode() async def execute_c...
from solution import execute_commands import asyncio def test_execute_commands(): commands = ['echo Hello', 'ls nonexistent_directory', 'sleep 1; echo Done'] results = asyncio.run(execute_commands(commands)) assert 'echo Hello' in results assert results['echo Hello'] == ('Hello\n', '') assert 'ls n...
[]
[ 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 asyncio\n\nasync def execute_commands(commands: list) -> dict:\n async def run_command(command):\n proc = await asyncio.create_subprocess_shell(\n ...
trial_gpt4o_2
{ "original_instruction": "### Assessment Question: Concurrent Subprocess Monitoring\n\nIn this task, you will implement a Python function that concurrently runs multiple shell commands using `asyncio`'s subprocess APIs. Your function will execute each command, capture its output, print the output, and handle any err...
0.673549
Docs: Python310_13547
C
[ "execute_command", "execute_commands" ]
2
[ [ "execute_commands", "execute_command" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1c33de22440e21c3ce57aa980c8ee526426019d8
5c03bca10eee569e1c5dbdff1c8fe258a916eb8a
v1.0
complete
Docs
Docs: Python310_12429_C
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor from functools import reduce import operator def parallel_factorial(n: int) -> int: """ Compute the factorial of a large number in a parallel fashion using the concurrent.futures module. >>> parallel_factorial(5) == 120 >>> parallel_fac...
import concurrent.futures from functools import reduce import operator def factorial_partial(start, end): """Compute partial factorial from `start` to `end` (both inclusive)""" result = 1 for i in range(start, end + 1): result *= i return result def parallel_factorial(n: int) -> int: if n ...
from solution import parallel_factorial def test_parallel_factorial_small_numbers(): assert parallel_factorial(0) == 1 assert parallel_factorial(1) == 1 assert parallel_factorial(2) == 2 assert parallel_factorial(3) == 6 assert parallel_factorial(4) == 24 assert parallel_factorial(5) == 120 de...
[ { "docstring": "Compute partial factorial from `start` to `end` (both inclusive)", "function_declaration": "def factorial_partial(start, end):", "function_name": "factorial_partial", "parameter_list": "(start, end)" }, { "docstring": null, "function_declaration": "def parallel_factorial(...
[ 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 concurrent.futures\nfrom functools import reduce\nfrom operator import mul\nfrom itertools import islice\n\ndef chunked_iterable(iterable, size):\n it = iter(...
trial_gpt4o_1
{ "original_instruction": "**Objective:** \nImplement a function that computes the factorial of a large number in a parallel fashion using the `concurrent.futures` module.\n\n**Task Description:**\n\nYou are required to write a function `parallel_factorial(n: int) -> int` that calculates the factorial of a given larg...
0.675086
Docs: Python310_12429
C
[ "factorial_partial", "parallel_factorial" ]
2
[ [ "parallel_factorial", "factorial_partial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9452aa0a26a47f0f17bf0828224ce878d7d4ca92
704d4309fa472690ba757c12c1e79f2f9d4bcc1a
v1.0
complete
Docs
Docs: Python310_13670_C
import numpy as np import timeit def naive_multiply(A, B): n = len(A) result = [[0] * n for _ in range(n)] for i in range(n): for j in range(n): for k in range(n): result[i][j] += A[i][k] * B[k][j] return result def numpy_multiply(A, B): return np.dot(A, B) def...
import numpy as np import timeit def naive_multiply(A, B): n = len(A) result = [[0] * n for _ in range(n)] for i in range(n): for j in range(n): for k in range(n): result[i][j] += A[i][k] * B[k][j] return result def numpy_multiply(A, B): return np.dot(A, B) def...
def test_compare_matrix_multiplication_times(): import timeit result = compare_matrix_multiplication_times(10) assert "naive" in result, "Result dictionary should contain 'naive' key" assert "numpy" in result, "Result dictionary should contain 'numpy' key" assert isinstance(result["naive"...
[ { "docstring": null, "function_declaration": "def naive_multiply(A, B):", "function_name": "naive_multiply", "parameter_list": "(A, B)" }, { "docstring": null, "function_declaration": "def numpy_multiply(A, B):", "function_name": "numpy_multiply", "parameter_list": "(A, B)" }, ...
[ 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 timeit\n\ndef naive_multiply(A, B):\n n = len(A)\n result = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range...
trial_gpt4o_0
{ "original_instruction": "You are provided with two matrix multiplication algorithms: a naive implementation and an optimized implementation using NumPy. You need to use the `timeit` module to compare the performance of these two matrix multiplication methods.\n\n**Objective**: Write a Python function `compare_matri...
0.598922
Docs: Python310_13670
C
[ "naive_multiply", "numpy_multiply", "generate_random_matrix", "compare_matrix_multiplication_times" ]
4
[ [ "compare_matrix_multiplication_times", "generate_random_matrix" ], [ "compare_matrix_multiplication_times", "naive_multiply" ], [ "compare_matrix_multiplication_times", "numpy_multiply" ] ]
3
[]
false
[]
false
pytest
false
[ "numpy" ]
false
2cc9ba3a8293b0dbc18680ea3b8ec671cd0dc649
192d7805486f4b2949328b0a025f305b91743d81
v1.0
complete
Docs
Docs: Scikit_12090_C
import pandas as pd from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering from sklearn.metrics import adjusted_rand_score, silhouette_score def load_data(file_path): """ Load the dataset from the CSV file. Args: - file_path (str): Path to the CSV file. Returns: - pd.Data...
import pandas as pd from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering from sklearn.metrics import adjusted_rand_score, silhouette_score def load_data(file_path): """ Load the dataset from the CSV file. Args: - file_path (str): Path to the CSV file. Returns: - pd.Data...
import pytest import pandas as pd from io import StringIO from solution import load_data, apply_clustering_and_evaluate def test_load_data(): data = """Feature1,Feature2,Feature3 5.1,3.5,1.4 4.9,3.0,1.4 4.7,3.2,1.3 4.6,3.1,1.5 5.0,3.6,1.4""" # Simulate a CSV file using StringIO df ...
[ { "docstring": "Load the dataset from the CSV file.\n\nArgs:\n- file_path (str): Path to the CSV file.\n\nReturns:\n- pd.DataFrame: Loaded dataset.", "function_declaration": "def load_data(file_path):", "function_name": "load_data", "parameter_list": "(file_path)" }, { "docstring": "Apply th...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering\nfrom sklearn.metrics import adjusted_rand_score, silhouette_score\n\ndef load_...
trial_gpt4o_3
{ "original_instruction": "#### Objective\nWrite a Python program that performs clustering on a given dataset using multiple clustering algorithms from the scikit-learn library and evaluates the performance of each clustering method.\n\n#### Requirements\n1. Implement clustering using the following algorithms:\n - ...
0.787953
Docs: Scikit_12090
C
[ "load_data", "apply_clustering_and_evaluate" ]
2
[ [ "apply_clustering_and_evaluate", "load_data" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas", "sklearn" ]
false
b36890ba912c1bf56d6449d959450f2d195df695
f7027eb964f708f07a9630a439c9c5ac8ee4cc47
v1.0
complete
Docs
Docs: Python310_13700_C
import asyncio from typing import List, Tuple async def asyncio_manage_tasks(task_list: List[Tuple[int, str]]) -> List[str]: """ Manage a set of tasks and collect their results in the order they complete concurrently using asyncio. Each task is represented by a tuple where the first element is the delay t...
import asyncio from typing import List, Tuple async def async_task(delay: int, message: str) -> str: await asyncio.sleep(delay) return message async def asyncio_manage_tasks(task_list: List[Tuple[int, str]]) -> List[str]: tasks = [asyncio.create_task(async_task(delay, message)) for delay, message in task_...
import asyncio import pytest from solution import asyncio_manage_tasks @pytest.mark.asyncio async def test_single_task(): task_list = [(2, "task1 completed")] result = await asyncio_manage_tasks(task_list) assert result == ["task1 completed"] @pytest.mark.asyncio async def test_multiple_tasks(): task_...
[]
[ 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\n\nasync def async_task(delay: int, message: str) -> str:\n await asyncio.sleep(delay)\n return message\n\nasync de...
trial_gpt4o_0
{ "original_instruction": "**Concurrency in Asyncio**\n\nYou are required to manage a set of tasks that need to be executed concurrently using Python's asyncio library. The challenge is to ensure these tasks are managed properly, and their results are collected efficiently. \n\n### Task Details\n\nYou need to impleme...
0.745643
Docs: Python310_13700
C
[ "async_task", "asyncio_manage_tasks" ]
2
[ [ "asyncio_manage_tasks", "async_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
97328b75b7b2c20e221bbededd5d06dfaa4b7fc7
4f6703a8ee0a557f6edd1511221bbc1c56b52dbe
v1.0
complete
Docs
Docs: Pytorch_12538_C
import torch import torch.nn as nn import torch.autograd.profiler as profiler class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.layer1 = nn.Linear(10, 20) self.layer2 = nn.Linear(20, 10) self.layer3 = nn.Linear(10, 5) def forward(self, x...
import torch import torch.nn as nn import torch.autograd.profiler as profiler class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.layer1 = nn.Linear(10, 20) self.layer2 = nn.Linear(20, 10) self.layer3 = nn.Linear(10, 5) def forward(self, x...
from solution import SimpleModel, profile_model import torch def test_model_structure(): model = SimpleModel() assert hasattr(model, 'layer1'), "Layer 1 is missing" assert hasattr(model, 'layer2'), "Layer 2 is missing" assert hasattr(model, 'layer3'), "Layer 3 is missing" assert isinstance(model.la...
[]
[ 0, 0, 0, 1, 1, 1, 1, 0, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.autograd.profiler as profiler\n\nclass SimpleModel(nn.Module):\n def __init__(self):\n super(SimpleModel, se...
trial_gpt4o_5
{ "original_instruction": "### Custom Profiling Callback with PyTorch\n\nIn this task, you are asked to implement a custom profiling callback in PyTorch using Python. You will use `torch.autograd.profiler` to measure the time taken by specific operations in a given neural network model. \n\n### Requirements\n\n1. Imp...
0.594369
Docs: Pytorch_12538
C
[ "custom_profiler_callback", "profile_model", "main" ]
3
[ [ "profile_model", "custom_profiler_callback" ] ]
1
[]
false
[ "SimpleModel" ]
true
pytest
true
[ "torch" ]
false
fa9991a6a429d012759c196f645bbe560f35f38c
ea7b7991ed1f1dd7c23d26e3d6d1b24c908d0a58
v1.0
complete
Docs
Docs: Python310_12933_C
import concurrent.futures import requests from typing import List, Dict def process_json_urls(urls: List[str], key: str) -> Dict[str, any]: """ Downloads and processes JSON files concurrently to extract the value associated with the specified key. Args: urls (List[str]): A list of URLs pointing to JSO...
import concurrent.futures import requests def fetch_json(url): try: response = requests.get(url) response.raise_for_status() return response.json() except (requests.RequestException, ValueError): return None def process_json_urls(urls, key): result = {} def process_url...
from solution import process_json_urls import requests from unittest.mock import patch def mock_requests_get(url): class MockResponse: def __init__(self, json_data, status_code): self.json_data = json_data self.status_code = status_code def json(self): return se...
[ { "docstring": null, "function_declaration": "def fetch_json(url):", "function_name": "fetch_json", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def process_json_urls(urls, key):", "function_name": "process_json_urls", "parameter_list": "(urls, key)"...
[ 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 concurrent.futures\nimport requests\nimport json\n\ndef fetch_json_data(url, key):\n \"\"\"\n Fetch JSON data from the given URL and extract the value asso...
trial_gpt4o_2
{ "original_instruction": "### Question: Parallel Data Processing with `concurrent.futures`\n\nYou are given a list of URLs pointing to various JSON data files on the web. Your task is to write a Python function that downloads and processes these JSON files concurrently to extract specific information. The informatio...
0.74743
Docs: Python310_12933
C
[ "fetch_json", "process_json_urls" ]
2
[ [ "process_json_urls", "fetch_json" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
9abb8f4a7df4f90744f22e5175b6cc7a2cc0ee2c
b65b79c3b1e5efbdb399f5df4177d2f5ae64d42f
v1.0
complete
Docs
Docs: Python310_13886_C
import asyncio async def worker(worker_id, task_duration, semaphore): """A single worker task that simulates work on accessing a shared resource with a specified duration. Args: worker_id (int): The identifier for the worker. task_duration (float): The duration for which the worker will simula...
import asyncio async def worker(worker_id, task_duration, semaphore): async with semaphore: print(f"Worker {worker_id} started working...") await asyncio.sleep(task_duration) print(f"Worker {worker_id} finished working.") async def coordinate_tasks(num_workers: int, task_duration: float): ...
import asyncio from solution import coordinate_tasks from io import StringIO import sys def test_coordinate_tasks(): # Capture the output captured_output = StringIO() sys.stdout = captured_output async def run_test(): await coordinate_tasks(5, 1) # Run the asyncio task asyncio.run...
[]
[ 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(worker_id, task_duration, semaphore):\n async with semaphore:\n print(f\"Worker {worker_id} started working...\")\n ...
trial_gpt4o_1
{ "original_instruction": "You are working on a shared resource management system using the `asyncio` module's synchronization primitives. Your task is to implement an asynchronous function `coordinate_tasks` that manages access to a shared resource among multiple tasks.\n\n**Function Signature:**\n```python\nasync d...
0.614763
Docs: Python310_13886
C
[ "worker", "coordinate_tasks" ]
2
[ [ "coordinate_tasks", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f05d535aea8231bcf471217695a3cc427670f234
4375a2a6edc70f1d2ab88c0791bdc099a3092b6b
v1.0
complete
Docs
Docs: Python310_11518_C
import xml.etree.ElementTree as ET from typing import Optional, Dict def parse_xml(xml_string: str) -> ET.ElementTree: """ Parses an XML string into an ElementTree object. Args: xml_string (str): XML string representing the product database. Returns: ElementTree: Parsed ElementTree object. ...
import xml.etree.ElementTree as ET from typing import Optional, Dict def parse_xml(xml_string: str) -> ET.ElementTree: """ Parses an XML string into an ElementTree object. """ return ET.ElementTree(ET.fromstring(xml_string)) def find_product_by_id(tree: ET.ElementTree, product_id: str) -> Optional[ET....
from solution import parse_xml, find_product_by_id, add_product, update_product_price, generate_xml def test_parse_xml(): xml_string = '<products><product id="p1"><name>Product 1</name></product></products>' tree = parse_xml(xml_string) assert tree.getroot().tag == 'products' def test_find_product_by_id()...
[ { "docstring": "Parses an XML string into an ElementTree object.", "function_declaration": "def parse_xml(xml_string):", "function_name": "parse_xml", "parameter_list": "(xml_string)" }, { "docstring": "Finds a product by its ID in the ElementTree.", "function_declaration": "def find_pro...
[ 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 xml.etree.ElementTree as ET\nfrom typing import Optional, Dict\n\ndef parse_xml(xml_string: str) -> ET.ElementTree:\n \"\"\"\n Parses an XML string into an...
trial_gpt4o_1
{ "original_instruction": "### XML Processing with ElementTree\n\n#### Objective\nImplement a function that parses, manipulates, and produces XML data using the `xml.etree.ElementTree` module.\n\n#### Problem Statement\nA company maintains a database of products in XML format. Each product entry includes details such...
0.52195
Docs: Python310_11518
C
[ "parse_xml", "find_product_by_id", "add_product", "update_product_price", "generate_xml" ]
5
[ [ "update_product_price", "find_product_by_id" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8c7060b4afdaf50c9f1f6f7a4e31ea2444fb0eea
75e43d3731048459ae12900fdd93d739a88ff148
v1.0
complete
Docs
Docs: Python310_13959_C
import asyncio import aiohttp async def fetch_data_concurrently(urls: list[str]) -> dict[str, str]: """ Fetch multiple URLs concurrently using asyncio and aiohttp. Args: urls (list of str): A list of URLs to be fetched. Returns: dict: A dictionary where the keys are the input URLs...
import asyncio import aiohttp async def fetch_data(url): async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.text() async def fetch_data_concurrently(urls: list[str]) -> dict[str, str]: async def fetch(url): try: ...
import asyncio from solution import fetch_data_concurrently async def test_fetch_data_concurrently(): urls = [ 'http://httpbin.org/get', 'http://invalid.url', # This should fail and return None 'http://example.com' ] expected_results = [ 'http://httpbin.org/get', 'http...
[]
[ 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_data(url):\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as response:\n ...
trial_gpt4o_2
{ "original_instruction": "<|Analysis Begin|>\n\nThe given documentation briefly introduces the `asyncio` module, which is a library used for writing concurrent code with the `async/await` syntax. It covers the following points:\n- Basic example of creating and running an asynchronous function.\n- Purpose and usage o...
0.538922
Docs: Python310_13959
C
[ "fetch_data", "fetch_data_concurrently" ]
2
[ [ "fetch_data_concurrently", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
7e66a1a90e5b3f74a967b0b1d9baa5aba1778c8f
8a1e24a4ee579838b569f541d4feb88b239252f7
v1.0
complete
Docs
Docs: Scikit_12822_C
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression, Ridge, Lasso from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.metrics import mean_squared_error, r2_score import matplotlib.py...
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression, Ridge, Lasso from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.metrics import mean_squared_error, r2_score import matplotlib.py...
# Import the functions for testing from solution import load_and_preprocess_data, calculate_correlation_matrix, train_linear_models, plot_results # Add pytest framework import pytest @pytest.fixture def example_dataset(): # Example dataframe for testing purposes data = { 'feature1': np.random.rand(100...
[ { "docstring": "Load and preprocess the data.\n\nArgs:\nfilepath (str): Path to the CSV file.\n\nReturns:\npd.DataFrame: Preprocessed DataFrame.", "function_declaration": "def load_and_preprocess_data(filepath):", "function_name": "load_and_preprocess_data", "parameter_list": "(filepath)" }, { ...
[ 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 pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso\nfrom skl...
trial_gpt4o_0
{ "original_instruction": "**Title: Multivariate Linear Regression and Regularization Techniques in scikit-learn**\n\n**Objective:**\nDemonstrate your understanding of linear regression models and regularization techniques in scikit-learn by analyzing a given dataset, addressing multicollinearity, and comparing the p...
0.773953
Docs: Scikit_12822
C
[ "load_and_preprocess_data", "calculate_correlation_matrix", "apply_pca", "train_linear_models", "plot_results" ]
5
[ [ "train_linear_models", "apply_pca" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "pandas", "sklearn" ]
false
e822e46c5aa06778e7ee165a7b64fae6e1e695f4
1bafd45b24687795c41811d2da73c94c191ce687
v1.0
complete
Docs
Docs: Python310_13555_C
import subprocess import ensurepip import sys def check_pip_installed(): """ Check if pip is already installed. Returns True if pip is installed, False otherwise. """ try: result = subprocess.run([sys.executable, '-m', 'pip', '--version'], capture_output=True, text=True) if result.retur...
import subprocess import ensurepip import sys def check_pip_installed(): try: result = subprocess.run([sys.executable, '-m', 'pip', '--version'], capture_output=True, text=True) if result.returncode == 0: print(f"pip is already installed. Version: {result.stdout}") return Tr...
from solution import check_pip_installed, get_ensurepip_version, setup_pip def test_check_pip_installed(monkeypatch): import subprocess def mock_run(*args, **kwargs): if args[0] == [sys.executable, '-m', 'pip', '--version']: mock_resp = subprocess.CompletedProcess(args, 0, stdout="pip ...
[ { "docstring": null, "function_declaration": "def check_pip_installed():", "function_name": "check_pip_installed", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def install_pip_cli():", "function_name": "install_pip_cli", "parameter_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 subprocess\nimport sys\nimport ensurepip\nimport os\n\n\ndef check_pip_installed():\n try:\n subprocess.run(['pip', '--version'], check=True, stdout=su...
trial_gpt4o_2
{ "original_instruction": "**Question**: Implement a Python program that uses the `ensurepip` module to achieve the following tasks. Your implementation should consist of two parts: using the CLI and the Module API of `ensurepip`.\n\n\n### Part 1: Command Line Interface:\nWrite a Python script to be executed using th...
0.618527
Docs: Python310_13555
C
[ "check_pip_installed", "install_pip_cli", "get_ensurepip_version", "setup_pip" ]
4
[ [ "setup_pip", "check_pip_installed" ], [ "setup_pip", "get_ensurepip_version" ], [ "setup_pip", "install_pip_cli" ] ]
3
[]
false
[]
false
pytest
true
[]
true
9f7654c71f888b021c9cdd4ddfd6263c8cf551f8
45b73ac5ff8e47b5db069e5887512c6a5e43713b
v1.0
complete
Docs
Docs: Python310_13298_C
import asyncio from typing import List async def manage_tasks() -> List[str]: """ Implement a function to manage three asynchronous tasks concurrently. The tasks are: - Task 1: Sleeps for 2 seconds and returns the message "Task 1 Completed". - Task 2: Sleeps for 3 seconds and returns the message "Task ...
import asyncio from typing import List async def task1(): await asyncio.sleep(2) return "Task 1 Completed" async def task2(): await asyncio.sleep(3) return "Task 2 Completed" async def task3(): await asyncio.sleep(1) return "Task 3 Completed" async def manage_tasks() -> List[str]: tasks ...
import pytest import asyncio from solution import manage_tasks @pytest.mark.asyncio async def test_manage_tasks(): results = await manage_tasks() assert results == ["Task 1 Completed", "Task 2 Completed", "Task 3 Completed"] def test_manage_tasks_event_loop(): loop = asyncio.get_event_loop() results =...
[]
[ 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 asyncio\nfrom typing import List\n\nasync def task1():\n await asyncio.sleep(2)\n return \"Task 1 Completed\"\n\nasync def task2():\n await asyncio.slee...
trial_gpt4o_2
{ "original_instruction": "### Asynchronous Task Management with asyncio\n\n**Objective:** \n\nYour task is to implement a Python function using the `asyncio` package, which demonstrates handling multiple asynchronous tasks concurrently.\n\n**Question:**\n\nWrite a function `manage_tasks` using asyncio that:\n\n1. Cr...
0.602452
Docs: Python310_13298
C
[ "task1", "task2", "task3", "manage_tasks" ]
4
[ [ "manage_tasks", "task1" ], [ "manage_tasks", "task2" ], [ "manage_tasks", "task3" ] ]
3
[]
false
[]
false
pytest
true
[]
true
3bff2c9d90dbf8fa9eccb631307e5284a69c9e25
8bdb9bfea4b7e4a0c9f62b81689b54e52d633ef8
v1.0
complete
Docs
Docs: Python310_14135_C
from typing import List, Optional def compute_factorials(numbers: List[int], max_workers: int) -> List[Optional[int]]: """ Compute factorials of given non-negative integers using parallel workers. Parameters: - numbers: List of non-negative integers. - max_workers: Maximum number of worker threads...
from typing import List, Optional from concurrent.futures import ThreadPoolExecutor, as_completed def factorial(n: int) -> int: """ Return the factorial of a given non-negative integer. """ if n < 0: return None result = 1 for i in range(2, n+1): result *= i return result d...
from solution import compute_factorials def test_factorials_with_small_numbers(): numbers = [0, 1, 2, 3, 4, 5] expected = [1, 1, 2, 6, 24, 120] assert compute_factorials(numbers, max_workers=3) == expected def test_factorials_with_large_numbers(): numbers = [6, 7, 8, 9, 10] expected = [720, 5040, ...
[ { "docstring": "Return the factorial of a given non-negative integer.", "function_declaration": "def factorial(n):", "function_name": "factorial", "parameter_list": "(n)" }, { "docstring": "Compute factorials of given non-negative integers using parallel workers.\n\nParameters:\n- numbers: L...
[ 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, Optional\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\ndef factorial(n: int) -> int:\n \"\"\"\n Return the factoria...
trial_gpt4o_0
{ "original_instruction": "Title: Task Execution and Aggregation with concurrent.futures\n\n**Problem Statement:**\n\nYou are given a list of integers and your goal is to calculate the factorial of each integer using multiple parallel workers such that the computation time is minimized. To achieve this, you will use ...
0.788262
Docs: Python310_14135
C
[ "factorial", "compute_factorials" ]
2
[ [ "compute_factorials", "factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
923e3576dd18e9a111370c8ec8d885e02228ac8c
19575350aeb59718aa2bd6d89705c7cdb2f638c2
v1.0
complete
Docs
Docs: Python310_12750_C
def process_integer_objects(int_list): """ Processes a list of integers by checking and converting them to PyLongObjects and back. Args: int_list (list of int): List of integers to process. Returns: list: List of C integers after processing. Raises: ValueError: If an integer cannot be...
import sys # Define the PyLongObject handling functions using the built-in Python functions def PyLong_Check(val): """ Mimic Python's PyLong_Check """ return isinstance(val, int) def PyLong_FromLong(val): """ Convert from C long (int) type to PyLongObject (int in Python) """ return int...
def test_process_integer_objects(): int_list = [10, 20, 30] result = process_integer_objects(int_list) assert result == [10, 20, 30], "Test failed for normal integers" def test_process_large_integers(): int_list = [10**20, -10**20] result = process_integer_objects(int_list) assert result == [],...
[ { "docstring": "Mimic Python's PyLong_Check", "function_declaration": "def PyLong_Check(val):", "function_name": "PyLong_Check", "parameter_list": "(val)" }, { "docstring": "Convert from C long (int) type to PyLongObject (int in Python)", "function_declaration": "def PyLong_FromLong(val)...
[ 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 sys\n\n# Define the PyLongObject handling functions using the built-in Python functions\ndef PyLong_Check(val):\n \"\"\"\n Mimic Python's PyLong_Check\n ...
trial_gpt4o_0
{ "original_instruction": "You are tasked with writing a function `process_integer_objects()` that performs various operations using `PyLongObject` handling functions provided in the `python310` package. The function should take a list of integers and perform the following tasks:\n\n1. Check if each integer qualifies...
0.598657
Docs: Python310_12750
C
[ "PyLong_Check", "PyLong_FromLong", "PyLong_AsLong", "process_integer_objects" ]
4
[ [ "process_integer_objects", "PyLong_AsLong" ], [ "process_integer_objects", "PyLong_Check" ], [ "process_integer_objects", "PyLong_FromLong" ] ]
3
[]
false
[]
false
pytest
false
[]
true
c30f4519b7c6d6ef947e8ab7d0a100f908d74de9
89a77938ef52947875c9e59fa4ad65be3ca75086
v1.0
complete
Docs
Docs: Python310_12649_C
from xml.dom.minidom import Document def parse_xml(xml_string: str) -> Document: """Parse the given XML string into a Document object. Args: xml_string (str): The XML document as a string. Returns: Document: The parsed XML document object. """ pass def find_element_by_tag_name(docu...
from xml.dom.minidom import parseString, Document def parse_xml(xml_string): """ Parse the given XML string into a Document object. """ return parseString(xml_string) def find_element_by_tag_name(document, tag_name): """ Find the first element in the document with the specified tag name. "...
import pytest from xml.dom.minidom import Document from solution import parse_xml, find_element_by_tag_name, add_element, remove_element_by_tag_name, serialize_document def test_parse_xml(): xml_string = "<root><child>data</child></root>" document = parse_xml(xml_string) assert isinstance(document, Documen...
[ { "docstring": "Parse the given XML string into a Document object.", "function_declaration": "def parse_xml(xml_string):", "function_name": "parse_xml", "parameter_list": "(xml_string)" }, { "docstring": "Find the first element in the document with the specified tag name.", "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 xml.dom.minidom import parseString, Document\n\ndef parse_xml(xml_string):\n \"\"\"\n Parse the given XML string into a Document object.\n \"\"\"\n ret...
trial_gpt4o_0
{ "original_instruction": "### XML Document Navigation and Modification using `xml.dom`\n\n**Objective:** \n\nDemonstrate your understanding of the `xml.dom` module by writing Python functions to navigate and modify an XML document.\n\n**Problem Statement:**\n\nYou are provided with an XML document represented as a s...
0.602542
Docs: Python310_12649
C
[ "parse_xml", "find_element_by_tag_name", "add_element", "remove_element_by_tag_name", "serialize_document" ]
5
[ [ "add_element", "find_element_by_tag_name" ], [ "remove_element_by_tag_name", "find_element_by_tag_name" ] ]
2
[]
false
[]
false
pytest
true
[]
true
f2c6614d6763b7885877ee2ebd8c8b83343ab98d
cc9228164ffbc936d7dbc60826e17f6c0379ea42
v1.0
complete
Docs
Docs: Python310_11984_C
import marshal from typing import Any def serialize_structure(data: Any, file_path: str, version: int = 4): """ Serialize data structure using the marshal module. Parameters: data (Any): The data structure to be serialized. file_path (str): Path to the file where data will be stored. ve...
import marshal def serialize_structure(data, file_path, version=4): """ Serializes the given data structure to the specified file using marshal. Parameters: - data: The data structure to be serialized. - file_path: The file path where the data should be serialized to. - version: The versio...
import os import pytest from solution import serialize_structure, deserialize_structure def test_serialize_and_deserialize_int(): data = 123 file_path = "test_serialize_and_deserialize_int.bin" serialize_structure(data, file_path) result = deserialize_structure(file_path) assert result == data ...
[ { "docstring": "Serializes the given data structure to the specified file using marshal.\n\nParameters:\n- data: The data structure to be serialized.\n- file_path: The file path where the data should be serialized to.\n- version: The version of the marshal format to use.\n\nRaises:\n- ValueError if the data con...
[ 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 marshal\n\ndef serialize_structure(data, file_path, version=4):\n \"\"\"\n Serializes the given data structure to the specified file using marshal.\n \n...
trial_gpt4o_0
{ "original_instruction": "Working with the `marshal` Module\n\n#### Objective:\nWrite a program that takes a complex nested data structure, serializes it using the `marshal` module, and then deserializes it back. Your task is to ensure that the data integrity is maintained and handle any possible unsupported types s...
0.592773
Docs: Python310_11984
C
[ "serialize_structure", "deserialize_structure", "test_serialization" ]
3
[ [ "test_serialization", "deserialize_structure" ], [ "test_serialization", "serialize_structure" ] ]
2
[]
false
[]
false
pytest
true
[]
true
0b89f7543bf9a3863905766c13f941765ed3aa43
be7327eb55aabe02b4459be93429c1da2560ce58
v1.0
complete
Docs
Docs: Pytorch_13439_C
import torch from typing import Dict def compute_loss(params: Dict[str, torch.Tensor], inputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: """ Computes the Mean Squared Error (MSE) loss between the model predictions and the targets. :param params: Dictionary of model parameters. :param i...
import torch from torch.func import functional_call, grad from typing import Dict def compute_loss(params: Dict[str, torch.Tensor], inputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: """ Computes the Mean Squared Error (MSE) loss between the model predictions and the targets. :param params:...
import torch from solution import compute_loss, compute_gradients def test_compute_loss(): inputs = torch.randn(64, 3) targets = torch.randn(64, 3) model = torch.nn.Linear(3, 3) params = {name: param.detach().requires_grad_() for name, param in model.named_parameters()} loss = compute_loss(par...
[ { "docstring": "Computes the Mean Squared Error (MSE) loss between the model predictions and the targets.\n\n:param params: Dictionary of model parameters.\n:param inputs: Input tensor.\n:param targets: Target tensor.\n:return: Computed loss.", "function_declaration": "def compute_loss(params, inputs, targe...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.func import functional_call, grad\n\ndef compute_loss(params, inputs, targets):\n \"\"\"\n Compute the Mean Squared Error (MSE) loss betw...
trial_gpt4o_9
{ "original_instruction": "PyTorch func Transformations and Gradient Calculation\n\nIn this assessment, you are required to demonstrate your understanding of the `torch.func` transformations and how to compute model gradients using these transformations.\n\n#### Problem Statement\n\nYou are provided with a simple mod...
0.591805
Docs: Pytorch_13439
C
[ "compute_loss", "compute_gradients" ]
2
[ [ "compute_gradients", "compute_loss" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
5f37e485b7f4617392a4db7f12dcace95dba31d8
283e7f97cb5d95cfe470f8241e7a3ffa8f146bce
v1.0
complete
Docs
Docs: Python310_13708_C
import asyncio async def tcp_echo_server(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): """ Implemenets a simple TCP echo server. """ pass # Implement server details async def start_server(): pass # Implement start server details async def start_client(): pass # Implement start c...
import asyncio import platform import sys async def tcp_echo_server(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): """ Implements a simple TCP echo server. """ data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received {mes...
import pytest import asyncio import platform from solution import start_server, start_client @pytest.mark.asyncio async def test_server_and_client_communication(): server_task = asyncio.create_task(start_server()) await asyncio.sleep(0.1) # Give the server time to start client_task = asyncio.create_task(...
[ { "docstring": null, "function_declaration": "def main():", "function_name": "main", "parameter_list": "()" } ]
[ 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 asyncio\nimport platform\nimport sys\n\nasync def tcp_echo_server(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):\n \"\"\"\n Implements a simp...
trial_gpt4o_0
{ "original_instruction": "**Task: Implement `asyncio` Function with Platform-specific Conditions**\n\nYou are tasked with writing a Python function using the `asyncio` module that handles platform-specific conditions effectively. The function should create a TCP echo server and client, keeping in mind the given plat...
0.589417
Docs: Python310_13708
C
[ "tcp_echo_server", "start_server", "start_client", "main_server", "main_client", "main" ]
6
[ [ "main_client", "start_client" ], [ "main_server", "start_server" ], [ "start_server", "tcp_echo_server" ] ]
3
[]
false
[]
false
pytest
true
[]
true
f17e9d9a9ad1333311b4de17bc2937b223a51320
0e1d6f6b0479fbb6d661193f86780b49d0a7cd9b
v1.0
complete
Docs
Docs: Python310_13503_C
import codecs class CustomCodecInfo: """ Custom Codec Implementation class This class provides methods to encode and decode messages with specific prefix "[ENC]" and suffix "[END]". Methods: - encode: Adds the prefix and suffix to the input text. - decode: Removes the prefix and suffix from th...
import codecs class CustomCodecInfo: prefix = "[ENC]" suffix = "[END]" @staticmethod def encode(input: str, errors: str = 'strict') -> tuple: encoded = CustomCodecInfo.prefix + input + CustomCodecInfo.suffix return encoded, len(encoded) @staticmethod def decode(input: ...
import codecs import pytest from solution import register_custom_codec, unregister_custom_codec, CustomCodecInfo def test_encode(): register_custom_codec() message = "Hello, World!" encoded = codecs.encode(message, "custom_enc") assert encoded == "[ENC]Hello, World![END]" unregister_custom_codec() ...
[]
[ 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 codecs\n\nclass CustomCodecInfo:\n prefix = \"[ENC]\"\n suffix = \"[END]\"\n \n @staticmethod\n def encode(input: str, errors: str = 'strict') -> ...
trial_gpt4o_0
{ "original_instruction": "**Custom Codec Implementation and Usage**\n\nYou are required to implement a custom codec to encode and decode a specific format. This format includes a prefix and suffix around the original message. \n\n### Specifications\n\n1. **Prefix**: `\"[ENC]\"`.\n2. **Suffix**: `\"[END]\"`.\n\nExamp...
0.619745
Docs: Python310_13503
C
[ "search_function", "register_custom_codec", "unregister_custom_codec" ]
3
[ [ "register_custom_codec", "search_function" ], [ "unregister_custom_codec", "search_function" ] ]
2
[]
false
[ "CustomCodecInfo" ]
true
pytest
true
[]
true
960110e0d1284ad45394ac211f244f1065345ff5
8185dbbac4f25e1a12f382226f0af0bb1b8f2093
v1.0
complete
Docs
Docs: Python310_13755_C
import asyncio async def perform_task(task_id: int) -> str: """ Simulates performing a task. Randomly raises an exception or completes successfully. Args: task_id (int): Identifier for the task. Returns: str: Task completion message or exception indication. """ async def run_tasks(n_ta...
import asyncio import random async def perform_task(task_id): """ Simulates performing a task. Randomly raises an exception or completes successfully. """ exceptions = [ asyncio.TimeoutError, asyncio.CancelledError, asyncio.InvalidStateError, asyncio.IncompleteReadError,...
import asyncio import pytest from solution import perform_task, run_tasks @pytest.mark.asyncio async def test_perform_task_success(): random.seed(0) # Control randomness for test predictability result = await perform_task(1) assert result == "Task 1 completed successfully" @pytest.mark.asyncio async def ...
[]
[ 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 random\n\nasync def perform_task(task_id):\n \"\"\"\n Simulates performing a task. Randomly raises specific asyncio exceptions or completes...
trial_gpt4o_1
{ "original_instruction": "**Problem: Asynchronous Task Manager**\n\nYou are required to implement a simplified asynchronous task manager that executes multiple asynchronous tasks concurrently. You must use the asyncio library and handle specific exceptions defined in the asyncio documentation accordingly.\n\n### Req...
0.516241
Docs: Python310_13755
C
[ "perform_task", "run_tasks" ]
2
[ [ "run_tasks", "perform_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
54c2e4c433a7f32143a9b560b7ed53589ccc26d4
93463171bf00b6decff00eef1464c7da24312d07
v1.0
complete
Docs
Docs: Python310_13790_C
import asyncio from typing import List async def download_file(url: str, destination: str) -> None: """ This coroutine should download the file from the given URL and save it to the specified destination. If an error occurs during the download, it should log the error and continue. """ pass async ...
import asyncio import aiohttp import os from typing import List async def download_file(url: str, destination: str) -> None: try: async with aiohttp.ClientSession() as session: async with session.get(url) as response: response.raise_for_status() filename = os.pat...
import os import aiohttp import shutil import pytest from unittest.mock import patch from solution import download_file, download_files, main BASE_URL = "http://example.com/" DEST_DIR = "./test_downloads/" @pytest.fixture def setup_and_teardown(): os.makedirs(DEST_DIR, exist_ok=True) yield if os.path.exis...
[ { "docstring": null, "function_declaration": "def main(urls, destination_dir):", "function_name": "main", "parameter_list": "(urls, destination_dir)" } ]
[ 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 aiohttp\nimport aiofiles\nimport os\nfrom typing import List\nimport logging\n\n# Setting up basic logging\nlogging.basicConfig(level=logging.INF...
trial_gpt4o_2
{ "original_instruction": "### Asynchronous Programming Assessment\n\n**Objective**: Demonstrate your understanding of Python's asynchronous programming by implementing a coroutine-based solution for a real-world problem.\n\n#### Problem Statement:\n\nYou are tasked with creating an asynchronous file download manager...
0.610228
Docs: Python310_13790
C
[ "download_file", "download_files", "main" ]
3
[ [ "download_files", "download_file" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
db03a005893230a7d1e3702d7cfce0ecf69876d4
2f5fb050ca3b7b923827cd02d140f5d1b1164807
v1.0
complete
Docs
Docs: Python310_14299_C
import os import tokenize from io import StringIO class CustomNannyNag(Exception): """Exception raised for ambiguous indentation detected by the customized tab nanny.""" pass def custom_tab_nanny(file_or_dir: str, verbose: bool = False, filename_only: bool = False): """ Custom tab nanny to check Pytho...
import os import tokenize from io import StringIO class CustomNannyNag(Exception): """Exception raised for ambiguous indentation detected by the customized tab nanny.""" pass def check_indentation(file_content): """ Check for indentation issues in the given file content. Returns the number of inde...
import os import tempfile from solution import custom_tab_nanny, CustomNannyNag def test_check_single_file_with_no_issues(): temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".py") temp_file.write(b"def foo():\n pass\n") temp_file.close() custom_tab_nanny(temp_file.name, verbose=Tru...
[]
[ 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 tokenize\n\nclass CustomNannyNag(Exception):\n pass\n\ndef check_indentation_issues(file_path):\n issues = []\n with open(file_path, 'r') as ...
trial_gpt4o_2
{ "original_instruction": "**Question: Ambiguous Indentation Checker**\n\n**Objective:**\nImplement a function `custom_tab_nanny(file_or_dir, verbose=False, filename_only=False)` that mimics the functionality of the `tabnanny` module but with the following custom features:\n1. The function should accept a directory o...
0.499397
Docs: Python310_14299
C
[ "check_indentation", "custom_tab_nanny" ]
2
[ [ "custom_tab_nanny", "check_indentation" ] ]
1
[]
false
[ "CustomNannyNag" ]
true
pytest
true
[]
true
1d0018c79d5f935cfc93dde5df14f89896d61924
1652d8b86540f1a4b057f41eac2e20bcbe8e2668
v1.0
complete
Docs
Docs: Python310_11421_C
import itertools from collections import defaultdict def log_iterator(file_path): """ Yields each line in the given log file. """ def parse_log(log_iter): """ Parses each line from log iterator into a tuple (timestamp, user_id, action). """ def filter_by_action(log_iter, action_type): """...
import itertools from collections import defaultdict def log_iterator(file_path): """ Yields each line in the given log file. """ with open(file_path, 'r') as file: for line in file: yield line.strip() def parse_log(log_iter): """ Parses each line from log iterator into a t...
import pytest from solution import log_iterator, parse_log, filter_by_action, group_by_user, user_activity_summary def test_log_iterator(tmp_path): file_path = tmp_path / "log.txt" lines = ["2023-10-01 12:00:00, user123, login", "2023-10-01 12:05:00, user123, upload"] file_path.write_text("\n".join(lines))...
[ { "docstring": "Yields each line in the given log file.", "function_declaration": "def log_iterator(file_path):", "function_name": "log_iterator", "parameter_list": "(file_path)" }, { "docstring": "Parses each line from log iterator into a tuple (timestamp, user_id, action).", "function_...
[ 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 itertools\nimport functools\n\ndef log_iterator(file_path):\n \"\"\"\n Returns an iterator that yields each line in the log file.\n \"\"\"\n with ope...
trial_gpt4o_1
{ "original_instruction": "### Advanced Python Functional Programming: Assess Students' Understanding of Iterators, Generators, and Higher-Order Functions\n\n#### Objective:\nCreate a Python script that processes a log file and extracts information about user activity. Use iterators, generators, and functions from it...
0.623073
Docs: Python310_11421
C
[ "log_iterator", "parse_log", "filter_by_action", "group_by_user", "user_activity_summary" ]
5
[ [ "user_activity_summary", "group_by_user" ], [ "user_activity_summary", "log_iterator" ], [ "user_activity_summary", "parse_log" ] ]
3
[]
false
[]
false
pytest
true
[]
true
3d7a2656f19b07df4acc541ba878e5b803cb6d94
80c855175de19d785b9dafccb001ae1a4357b064
v1.0
complete
Docs
Docs: Python310_14116_C
import asyncio import os async def download_file(url: str, dest: str) -> None: """ Downloads a file from the given URL to the destination dest asynchronously. """ pass async def download_manager(urls: list[str], dest_folder: str) -> None: """ Manages the concurrent downloading of files from th...
import asyncio import aiohttp import os async def download_file(url: str, dest: str) -> None: """ Downloads a file from the given URL to the destination dest asynchronously. """ async with aiohttp.ClientSession() as session: async with session.get(url) as response: if response.statu...
import asyncio import aiohttp import os import pytest from unittest.mock import patch, mock_open from solution import download_file, download_manager @pytest.mark.asyncio async def test_download_file(): url = "http://example.com/file1" dest = "test_downloads/file1" with patch("aiohttp.ClientSession....
[]
[ 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 asyncio\nimport aiohttp\nimport os\n\nasync def download_file(url: str, dest: str) -> None:\n \"\"\"\n Downloads a file from a given URL to a specified des...
trial_gpt4o_2
{ "original_instruction": "**Question: Asynchronous File Download Manager**\n\n**Background:**\nYou are tasked with creating an asynchronous file download manager. Using the asyncio library, the manager should be able to:\n1. Establish an event loop.\n2. Schedule multiple file download tasks concurrently.\n3. Provide...
0.579521
Docs: Python310_14116
C
[ "download_file", "download_manager" ]
2
[ [ "download_manager", "download_file" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
6698dd050b751b1f596464b7ad620f57dab7b3c9
314bd7efed49e326b1d2f31d1d83308b67e6a992
v1.0
complete
Docs
Docs: Python310_14418_C
import multiprocessing from multiprocessing import Pool, Queue import logging def fetch_url(queue, url): """ Function that fetches the content of a URL and puts it into a queue. """ pass def concurrent_web_scraper(urls: list[str], num_workers: int) -> dict[str, str]: """ Fetch HTML content fro...
import multiprocessing import requests from multiprocessing import Pool, Queue import logging def fetch_url(queue, url): """ Function that fetches the content of a URL and puts it into a queue. """ try: response = requests.get(url) response.raise_for_status() queue.put((url, res...
from solution import concurrent_web_scraper def test_concurrent_web_scraper(): urls = [ "https://httpbin.org/get", "https://httpbin.org/status/404" ] results = concurrent_web_scraper(urls, num_workers=2) assert "https://httpbin.org/get" in results assert "https://httpbin.o...
[ { "docstring": "Function that fetches the content of a URL and puts it into a queue.", "function_declaration": "def fetch_url(queue, url):", "function_name": "fetch_url", "parameter_list": "(queue, url)" }, { "docstring": "Fetch HTML content from a list of URLs concurrently using multiproces...
[ 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 multiprocessing\nimport requests\nfrom multiprocessing import Pool, Queue\nimport logging\n\ndef fetch_url(queue, url):\n \"\"\"\n Function that fetches th...
trial_gpt4o_0
{ "original_instruction": "In this assessment, your task is to implement a Python program that uses the `multiprocessing` module to simulate a simplified version of a concurrent web scraper. You will create multiple worker processes to fetch data from a list of URLs concurrently, process the fetched data, and store t...
0.615707
Docs: Python310_14418
C
[ "fetch_url", "concurrent_web_scraper" ]
2
[ [ "concurrent_web_scraper", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
6263a937c61a2d7ce6aa33e4d6fb4e0fd6e4847e
93401576a977a944a0011fc23c0c6d10ab867c91
v1.0
complete
Docs
Docs: Scikit_14035_C
import numpy as np from sklearn.metrics import mean_absolute_error, r2_score def custom_scorer(y_true, y_pred): """ Custom scoring function that combines the Mean Absolute Error (MAE) and R² score. Parameters: y_true (array-like): True target values y_pred (array-like): Predicted target values...
import numpy as np from sklearn.metrics import mean_absolute_error, r2_score def custom_scorer(y_true, y_pred): """ Custom scoring function that combines the Mean Absolute Error (MAE) and R² score. Parameters: y_true (array-like): True target values y_pred (array-like): Predicted target values...
from solution import custom_scorer, evaluate_models import numpy as np import pandas as pd def test_custom_scorer(): # Test with simple data y_true = np.array([100, 200, 300]) y_pred = np.array([110, 190, 290]) score = custom_scorer(y_true, y_pred) # Calculate manually mae = np.mean(np.abs...
[ { "docstring": "Custom scoring function that combines the Mean Absolute Error (MAE) and R² score.\n\nParameters:\ny_true (array-like): True target values\ny_pred (array-like): Predicted target values\n\nReturns:\nfloat: Custom score calculated as (1 - MAE/mean(y_true)) * (R² + 1)", "function_declaration": "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.metrics import mean_absolute_error, r2_score\n\ndef custom_scorer(y_true, y_pred):\n \"\"\"\n Custom scoring function that combin...
trial_gpt4o_2
{ "original_instruction": "#### Objective\nDemonstrate your ability to use scikit-learn's evaluation metrics by implementing a custom scoring function for a regression task. Then, use this custom scorer to evaluate and compare models using cross-validation.\n\n#### Problem Statement\nYou are given a dataset of house ...
0.687357
Docs: Scikit_14035
C
[ "custom_scorer", "evaluate_models" ]
2
[ [ "evaluate_models", "custom_scorer" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "pandas", "sklearn" ]
false
97a98ad17d9f9ec034822d0d2ccb703a45a2ba8e
905a1adb655a0027c436b7c0805b3896ec7b728e
v1.0
complete
Docs
Docs: Python310_14449_C
import heapq import itertools def add_task(scheduler, task, priority): """Add a new task with the given priority. If the task already exists, update its priority. """ ... def remove_task(scheduler, task): """Remove the task from the scheduler. Mark it as removed. """ ... def pop_task(...
import heapq import itertools def add_task(scheduler, task, priority): """ Add a new task or update the priority of an existing task. """ if task in scheduler['entry_finder']: remove_task(scheduler, task) count = next(scheduler['counter']) entry = [priority, count, task] scheduler['...
import pytest from solution import add_task, remove_task, pop_task, change_task_priority def test_add_task(): scheduler = {'pq': [], 'entry_finder': {}, 'REMOVED': '<removed-task>', 'counter': itertools.count()} add_task(scheduler, 'task1', 2) add_task(scheduler, 'task2', 1) assert 'task1' in scheduler...
[ { "docstring": "Add a new task or update the priority of an existing task.", "function_declaration": "def add_task(scheduler, task, priority):", "function_name": "add_task", "parameter_list": "(scheduler, task, priority)" }, { "docstring": "Mark a task as removed. Raise KeyError if not found...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\nimport itertools\n\ndef add_task(scheduler, task, priority):\n \"\"\"\n Add a new task or update the priority of an existing task.\n \"\"\"\n ...
trial_gpt4o_8
{ "original_instruction": "<|Analysis Begin|>\n\nThe provided documentation pertains to the `heapq` module in Python, which implements the heap queue algorithm, also known as the priority queue algorithm. The module supports various operations on heaps, such as pushing elements, popping the smallest element, pushing ...
0.577583
Docs: Python310_14449
C
[ "add_task", "remove_task", "pop_task", "change_task_priority" ]
4
[ [ "add_task", "remove_task" ], [ "change_task_priority", "add_task" ], [ "change_task_priority", "remove_task" ] ]
3
[]
false
[]
false
pytest
true
[]
true
5ef8a570798c78b5b9703939a1d032e17fe3e6bf
3095bf1836254b5b84691c9236d287dbb767583d
v1.0
complete
Docs
Docs: Python310_14211_C
import signal import time import sys def cleanup(): """ Perform cleanup operations such as releasing resources or printing final messages. """ # Implement the cleanup logic def sigint_handler(signum, frame): """ Handle SIGINT signal (Interrupt from keyboard). """ # Implement the SIGINT handler def si...
import signal import time import sys def cleanup(): print("Performing cleanup operations...") def sigint_handler(signum, frame): print("SIGINT received. Cleaning up...") cleanup() sys.exit(0) def sigalrm_handler(signum, frame): print("SIGALRM: Operation timed out.") def sigterm_handler(signum, f...
import subprocess import time import os import signal def test_sigint_handling(): process = subprocess.Popen(["python3", "solution.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) time.sleep(2) os.kill(process.pid, signal.SIGINT) stdout, stderr = process.communicate() assert b"SIGINT received....
[ { "docstring": null, "function_declaration": "def cleanup():", "function_name": "cleanup", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def sigint_handler(signum, frame):", "function_name": "sigint_handler", "parameter_list": "(signum, frame)" }, { ...
[ 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import signal\nimport time\nimport sys\n\ndef cleanup():\n print(\"Performing cleanup operations...\")\n\ndef sigint_handler(signum, frame):\n print(\"SIGINT rece...
trial_gpt4o_0
{ "original_instruction": "### **Advanced Signal Handling in Python**\n\n### Objective\n\nWrite a Python program demonstrating advanced usage of the `signal` module. Your task is to implement a robust signal handling mechanism that can handle multiple specific signals, perform a timed operation, and ensure proper cle...
0.520231
Docs: Python310_14211
C
[ "cleanup", "sigint_handler", "sigalrm_handler", "sigterm_handler", "long_running_operation", "main" ]
6
[ [ "long_running_operation", "cleanup" ], [ "sigint_handler", "cleanup" ], [ "sigterm_handler", "cleanup" ] ]
3
[]
false
[]
false
pytest
false
[]
true
35f383c51dbdb36c0841a1146721bfd7a61347a5
d7b409673598c98c5b9d4f24286cc7595445f80e
v1.0
complete
Docs
Docs: Python310_13422_C
import asyncio import random from typing import List async def task_coro(task_id: int) -> str: """ Simulates a task that will take between 1 to 5 seconds to complete. Once done, it will return a string `Task {task_id} completed`. """ ... async def gather_tasks(n: int) -> List[str]: """ Creates and...
import asyncio import random from typing import List async def task_coro(task_id: int) -> str: """ Simulates a task that takes between 1 to 5 seconds to complete. Once done, it returns a string `Task {task_id} completed`. """ await asyncio.sleep(random.uniform(1, 5)) return f'Task {task_id} com...
import pytest import asyncio from solution import task_coro, gather_tasks, main @pytest.mark.asyncio async def test_task_coro(): result = await task_coro(1) assert result == 'Task 1 completed' @pytest.mark.asyncio async def test_gather_tasks(): results = await gather_tasks(5) assert len(results) == 5 ...
[]
[ 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 asyncio\nimport random\nfrom typing import List\n\nasync def task_coro(task_id: int) -> str:\n \"\"\"\n Simulates a task that takes between 1 to 5 seconds ...
trial_gpt4o_0
{ "original_instruction": "### Asynchronous Task Management with asyncio\n\n**Objective:**\nImplement an asynchronous Python program that utilizes different features of the asyncio package to manage and coordinate multiple tasks.\n\n**Problem Statement:**\nYou are required to create an asynchronous program that execu...
0.604728
Docs: Python310_13422
C
[ "task_coro", "gather_tasks", "main" ]
3
[ [ "gather_tasks", "task_coro" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2c4fe51eca406f97b4d4a939d66a31e4d91b1519
065d842f7f0ea172a559ef2d44bd6e469eaccd32
v1.0
complete
Docs
Docs: Python310_14755_C
import asyncio clients = set() async def handle_client(reader, writer): """ An asynchronous function to manage communication with each connected client. Reads messages from a client, and upon receiving a message, broadcasts it to all other clients. """ pass async def broadcast_message(message, cl...
import asyncio import traceback clients = set() async def handle_client(reader, writer): addr = writer.get_extra_info('peername') print(f"{addr} is connected") clients.add(writer) try: while True: data = await reader.read(100) # Customize the buffer size as needed ...
import asyncio import pytest from solution import start_server, handle_client, broadcast_message from asyncio import StreamReader, StreamWriter @pytest.fixture def event_loop(): loop = asyncio.new_event_loop() yield loop loop.close() @pytest.mark.asyncio async def test_broadcast_message(): clients = ...
[]
[ 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\nclients = []\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n print(f\"Connected with {addr}\")\n cli...
trial_gpt4o_2
{ "original_instruction": "You are required to implement a Python program using the asyncio library to simulate a simplified multi-user chat server. The server will allow multiple clients to connect, send messages, and broadcast them to all connected clients simultaneously.\n\n### Objectives\n\n1. **Create a Chat Ser...
0.544818
Docs: Python310_14755
C
[ "handle_client", "broadcast_message", "start_server" ]
3
[ [ "handle_client", "broadcast_message" ], [ "start_server", "handle_client" ] ]
2
[]
false
[]
false
pytest
true
[]
true
82ebd5b31b76877aaeed9ab3f362cc813d274be8
3cc8a3d37a04fed0bc39e2dfc0a38d8318604585
v1.0
complete
Docs
Docs: Python310_14547_C
import hmac import hashlib from typing import Tuple def generate_hmac(key: bytes, message: bytes, digestmod: str) -> str: """ Generates an HMAC digest for the given message using the provided key and digest method. >>> generate_hmac(b'secret_key', b'This is a critical message.', 'sha256') # Expected: ...
import hmac import hashlib from typing import Tuple def generate_hmac(key: bytes, message: bytes, digestmod: str) -> str: """ Generates an HMAC digest for the given message using the provided key and digest method. Parameters: - key (bytes): The secret key used for HMAC generation. - messa...
from solution import generate_hmac, verify_hmac, authenticate_message def test_generate_hmac(): key = b'secret_key' message = b'This is a critical message.' digestmod = 'sha256' hmac_digest = generate_hmac(key, message, digestmod) assert isinstance(hmac_digest, str) assert len(hmac_digest) == 6...
[ { "docstring": "Generates an HMAC digest for the given message using the provided key\nand digest method.\n\nParameters:\n- key (bytes): The secret key used for HMAC generation.\n- message (bytes): The message to generate the HMAC for.\n- digestmod (str): The hash algorithm to use (e.g., 'sha256').\n\nReturns:\...
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import hmac\nimport hashlib\nfrom typing import Tuple\n\ndef generate_hmac(key: bytes, message: bytes, digestmod: str) -> str:\n \"\"\"\n ...
trial_gpt4o_1
{ "original_instruction": "**Question: HMAC Authentication System**\n\nYou are tasked with designing a secure authentication system for a sensitive application. The system should use the HMAC (Keyed-Hashing for Message Authentication) algorithm to generate and verify message digests to ensure the integrity and authen...
0.861676
Docs: Python310_14547
C
[ "generate_hmac", "verify_hmac", "authenticate_message" ]
3
[ [ "authenticate_message", "generate_hmac" ], [ "authenticate_message", "verify_hmac" ], [ "verify_hmac", "generate_hmac" ] ]
3
[]
false
[]
false
pytest
true
[]
true
e8c70f53fd2d9ee40d4bb9a75c0a2c85a4b08a94
a26228ed270aa90a8a2e82deb98ca417d5b38dfa
v1.0
complete
Docs
Docs: Python310_14445_C
def is_pylong_object(obj: Any) -> bool: """ Returns True if the object is an instance of int, False otherwise. >>> is_pylong_object(123) True >>> is_pylong_object("123") False """ pass def create_pylong_from_c_long(value: int) -> int: """ Returns a Python integer created from a ...
def is_pylong_object(obj): """ Returns True if the object is an instance of int, False otherwise. """ return isinstance(obj, int) def create_pylong_from_c_long(value): """ Returns a Python integer created from a C long, which is conceptually similar to a regular int in Python. Raises Va...
import pytest from solution import ( is_pylong_object, create_pylong_from_c_long, convert_pylong_to_c_long, create_pylong_from_string ) def test_is_pylong_object(): assert is_pylong_object(123) is True assert is_pylong_object(0) is True assert is_pylong_object(-123) is True assert is_p...
[ { "docstring": "Returns True if the object is an instance of int, False otherwise.", "function_declaration": "def is_pylong_object(obj):", "function_name": "is_pylong_object", "parameter_list": "(obj)" }, { "docstring": "Returns a Python integer created from a C long, which is\nconceptually ...
[ 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 is_pylong_object(obj):\n \"\"\"\n Returns True if the object is an instance of int, False otherwise.\n \"\"\"\n return isinstance(obj, int)\n\ndef creat...
trial_gpt4o_0
{ "original_instruction": "### Question: PyLongObject Conversion Utility\n\nYou are tasked with implementing a utility that deals with Python integer objects (`PyLongObject`). This utility should perform multiple operations, including type checking, conversions, and error handling. \n\n#### Functions to Implement\n\n...
0.52585
Docs: Python310_14445
C
[ "is_pylong_object", "create_pylong_from_c_long", "convert_pylong_to_c_long", "create_pylong_from_string" ]
4
[ [ "convert_pylong_to_c_long", "is_pylong_object" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b335dcb8eed8bfacad606abcfd5e17ffe792e446
30d6f79ad30cd4f982362ae83ef7f202f4146308
v1.0
complete
Docs
Docs: Pytorch_14434_C
import torch import torch.autograd.profiler as profiler def on_function_enter(record_fn): """ Log entering information of an operator. >>> on_function_enter(FakeRecordFunction()) Entering test_func with 3 inputs """ print(f"Entering {record_fn.name} with {len(record_fn.inputs)} inputs") def on...
import torch import torch.autograd.profiler as profiler def on_function_enter(record_fn): print(f"Entering {record_fn.name} with {len(record_fn.inputs)} inputs") def on_function_exit(record_fn): print(f"Exiting {record_fn.name}") def init_operator_profiling(): torch.autograd.profiler.addGlobalCallback( ...
from solution import on_function_enter, on_function_exit, log_api_usage import pytest def test_on_function_enter(capsys): class FakeRecordFunction: name = 'test_func' inputs = [1, 2, 3] on_function_enter(FakeRecordFunction()) captured = capsys.readouterr() assert "Entering test_fun...
[ { "docstring": null, "function_declaration": "def on_function_enter(record_fn):", "function_name": "on_function_enter", "parameter_list": "(record_fn)" }, { "docstring": null, "function_declaration": "def on_function_exit(record_fn):", "function_name": "on_function_exit", "parame...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.autograd.profiler as profiler\n\ndef on_function_enter(record_fn):\n print(f\"Entering {record_fn.name} with {len(record_fn.inputs)} input...
trial_gpt4o_8
{ "original_instruction": "### PyTorch Fleet-wide Operator Profiling and Logging\n\nIn large-scale machine learning deployments, it is crucial to monitor the performance and utilization of various operations to optimize resource usage and debug efficiently. PyTorch provides hooks and callbacks to facilitate this kind...
0.433537
Docs: Pytorch_14434
C
[ "on_function_enter", "on_function_exit", "init_operator_profiling", "log_api_usage", "init_api_usage_logging" ]
5
[ [ "init_api_usage_logging", "log_api_usage" ], [ "init_operator_profiling", "on_function_enter" ], [ "init_operator_profiling", "on_function_exit" ] ]
3
[]
false
[]
false
pytest
true
[ "torch" ]
false
50486428c634a24aa26bcddc9c58aeb2d2908b24
a6e3571be268d2e6d469c47974611d5f43a30b59
v1.0
complete
Docs
Docs: Python310_14291_C
import asyncio async def io_bound_task(task_name: str, delay: int): """ Coroutine to simulate I/O-bound operation Args: task_name (str): Name of the task. delay (int): Time in seconds for which the task should "sleep". Prints: Start message: "Task <task_name> started" ...
import asyncio # Coroutine to simulate I/O-bound operation async def io_bound_task(task_name, delay): print(f"Task {task_name} started") await asyncio.sleep(delay) print(f"Task {task_name} completed") # Main execution function async def main_execution(): task_configs = [("A", 2), ("B", 6), ("C", 3)] ...
import asyncio import pytest from solution import io_bound_task, main_execution @pytest.mark.asyncio async def test_io_bound_task(capsys): await io_bound_task("X", 1) captured = capsys.readouterr() assert "Task X started" in captured.out assert "Task X completed" in captured.out @pytest.mark.asyncio a...
[]
[ 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\n\n# Coroutine to simulate I/O-bound operation\nasync def io_bound_task(task_name, delay):\n print(f\"Task {task_name} started\")\n await asyncio.s...
trial_gpt4o_1
{ "original_instruction": "### AsyncIO Concurrency Problem\n\n#### Description\n\nYou are tasked with writing a Python script that performs multiple I/O-bound operations concurrently using the asyncio library. The problem is designed to assess your understanding of async/await syntax, task creation, managing concurre...
0.629321
Docs: Python310_14291
C
[ "io_bound_task", "main_execution" ]
2
[ [ "main_execution", "io_bound_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
561a99d7ac58ceff95442c3dae27eb019d28a20c
0fe60edde6f143214d837cc78272392e84086bd5
v1.0
complete
Docs
Docs: Python310_14184_C
import asyncio import socket from asyncio import StreamReader, StreamWriter async def handle_client(reader: StreamReader, writer: StreamWriter): """ Handle the client sending messages and echo back with "Echo: " prefix. """ data = await reader.read(100) message = data.decode() echo_message = f...
import asyncio import socket async def handle_client(reader, writer): data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received {message} from {addr}") echo_message = f"Echo: {message}" writer.write(echo_message.encode()) await writer....
import asyncio import pytest from asyncio import StreamReader, StreamWriter # Import the solution code from solution import handle_client, run_server, run_client @pytest.mark.asyncio async def test_handle_client(): async def mock_client(reader: StreamReader, writer: StreamWriter): writer.write(b"Hello, Se...
[]
[ 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\n# Asynchronous TCP Server\nasync def handle_client(reader, writer):\n while True:\n data = await reader.read(100)\n if not data:\n ...
trial_gpt4o_1
{ "original_instruction": "**Networking and Asynchronous I/O Coding Challenge**\n\n**Objective:**\nImplement a simple asynchronous TCP server and client using Python's `asyncio` and `socket` modules.\n\n**Problem Statement:**\n\n1. **Async TCP Server:**\n - Create an asynchronous TCP server that listens on a specif...
0.671726
Docs: Python310_14184
C
[ "handle_client", "run_server", "run_client" ]
3
[ [ "run_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
264d6f48dd4541e2c7aac71d2c9380fde7232db5
ca19e4803aec3994db19360b83d758372c64aeac
v1.0
complete
Docs
Docs: Pytorch_14268_C
import torch def create_block_mask(shape, fill_value): """Utility to create a simple block mask.""" return torch.full(shape, fill_value) def create_mask(shape, fill_value): """Utility to create a simple mask.""" return torch.full(shape, fill_value) def and_masks(mask1, mask2): """Combine two mask...
import torch import torch.nn.functional as F def create_block_mask(shape, fill_value): """Utility to create a simple block mask.""" return torch.full(shape, fill_value) def create_mask(shape, fill_value): """Utility to create a simple mask.""" return torch.full(shape, fill_value) def and_masks(mask1,...
import pytest import torch from solution import apply_complex_mask def test_apply_complex_mask_basic(): tensor = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) mask_shape = (3, 3) result = apply_complex_mask(tensor, mask_shape) expected = tensor # Since all masks are true, the output should be the sa...
[ { "docstring": "Utility to create a simple block mask.", "function_declaration": "def create_block_mask(shape, fill_value):", "function_name": "create_block_mask", "parameter_list": "(shape, fill_value)" }, { "docstring": "Utility to create a simple mask.", "function_declaration": "def c...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.nn.attention.flex_attention import create_block_mask, create_mask, and_masks, or_masks\n\ndef apply_complex_mask(tensor: torch.Tensor, mask_sha...
trial_gpt4o_3
{ "original_instruction": "#### Objective\nImplement a function that creates a complex mask by combining several basic masks using the block mask utilities provided in the `torch.nn.attention.flex_attention` module. Then, apply this combined mask to a given tensor to filter out specific elements as defined by the mas...
0.471112
Docs: Pytorch_14268
C
[ "create_block_mask", "create_mask", "and_masks", "or_masks", "apply_complex_mask" ]
5
[ [ "apply_complex_mask", "and_masks" ], [ "apply_complex_mask", "create_block_mask" ], [ "apply_complex_mask", "create_mask" ], [ "apply_complex_mask", "or_masks" ] ]
4
[]
false
[]
false
pytest
true
[ "torch" ]
false
7810224f88cbcabdaddd2a387a7c04c3a6d31e1d
75e914ea6cd2d77ea06ad1e7311996e894d19023
v1.0
complete
Docs
Docs: Python310_14855_C
import asyncio async def compute_square(fut, n): """Calculate the square of n and set it as the result of the Future object. >>> loop = asyncio.get_running_loop() >>> fut = loop.create_future() >>> await compute_square(fut, 3) >>> fut.result() 9 """ pass async def gather_squares(number...
import asyncio async def compute_square(fut, n): # Simulate a delay await asyncio.sleep(2) # Set the result of the Future fut.set_result(n * n) async def gather_squares(numbers): loop = asyncio.get_running_loop() futures = [] for number in numbers: fut = loop.create_future() ...
import asyncio from solution import compute_square, gather_squares, main async def test_compute_square(): loop = asyncio.get_running_loop() fut = loop.create_future() await compute_square(fut, 3) assert fut.result() == 9 async def test_gather_squares(): result = await gather_squares([1, 2, 3]) ...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def compute_square(fut, n):\n # Simulate a delay\n await asyncio.sleep(2)\n # Set the result of the Future\n fut.set_result(n * n)\n...
trial_gpt4o_0
{ "original_instruction": "**Programming Task: Work with Future and Task Objects in Asyncio**\n\n**Objective:**\nWrite a Python program to create and manage `Future` and `Task` objects using the `asyncio` library.\n\n**Task Description:**\n1. Create an asynchronous function `async compute_square(fut, n)` that takes a...
0.5387
Docs: Python310_14855
C
[ "compute_square", "gather_squares", "main" ]
3
[ [ "gather_squares", "compute_square" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6682c4a40fa8eb803215bfe84227bc519b73b50e
1ca5189bcb2fac2ec4fe1636d7ac91acc39d03e1
v1.0
complete
Docs
Docs: Pytorch_14370_C
import torch from torch.nn.functional import softmax def custom_attention(input_tensor: torch.Tensor, block_size: int) -> torch.Tensor: """ Apply a custom attention mechanism using block masks to the input tensor. Args: input_tensor (torch.Tensor): The input tensor of shape (batch_size, seq_length...
import torch from torch.nn.functional import softmax def create_block_mask(seq_length, block_size): mask = torch.zeros(seq_length, seq_length, dtype=torch.bool) for i in range(0, seq_length, block_size): mask[i:i+block_size, i:i+block_size] = 1 return mask def custom_attention(input_tensor: torch....
import torch from solution import custom_attention def test_custom_attention_basic(): input_tensor = torch.randn(2, 10, 64) # (batch_size, seq_length, embedding_dim) block_size = 3 output_tensor = custom_attention(input_tensor, block_size) assert output_tensor.shape == input_tensor.shape def test_cus...
[ { "docstring": null, "function_declaration": "def create_block_mask(seq_length, block_size):", "function_name": "create_block_mask", "parameter_list": "(seq_length, block_size)" }, { "docstring": "Apply a custom attention mechanism using block masks to the input tensor.\n\nArgs:\n input_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 torch\nfrom torch.nn.functional import softmax\n\ndef create_block_mask(seq_length, block_size):\n \"\"\"\n Creates a block mask of shape (seq_length, seq_...
trial_gpt4o_5
{ "original_instruction": "### Advanced PyTorch Coding Challenge: Attention Masks\n\n#### Background\nIn attention mechanisms, masks are used to control which positions can be attended to, allowing you to build more complex and flexible models. PyTorch provides various utilities to create and manipulate these masks w...
0.572405
Docs: Pytorch_14370
C
[ "create_block_mask", "custom_attention" ]
2
[ [ "custom_attention", "create_block_mask" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
5b945159c27f5375dfa44e9efd624e1ff0631d7a
5e5572a2ccdfc0f913e21aa45719523c5a7ce1d4
v1.0
complete
Docs
Docs: Python310_14870_C
import concurrent.futures from typing import List, Dict import urllib.request def fetch_status(url: str, timeout: float) -> bool: try: with urllib.request.urlopen(url, timeout=timeout) as response: return response.status == 200 except: return False def check_urls(urls: List[str], m...
import concurrent.futures from typing import List, Dict import urllib.request def fetch_status(url: str, timeout: float) -> bool: try: with urllib.request.urlopen(url, timeout=timeout) as response: return response.status == 200 except: return False def check_urls(urls: List[str], m...
from solution import check_urls def test_check_urls_all_reachable(): urls = [ "http://www.google.com", "http://www.python.org" ] results = check_urls(urls, max_workers=2, timeout=5.0) assert results == { "http://www.google.com": True, "http://www.python.org": True } ...
[ { "docstring": null, "function_declaration": "def fetch_status(url, timeout):", "function_name": "fetch_status", "parameter_list": "(url, timeout)" }, { "docstring": null, "function_declaration": "def check_urls(urls, max_workers, timeout):", "function_name": "check_urls", "param...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import concurrent.futures\nfrom typing import List, Dict\nimport urllib.request\n\ndef fetch_status(url: str, timeout: float) -> bool:\n try:\n with urllib.re...
trial_gpt4o_0
{ "original_instruction": "#### Objective\nTo assess the understanding and ability to use Python's `concurrent.futures` module, specifically focusing on `ThreadPoolExecutor` and `ProcessPoolExecutor` for managing asynchronous tasks.\n\n#### Question\nYou are tasked with processing a list of URLs to check whether they...
0.66682
Docs: Python310_14870
C
[ "fetch_status", "check_urls" ]
2
[ [ "check_urls", "fetch_status" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6188830b94d03c2473d8ce3e7d6b41583b53441d
9bb532de2ff58949186020be10531df2c1465b08
v1.0
complete
Docs
Docs: Pytorch_13475_C
import torch def select_cuda_device(device_index: int): """ Sets the selected CUDA device and prints the device name. Raises an error if the device is not available. """ if not torch.cuda.is_available(): raise RuntimeError("CUDA is not available.") if device_index < 0 or device_index >=...
import torch import time def select_cuda_device(device_index): """ Sets the selected CUDA device and prints the device name. Raises an error if the device is not available. """ if not torch.cuda.is_available(): raise RuntimeError("CUDA is not available.") if device_index < 0 or device_i...
import pytest import torch from solution import select_cuda_device, perform_tensor_operations, async_tensor_operations, cuda_graph_operations def test_select_cuda_device(): if torch.cuda.is_available(): select_cuda_device(0) # Assuming at least one CUDA device is available assert True else: ...
[ { "docstring": "Sets the selected CUDA device and prints the device name.\nRaises an error if the device is not available.", "function_declaration": "def select_cuda_device(device_index):", "function_name": "select_cuda_device", "parameter_list": "(device_index)" }, { "docstring": "Creates t...
[ 0, 0, 0, 0, 0, 1, 0, 1, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport time\n\ndef select_cuda_device(device_index):\n \"\"\"\n Selects a CUDA device based on the given index and verifies its availability.\n \...
trial_gpt4o_5
{ "original_instruction": "### Description\n\nYou are tasked with implementing a custom CUDA tensor operation pipeline using PyTorch, incorporating various CUDA features, such as device management, memory management, and CUDA streams. The pipeline will process data stored on multiple CUDA devices, perform operations ...
0.466071
Docs: Pytorch_13475
C
[ "select_cuda_device", "perform_tensor_operations", "async_tensor_operations", "cuda_graph_operations" ]
4
[ [ "async_tensor_operations", "select_cuda_device" ], [ "cuda_graph_operations", "select_cuda_device" ], [ "perform_tensor_operations", "select_cuda_device" ] ]
3
[]
false
[]
false
pytest
true
[ "torch" ]
false
1ce7093e2cca4760eeba47cd96160d363f2e2f16
c219e3aad16abb354c0174172f7f5bc0aa286191
v1.0
complete
Docs
Docs: Python310_13953_C
import string import random import mailcap def generate_secure_filename() -> str: """Generate a secure temporary filename.""" return ''.join(random.choices(string.ascii_letters + string.digits, k=12)) def generate_mailcap_command(mime_type: str, key: str, params: dict = None) -> tuple: """ Uses the m...
import string import random import mailcap def generate_secure_filename() -> str: """Generate a secure temporary filename.""" return ''.join(random.choices(string.ascii_letters + string.digits, k=12)) def generate_mailcap_command(mime_type: str, key: str, params: dict = None) -> tuple: caps = mailcap.getc...
from solution import generate_mailcap_command def test_generate_mailcap_command_view(): result = generate_mailcap_command('text/plain', 'view') assert result is not None assert isinstance(result, tuple) assert len(result) == 2 assert isinstance(result[0], str) or result[0] is None assert isinst...
[ { "docstring": "Generate a secure temporary filename.", "function_declaration": "def generate_secure_filename():", "function_name": "generate_secure_filename", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def generate_mailcap_command(mime_type, key, params=None...
[ 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 mailcap\nimport random\nimport string\nimport shlex\n\ndef generate_secure_filename() -> str:\n \"\"\"Generate a secure temporary filename using alphanumeric ...
trial_gpt4o_2
{ "original_instruction": "#### Objective:\nYou are required to implement a Python function utilizing the `mailcap` module to find applicable commands for given MIME types from Mailcap files, and enhance the command by generating a secure filename.\n\n#### Problem Statement:\nImplement a function `generate_mailcap_co...
0.56283
Docs: Python310_13953
C
[ "generate_secure_filename", "generate_mailcap_command" ]
2
[ [ "generate_mailcap_command", "generate_secure_filename" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e4ed33711dc95d081a0fc1053dc22e56edbe9e5a
4690728497cc15f2803e41640daef3ddd3cd0e0d
v1.0
complete
Docs
Docs: Pytorch_14826_C
import torch import torch.nn as nn import torch.utils.data as data import torch.multiprocessing as mp def asynchronous_train(model: torch.nn.Module, dataset: torch.utils.data.Dataset, num_processes: int, epochs: int, learni...
import torch import torch.optim as optim import torch.utils.data as data import torch.multiprocessing as mp from torch.multiprocessing import Pool def data_loader(dataset): return torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True) def loss_fn(output, target): return torch.nn.functional.cross_en...
import torch import torch.nn as nn import torch.utils.data as data import torch.multiprocessing as mp from solution import asynchronous_train class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.linear = nn.Linear(784, 10) def forward(self, x): ret...
[ { "docstring": null, "function_declaration": "def data_loader(dataset):", "function_name": "data_loader", "parameter_list": "(dataset)" }, { "docstring": null, "function_declaration": "def loss_fn(output, target):", "function_name": "loss_fn", "parameter_list": "(output, target)"...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.optim as optim\nimport torch.utils.data as data\nfrom torch.multiprocessing import Pool\nimport torch.multiprocessing as mp\n\ndef data_loade...
trial_gpt4o_3
{ "original_instruction": "#### Asynchronous Model Training using PyTorch Multiprocessing\n\n**Objective:**\nImplement a function to train a neural network model asynchronously using PyTorch's multiprocessing package. Ensure efficient use of resources and proper handling of potential pitfalls such as deadlocks and CP...
0.589313
Docs: Pytorch_14826
C
[ "data_loader", "loss_fn", "train_model", "asynchronous_train" ]
4
[ [ "train_model", "data_loader" ], [ "train_model", "loss_fn" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
5afe88fd3a5edcb40795ea20b112210d402500b7
86c3c68e58d28b02a7ffee0df579da6b6d6a5e6f
v1.0
complete
Docs
Docs: Python310_13900_C
import os import tokenize def custom_check(file_or_dir: str) -> int: """ Check the specified directory (recursively) or a single Python source file for whitespace related problems and return the total count of such issues. Args: file_or_dir (str): The directory or file path to check for whites...
import os import tokenize def count_whitespace_issues(file_path): issues = 0 with open(file_path, 'r') as f: tokens = tokenize.generate_tokens(f.readline) indents = [] for toknum, tokval, _, _, _ in tokens: if toknum == tokenize.INDENT: indents.append(tokval)...
import os import pytest from solution import custom_check def test_single_file_with_issues(tmp_path): content = "def example():\n x = 1\n y = 2\n" test_file = tmp_path / "example.py" test_file.write_text(content) assert custom_check(test_file) == 1 def test_single_file_without_issues(tmp_path...
[ { "docstring": null, "function_declaration": "def count_whitespace_issues(file_path):", "function_name": "count_whitespace_issues", "parameter_list": "(file_path)" }, { "docstring": null, "function_declaration": "def custom_check(file_or_dir):", "function_name": "custom_check", "...
[ 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 os\nimport tokenize\n\ndef count_whitespace_issues(file_path):\n issues = 0\n with open(file_path, 'r') as f:\n tokens = tokenize.generate_tokens(f....
trial_gpt4o_0
{ "original_instruction": "**Objective:**\n\nImplement a function similar to `tabnanny.check()` that not only detects ambiguous indentations but also counts the total number of whitespace issues in a directory or a file. Your implementation should demonstrate a clear understanding of directory traversal, token proces...
0.634404
Docs: Python310_13900
C
[ "count_whitespace_issues", "custom_check" ]
2
[ [ "custom_check", "count_whitespace_issues" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d840c1e7ed0ce8958d8b39671721356d85379918
df0b6faae45807f46a40d8e8812f868dd352825d
v1.0
complete
Docs
Docs: Python310_14571_C
import codecs class CustomCodec(codecs.Codec): def __init__(self, shift): self.shift = shift def encode(self, input, errors='strict'): """ Encode a given string by shifting each character's Unicode code point by a specified number. >>> codec = CustomCodec(3) >>> codec.encod...
import codecs class CustomCodec(codecs.Codec): def __init__(self, shift): self.shift = shift def encode(self, input, errors='strict'): output = shift_encode(input, self.shift) return output, len(input) def decode(self, input, errors='strict'): output = shift_decode...
import codecs def test_shift_encode(): assert shift_encode("Hello, World!", 3) == b'Khoor/#Zruog$' def test_shift_decode(): assert shift_decode(b'Khoor/#Zruog$', 3) == "Hello, World!" def test_codec_encode(): codec = CustomCodec(3) assert codec.encode("Hello, World!")[0] == b'Khoor/#Zruog$' def test...
[]
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import codecs\n\nclass CustomCodec(codecs.Codec):\n def __init__(self, shift=3):\n self.shift = shift\n \n def encode(self, input, errors='strict'):\n ...
trial_gpt4o_3
{ "original_instruction": "### Custom Codec Implementation\n\n#### Objective\nYou are required to implement a custom codec for encoding and decoding data. Your custom codec should be able to encode a given string by shifting each character's Unicode code point by a specified number and decode it by reversing the proc...
0.729697
Docs: Python310_14571
C
[ "shift_encode", "shift_decode", "getregentry", "register_custom_codec" ]
4
[ [ "register_custom_codec", "getregentry" ] ]
1
[]
false
[ "CustomCodec", "IncrementalEncoder", "IncrementalDecoder" ]
true
pytest
false
[]
true
f3edc49babda36f4bfe0a9059b6284884839c330
c649b8d0739d74df29dab006f4f01b3a02e8b78b
v1.0
complete
Docs
Docs: Python310_15279_C
import asyncio import aiohttp from typing import List async def fetch_data(url: str) -> str: """ Performs an HTTP GET request to the given URL and returns the response text. Implements a timeout of 3 seconds. """ pass async def scrape_urls(urls: List[str]) -> List[str]: """ Takes a list of...
import asyncio import aiohttp from typing import List async def fetch_data(url: str) -> str: """ Performs an HTTP GET request to the given URL and returns the response text. Implements a timeout of 3 seconds. """ async with aiohttp.ClientSession() as session: try: async with ses...
import asyncio from solution import fetch_data, scrape_urls async def test_fetch_data(): result = await fetch_data("https://jsonplaceholder.typicode.com/posts") assert "userId" in result async def test_fetch_data_timeout(): result = await fetch_data("https://httpbin.org/delay/5") # This URL delays respon...
[]
[ 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\nfrom typing import List\n\nasync def fetch_data(url: str) -> str:\n \"\"\"\n Performs an HTTP GET request to the given URL and ret...
trial_gpt4o_0
{ "original_instruction": "Asynchronous Web Scraper\n\n**Objective**: The goal of this exercise is to demonstrate your understanding of Python's `asyncio` library, including creating and running coroutines, managing tasks, handling concurrency, and implementing timeouts and cancellations.\n\n**Problem Statement**:\nY...
0.639839
Docs: Python310_15279
C
[ "fetch_data", "scrape_urls", "main" ]
3
[ [ "scrape_urls", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
589c49b39028a5200781b4d70459e7ae487dcf36
62207d63a56504b26b9c49f55ae595bacbc82990
v1.0
complete
Docs
Docs: Python310_15206_C
from concurrent.futures import ThreadPoolExecutor import threading import contextvars import time import random # Create a context variable named task_id task_id = contextvars.ContextVar('task_id') def set_task_id(id): task_id.set(id) def start_task(task_number): """ Start a task by setting the task_id c...
from concurrent.futures import ThreadPoolExecutor import contextvars import threading import time import random # Step 1: Create a context variable named task_id task_id = contextvars.ContextVar('task_id') def set_task_id(id): task_id.set(id) # Step 2: Implement the start_task function def start_task(task_number...
from solution import start_task, run_tasks_in_threads def test_start_task(): task_number = 42 assert start_task(task_number) == task_number def test_run_tasks_in_threads_single_task(): task_numbers = [1] results = run_tasks_in_threads(task_numbers) assert results == task_numbers def test_run_task...
[ { "docstring": null, "function_declaration": "def set_task_id(id):", "function_name": "set_task_id", "parameter_list": "(id)" }, { "docstring": null, "function_declaration": "def start_task(task_number):", "function_name": "start_task", "parameter_list": "(task_number)" }, { ...
[ 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 concurrent.futures import ThreadPoolExecutor\nimport contextvars\nimport threading\nimport time\nimport random\n\n# Step 1: Create a context variable named task_id...
trial_gpt4o_2
{ "original_instruction": "### Advanced Python310 Coding Assessment\n\n**Objective**: Demonstrate your understanding of Python's `contextvars` module by creating a complex multi-threaded application that utilizes context variables to maintain state.\n\n**Problem Statement**:\n\nYou are required to write a Python prog...
0.610282
Docs: Python310_15206
C
[ "set_task_id", "start_task", "run_tasks_in_threads" ]
3
[ [ "run_tasks_in_threads", "start_task" ], [ "start_task", "set_task_id" ] ]
2
[]
false
[]
false
pytest
true
[]
true
0eb42b1f66e2dc4e006553298fa3cad807c63366
93e827979e780e7196c73660795d3551d86e4c43
v1.0
complete
Docs
Docs: Python310_15392_C
import sys from typing import List, Dict def setup_audit_logger(events_to_log: List[str], log_file: str) -> None: """ Sets up an audit hook to log specified events to a file. Parameters: events_to_log (List[str]): A list of event names to log. log_file (str): Path to the file for logging events. ""...
import sys import os from typing import List, Dict def audit_hook(event, args): """ This function will be used as the audit hook to log events. """ if event in sys.audit_events_to_log: with open(sys.audit_log_file, "a") as f: f.write(f"{event}: {args}\n") def setup_audit_logger(eve...
import os import sys from solution import setup_audit_logger, summarize_events def test_setup_audit_logger(): # Setting up for test events = ["os.remove", "os.rmdir"] log_file_path = "test_audit_log.txt" # Clearing log file with open(log_file_path, "w"): pass # Setting up the audit log ...
[ { "docstring": "This function will be used as the audit hook to log events.", "function_declaration": "def audit_hook(event, args):", "function_name": "audit_hook", "parameter_list": "(event, args)" }, { "docstring": "Sets up the audit logger to listen for specific events and logs them to a ...
[ 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 audit\nimport json\nfrom typing import List, Dict\n\ndef setup_audit_logger(events_to_log: List[str], log_file: str) -> None:\n def audit_hook(event, args):\n...
trial_gpt4o_2
{ "original_instruction": "### Coding Assessment: Audit Event Logger\n\n#### Objective:\nYou are to implement a Python function that sets up an audit hook, logs specific audit events to a file, and then provides a summary of these events.\n\n#### Requirements:\n1. Implement a function `setup_audit_logger(events_to_lo...
0.645935
Docs: Python310_15392
C
[ "audit_hook", "setup_audit_logger", "summarize_events" ]
3
[ [ "setup_audit_logger", "audit_hook" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1b3b80002fb1030035d063cbd83253b0c6c99d57
bbd9b315a37b205afa710860ba1dc709342d38a6
v1.0
complete
Docs
Docs: Python310_14244_C
import asyncio async def perform_async_operations(timeout: int, cancel_task2: bool) -> dict: """ Demonstrate handling different asyncio exceptions by performing multiple asynchronous operations. Args: timeout (int): Time limit for task1. cancel_task2 (bool): Whether to cancel task2. Retur...
import asyncio async def task1(timeout): try: await asyncio.wait_for(asyncio.sleep(timeout + 1), timeout) except asyncio.TimeoutError: raise asyncio.TimeoutError("Task1 exceeded the time limit.") async def task2(cancel_task2): try: await asyncio.sleep(5) except asyncio.Cancelle...
import asyncio import pytest from solution import perform_async_operations @pytest.mark.asyncio async def test_task1_timeout_error(): result = await perform_async_operations(0, False) assert result['task1_result'] == "Task1 exceeded the time limit." @pytest.mark.asyncio async def test_task1_success(): res...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def task1(timeout):\n try:\n await asyncio.wait_for(asyncio.sleep(timeout + 1), timeout)\n except asyncio.TimeoutError:\n ra...
trial_gpt4o_1
{ "original_instruction": "#### Objective\nDemonstrate your understanding of handling different types of exceptions in asynchronous code by implementing a function that performs multiple asynchronous operations, each designed to potentially raise one of the documented `asyncio` exceptions.\n\n#### Question\nWrite a f...
0.530198
Docs: Python310_14244
C
[ "task1", "task2", "task3", "perform_async_operations" ]
4
[ [ "perform_async_operations", "task1" ], [ "perform_async_operations", "task2" ], [ "perform_async_operations", "task3" ] ]
3
[]
false
[ "FakeStream" ]
true
pytest
true
[]
true
b4820dd5e593c7d8ff3b20653161e413526fc46e
16e29fdcfd10d7d58d7a58b440d4d0f1644f0610
v1.0
complete
Docs
Docs: Python310_15101_C
import readline import atexit import os def setup_readline(history_file, commands): """ Initialize the readline module with command history and custom completion. Args: history_file (str): Path to the file where history will be saved. commands (list): List of available command strings. ...
import readline import atexit import os def setup_readline(history_file, commands): # Initialize history try: readline.read_history_file(history_file) except FileNotFoundError: open(history_file, 'wb').close() readline.set_history_length(500) readline.parse_and_bind("tab: c...
import os import readline from solution import setup_readline, run_prompt def test_setup_readline(): history_file = "test_history" commands = ["hello", "exit"] # Remove file if it exists if os.path.exists(history_file): os.remove(history_file) # Setup readline with test history fi...
[ { "docstring": null, "function_declaration": "def setup_readline(history_file, commands):", "function_name": "setup_readline", "parameter_list": "(history_file, commands)" }, { "docstring": null, "function_declaration": "def run_prompt():", "function_name": "run_prompt", "paramet...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import readline\nimport atexit\nimport os\n\ndef setup_readline(history_file, commands):\n # Initialize history\n try:\n readline.read_history_file(history...
trial_gpt4o_9
{ "original_instruction": "#### Objective\nCreate an advanced interactive command-line prompt that uses features from the `readline` module to enhance user experience. The prompt should be able to handle command history, support custom tab completion, and save the session history to a file.\n\n#### Task\n1. Implement...
0.379613
Docs: Python310_15101
C
[ "setup_readline", "run_prompt" ]
2
[ [ "run_prompt", "setup_readline" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4d5630b1159d66210c8357699db0e037085d0ead
582a6aa366c363bc58102a214f6cb9a9353838d2
v1.0
complete
Docs
Docs: Python310_15321_C
import asyncio async def process_tasks() -> list: """Coordinate multiple asynchronous operations using `Future` objects. Schedules three asynchronous operations, each waiting for different durations before setting a result. Collects the results into a list once all operations are complete. """
import asyncio async def set_future_after_delay(future, result, delay): await asyncio.sleep(delay) future.set_result(result) async def process_tasks() -> list: loop = asyncio.get_event_loop() future1 = loop.create_future() future2 = loop.create_future() future3 = loop.create_future() ...
import pytest import asyncio from solution import process_tasks @pytest.mark.asyncio async def test_process_tasks(): results = await process_tasks() assert results == ['result1', 'result2', 'result3']
[]
[ 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 set_future_after_delay(future, result, delay):\n await asyncio.sleep(delay)\n future.set_result(result)\n\nasync def process_tasks() -...
trial_gpt4o_0
{ "original_instruction": "**Objective**: Demonstrate a deep understanding of asyncio's `Future` class and related functionalities in Python.\n\n**Requirements**: Implement a function that coordinates multiple asynchronous operations using `Future` objects. Specifically, you will write a function `process_tasks` that...
0.620026
Docs: Python310_15321
C
[ "set_future_after_delay", "process_tasks" ]
2
[ [ "process_tasks", "set_future_after_delay" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dc890ec962e615f81a6dbdb122421f7dd968ea55
aacdd4cdc16754fb3f7c149e8c752b394ed78394
v1.0
complete
Docs
Docs: Scikit_14853_C
import numpy as np from sklearn.svm import SVC def polynomial_rbf_kernel(X, Y, d=3, gamma=0.1): """ Custom kernel function that combines polynomial and RBF kernels. Args: - X: np.ndarray, first input matrix of shape (n_samples_X, n_features) - Y: np.ndarray, second input matrix of shape (n_samples...
import numpy as np from sklearn.svm import SVC def polynomial_rbf_kernel(X, Y, d=3, gamma=0.1): """ Custom kernel function that combines polynomial and RBF kernels. Args: - X: np.ndarray, first input matrix of shape (n_samples_X, n_features) - Y: np.ndarray, second input matrix of shape (n_sam...
import numpy as np from solution import polynomial_rbf_kernel, svm_with_custom_kernel def test_polynomial_rbf_kernel(): X = np.array([[1, 2], [3, 4]]) Y = np.array([[5, 6], [7, 8]]) result = polynomial_rbf_kernel(X, Y, d=3, gamma=0.1) assert result.shape == (2, 2) assert np.all(result > 0) def tes...
[]
[ 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 sklearn.svm import SVC\nimport numpy as np\n\ndef polynomial_rbf_kernel(X, Y, d=3, gamma=0.1):\n polynomial = (np.dot(X, Y.T) + 1) ** d\n rbf = np.exp(-gamma...
trial_gpt4o_2
{ "original_instruction": "### Question: Implementing a Custom Kernel SVM for Classification with Class Imbalance Handling\n\nYou are provided with a dataset that you need to classify using a Support Vector Machine (SVM). However, this problem has certain nuances:\n1. You need to implement a custom kernel function.\n...
0.590408
Docs: Scikit_14853
C
[ "polynomial_rbf_kernel", "svm_with_custom_kernel" ]
2
[ [ "svm_with_custom_kernel", "polynomial_rbf_kernel" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
5b50ce978d45a48c28ef5586fa2329b2ed1100ef
60fbafae64858c94b82256d42213157bddab3848
v1.0
complete
Docs
Docs: Python310_15502_C
import asyncio import socket async def handle_client(reader, writer): """Handle the client connection by echoing received data back to the client.""" pass async def run_server(host, port): """Run the asynchronous TCP server.""" pass async def client(host, port, message): """Run the asynchronous c...
import asyncio import socket async def handle_client(reader, writer): try: data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received {message} from {addr}") print(f"Send: {message}") writer.write(data) aw...
import asyncio from solution import run_server, client async def test_server_client_interaction(): server_task = asyncio.create_task(run_server('127.0.0.1', 8888)) await asyncio.sleep(1) # Give the server a moment to start client_task1 = asyncio.create_task(client('127.0.0.1', 8888, "Hello, World!")) ...
[ { "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\nimport socket\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n print(f\"Accepted connection from {addr}\")...
trial_gpt4o_1
{ "original_instruction": "**Coding Assessment Question:**\n\n### Objective\nWrite a Python program that demonstrates the use of both `asyncio` and `socket` modules for creating a simple asynchronous TCP server that echoes back any data it receives from clients.\n\n### Requirements\n\n1. **Server Implementation**:\n ...
0.678686
Docs: Python310_15502
C
[ "handle_client", "run_server", "client", "main" ]
4
[ [ "run_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d73759b003740c18bed9f43f67fe3dfa5f239048
f32be271356d74eaaa5a8054d4525e1d33715fdc
v1.0
complete
Docs
Docs: Python310_15419_C
import resource import functools import os def set_resource_limits(cpu_time_limit, file_size_limit): """ Sets the resource limits for CPU time and file size. Parameters: cpu_time_limit (int): Maximum CPU time in seconds. file_size_limit (int): Maximum file size in bytes. Returns: None ...
import resource import functools import os def set_resource_limits(cpu_time_limit, file_size_limit): """ Sets the resource limits for CPU time and file size. Parameters: cpu_time_limit (int): Maximum CPU time in seconds. file_size_limit (int): Maximum file size in bytes. Returns: None ...
from solution import set_resource_limits, get_resource_usage, resource_limited_execution def test_set_resource_limits(): set_resource_limits(10, 10485760) # 10 seconds CPU time limit, 10 MB file size limit cpu_limit = resource.getrlimit(resource.RLIMIT_CPU) file_size_limit = resource.getrlimit(resource.RL...
[ { "docstring": "Sets the resource limits for CPU time and file size.\n\nParameters:\ncpu_time_limit (int): Maximum CPU time in seconds.\nfile_size_limit (int): Maximum file size in bytes.\n\nReturns:\nNone", "function_declaration": "def set_resource_limits(cpu_time_limit, file_size_limit):", "function_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 resource\nimport functools\nimport os\n\ndef set_resource_limits(cpu_time_limit, file_size_limit):\n \"\"\"\n Sets the resource limits for CPU time and fil...
trial_gpt4o_0
{ "original_instruction": "### Resource Management and Monitoring in Python\n\nGiven the following scenario:\n\nYou are developing a Python application that performs heavy computations and file processing. To prevent the application from consuming too many system resources (which could affect other applications runni...
0.618992
Docs: Python310_15419
C
[ "set_resource_limits", "get_resource_usage", "resource_limited_execution" ]
3
[ [ "resource_limited_execution", "get_resource_usage" ], [ "resource_limited_execution", "set_resource_limits" ] ]
2
[]
false
[]
false
pytest
true
[]
true
909c40d7975a65c98ddae008a553d3532a09cde8
443e8e2a474358640d18f1fd14baae9b2ac62286
v1.0
complete
Docs
Docs: Python310_15343_C
import asyncio import random async def sample_task(): """ Asynchronous task that waits for a random amount of time between 1 and 5 seconds and returns the elapsed time. >>> result = asyncio.run(sample_task()) >>> 1 <= result <= 5 True """ await asyncio.sleep(random.randint(1, 5)) return ran...
import asyncio import random import selectors import platform async def sample_task(): await asyncio.sleep(random.randint(1, 5)) return random.randint(1, 5) def configure_event_loop(): sys_platform = platform.system() if sys_platform == 'Windows': asyncio.set_event_loop(asyncio.ProactorEventLo...
import pytest import asyncio import random from solution import sample_task, schedule_tasks @pytest.mark.asyncio async def test_schedule_tasks(): # Create a list of sample tasks tasks = [sample_task() for _ in range(5)] results = await schedule_tasks(tasks) # Check that we have results for each ta...
[ { "docstring": null, "function_declaration": "def configure_event_loop():", "function_name": "configure_event_loop", "parameter_list": "()" } ]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport platform\nimport random\nimport selectors\n\nasync def sample_task():\n \"\"\"\n A sample task that waits for a random time between 1 and 5...
trial_gpt4o_1
{ "original_instruction": "Cross-Platform Asynchronous Task Manager\n\nYou are tasked with creating a cross-platform asynchronous task manager using Python's `asyncio` module. The task manager must be able to:\n1. Schedule and wait for completion of multiple asynchronous tasks.\n2. Handle cross-platform differences i...
0.633563
Docs: Python310_15343
C
[ "sample_task", "configure_event_loop", "schedule_tasks" ]
3
[ [ "schedule_tasks", "configure_event_loop" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7d00e78f344faa83504f7899132bd913dd32e963
019e1e1d44332f0fc9d1e21a7e9b1f5332f03a30
v1.0
complete
Docs
Docs: Python310_15055_C
import multiprocessing def square(x): """Returns the square of x""" return x * x def cube(x): """Returns the cube of x""" return x * x * x def double(x): """Returns the double of x""" return x * 2 def parallel_process_operations(operations: list[tuple[str, int]]) -> list[int]: """ Pr...
import multiprocessing def square(x): return x * x def cube(x): return x * x * x def double(x): return x * 2 def process_operation(operation_value_tuple): operation, value = operation_value_tuple operation_map = { 'square': square, 'cube': cube, 'double': double } ...
import multiprocessing from solution import parallel_process_operations def test_parallel_process_operations_basic(): operations = [('square', 2), ('cube', 3), ('double', 4)] expected = [4, 27, 8] assert parallel_process_operations(operations) == expected def test_parallel_process_operations_different_ord...
[ { "docstring": null, "function_declaration": "def square(x):", "function_name": "square", "parameter_list": "(x)" }, { "docstring": null, "function_declaration": "def cube(x):", "function_name": "cube", "parameter_list": "(x)" }, { "docstring": null, "function_declara...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import multiprocessing\n\ndef square(x):\n return x * x\n\ndef cube(x):\n return x * x * x\n\ndef double(x):\n return x * 2\n\ndef parallel_process_operations(...
trial_gpt4o_3
{ "original_instruction": "### Coding Assessment: Parallel Processing with `multiprocessing`\n\n#### Objective:\nThe aim of this exercise is to assess your understanding and utilization of the `multiprocessing` package in Python. You will be required to implement a function that processes a list of numbers in paralle...
0.679902
Docs: Python310_15055
C
[ "square", "cube", "double", "process_operation", "parallel_process_operations" ]
5
[ [ "parallel_process_operations", "process_operation" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bda67278ecd36cb0398685bf45cbab797835dfb1
8f1c26e367475ad9afa3cfd9468f20c38a08230b
v1.0
complete
Docs
Docs: Python310_15488_C
def custom_findmatch(mailcap_file: str, MIMEtype: str, key: str = 'view', filename: str = '/dev/null', plist: list = []) -> tuple: """ Simulates the behavior of the `mailcap.findmatch` function from the deprecated `mailcap` module. Args: - mailcap_file (str): Path to the mailcap file. - MIMEtype (s...
import re def parse_mailcap_file(mailcap_file): mailcap_entries = [] with open(mailcap_file, 'r') as f: for line in f: line = line.strip() if not line or line.startswith('#'): continue mime_type, rest = line.split(';', 1) mime_type = mime_...
import pytest from solution import custom_findmatch, parse_mailcap_file def test_parse_mailcap_file(): mock_mailcap_content = """ text/plain; cat %s video/mpeg; xmpeg %s; test=test -n $DISPLAY """ with open('mock.mailcap', 'w') as f: f.write(mock_mailcap_content.strip()) expected_o...
[ { "docstring": null, "function_declaration": "def parse_mailcap_file(mailcap_file):", "function_name": "parse_mailcap_file", "parameter_list": "(mailcap_file)" }, { "docstring": null, "function_declaration": "def custom_findmatch(mailcap_file, MIMEtype, key='view', filename='/dev/null', ...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\nfrom typing import Tuple, List, Dict\n\ndef custom_findmatch(mailcap_file: str, MIMEtype: str, key: str = 'view', filename: str = '/dev/null', plist: list = ...
trial_gpt4o_3
{ "original_instruction": "You are tasked with creating a Python function that simulates the behavior of the `mailcap.findmatch` function from the deprecated `mailcap` module. Your function should process a single mailcap file and return the command to handle a specified MIME type given certain conditions.\n\n### Fun...
0.528563
Docs: Python310_15488
C
[ "parse_mailcap_file", "custom_findmatch" ]
2
[ [ "custom_findmatch", "parse_mailcap_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0b1f1535773ed8fb84e30804210f0b67ad3cd072
38f2eaba9fe18cb46a63731de4b9afb3e4d16065