version stringclasses 1
value | style stringclasses 2
values | subset stringclasses 12
values | question_id stringlengths 9 23 | question stringlengths 27 8.13k | solution stringlengths 99 5.97k | test stringlengths 105 4.45k | test_info listlengths 0 13 | gpt_pass_sequence listlengths 1 10 | gpt_pass_trial_num int64 1 10 | gpt_difficulty stringclasses 3
values | gpt_pass_percentage float64 0.1 1 | trials dict | chosen_trial stringclasses 10
values | metadata dict | benchmark_similarity float64 0.16 0.93 | benchmark_instruction stringclasses 1
value | benchmark_task_id stringclasses 1
value | filter_reason stringclasses 1
value | base_id stringlengths 7 21 | variant stringclasses 2
values | top_function_names listlengths 2 13 | n_top_functions int64 2 13 | helper_call_edges listlengths 1 16 | n_helper_call_edges int64 1 16 | harness_functions listlengths 0 3 | structural_wrapper bool 1
class | class_names listlengths 0 5 | has_class bool 2
classes | test_kind stringclasses 1
value | test_has_solution_import bool 2
classes | third_party_imports listlengths 0 5 | stdlib_only bool 2
classes | question_norm_sha1 stringlengths 40 40 | solution_ast_sha1 stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v1.0 | instruct | Docs | Docs: Python310_24113_I | As a Python developer, you are tasked with creating a Python bytes object that meets specific requirements, manipulating it, and extracting information from it using the Python/C-API functions described in the documentation.
#### Requirements:
1. **Create a bytes object from a string**.
2. **Check if the created objec... | def create_bytes(input_string):
"""
Create a bytes object from a string.
Args:
input_string (str): The string to convert to bytes.
Returns:
bytes: The resulting bytes object.
"""
try:
return bytes(input_string, 'utf-8')
except TypeError as e:
raise V... | from solution import create_bytes, is_bytes_object, get_bytes_size, bytes_to_string, concatenate_bytes, resize_bytes
def test_create_bytes():
assert create_bytes("hello") == b"hello"
assert create_bytes("123") == b"123"
def test_is_bytes_object():
assert is_bytes_object(b"hello") == True
assert is_byt... | [
{
"docstring": "Create a bytes object from a string.\n\nArgs:\n input_string (str): The string to convert to bytes.\n\nReturns:\n bytes: The resulting bytes object.",
"function_declaration": "def create_bytes(input_string):",
"function_name": "create_bytes",
"parameter_list": "(input_string)"
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def create_bytes(string):\n \"\"\"\n Create a bytes object from a string.\n\n Args:\n - string (str): The input string to convert to bytes.\n\n Returns:\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024113",
"row_id": 24113,
"seed_ids": "[19]"
} | 0.524641 | Docs: Python310_24113 | I | [
"create_bytes",
"is_bytes_object",
"get_bytes_size",
"bytes_to_string",
"concatenate_bytes",
"resize_bytes"
] | 6 | [
[
"bytes_to_string",
"is_bytes_object"
],
[
"concatenate_bytes",
"is_bytes_object"
],
[
"get_bytes_size",
"is_bytes_object"
],
[
"resize_bytes",
"is_bytes_object"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 15afd8ee77d2c9ddd7e3b0b27df26af084a7835f | 05ebdcef68e82b4efdd7293bfcc3f6f9349cd29a | |||
v1.0 | instruct | Docs | Docs: Python310_24118_I | ### Codec Encoding and Decoding Assessment
#### Objective:
You are tasked with implementing a custom codec registration, encoding, and decoding system in Python. You will use the Python codec registry and support functions to create, register, and use a custom encoding and error handling method.
#### Problem Statemen... | import codecs
# Custom encoding function
def reverse_encode(input_str):
return input_str[::-1], len(input_str)
# Custom decoding function
def reverse_decode(input_str):
return input_str[::-1], len(input_str)
# Custom error handler function
def custom_error_handler(error):
return ("<ERROR>", error.start +... | from solution import register_custom_codec, custom_encode, custom_decode
def test_reverse_codec_encoding_decoding():
register_custom_codec()
encoded_str = custom_encode("hello")
assert encoded_str == "olleh"
decoded_str = custom_decode(encoded_str)
assert decoded_str == "hello"
def test_reverse_c... | [] | [
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 codecs\n\n# Custom encoding function\ndef reverse_encode(input_str):\n return input_str[::-1], len(input_str)\n\n# Custom decoding function\ndef reverse_decod... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00024118",
"row_id": 24118,
"seed_ids": "[47]"
} | 0.602763 | Docs: Python310_24118 | I | [
"reverse_encode",
"reverse_decode",
"custom_error_handler",
"reverse_codec_search",
"register_custom_codec",
"custom_encode",
"custom_decode"
] | 7 | [
[
"register_custom_codec",
"custom_error_handler"
],
[
"register_custom_codec",
"reverse_codec_search"
]
] | 2 | [] | false | [
"ReverseCodec"
] | true | pytest | true | [] | true | 764684cf07f50718b2fc3833453940cdba58d743 | 5ea7bedcce44cd90f51e4457951578290242985a | |||
v1.0 | instruct | Docs | Docs: Python310_24142_I | ### Context Management with `ExitStack`
**Problem Statement:**
You are required to write a function `manage_resources(file_paths: List[str], special_resource_required: bool) -> List[str]` that accepts:
1. A list of file paths (`file_paths: List[str]`) that need to be opened and read.
2. A boolean flag (`special_resou... | import contextlib
# Provided functions
def acquire_special_resource():
"""
This function simulates the acquisition of a special resource.
"""
print("Special resource acquired.")
return "SpecialResource"
def release_special_resource(resource):
"""
This function simulates the release of a sp... | import pytest
from unittest import mock
from solution import manage_resources, acquire_special_resource, release_special_resource
def test_manage_resources_with_no_special_resource(tmpdir):
# Create temporary files with some content
file1 = tmpdir.join("file1.txt")
file1.write("Content of file 1")
... | [
{
"docstring": "This function simulates the acquisition of a special resource.",
"function_declaration": "def acquire_special_resource():",
"function_name": "acquire_special_resource",
"parameter_list": "()"
},
{
"docstring": "This function simulates the release of a special resource.",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import contextlib\n\ndef acquire_special_resource():\n \"\"\"\n This function simulates the acquisition of a special resource.\n \"\"\"\n print(\"Special re... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024142",
"row_id": 24142,
"seed_ids": "[177]"
} | 0.525081 | Docs: Python310_24142 | I | [
"acquire_special_resource",
"release_special_resource",
"manage_resources"
] | 3 | [
[
"manage_resources",
"acquire_special_resource"
],
[
"manage_resources",
"release_special_resource"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6f714e63f7ed4ef1989f3a82039ec1788cde0efa | ccc451982164ee652df395ac178f0bb357c699eb | |||
v1.0 | instruct | Docs | Docs: Python310_24148_I | #### Objective:
Use the provided Python debugging and profiling tools to identify and optimize a performance bottleneck in a given Python program. You will demonstrate your skill in using these tools by providing not only the optimized code but also an explanation of how you identified the bottleneck and your optimizat... | import time
import cProfile
def slow_function():
print("Starting slow function")
time.sleep(2)
print("Slow function completed")
def another_slow_function():
print("Starting another slow function")
result = 0
for i in range(10000):
for j in range(10000):
result += i * j
... | from solution import optimized_another_slow_function, optimized_main
def test_optimized_another_slow_function():
import timeit
execution_time = timeit.timeit(optimized_another_slow_function, number=1)
assert execution_time < 0.1 # We expect the optimized function to be very fast
def test_optimized_main()... | [
{
"docstring": null,
"function_declaration": "def slow_function():",
"function_name": "slow_function",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def another_slow_function():",
"function_name": "another_slow_function",
"parameter_list": "()"
},
{
... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import timeit\nimport time\n\ndef slow_function():\n print(\"Starting slow function\")\n time.sleep(2)\n print(\"Slow function completed\")\n\ndef another_slow... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00024148",
"row_id": 24148,
"seed_ids": "[364]"
} | 0.477224 | Docs: Python310_24148 | I | [
"slow_function",
"another_slow_function",
"optimized_another_slow_function",
"main",
"optimized_main"
] | 5 | [
[
"optimized_main",
"optimized_another_slow_function"
],
[
"optimized_main",
"slow_function"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2a3fed4d0b9c492935fc00e46c5399b932ad64d3 | 931bc86ae2671ee2cc7c32d48fd75db9611f84ed | |||
v1.0 | instruct | Docs | Docs: Python310_24198_I | **Title:** Functional Programming: Generators and Iterators
**Objective:** Implement a series of functions that demonstrate your understanding of Python's iterators, generators, and functional-style programming using itertools and functools modules.
**Problem Statement:**
You are given a large dataset of integers ra... | import itertools
from functools import reduce
def infinite_iterator(dataset):
"""
Returns an infinite iterator that cycles through the input dataset.
"""
return itertools.cycle(dataset)
def even_numbers(iterator):
"""
A generator function that yields only the even numbers from an input iterato... | from solution import infinite_iterator, even_numbers, filtered_sum, zip_iterables
def test_infinite_iterator():
dataset = [1, 2, 3]
iterator = infinite_iterator(dataset)
output = [next(iterator) for _ in range(6)]
assert output == [1, 2, 3, 1, 2, 3]
def test_even_numbers():
dataset = [1, 2, 3, 4, ... | [
{
"docstring": "Returns an infinite iterator that cycles through the input dataset.",
"function_declaration": "def infinite_iterator(dataset):",
"function_name": "infinite_iterator",
"parameter_list": "(dataset)"
},
{
"docstring": "A generator function that yields only the even numbers from ... | [
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\nfrom functools import reduce\n\ndef infinite_iterator(dataset):\n \"\"\"\n Returns an infinite iterator that cycles through the dataset repeated... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024198",
"row_id": 24198,
"seed_ids": "[78]"
} | 0.631608 | Docs: Python310_24198 | I | [
"infinite_iterator",
"even_numbers",
"filtered_sum",
"zip_iterables"
] | 4 | [
[
"filtered_sum",
"even_numbers"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a8c2d3b8035cbacea105cb7adc47e2088505a0a1 | 8fba656cb242a2ad0d9d831d3ebd198e44f58e34 | |||
v1.0 | instruct | Docs | Docs: Python310_24298_I | **Objective:**
Design a Python program that demonstrates your understanding of the logging module in Python. Your task is to configure a logging system for a simulated application that records log messages of various severity levels to both the console and a file. Additionally, you must implement custom formatting for ... | import logging
class IgnoreFilter(logging.Filter):
def filter(self, record):
return 'ignore' not in record.getMessage()
def configure_logger():
# Create logger
logger = logging.getLogger('appLogger')
logger.setLevel(logging.DEBUG)
# Create console handler and set level to INFO
ch = lo... | import os
import logging
from solution import configure_logger, simulate_application
def test_logging_configuration():
# Clean up previous log files if any
if os.path.exists('app.log'):
os.remove('app.log')
logger = configure_logger()
assert logger.name == 'appLogger'
assert logger.lev... | [] | [
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 logging\n\nclass IgnoreFilter(logging.Filter):\n def filter(self, record):\n return 'ignore' not in record.getMessage()\n\ndef configure_logger():\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00024298",
"row_id": 24298,
"seed_ids": "[72]"
} | 0.672291 | Docs: Python310_24298 | I | [
"configure_logger",
"simulate_application"
] | 2 | [
[
"simulate_application",
"configure_logger"
]
] | 1 | [] | false | [
"IgnoreFilter"
] | true | pytest | true | [] | true | 5d45e7633e40d32a8315ba19d87378c7a5367b26 | 4d4bcc7d4200780ffbd02b01cb55d8d84a472864 | |||
v1.0 | instruct | Docs | Docs: Python310_24323_I | **Objective**: Demonstrate the use of Python's `atexit` module to manage cleanup functions that run on program termination.
### Problem Statement
You are tasked with creating a small module that manages an in-memory list of user activities. Throughout the execution of the program, activities may be added to this list... | import atexit
activities = []
def add_activity(activity: str) -> None:
"""
Adds an activity to the list.
"""
activities.append(activity)
@atexit.register
def save_activities() -> None:
"""
Saves activities to a file when the program terminates.
"""
try:
with open('activities.t... | import os
import pytest
from solution import add_activity, save_activities, activities, unregister_save_activities
def test_add_activity():
# Clear the activities list before the test
activities.clear()
add_activity("Login")
add_activity("View Dashboard")
add_activity("Logout")
assert activitie... | [
{
"docstring": "Adds an activity to the list.",
"function_declaration": "def add_activity(activity):",
"function_name": "add_activity",
"parameter_list": "(activity)"
},
{
"docstring": "Saves activities to a file when the program terminates.",
"function_declaration": "def save_activities... | [
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 atexit\n\nactivities = []\n\ndef add_activity(activity: str) -> None:\n \"\"\"\n Adds an activity string to the global activities list.\n \"\"\"\n ac... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00024323",
"row_id": 24323,
"seed_ids": "[278]"
} | 0.438825 | Docs: Python310_24323 | I | [
"add_activity",
"save_activities",
"unregister_save_activities"
] | 3 | [
[
"unregister_save_activities",
"save_activities"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 54dffa98c74304c1e75d228f3f0c72a7be1b7867 | 289933c7fe42de3ab8d8dd84d94537c72c179665 | |||
v1.0 | instruct | Docs | Docs: Python310_24360_I | ### Advanced Python `multiprocessing` Assessment
Using the `multiprocessing` module, write a Python program that performs the following tasks:
1. **Task 1: Calculate Factorial in Parallel**
- Create a function `factorial_task(n: int) -> int` that calculates the factorial of a given integer `n` (where 0 <= n <= 10... | import multiprocessing
from typing import List
def factorial_task(n: int) -> int:
"""
Function to calculate the factorial of a given integer n.
"""
if n == 0:
return 1
factorial = 1
for i in range(1, n + 1):
factorial *= i
return factorial
def parallel_factorials(numbers: L... | import pytest
from solution import factorial_task, parallel_factorials, print_factorial_results, shared_memory_sum
def test_factorial_task():
assert factorial_task(0) == 1
assert factorial_task(1) == 1
assert factorial_task(5) == 120
assert factorial_task(7) == 5040
def test_parallel_factorials():
... | [
{
"docstring": "Function to calculate the factorial of a given integer n.",
"function_declaration": "def factorial_task(n):",
"function_name": "factorial_task",
"parameter_list": "(n)"
},
{
"docstring": "Function to calculate factorials of a list of numbers using multiple processes.",
"f... | [
0,
0,
0,
1,
0,
0,
0,
1,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from multiprocessing import Pool, Lock, Value\nimport os\nfrom typing import List\nimport math\n\ndef factorial_task(n: int) -> int:\n \"\"\"\n Calculate the fact... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00024360",
"row_id": 24360,
"seed_ids": "[338]"
} | 0.796212 | Docs: Python310_24360 | I | [
"factorial_task",
"parallel_factorials",
"print_factorial_results",
"shared_memory_sum"
] | 4 | [
[
"parallel_factorials",
"factorial_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9ac16f8d4a409382323313b7092cf4ee22de1ead | 390f5da42edc40559e56db9375d66e2611355ac8 | |||
v1.0 | instruct | Docs | Docs: Python310_24367_I | ### Priority Queue Management with `heapq`
#### Problem Statement
You are tasked with implementing a simple priority queue for managing tasks using the `heapq` module. The priority queue should allow adding tasks with priorities, updating the priorities of existing tasks, and retrieving tasks based on their priority.... | import itertools
import heapq
REMOVED = '<removed-task>'
def add_task(pq, entry_finder, counter, task, priority):
"""
Add a task or update an existing task's priority.
"""
if task in entry_finder:
remove_task(pq, entry_finder, task)
count = next(counter)
entry = [priority, count, task]... | import pytest
from solution import add_task, remove_task, pop_task
@pytest.fixture
def setup_pq():
pq = []
entry_finder = {}
counter = itertools.count()
return pq, entry_finder, counter
def test_add_task(setup_pq):
pq, entry_finder, counter = setup_pq
add_task(pq, entry_finder, counter, '... | [
{
"docstring": "Add a task or update an existing task's priority.",
"function_declaration": "def add_task(pq, entry_finder, counter, task, priority):",
"function_name": "add_task",
"parameter_list": "(pq, entry_finder, counter, task, priority)"
},
{
"docstring": "Mark an existing task as REM... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\nimport heapq\n\nREMOVED = '<removed-task>' # placeholder for a removed task\n\ndef add_task(pq, entry_finder, counter, task, priority):\n \"\"\"\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00024367",
"row_id": 24367,
"seed_ids": "[241]"
} | 0.597927 | Docs: Python310_24367 | I | [
"add_task",
"remove_task",
"pop_task"
] | 3 | [
[
"add_task",
"remove_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 264b1f4ca439f6d60223e994737abd23f66668b0 | 57719c67dd57a477502963c1bbe568f739a3e3b0 | |||
v1.0 | instruct | Docs | Docs: Python310_24373_I | ### Objective
To assess students' understanding of using SystemTap to monitor CPython processes and write scripts that gather and display specific data about the function calls within a Python script.
### Task
You are required to write a Python script and a SystemTap script to monitor and report the function call hier... | def function_3():
pass
def function_1():
function_3()
def function_2():
function_1()
function_3()
def function_4():
pass
def function_5():
function_4()
def start():
function_1()
function_2()
function_3()
function_4()
function_5()
if __name__ == "__main__":
start() | from solution import function_3, function_1, function_2, function_4, function_5, start
def test_function_3():
assert function_3() is None
def test_function_1():
assert function_1() is None
def test_function_2():
assert function_2() is None
def test_function_4():
assert function_4() is None
def test... | [
{
"docstring": null,
"function_declaration": "def function_3():",
"function_name": "function_3",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def function_1():",
"function_name": "function_1",
"parameter_list": "()"
},
{
"docstring": null,
"... | [
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 function_3():\n pass\n\ndef function_1():\n function_3()\n\ndef function_2():\n function_1()\n function_3()\n\ndef function_4():\n pass\n\ndef functi... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024373",
"row_id": 24373,
"seed_ids": "[79]"
} | 0.55151 | Docs: Python310_24373 | I | [
"function_3",
"function_1",
"function_2",
"function_4",
"function_5",
"start"
] | 6 | [
[
"function_1",
"function_3"
],
[
"function_2",
"function_1"
],
[
"function_2",
"function_3"
],
[
"function_5",
"function_4"
],
[
"start",
"function_1"
],
[
"start",
"function_2"
],
[
"start",
"function_3"
],
[
"start",
"fun... | 9 | [] | false | [] | false | pytest | true | [] | true | 436e580c7e334044a4a0a0dde7db69f69fe27d0f | 1d0106cb63633dafda82f78b52bdd05915855b00 | |||
v1.0 | instruct | Docs | Docs: Python310_24385_I | ## Problem: Profiling and Optimizing a Python Function
You are given a Python module that defines several functions for computing statistics on a list of numbers. Your task is to profile the performance of these functions, analyze the profiling data, and suggest improvements to optimize the code.
### Module: `stats_m... | def sum_numbers(numbers):
"""
Returns the sum of a list of numbers.
"""
return sum(numbers)
def mean(numbers):
"""
Returns the mean (average) of a list of numbers.
"""
return sum_numbers(numbers) / len(numbers)
def variance(numbers):
"""
Returns the variance of a list of number... | from solution import sum_numbers, mean, variance, standard_deviation, slow_function
def test_sum_numbers():
assert sum_numbers([1, 2, 3, 4, 5]) == 15
assert sum_numbers([0, 0, 0, 0, 0]) == 0
assert sum_numbers([-1, -2, -3, -4, -5]) == -15
def test_mean():
assert mean([1, 2, 3, 4, 5]) == 3
assert m... | [
{
"docstring": "Returns the sum of a list of numbers.",
"function_declaration": "def sum_numbers(numbers):",
"function_name": "sum_numbers",
"parameter_list": "(numbers)"
},
{
"docstring": "Returns the mean (average) of a list of numbers.",
"function_declaration": "def mean(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": "def sum_numbers(numbers):\n \"\"\"\n Returns the sum of a list of numbers.\n \"\"\"\n return sum(numbers)\n\ndef mean(numbers):\n \"\"\"\n Returns the... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024385",
"row_id": 24385,
"seed_ids": "[142]"
} | 0.542645 | Docs: Python310_24385 | I | [
"sum_numbers",
"mean",
"variance",
"standard_deviation",
"slow_function"
] | 5 | [
[
"mean",
"sum_numbers"
],
[
"standard_deviation",
"variance"
],
[
"variance",
"mean"
],
[
"variance",
"sum_numbers"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | d5fee8c7a46b2d7e251fc49a89ed97bcacd0f96a | 4072fdc42187717c00c4d2c0e0c22c1f49c793ff | |||
v1.0 | instruct | Docs | Docs: Python310_24437_I | **Objective:**
Write a Python function using the `grp` module to determine common group memberships between two Unix users.
**Task:**
You are required to implement a function called `common_groups(user1: str, user2: str) -> List[str]` which returns a list of common group names that the two specified Unix users belon... | import grp
def get_user_groups(username: str) -> set:
"""
Helper function to get all groups a user belongs to.
"""
groups = set()
for group in grp.getgrall():
if username == group.gr_name or username in group.gr_mem:
groups.add(group.gr_name)
return groups
def common_groups... | def test_common_groups():
# Mock grp.getgrall() response
original_getgrall = grp.getgrall
class MockGroup:
def __init__(self, gr_name, gr_mem):
self.gr_name = gr_name
self.gr_mem = gr_mem
def mock_getgrall():
return [
MockGroup('admin', ['use... | [
{
"docstring": "Helper function to get all groups a user belongs to.",
"function_declaration": "def get_user_groups(username):",
"function_name": "get_user_groups",
"parameter_list": "(username)"
},
{
"docstring": "Returns a list of common group names that the two specified Unix users belong... | [
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 grp\n\ndef get_user_groups(username: str) -> set:\n \"\"\"\n Helper function to get all groups a user belongs to.\n \"\"\"\n groups = set()\n for ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00024437",
"row_id": 24437,
"seed_ids": "[268]"
} | 0.517101 | Docs: Python310_24437 | I | [
"get_user_groups",
"common_groups"
] | 2 | [
[
"common_groups",
"get_user_groups"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | ecb475bedcd711fd8d1cbef84c432bb029b10ec4 | 8b862317776af09fd3b81050954f1f8132c65b99 | |||
v1.0 | instruct | Docs | Docs: Python310_24487_I | ### Context-Aware Logging System
**Objective:** Implement a context-aware logging system using the `contextvars` module to track and log actions in synchronous and asynchronous code.
#### Requirements:
1. **Context Variables Declaration:**
- Create a `ContextVar` for `user_id` which will store the user identity fo... | import contextvars
from typing import List
# Create a ContextVar for user_id and request_id
user_id_var = contextvars.ContextVar('user_id', default='unknown')
request_id_var = contextvars.ContextVar('request_id', default='unknown')
def log_action(action: str) -> None:
"""
Logs the given action, user ID, and r... | import asyncio
from solution import handle_request, handle_request_async
# Define synchronous tests
def test_handle_request():
handle_request("user123", "req456", ["login", "view_page", "logout"])
def test_handle_request_with_unknown_user_and_request():
handle_request("", "", ["action1", "action2"])
# Define... | [
{
"docstring": "Logs the given action, user ID, and request ID.",
"function_declaration": "def log_action(action):",
"function_name": "log_action",
"parameter_list": "(action)"
},
{
"docstring": "Process the list of actions by setting context variables and logging actions.",
"function_de... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import contextvars\nimport asyncio\nfrom typing import List\n\n# Declare context variables\nuser_id_var = contextvars.ContextVar('user_id', default='unknown')\nrequest_... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024487",
"row_id": 24487,
"seed_ids": "[392]"
} | 0.37825 | Docs: Python310_24487 | I | [
"log_action",
"handle_request",
"handle_request_async"
] | 3 | [
[
"handle_request",
"log_action"
],
[
"handle_request_async",
"log_action"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a0f7aa4512fd145dabe399756c57aea7b83e2c0f | 93fa9c85215a73a63cfc48c47da69da56f33d33a | |||
v1.0 | instruct | Docs | Docs: Pytorch_24512_I | ### PyTorch Coding Assessment Question
You are provided with multiple datasets of varying sizes and tasked with training a neural network in a distributed fashion using PyTorch. The challenge involves ensuring that all distributed workers can finish their tasks even when the datasets are uneven. You need to utilize th... | import torch
import torch.nn as nn
import torch.optim as optim
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import Dataset, DataLoader
from torch.distributed.algorithms.join import Join
from torch.distributed.algorithms.join import Joinable, JoinHoo... | import pytest
import torch
import torch.distributed as dist
from torch.utils.data import DataLoader
from solution import CustomDataset, SimpleNeuralNet, generate_dataloader, train, main
def test_custom_dataset():
data = [1, 2, 3, 4, 5]
dataset = CustomDataset(data)
assert len(dataset) == 5
assert datas... | [] | [
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 torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom t... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00024512",
"row_id": 24512,
"seed_ids": "[135]"
} | 0.425492 | Docs: Pytorch_24512 | I | [
"generate_dataloader",
"train",
"main"
] | 3 | [
[
"train",
"generate_dataloader"
]
] | 1 | [] | false | [
"CustomDataset",
"SimpleNeuralNet"
] | true | pytest | true | [
"torch"
] | false | 0c3d7bb3ffd907d8dc7b68d2763d63e710fae61d | deb9c3f9cf20d26714a43f3b07b6a792f7815b1d | |||
v1.0 | instruct | Docs | Docs: Pytorch_24515_I | ### Question: Implementing and Using a Custom DDP Communication Hook in PyTorch
You have been provided with basic information about DistributedDataParallel (DDP) and communication hooks in PyTorch. Your task is to implement a custom communication hook and use it in a DDP model. The custom hook should apply a simple op... | import os
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc1 = nn.Line... | # Note: These tests would need to be run in a distributed environment which requires at least 2 GPUs.
# To simplify this example, we will mock certain functionalities to emulate a distributed environment.
import pytest
import torch
from unittest.mock import MagicMock, patch
from solution import SimpleModel, custom_com... | [] | [
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 os\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.multiprocessing as mp\nfrom torch.nn.paralle... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00024515",
"row_id": 24515,
"seed_ids": "[92]"
} | 0.441059 | Docs: Pytorch_24515 | I | [
"setup",
"cleanup",
"custom_comm_hook",
"run_demo_custom_hook"
] | 4 | [
[
"run_demo_custom_hook",
"cleanup"
],
[
"run_demo_custom_hook",
"custom_comm_hook"
],
[
"run_demo_custom_hook",
"setup"
]
] | 3 | [] | false | [
"SimpleModel"
] | true | pytest | true | [
"torch"
] | false | 1587ae9a792a986695f0a584e224b53e7dee14ea | 5c469a6de7ffe89f5608fa5493ef59cd6b10734e | |||
v1.0 | instruct | Docs | Docs: Seaborn_24517_I | #### Objective:
You are required to create a seaborn visualization that leverages the combination of different types of plots and rug plots with customization. This exercise will test your understanding of seaborn's capabilities for advanced visualizations.
#### Problem Statement:
You are given two datasets: `iris` an... | import seaborn as sns
import matplotlib.pyplot as plt
def create_iris_scatter_with_rug():
sns.set_theme()
iris = sns.load_dataset("iris")
plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1)
sns.scatterplot(data=iris, x='sepal_length', y='sepal_width', hue='species')
sns.rugplot(data=iris, x='sepa... | import pytest
from matplotlib import pyplot as plt
from solution import create_composite_visualization
def test_create_composite_visualization():
# Use plt.ion() to enable interactive mode to avoid blocking the test
plt.ion()
create_composite_visualization()
figures = [plt.figure(n) for n in plt.g... | [
{
"docstring": null,
"function_declaration": "def create_iris_scatter_with_rug():",
"function_name": "create_iris_scatter_with_rug",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def create_tips_scatter_with_custom_rug():",
"function_name": "create_tips_scat... | [
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 seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef create_composite_visualization():\n sns.set_theme()\n\n # Create scatter plot with rug plot for the ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024517",
"row_id": 24517,
"seed_ids": "[26]"
} | 0.68311 | Docs: Seaborn_24517 | I | [
"create_iris_scatter_with_rug",
"create_tips_scatter_with_custom_rug",
"create_composite_visualization"
] | 3 | [
[
"create_composite_visualization",
"create_iris_scatter_with_rug"
],
[
"create_composite_visualization",
"create_tips_scatter_with_custom_rug"
]
] | 2 | [] | false | [] | false | pytest | true | [
"matplotlib",
"seaborn"
] | false | 82e764aa668e0fbdfa0695fea0a9df2fc8110072 | 5c3c7f62b8b70fc6db88ed07a09a5f42a0f0dd05 | |||
v1.0 | instruct | Docs | Docs: Scikit_24518_I | #### Objective
Implement an out-of-core learning system using scikit-learn to handle a large dataset that cannot fit into memory. The task is to build a text classification model that can learn incrementally and demonstrate performance improvement over time.
#### Problem Statement
You are given a large text dataset th... | from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
def data_stream(file_path, batch_size=1000):
"""Generator function to read data in mini-batches"""
texts = []
labels = []
with open(file_path, 'r', enc... | import pytest
from solution import data_stream, incremental_training
def test_data_stream():
file_path = 'test_data.txt'
with open(file_path, 'w') as f:
for i in range(2500):
f.write(f'Article text {i}\tCategory{i%3}\n')
batches = list(data_stream(file_path, batch_size=1000))
assert... | [
{
"docstring": "Generator function to read data in mini-batches",
"function_declaration": "def data_stream(file_path, batch_size=1000):",
"function_name": "data_stream",
"parameter_list": "(file_path, batch_size=1000)"
},
{
"docstring": null,
"function_declaration": "def incremental_trai... | [
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.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\nimport numpy ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00024518",
"row_id": 24518,
"seed_ids": "[63]"
} | 0.533861 | Docs: Scikit_24518 | I | [
"data_stream",
"incremental_training"
] | 2 | [
[
"incremental_training",
"data_stream"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sklearn"
] | false | d1d90d725a10b31b3531dde340fd7eb866668914 | 0543f32d111a536d5ef937a517541636d399dc65 | |||
v1.0 | instruct | Docs | Docs: Python310_24526_I | You are tasked with creating a web scraper that is respectful of the websites it scrapes by adhering to the rules specified in their `robots.txt` files. You will use the `urllib.robotparser` module to parse and interpret these files. For this task, you will implement a function that checks if a given user agent can fet... | import urllib.robotparser
from urllib.parse import urlparse
def get_hostname(url: str) -> str:
parsed_url = urlparse(url)
return parsed_url.scheme + '://' + parsed_url.netloc
def check_robots_txt(useragent: str, url_list: list) -> dict:
if not url_list:
return {}
hostname = get_hostname(u... | def test_get_hostname():
assert get_hostname('http://example.com/path') == 'http://example.com'
assert get_hostname('https://example.com/path') == 'https://example.com'
assert get_hostname('http://example.com:8080/path') == 'http://example.com:8080'
assert get_hostname('https://example.com:8080/path') =... | [
{
"docstring": null,
"function_declaration": "def get_hostname(url):",
"function_name": "get_hostname",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def check_robots_txt(useragent, url_list):",
"function_name": "check_robots_txt",
"parameter_list": "... | [
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": "from urllib.robotparser import RobotFileParser\nfrom urllib.parse import urlparse\nimport requests\n\ndef get_hostname(url: str) -> str:\n parsed_url = urlparse(url)... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00024526",
"row_id": 24526,
"seed_ids": "[397]"
} | 0.666414 | Docs: Python310_24526 | I | [
"get_hostname",
"check_robots_txt"
] | 2 | [
[
"check_robots_txt",
"get_hostname"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 92b201bb2d43d2fabc3aa6f1077b1ca5e57f38c7 | 91ddde78ebc8dec578c0dcdebde34bebbab60309 | |||
v1.0 | instruct | Docs | Docs: Python310_24567_I | ### Asyncio TCP Echo Server and Client
#### Objective:
To assess your understanding of the `asyncio` module, particularly focusing on event loop, networking, and async/await syntax, you are required to implement an asynchronous TCP echo server and client using `asyncio`.
#### Requirements:
1. **Echo Server**:
- C... | import asyncio
# Echo Server
async def handle_client(reader, writer):
"""
Handle the client connection, read data from the client and echo it back.
"""
while True:
data = await reader.read(100)
if not data:
break
message = data.decode()
writer.write(data)
... | import asyncio
import pytest
import socket
from solution import handle_client, run_server, tcp_echo_client
# Utility function to check if a port is in use
def is_port_in_use(port, host='localhost'):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex((host, port)) == 0
# Unit... | [] | [
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# Echo Server\nasync def handle_client(reader, writer):\n \"\"\"\n Handle the client connection, read data from the client and echo it back.\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00024567",
"row_id": 24567,
"seed_ids": "[101]"
} | 0.643817 | Docs: Python310_24567 | I | [
"handle_client",
"run_server",
"tcp_echo_client",
"main"
] | 4 | [
[
"run_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e74fea3b74e6c04eb92df88a5a407a4b5b8b6ff0 | 5d38f635d72b1acd529346a9c3790a1715a0650e | |||
v1.0 | instruct | Docs | Docs: Python310_24652_I | #### Objective
Implement serialization and deserialization of a custom configuration using the `marshal` module and ensure proper handling of unsupported types.
#### Question
You are given a task to serialize and deserialize a Python dictionary using the `marshal` module. The dictionary represents a configuration with... | import marshal
import logging
# Setting up basic logging configuration
logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger()
def handle_unsupported_types(data, key_path=""):
"""
Recursively traverses the dictionary to replace unsupported types with None and logs them.
... | import os
from solution import serialize_configuration, deserialize_configuration
def test_serialization_and_deserialization():
config = {
"app": "MyApp",
"version": 1.0,
"settings": {
"resolution": (1920, 1080),
"fullscreen": True,
"unsupported_type": se... | [
{
"docstring": "Recursively traverses the dictionary to replace unsupported types with None and logs them.",
"function_declaration": "def handle_unsupported_types(data, key_path=''):",
"function_name": "handle_unsupported_types",
"parameter_list": "(data, key_path='')"
},
{
"docstring": "Ser... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import marshal\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\ndef serialize_configuration(config, file_path):\n def handle_unsupported_types(d):\n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00024652",
"row_id": 24652,
"seed_ids": "[190]"
} | 0.547849 | Docs: Python310_24652 | I | [
"handle_unsupported_types",
"serialize_configuration",
"deserialize_configuration"
] | 3 | [
[
"serialize_configuration",
"handle_unsupported_types"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ece99c4145d16b3589d6b00da539067f438a5588 | 71abab3983bcbfd3260a9a1ca15068eb69830751 | |||
v1.0 | instruct | Docs | Docs: Python310_24718_I | ### Student Management System
You are tasked with implementing a simplified student management system using Python. Your system should allow you to store student records, each containing a unique ID, name, list of grades, and compute some aggregate data about the grades.
#### Requirements:
1. Define a `Student` class ... | class Student:
def __init__(self, student_id: int, name: str, grades: list[int] = None):
if grades is None:
grades = []
self.student_id = student_id
self.name = name
self.grades = grades
def add_grade(self, grade: int):
if not (0 <= grade <= 100):
... | import pytest
from solution import Student, create_student
def test_add_grade():
student = create_student(1, "Alice")
student.add_grade(85)
assert student.grades == [85]
with pytest.raises(ValueError):
student.add_grade(110)
def test_average_grade():
student = create_student(1, "Alice", [7... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Student:\n def __init__(self, student_id, name, grades=None):\n if grades is None:\n grades = []\n self.student_id = student_id\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024718",
"row_id": 24718,
"seed_ids": "[426]"
} | 0.654024 | Docs: Python310_24718 | I | [
"create_student",
"manage_students"
] | 2 | [
[
"manage_students",
"create_student"
]
] | 1 | [] | false | [
"Student"
] | true | pytest | true | [] | true | 3e939be24d37e383a3fc885f36c506d3de1e4c38 | e7329c846aa411f78336ee8a0f9ebc5ee83a0c60 | |||
v1.0 | instruct | Docs | Docs: Python310_24739_I | ### Question: Implement and Manipulate a Custom SQLite Database with Custom Type Conversion
You are tasked with creating and managing a SQLite database to store and manipulate geometrical shapes. Each shape will be either a `Circle` or a `Rectangle`, with specific attributes for each:
- `Circle`:
- `radius` (a floa... | import sqlite3
class Shape:
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def __repr__(self):
return f"Circle(radius={self.radius})"
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width... | import pytest
import sqlite3
from solution import Circle, Rectangle, create_shapes_table, insert_shape, retrieve_shapes
def test_insert_and_retrieve_circle():
conn = sqlite3.connect(":memory:")
create_shapes_table(conn)
circle = Circle(3.4)
insert_shape(conn, circle)
retrieved_shapes = retrieve_sha... | [] | [
0,
0,
0,
1,
0,
1,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sqlite3\n\nclass Shape:\n pass\n\nclass Circle(Shape):\n def __init__(self, radius):\n self.radius = radius\n \n def __repr__(self):\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00024739",
"row_id": 24739,
"seed_ids": "[103]"
} | 0.434991 | Docs: Python310_24739 | I | [
"adapt_circle",
"convert_circle",
"adapt_rectangle",
"convert_rectangle",
"create_shapes_table",
"insert_shape",
"retrieve_shapes"
] | 7 | [
[
"insert_shape",
"adapt_circle"
],
[
"insert_shape",
"adapt_rectangle"
],
[
"retrieve_shapes",
"convert_circle"
],
[
"retrieve_shapes",
"convert_rectangle"
]
] | 4 | [] | false | [
"Shape",
"Circle",
"Rectangle"
] | true | pytest | true | [] | true | 53230770510a9067d6c998b4d9bf6b446b16a060 | d726e541667c848bd77cdddabf39fb4b2f1ae875 | |||
v1.0 | instruct | Docs | Docs: Python310_24759_I | ### Derangement Problem
In combinatorics, a derangement is a permutation of a set such that none of the elements appear in their original positions. For example, the derangements of `[1, 2, 3]` are `[2, 3, 1]`, `[3, 1, 2]`.
Using the functional programming modules `itertools`, `functools`, and `operator`, write a fun... | import itertools
from functools import partial
def is_derangement(perm, original):
return all(map(lambda i: perm[i] != original[i], range(len(original))))
def find_derangements(arr):
all_permutations = itertools.permutations(arr)
return list(filter(partial(is_derangement, original=arr), all_permutations))... | from solution import find_derangements
def test_find_derangements():
# Test case 1: Basic case
input_list = [1, 2, 3]
expected_output = [(2, 3, 1), (3, 1, 2)]
result = find_derangements(input_list)
assert sorted(result) == sorted(expected_output), f"Output was {result}"
# Test case 2: Longer l... | [
{
"docstring": null,
"function_declaration": "def is_derangement(perm, original):",
"function_name": "is_derangement",
"parameter_list": "(perm, original)"
},
{
"docstring": null,
"function_declaration": "def find_derangements(arr):",
"function_name": "find_derangements",
"parame... | [
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": "from itertools import permutations\nfrom functools import partial\nfrom operator import ne\n\ndef is_derangement(permutation, original):\n return all(map(ne, permuta... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00024759",
"row_id": 24759,
"seed_ids": "[387]"
} | 0.598009 | Docs: Python310_24759 | I | [
"is_derangement",
"find_derangements"
] | 2 | [
[
"find_derangements",
"is_derangement"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b0383c34d469d3d285ee2cc8c9d0b78755bcdeef | 827330133a3dce1178507ec8ad8d7e2798042478 | |||
v1.0 | instruct | Docs | Docs: Python310_24791_I | ### Custom Exception Handling and Chaining in Python
**Objective:**
Write a Python program that demonstrates your understanding of creating custom exceptions, raising them, and properly chaining exceptions.
### Task:
1. **Define a Custom Exception:**
- Create a custom exception `InvalidAgeError` which inherits fr... | # Custom exceptions definition
class InvalidAgeError(ValueError):
def __init__(self, age, message="Invalid age provided"):
self.age = age
self.message = message
super().__init__(f"{message}: {age}")
class InvalidInputError(Exception):
def __init__(self, input_data, message="Invalid inpu... | import pytest
from solution import InvalidAgeError, InvalidInputError, check_age, validate_age_input
def test_check_age_valid():
assert check_age(25) == "Valid age"
assert check_age(0) == "Valid age"
assert check_age(150) == "Valid age"
def test_check_age_invalid():
with pytest.raises(InvalidAgeError)... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class InvalidAgeError(ValueError):\n def __init__(self, age, message=\"Invalid age provided\"):\n self.age = age\n self.message = message\n supe... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00024791",
"row_id": 24791,
"seed_ids": "[256]"
} | 0.457304 | Docs: Python310_24791 | I | [
"check_age",
"validate_age_input"
] | 2 | [
[
"validate_age_input",
"check_age"
]
] | 1 | [] | false | [
"InvalidAgeError",
"InvalidInputError"
] | true | pytest | true | [] | true | 271d19b26650f889fb156bdac3aea0142f8559c3 | b77e93d31dc8519dea36bdf45516e574bb4a0473 | |||
v1.0 | instruct | Docs | Docs: Pandas_24863_I | #### Problem Statement
You are given a dataset containing survey responses collected from a group of participants on various aspects. Each participant's responses are represented in a DataFrame where certain columns represent categorical data. The objective is to manipulate and optimize this categorical data efficientl... | import pandas as pd
import numpy as np
def create_dataframe():
data = {
"Participant": [101, 102, 103, 104, 105, 106],
"Gender": ["Male", "Female", "Female", "Male", "Female", "Male"],
"AgeGroup": ["18-25", "26-35", "18-25", "46-55", "36-45", "36-45"],
"Satisfaction": ["Very Satisfi... | import pytest
import pandas as pd
import numpy as np
from solution import create_dataframe, convert_to_categorical, manipulate_data, handle_missing_data, memory_optimization, combine_dataframes
def test_create_dataframe():
df = create_dataframe()
assert df.shape == (6, 4)
assert list(df.columns) == ["Parti... | [
{
"docstring": null,
"function_declaration": "def create_dataframe():",
"function_name": "create_dataframe",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def convert_to_categorical(df):",
"function_name": "convert_to_categorical",
"parameter_list": "(df... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport numpy as np\n\ndef load_data():\n data = {\n \"Participant\": [101, 102, 103, 104, 105, 106],\n \"Gender\": [\"Male\", \"Fe... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00024863",
"row_id": 24863,
"seed_ids": "[5]"
} | 0.679304 | Docs: Pandas_24863 | I | [
"create_dataframe",
"convert_to_categorical",
"manipulate_data",
"handle_missing_data",
"memory_optimization",
"combine_dataframes"
] | 6 | [
[
"memory_optimization",
"convert_to_categorical"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas"
] | false | 320744d92de987318a6b898472a068ddd9528134 | 9b490dca7ee453a17fe912b6ec04cecff90168aa | |||
v1.0 | instruct | Docs | Docs: Scikit_25048_I | **Question: Implementing and Comparing SVM Classifiers for Multiclass Classification**
**Objective:**
Demonstrate understanding of scikit-learn's SVM classifiers by implementing and comparing different SVM strategies for a multiclass classification problem.
**Task:**
1. Load a dataset suitable for multiclass classifi... | import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC, LinearSVC
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
def load_and_p... | from solution import load_and_prepare_data, train_and_evaluate_svc, train_and_evaluate_linear_svc
def test_data_loading():
X_train, X_test, y_train, y_test = load_and_prepare_data()
assert X_train.shape == (120, 4)
assert X_test.shape == (30, 4)
assert y_train.shape == (120,)
assert y_test.shape ==... | [
{
"docstring": null,
"function_declaration": "def load_and_prepare_data():",
"function_name": "load_and_prepare_data",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def evaluate_model(y_true, y_pred):",
"function_name": "evaluate_model",
"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 numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing impo... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025048",
"row_id": 25048,
"seed_ids": "[31]"
} | 0.616133 | Docs: Scikit_25048 | I | [
"load_and_prepare_data",
"evaluate_model",
"train_and_evaluate_svc",
"train_and_evaluate_linear_svc",
"plot_decision_boundaries",
"main"
] | 6 | [
[
"train_and_evaluate_linear_svc",
"evaluate_model"
],
[
"train_and_evaluate_svc",
"evaluate_model"
]
] | 2 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"sklearn"
] | false | 252f45c433115057507b304fd75f6567ba5197b0 | 75f9eefea132d4b07136d3adaefada6523c44720 | |||
v1.0 | instruct | Docs | Docs: Python310_25145_I | ## Coding Assessment Question
### Objective
You are required to write a function that takes an input ZIP file, processes its contents, and generates a report with specific details about each file in the archive.
### Problem Statement
Write a function `process_zip_file(file_path: str) -> List[Dict[str, Union[str, int]... | from typing import List, Dict, Union
import zipfile
from datetime import datetime
def process_zip_file(file_path: str) -> List[Dict[str, Union[str, int]]]:
try:
with zipfile.ZipFile(file_path, 'r') as zip_ref:
report = []
for file_info in zip_ref.infolist():
file_rep... | import pytest
from solution import process_zip_file
import zipfile
import os
@pytest.fixture
def create_zipfile(tmp_path):
zip_path = tmp_path / "test.zip"
with zipfile.ZipFile(zip_path, 'w') as zip_ref:
zip_ref.writestr('file1.txt', 'This is some text data for file1.')
zip_ref.writestr('file2.... | [
{
"docstring": null,
"function_declaration": "def process_zip_file(file_path):",
"function_name": "process_zip_file",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def get_compression_type(compress_type):",
"function_name": "get_compression_type",
... | [
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 zipfile\nfrom typing import List, Dict, Union\n\ndef process_zip_file(file_path: str) -> List[Dict[str, Union[str, int]]]:\n try:\n with zipfile.ZipFil... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025145",
"row_id": 25145,
"seed_ids": "[242]"
} | 0.702593 | Docs: Python310_25145 | I | [
"process_zip_file",
"get_compression_type"
] | 2 | [
[
"process_zip_file",
"get_compression_type"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c0eb93f7eba348136f894b1555709af3e91a8b6b | 04f2ae601089c360a2e32936fa0b4984618bd2a6 | |||
v1.0 | instruct | Docs | Docs: Scikit_25147_I | **Question: Isotonic Regression Implementation and Evaluation**
You are tasked with implementing and evaluating the `IsotonicRegression` model using the `scikit-learn` library. Your task has several components:
1. **Data Preparation**:
- Generate a dataset `X` of 100 data points uniformly spaced between 0 and 1.
... | import numpy as np
import matplotlib.pyplot as plt
from sklearn.isotonic import IsotonicRegression
from sklearn.metrics import mean_squared_error
def generate_data():
np.random.seed(42)
X = np.linspace(0, 1, 100)
noise = np.random.normal(0, 0.1, 100)
y = 3 * X + noise
return X, y
def fit_and_predi... | from solution import generate_data, fit_and_predict
from sklearn.metrics import mean_squared_error
import numpy as np
def test_generate_data():
X, y = generate_data()
assert len(X) == 100
assert len(y) == 100
assert np.all(np.isfinite(y))
def test_fit_and_predict():
X, y = generate_data()
new_... | [
{
"docstring": null,
"function_declaration": "def generate_data():",
"function_name": "generate_data",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def fit_and_predict(X, y, new_X, increasing=True):",
"function_name": "fit_and_predict",
"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 numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.isotonic import IsotonicRegression\nfrom sklearn.metrics import mean_squared_error\n\ndef generate_dat... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025147",
"row_id": 25147,
"seed_ids": "[48]"
} | 0.59879 | Docs: Scikit_25147 | I | [
"generate_data",
"fit_and_predict",
"evaluate_and_plot"
] | 3 | [
[
"evaluate_and_plot",
"fit_and_predict"
],
[
"evaluate_and_plot",
"generate_data"
]
] | 2 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"sklearn"
] | false | 8a2b89f7588e17b8a86b85629bbeb251af6f1853 | 33a0eeba4994af71c26b1b38b82684778113d4c7 | |||
v1.0 | instruct | Docs | Docs: Pytorch_25150_I | ### Question: Implementing and Using Custom DDP Communication Hook in PyTorch
#### Objective:
Demonstrate your understanding of PyTorch’s `DistributedDataParallel` (DDP) and communication hooks by implementing a custom gradient compression hook and using it in a distributed training setup.
#### Description:
You are r... | import os
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel
class SimpleModel(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(24, 24)
... | from solution import my_custom_compress_hook
import torch
def test_my_custom_compress_hook():
class MockState:
pass
class MockBucket:
def buffer(self):
return [torch.tensor([2.0, 4.0, 6.0]), torch.tensor([8.0, 10.0, 12.0])]
state = MockState()
bucket = MockBucket()
... | [] | [
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 os\nimport tempfile\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.multiprocessing as mp\nfrom... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00025150",
"row_id": 25150,
"seed_ids": "[92]"
} | 0.444202 | Docs: Pytorch_25150 | I | [
"my_custom_compress_hook",
"setup",
"cleanup",
"run_demo",
"demo_custom_hook"
] | 5 | [
[
"demo_custom_hook",
"cleanup"
],
[
"demo_custom_hook",
"my_custom_compress_hook"
],
[
"demo_custom_hook",
"setup"
]
] | 3 | [] | false | [
"SimpleModel"
] | true | pytest | true | [
"torch"
] | false | b883b9bf9d15efb9d772bb372c4e5f857009885e | 064f27dcb762fc67db64d8fd03c7fcc042630a8f | |||
v1.0 | instruct | Docs | Docs: Python310_25161_I | ### Question: Implement a Filename Filtering Function using Shell-Style Wildcards
You are tasked with implementing a function that filters a list of filenames based on a given UNIX shell-style pattern. This function will simulate the behavior of the `fnmatch.filter` function but with some additional constraints.
####... | from typing import List
def matches_pattern(filename: str, pattern: str) -> bool:
i, j = 0, 0
while i < len(filename) and j < len(pattern):
if pattern[j] == '*':
while j < len(pattern) and pattern[j] == '*':
j += 1
if j == len(pattern):
return Tru... | from solution import custom_filter
def test_wildcard_star():
filenames = ["test.txt", "file.TXT", "data.csv", "report.doc"]
pattern = "*.txt"
assert custom_filter(filenames, pattern) == ["test.txt", "file.TXT"]
def test_wildcard_question():
filenames = ["test.txt", "file.TXT", "data.csv", "report.doc"... | [
{
"docstring": null,
"function_declaration": "def matches_pattern(filename, pattern):",
"function_name": "matches_pattern",
"parameter_list": "(filename, pattern)"
},
{
"docstring": null,
"function_declaration": "def custom_filter(filenames, pattern):",
"function_name": "custom_filte... | [
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef custom_filter(filenames: List[str], pattern: str) -> List[str]:\n def match(filename: str, pattern: str) -> bool:\n filename = ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00025161",
"row_id": 25161,
"seed_ids": "[395]"
} | 0.623031 | Docs: Python310_25161 | I | [
"matches_pattern",
"custom_filter"
] | 2 | [
[
"custom_filter",
"matches_pattern"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dc4fdd73c6638017ae2bdbdbde6d2eef7d897df7 | 4487a8b7df99e73ff28b1c7e1dda139a967e85fb | |||
v1.0 | instruct | Docs | Docs: Pytorch_25179_I | ### PyTorch SIMD Optimization Checker
**Objective:**
Create a PyTorch utility to verify SIMD support on the current system and demonstrate optimization of a neural network computation using SIMD features if available.
**Task:**
1. Write a function `check_simd_support()` that checks for SIMD support (AVX, AVX2, AVX-... | import torch
import subprocess
def check_simd_support():
"""
Checks for SIMD support (AVX, AVX2, AVX-512, AMX) on the current machine.
Returns:
dict: Dictionary containing the SIMD types supported (keys: 'AVX', 'AVX2', 'AVX-512', 'AMX'; values: boolean indicating support).
"""
simd_sup... | from solution import check_simd_support, optimize_computation
import torch
def test_check_simd_support():
simd_support = check_simd_support()
assert isinstance(simd_support, dict)
assert 'AVX' in simd_support
assert 'AVX2' in simd_support
assert 'AVX-512' in simd_support
assert 'AMX' in simd_su... | [
{
"docstring": "Checks for SIMD support (AVX, AVX2, AVX-512, AMX) on the current machine.\n\nReturns:\n dict: Dictionary containing the SIMD types supported (keys: 'AVX', 'AVX2', 'AVX-512', 'AMX'; values: boolean indicating support).",
"function_declaration": "def check_simd_support():",
"function_na... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import subprocess\nimport torch\nimport torch.nn.functional as F\n\ndef check_simd_support():\n simd_support = {\n 'AVX': False,\n 'AVX2': False,\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00025179",
"row_id": 25179,
"seed_ids": "[99]"
} | 0.497937 | Docs: Pytorch_25179 | I | [
"check_simd_support",
"optimize_computation"
] | 2 | [
[
"optimize_computation",
"check_simd_support"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 6d09956acdda2f7e6e421b16133604a58c7e95a7 | 555ad84665bab5bb9f239685c372087e4b580d6a | |||
v1.0 | instruct | Docs | Docs: Python310_25232_I | ### Advanced Turtle Graphics: Mandelbrot Set Visualization
#### Objective:
Create a program using the Python `turtle` module to visualize the Mandelbrot Set, a famous fractal. The Mandelbrot Set is a set of complex numbers that forms a fractal, defined iteratively and visualized in a 2D plane.
#### Problem Statement:... | import turtle
def mandelbrot(c, max_iter):
z = 0
n = 0
while abs(z) <= 2 and n < max_iter:
z = z*z + c
n += 1
return n
def draw_mandelbrot(width, height, x_center, y_center, zoom, max_iter):
screen = turtle.Screen()
screen.setup(width, height)
screen.setworldcoordinates(0, ... | # Since the draw_mandelbrot function creates a graphical window with no return
# value, “testing" it isn’t straightforward. However, we can check the points
# at given parameters to verify the mandelbrot implementation by mocking
# the turtle methods.
# We will use mock library to test turtle operations
from unittest... | [
{
"docstring": null,
"function_declaration": "def mandelbrot(c, max_iter):",
"function_name": "mandelbrot",
"parameter_list": "(c, max_iter)"
},
{
"docstring": null,
"function_declaration": "def draw_mandelbrot(width, height, x_center, y_center, zoom, max_iter):",
"function_name": "d... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import turtle\n\ndef mandelbrot(c, max_iter):\n z = 0\n n = 0\n while abs(z) <= 2 and n < max_iter:\n z = z*z + c\n n += 1\n return n\n\ndef d... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00025232",
"row_id": 25232,
"seed_ids": "[296]"
} | 0.503129 | Docs: Python310_25232 | I | [
"mandelbrot",
"draw_mandelbrot"
] | 2 | [
[
"draw_mandelbrot",
"mandelbrot"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 37c8bd22fa00d510af13456b701521a129b147d5 | 6247221ca8562609f1b3f565dc1b70b9cd9fffe3 | |||
v1.0 | instruct | Docs | Docs: Python310_25237_I | ### Question: Implement and Use Custom HMAC-Based Authentication
**Objective:**
Your task is to implement a Python function that uses the `hmac` module to authenticate messages using a secret key. This function should be capable of generating a secure HMAC digest and verifying a provided digest against the original me... | import hmac
import hashlib
def generate_hmac(message: str, key: str, digestmod: str) -> str:
"""
Generates an HMAC digest for a given message using a secret key and specified hashing algorithm.
Args:
- message (str): The message to be authenticated.
- key (str): The secret key.
- digestmod... | from solution import generate_hmac, verify_hmac
def test_generate_hmac():
message = "Hello, World!"
key = "supersecretkey"
digestmod = "sha256"
expected_digest_length = 64 # SHA-256 produces a 64-character hexadecimal string
hmac_digest = generate_hmac(message, key, digestmod)
assert len(hmac... | [
{
"docstring": "Generates an HMAC digest for a given message using a secret key and specified hashing algorithm.\n\nArgs:\n- message (str): The message to be authenticated.\n- key (str): The secret key.\n- digestmod (str): The hash algorithm to use (e.g., 'sha256').\n\nReturns:\n- str: The hexadecimal HMAC dige... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hmac\nimport hashlib\n\ndef generate_hmac(message: str, key: str, digestmod: str) -> str:\n \"\"\"\n Generate an HMAC digest for a given message using a se... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00025237",
"row_id": 25237,
"seed_ids": "[298]"
} | 0.843664 | Docs: Python310_25237 | I | [
"generate_hmac",
"verify_hmac"
] | 2 | [
[
"verify_hmac",
"generate_hmac"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7f5a22585f00f06d77285e1c282b78d904c4d753 | 01793b8080ade452625d1df45ea36a8adde007db | |||
v1.0 | instruct | Docs | Docs: Python310_25266_I | You are tasked with parallelizing the execution of a computationally intensive function while managing the results efficiently. You must use Python’s `multiprocessing` package to achieve this. Specifically, you will create a program that computes the sum of squares for a given list of integers using multiple processes ... | from multiprocessing import Pool
def sum_of_squares(numbers):
"""Helper function to compute sum of squares of a list of numbers."""
return sum(x ** 2 for x in numbers)
def compute_sum_of_squares(numbers):
"""
Compute the sum of squares of a list of integers using multiple processes.
"""
if not... | from solution import compute_sum_of_squares
def test_sum_of_squares_small_list():
assert compute_sum_of_squares([1, 2, 3, 4, 5]) == 55
def test_sum_of_squares_single_element():
assert compute_sum_of_squares([4]) == 16
def test_sum_of_squares_empty_list():
assert compute_sum_of_squares([]) == 0
def test_... | [
{
"docstring": "Helper function to compute sum of squares of a list of numbers.",
"function_declaration": "def sum_of_squares(numbers):",
"function_name": "sum_of_squares",
"parameter_list": "(numbers)"
},
{
"docstring": "Compute the sum of squares of a list of integers using multiple proces... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from multiprocessing import Pool\n\ndef sum_of_squares(numbers):\n \"\"\"Helper function to compute sum of squares of a list of numbers.\"\"\"\n return sum(x ** 2... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00025266",
"row_id": 25266,
"seed_ids": "[338]"
} | 0.761582 | Docs: Python310_25266 | I | [
"sum_of_squares",
"compute_sum_of_squares"
] | 2 | [
[
"compute_sum_of_squares",
"sum_of_squares"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a7cc644c53b4ed2b59f0d8af4e9caad412fc7586 | 86d16f3b2850737f6468b007028ac2b0681e2090 | |||
v1.0 | instruct | Docs | Docs: Python310_25272_I | ### Objective:
Implement a function that demonstrates the utilization of the `tarfile` module for safe extraction of files from a tar archive, applying necessary security filters.
### Problem Statement:
You are provided with a tar archive file that contains multiple files and folders. Your task is to safely extract s... | import os
import tarfile
def is_safe_path(base_path, target_path, follow_symlinks=True):
if follow_symlinks:
return os.path.realpath(target_path).startswith(os.path.realpath(base_path))
return os.path.abspath(target_path).startswith(os.path.abspath(base_path))
def safe_extract_tarfile(tar_file_path: s... | from solution import safe_extract_tarfile
import os
def test_safe_extract_txt_files(tmp_path):
# Create a mock tar file
tar_file_path = tmp_path / "test_archive.tar"
extract_to = tmp_path / "extracted"
file_content = "This is a test file."
with tarfile.open(tar_file_path, "w") as tar:
# Cr... | [
{
"docstring": null,
"function_declaration": "def is_safe_path(base_path, target_path, follow_symlinks=True):",
"function_name": "is_safe_path",
"parameter_list": "(base_path, target_path, follow_symlinks=True)"
},
{
"docstring": "Extracts files with a specific extension from a tar archive t... | [
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 tarfile\n\ndef is_safe_path(base_path, target_path):\n # Ensure the target path is within the base path\n base_path = os.path.abspath(base_path)... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025272",
"row_id": 25272,
"seed_ids": "[163]"
} | 0.661386 | Docs: Python310_25272 | I | [
"is_safe_path",
"safe_extract_tarfile"
] | 2 | [
[
"safe_extract_tarfile",
"is_safe_path"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4860f9ec2d9dee560326a3bab6b39d873f132012 | d640237d4f19bf2026e5f2be0503854f3bc65b16 | |||
v1.0 | instruct | Docs | Docs: Python310_25277_I | ### Secure File Integrity Verification with HMAC
You have been hired as a security expert to ensure the data integrity of files sent over a network. To achieve this, you need to calculate and verify the HMAC of files using different hash algorithms. Implement the following two functions:
1. `generate_file_hmac(filepa... | import hmac
import hashlib
def generate_file_hmac(filepath: str, key: bytes, digestmod: str) -> str:
"""
Calculates the HMAC for a given file.
Parameters:
filepath (str): Path to the file for which HMAC needs to be calculated.
key (bytes): Secret key used to calculate the HMAC.
... | import pytest
from solution import generate_file_hmac, verify_file_hmac
import os
# Prepare test setup
def setup_module(module):
with open("testfile.txt", "w") as file:
file.write("This is a test file.")
def teardown_module(module):
os.remove("testfile.txt")
# Test cases for generate_file_hmac
def te... | [
{
"docstring": "Calculates the HMAC for a given file.\n\nParameters:\n filepath (str): Path to the file for which HMAC needs to be calculated.\n key (bytes): Secret key used to calculate the HMAC.\n digestmod (str): Name of the digest algorithm to use (e.g., 'sha256', 'sha1').\n \nReturns:\n str:... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hmac\nimport hashlib\nimport os\n\ndef generate_file_hmac(filepath: str, key: bytes, digestmod: str) -> str:\n if not os.path.isfile(filepath):\n raise... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025277",
"row_id": 25277,
"seed_ids": "[298]"
} | 0.642947 | Docs: Python310_25277 | I | [
"generate_file_hmac",
"verify_file_hmac"
] | 2 | [
[
"verify_file_hmac",
"generate_file_hmac"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1ef783caa72d3a80c27a1d6d1bde67bd949b455d | d00194ee7753db512aa6c7c3c9b636126fb5208d | |||
v1.0 | instruct | Docs | Docs: Python310_25281_I | ### Objective
Write a Python program that uses the `trace` module to trace the execution of a function that sorts a list of numbers. Your task is to use the `trace.Trace` class to count how many times each line in the sorting algorithm is executed and generate the coverage report.
### Requirements
1. Implement a sorti... | from trace import Trace
def quicksort(nums):
"""
Implementation of the quicksort algorithm.
"""
if len(nums) <= 1:
return nums
pivot = nums[len(nums) // 2]
left = [x for x in nums if x < pivot]
middle = [x for x in nums if x == pivot]
right = [x for x in nums if x > pivot]
r... | from solution import quicksort, run_trace
def test_quicksort_sorted():
assert quicksort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_quicksort_reverse_sorted():
assert quicksort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_quicksort_mixed():
assert quicksort([3, 1, 4, 1, 5]) == [1, 1, 3, 4, 5]
def test_... | [
{
"docstring": "Implementation of the quicksort algorithm.",
"function_declaration": "def quicksort(nums):",
"function_name": "quicksort",
"parameter_list": "(nums)"
},
{
"docstring": null,
"function_declaration": "def run_trace(nums):",
"function_name": "run_trace",
"parameter_l... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from trace import Trace\n\ndef quicksort(nums):\n \"\"\"\n Implementation of the quicksort algorithm.\n \"\"\"\n if len(nums) <= 1:\n return nums\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00025281",
"row_id": 25281,
"seed_ids": "[187]"
} | 0.540338 | Docs: Python310_25281 | I | [
"quicksort",
"run_trace"
] | 2 | [
[
"run_trace",
"quicksort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7d25fdd4a6c1d18178273ba0d63e8363bd3c27ea | 0b376308515ea4f6c052875bee211274bea6c102 | |||
v1.0 | instruct | Docs | Docs: Python310_25295_I | #### Background:
You are given a dataset of multiple URLs, and your task is to fetch data from these URLs concurrently to speed up the process using the `concurrent.futures` module. Fetching data from a single URL is done using the `requests` library, but to optimize and handle multiple requests efficiently, you will e... | import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import List, Tuple, Union, Dict
def fetch_url(url: str) -> Union[Dict, None]:
try:
response = requests.get(url)
response.raise_for_status() # Raise HTTPError for bad responses
return response.json()... | from solution import fetch_urls_concurrently
import pytest
from unittest.mock import patch
def mock_requests_get_success(url):
class MockResponse:
def json(self):
return {"url": url, "status": "success"}
def raise_for_status(self):
pass
return MockResponse()
de... | [
{
"docstring": null,
"function_declaration": "def fetch_url(url):",
"function_name": "fetch_url",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def fetch_urls_concurrently(urls, max_workers):",
"function_name": "fetch_urls_concurrently",
"parameter_li... | [
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 requests\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom typing import List, Tuple, Union, Dict\n\ndef fetch_url(url: str) -> Union[Dict, ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025295",
"row_id": 25295,
"seed_ids": "[224]"
} | 0.584632 | Docs: Python310_25295 | I | [
"fetch_url",
"fetch_urls_concurrently"
] | 2 | [
[
"fetch_urls_concurrently",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 8e3c50d84cbf568b5d9c65eab2e848ebfb9de0d5 | f56c3c3a7426abc06977e3902822895a69ceae27 | |||
v1.0 | instruct | Docs | Docs: Pytorch_25365_I | ### Question: Implement and Train a Simple Neural Network on the MPS Device
**Problem Description:**
You are required to implement a simple neural network and train it on the MPS device using the PyTorch framework. The task will help in understanding how to utilize the MPS backend for GPU acceleration on macOS device... | import torch
import torch.nn as nn
import torch.optim as optim
def check_mps_availability():
# Check that MPS is available
if not torch.backends.mps.is_available():
if not torch.backends.mps.is_built():
raise RuntimeError("MPS not available because the current PyTorch install was not built ... | import pytest
import torch
# Import the relevant functions and classes from the solution
from solution import check_mps_availability, SimpleNet, train_simple_net_on_mps
def test_check_mps_availability():
if torch.backends.mps.is_available():
assert check_mps_availability() == torch.device("mps")
else:... | [] | [
0,
0,
0,
1,
1,
0,
1,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\n# Check that MPS is available\nif not torch.backends.mps.is_available():\n if not torch.backends.... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00025365",
"row_id": 25365,
"seed_ids": "[167]"
} | 0.472114 | Docs: Pytorch_25365 | I | [
"check_mps_availability",
"train_simple_net_on_mps"
] | 2 | [
[
"train_simple_net_on_mps",
"check_mps_availability"
]
] | 1 | [] | false | [
"SimpleNet"
] | true | pytest | true | [
"torch"
] | false | 593d7f327c40a27a05fdc4c4c92616f8005a4dff | 01ee38566e70c54d9dabd47ab9768eb04c5614b2 | |||
v1.0 | instruct | Docs | Docs: Python310_25382_I | You are tasked with understanding the `__future__` module in Python and creating a utility function that processes data regarding the future statements and their release versions.
### Problem Statement
Write a Python function called `future_features_info` that retrieves information about all features in the `__future_... | import __future__ as future_module
def future_features_info():
feature_info = {}
for feature_name, feature in future_module.__dict__.items():
if isinstance(feature, future_module._Feature):
optional = feature.optional
mandatory = feature.mandatory
feature_info[featur... | from solution import future_features_info, mandatory_in_version
def test_future_features_info():
feature_names = ["nested_scopes", "generators", "division", "absolute_import", "print_function", "unicode_literals"]
features = future_features_info()
for name in feature_names:
assert name in features
... | [
{
"docstring": null,
"function_declaration": "def future_features_info():",
"function_name": "future_features_info",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def mandatory_in_version(version):",
"function_name": "mandatory_in_version",
"parameter_li... | [
0,
0,
0,
1,
1,
0,
0,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import __future__\n\ndef future_features_info():\n \"\"\"\n Retrieves information about all features in the __future__ module.\n \n Returns:\n dict: ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00025382",
"row_id": 25382,
"seed_ids": "[181]"
} | 0.438217 | Docs: Python310_25382 | I | [
"future_features_info",
"mandatory_in_version"
] | 2 | [
[
"mandatory_in_version",
"future_features_info"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7a1d733135c850da0046e1d7d4fdcc5c3a8a8344 | 49384119f670f11633fc044361339e903ca83af6 | |||
v1.0 | instruct | Docs | Docs: Python310_25383_I | **Question**: You are tasked with designing a file backup script using the `shutil` module. The script should:
- Backup a specified directory by creating a compressed archive of it.
- Verify that the backup was successful by checking the size of the original directory and the archive.
- Clean up by deleting the origina... | import shutil
import os
def get_directory_size(directory):
total_size = 0
for dirpath, dirnames, filenames in os.walk(directory):
for f in filenames:
fp = os.path.join(dirpath, f)
if os.path.exists(fp):
total_size += os.path.getsize(fp)
return total_size
def... | import os
import tempfile
import pytest
import shutil
from solution import backup_and_cleanup, get_directory_size
@pytest.fixture
def setup_directories():
source_dir = tempfile.mkdtemp()
backup_dir = tempfile.mkdtemp()
# Create some files in source_dir
with open(os.path.join(source_dir, 'file1.txt'), ... | [
{
"docstring": null,
"function_declaration": "def get_directory_size(directory):",
"function_name": "get_directory_size",
"parameter_list": "(directory)"
},
{
"docstring": null,
"function_declaration": "def backup_and_cleanup(source_dir, backup_dir, archive_name):",
"function_name": ... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import shutil\nimport os\n\ndef backup_and_cleanup(source_dir: str, backup_dir: str, archive_name: str) -> str:\n try:\n # Create a compressed archive of the ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025383",
"row_id": 25383,
"seed_ids": "[100]"
} | 0.775448 | Docs: Python310_25383 | I | [
"get_directory_size",
"backup_and_cleanup"
] | 2 | [
[
"backup_and_cleanup",
"get_directory_size"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dac4cd51b1dd5c61283b779cc0cb877a8f70cc79 | 97eea75dc0be6f955086a9386a827ac37c5b55b1 | |||
v1.0 | instruct | Docs | Docs: Python310_25394_I | In this exercise, you will demonstrate your understanding of the `signal` module by implementing a feature that handles timeouts for potentially long-running operations and properly manages different signals for a multi-threaded program.
### Requirements
1. **Operation Timeout**: Implement a Python function `timed_op... | import signal
from typing import Callable, Any
class TimeoutError(Exception):
"""Custom Timeout Exception."""
pass
# Custom handler for SIGINT
def handler_sigint(signum, frame):
print("SIGINT received. Gracefully shutting down.")
raise KeyboardInterrupt
# Custom handler for SIGALRM
def handler_sigalr... | import pytest
from solution import timed_operation, TimeoutError
import time
def long_running_operation():
time.sleep(10)
return "Completed!"
def quick_operation():
return "Quick completed!"
def test_timed_operation_success():
result = timed_operation(quick_operation, 5)
assert result == "Quick c... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import signal\nimport threading\nfrom typing import Callable, Any\n\n\ndef handler_sigint(signum, frame):\n print(\"SIGINT received. Gracefully shutting down.\")\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025394",
"row_id": 25394,
"seed_ids": "[253]"
} | 0.552216 | Docs: Python310_25394 | I | [
"handler_sigint",
"handler_sigalrm",
"handler_other",
"timed_operation"
] | 4 | [
[
"timed_operation",
"handler_other"
],
[
"timed_operation",
"handler_sigalrm"
],
[
"timed_operation",
"handler_sigint"
]
] | 3 | [] | false | [
"TimeoutError"
] | true | pytest | true | [] | true | 626b60399015cab01e5bcdb6e493e56b0047137a | 08011cb81764a830093a749275878cf8488d02d5 | |||
v1.0 | instruct | Docs | Docs: Python310_25421_I | ### Python Coding Assessment Question
#### Problem Description
You are given a set of text documents, and your task is to identify and extract structured data from these documents using Python's text processing capabilities. Specifically, you are required to extract all email addresses and phone numbers from the docu... | import re
import difflib
from typing import List, Dict, Any
def extract_emails(text: str) -> List[str]:
email_pattern = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'
return re.findall(email_pattern, text)
def extract_and_normalize_phones(text: str) -> List[str]:
phone_pattern = r'(\+1[-.\s]?)?(\(?\d{3... | from solution import process_documents
def test_process_documents():
documents = [
"Contact us at info@example.com or call (123) 456-7890.",
"Send an email to support@example.com or ring 123.456.7890 for help.",
"For more info, email sales@example.org or dial +1-123-456-7890."
]
... | [
{
"docstring": null,
"function_declaration": "def extract_emails(text):",
"function_name": "extract_emails",
"parameter_list": "(text)"
},
{
"docstring": null,
"function_declaration": "def extract_and_normalize_phones(text):",
"function_name": "extract_and_normalize_phones",
"par... | [
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 re\nimport difflib\nfrom typing import List, Dict, Any\n\ndef extract_emails(text: str) -> List[str]:\n email_pattern = r'\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025421",
"row_id": 25421,
"seed_ids": "[292]"
} | 0.566078 | Docs: Python310_25421 | I | [
"extract_emails",
"extract_and_normalize_phones",
"compare_documents",
"process_documents"
] | 4 | [
[
"process_documents",
"compare_documents"
],
[
"process_documents",
"extract_and_normalize_phones"
],
[
"process_documents",
"extract_emails"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 937d6858f95420d86c1edcb94b8d76d21ee270ad | 4741d77aa479b9f7153e86bf5bd0a98c32f73bb2 | |||
v1.0 | instruct | Docs | Docs: Scikit_25429_I | ### Question
In this assessment, you will demonstrate your understanding of the scikit-learn `cross_decomposition` module by implementing and applying a `PLSRegression` model to a synthetic dataset.
#### Task
1. **Generate a Synthetic Dataset:**
- Create two random matrices, `X` and `Y`, each with `100` samples a... | import numpy as np
from sklearn.cross_decomposition import PLSRegression
def generate_data(seed=0):
np.random.seed(seed)
X = np.random.rand(100, 20)
Y = np.random.rand(100, 10)
return X, Y
def pls_fit_transform(X, Y, n_components=5):
pls = PLSRegression(n_components=n_components)
pls.fit(X, Y)... | from solution import generate_data, pls_fit_transform, maximum_covariance
import numpy as np
def test_generate_data():
X, Y = generate_data()
assert X.shape == (100, 20)
assert Y.shape == (100, 10)
def test_pls_fit_transform():
X, Y = generate_data()
X_transformed, Y_transformed = pls_fit_transfor... | [
{
"docstring": null,
"function_declaration": "def generate_data(seed=0):",
"function_name": "generate_data",
"parameter_list": "(seed=0)"
},
{
"docstring": null,
"function_declaration": "def pls_fit_transform(X, Y, n_components=5):",
"function_name": "pls_fit_transform",
"paramet... | [
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 numpy as np\nfrom sklearn.cross_decomposition import PLSRegression\n\ndef generate_data(seed=0):\n \"\"\"\n Generates random matrices X and Y with specifie... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025429",
"row_id": 25429,
"seed_ids": "[28]"
} | 0.58552 | Docs: Scikit_25429 | I | [
"generate_data",
"pls_fit_transform",
"maximum_covariance"
] | 3 | [
[
"maximum_covariance",
"generate_data"
],
[
"maximum_covariance",
"pls_fit_transform"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 8e676be1906f6527220016e94e2cd30ab25c66d9 | a60b4e6fd7854e03ed9c2c66a63da62695ceea87 | |||
v1.0 | instruct | Docs | Docs: Python310_25448_I | **Context Management with `contextlib`**
**Objective:**
The goal of this exercise is to test your understanding and ability to implement effective resource management using the `contextlib` utilities. You will need to create custom context managers and utilize the `ExitStack` class to manage and clean up multiple res... | from contextlib import ExitStack
import logging
logging.basicConfig(level=logging.INFO)
def acquire_resource(name: str) -> str:
"""
Acquires a resource based on the name. This could be a database connection, file, etc.
"""
if "fail" in name:
raise ValueError(f"Resource {name} cannot be acquire... | from solution import manage_resources, acquire_resource, release_resource, condition_function
def test_manage_resources():
# Test normal case with no exceptions
resources = manage_resources(["resource1", "resource2"], condition_function, ())
assert resources == ["Resource resource1", "Resource resource2", ... | [] | [
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 logging\nfrom contextlib import ExitStack\nfrom typing import Callable, List, Tuple, Type\n\nlogging.basicConfig(level=logging.INFO)\n\ndef acquire_resource(name... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025448",
"row_id": 25448,
"seed_ids": "[177]"
} | 0.390197 | Docs: Python310_25448 | I | [
"acquire_resource",
"release_resource",
"condition_function",
"manage_resources"
] | 4 | [
[
"manage_resources",
"acquire_resource"
],
[
"manage_resources",
"release_resource"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a0daa5e7a2db2385304209da3ff4434dfcbd97a5 | fde5020d5b9a2c51f3fde20a2e707604ed2749f7 | |||
v1.0 | instruct | Docs | Docs: Python310_25475_I | #### Monitoring Python Function Executions with SystemTap
You are required to write a Python script and a SystemTap script that work together to monitor and report on the function calls of the Python script. Your task is to trace the execution flow of specific functions and generate a detailed report on their runtime ... | # my_script.py
def start():
print("Start function called")
function_a()
function_b()
def function_a():
print("Function A called")
dummy_a()
def function_b():
print("Function B called")
function_c()
dummy_b()
def function_c():
print("Function C called")
def dummy_a():
pri... | # Assuming the filename is solution.py for testing purposes
from solution import start, function_a, function_b, function_c, dummy_a, dummy_b
from io import StringIO
import sys
def test_start_function(capsys):
start()
captured = capsys.readouterr()
assert "Start function called" in captured.out
assert "... | [
{
"docstring": null,
"function_declaration": "def start():",
"function_name": "start",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def function_a():",
"function_name": "function_a",
"parameter_list": "()"
},
{
"docstring": null,
"function_d... | [
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 start():\n \"\"\"\n Entry point of the script, which calls other functions.\n \"\"\"\n function_a()\n function_b()\n\ndef function_a():\n \"\"\"\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025475",
"row_id": 25475,
"seed_ids": "[79]"
} | 0.572144 | Docs: Python310_25475 | I | [
"start",
"function_a",
"function_b",
"function_c",
"dummy_a",
"dummy_b"
] | 6 | [
[
"function_a",
"dummy_a"
],
[
"function_b",
"dummy_b"
],
[
"function_b",
"function_c"
],
[
"start",
"function_a"
],
[
"start",
"function_b"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 86b78ec2b915a806d57e34f2b92eae304baabe43 | a2204d351e0b33dee0cfed3a182dce4bec888805 | |||
v1.0 | instruct | Docs | Docs: Python310_25476_I | ### Asynchronous File Processing with `concurrent.futures`
#### Objective:
Write a Python program that processes text files asynchronously. Your task is to implement a function that reads multiple text files, counts the occurrence of each word, and then writes the word count results to an output file. This task must b... | from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from collections import Counter
from typing import List
import os
def read_file(file_path: str) -> str:
try:
with open(file_path, 'r') as file:
return file.read()
except Exception as e:
print(f"Error reading file... | import os
import pytest
from solution import process_files
def create_test_file(filename: str, content: str):
with open(filename, 'w') as f:
f.write(content)
def test_process_files():
input_files = ['file1.txt', 'file2.txt']
output_file = 'word_counts.txt'
# Create test files
create_t... | [
{
"docstring": null,
"function_declaration": "def read_file(file_path):",
"function_name": "read_file",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def count_words(text):",
"function_name": "count_words",
"parameter_list": "(text)"
},
{
... | [
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 concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\nfrom collections import Counter\nfrom typing import List\nimport os\n\ndef read_file(file_path: ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00025476",
"row_id": 25476,
"seed_ids": "[347]"
} | 0.58683 | Docs: Python310_25476 | I | [
"read_file",
"count_words",
"process_files"
] | 3 | [
[
"process_files",
"count_words"
],
[
"process_files",
"read_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 32ec3d226bae6f2468d177afcd42fa03add78b71 | a857ed1769e7aa3babac98723d918c56cf179c36 | |||
v1.0 | instruct | Docs | Docs: Python310_25490_I | URL Status Checker with Timeout
You are tasked with implementing a utility to check the status of a list of URLs concurrently. You will use the `concurrent.futures` module to perform this action efficiently. Your implementation should handle timeouts gracefully and ensure all threads are properly cleaned up.
### Fun... | import concurrent.futures
import urllib.request
from typing import List, Dict, Union
def check_url(url: str, timeout: float) -> Union[int, str]:
try:
with urllib.request.urlopen(url, timeout=timeout) as response:
return response.getcode()
except urllib.request.URLError as e:
return ... | import pytest
from solution import check_urls_status
def test_check_urls_status():
urls = [
'http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://nonexistant-subdomain.python.org/' # this should return 'error'
]
... | [
{
"docstring": null,
"function_declaration": "def check_url(url, timeout):",
"function_name": "check_url",
"parameter_list": "(url, timeout)"
},
{
"docstring": null,
"function_declaration": "def check_urls_status(urls, timeout, max_workers):",
"function_name": "check_urls_status",
... | [
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 concurrent.futures\nimport urllib.request\nfrom typing import List, Dict, Union\n\ndef check_url(url: str, timeout: float) -> Union[int, str]:\n try:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025490",
"row_id": 25490,
"seed_ids": "[347]"
} | 0.652149 | Docs: Python310_25490 | I | [
"check_url",
"check_urls_status"
] | 2 | [
[
"check_urls_status",
"check_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 85853dcb2575b8c1dbf41ff697479834ca5539c7 | 47125b1e8c825560030ba144ce22a3526699a419 | |||
v1.0 | instruct | Docs | Docs: Scikit_25493_I | #### Objective:
The goal of this coding assessment is to evaluate your understanding of scikit-learn's out-of-core learning capabilities for text classification. You will stream data from a text file, extract features using the hashing trick, and train an incremental classifier.
#### Task:
Write a Python script that:
... | import os
import numpy as np
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
def parse_line(line):
"""
Parse a single line from the file into a label and document.
Parameters:
line (str): A line... | import os
from solution import incremental_text_classification
def create_test_file(file_path, content):
with open(file_path, 'w') as file:
file.write(content)
def test_incremental_text_classification():
# Setup
file_path = 'test_data.txt'
content = ("pos\tThe movie was fantastic!\n"
... | [
{
"docstring": "Parse a single line from the file into a label and document.\n\nParameters:\n line (str): A line from the text file in the format 'label document'.\n\nReturns:\n tuple: A tuple containing the label and document.",
"function_declaration": "def parse_line(line):",
"function_name... | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics impor... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00025493",
"row_id": 25493,
"seed_ids": "[63]"
} | 0.559594 | Docs: Scikit_25493 | I | [
"parse_line",
"incremental_text_classification"
] | 2 | [
[
"incremental_text_classification",
"parse_line"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 544490d1848df4b3396166f5bc02f338bc769af9 | c206044913c3c953fcc9b7fb884bcca070c16842 | |||
v1.0 | instruct | Docs | Docs: Seaborn_25502_I | ### Question
You are provided with a dataset `healthexp` containing health expenditure data from various countries over the years. Your task is to write a function that:
1. Loads and preprocesses the dataset.
2. Generates a set of visualizations using Seaborn's objects interface (`so`).
### Requirements
#### Functio... | import seaborn.objects as so
import seaborn as sns
import pandas as pd
def preprocess_data():
# Loading the dataset
healthexp = sns.load_dataset("healthexp")
# Displaying the first few rows of the dataset for reference
print(healthexp.head())
# Returning the preprocessed dataframe
ret... | import pytest
from solution import visualize_healthexp, preprocess_data
def test_preprocess_data():
healthexp = preprocess_data()
# Test the data being correctly loaded and preprocessed
assert not healthexp.empty, "Dataframe should not be empty"
assert "Year" in healthexp.columns, "Dataframe should con... | [
{
"docstring": null,
"function_declaration": "def preprocess_data():",
"function_name": "preprocess_data",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def visualize_healthexp():",
"function_name": "visualize_healthexp",
"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 seaborn as sns\nimport seaborn.objects as so\nimport pandas as pd\n\ndef visualize_healthexp():\n healthexp = sns.load_dataset(\"healthexp\")\n \n # Fac... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025502",
"row_id": 25502,
"seed_ids": "[84]"
} | 0.702571 | Docs: Seaborn_25502 | I | [
"preprocess_data",
"visualize_healthexp"
] | 2 | [
[
"visualize_healthexp",
"preprocess_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas",
"seaborn"
] | false | d4d942f4a7b8b43fac9f4072fd75c4e41e1dc1b2 | 2d20d05fa908af699caefeff751480f05e160635 | |||
v1.0 | instruct | Docs | Docs: Pytorch_25555_I | ## Coding Assessment Question
### Objective:
Implement an attention mechanism using PyTorch with block masks, focusing on the functions and class in the `torch.nn.attention.flex_attention` module.
### Problem Statement:
You are provided with a sequence of data and need to apply an attention mechanism that uses block ... | import torch
def create_block_mask(seq_len, block_size):
# Create a mask with block_size blocks set to True, rest set to False
mask = torch.zeros(seq_len, seq_len)
for i in range(0, seq_len, block_size):
mask[i:i+block_size, i:i+block_size] = 1
return mask
def create_nested_block_mask(seq_len,... | import torch
from solution import block_attention
def test_block_attention_block_mask():
seq_len, d_model = 10, 4
sequence = torch.rand((seq_len, d_model))
block_size = 2
result = block_attention(sequence, "block", block_size)
assert result.shape == (seq_len, d_model), "Output shape mismatch for bl... | [] | [
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\n\ndef create_block_mask(seq_len, block_size):\n mask = torch.zeros(seq_len, seq_len)\n for i in range(0, seq_len, block_size):\n mask[i:i + b... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025555",
"row_id": 25555,
"seed_ids": "[0]"
} | 0.461111 | Docs: Pytorch_25555 | I | [
"create_block_mask",
"create_nested_block_mask",
"noop_mask",
"block_attention"
] | 4 | [
[
"block_attention",
"create_block_mask"
],
[
"block_attention",
"create_nested_block_mask"
],
[
"block_attention",
"noop_mask"
]
] | 3 | [] | false | [
"BlockMask"
] | true | pytest | true | [
"torch"
] | false | 47c933784c96c35a9d44dab92eb263d880a65986 | 11c209268eb6901985d25e833cc1a5e8ceafc0fe | |||
v1.0 | instruct | Docs | Docs: Python310_25571_I | #### Objective
Write a Python program that traverses a given directory and generates a summary report containing the count of each type of file (regular files, directories, etc.), as well as their permissions in a human-readable format.
#### Input
- A string `directory_path` representing the path to the directory to ... | import os
import stat
def file_type(mode):
if stat.S_ISDIR(mode):
return "Directories"
elif stat.S_ISREG(mode):
return "Regular files"
elif stat.S_ISLNK(mode):
return "Symbolic links"
elif stat.S_ISSOCK(mode):
return "Sockets"
elif stat.S_ISCHR(mode):
return ... | import pytest
from solution import generate_directory_summary
def test_example_dir_structure(tmp_path):
# Create example directory structure
(tmp_path / "file1.txt").write_text("content")
(tmp_path / "file2.txt").write_text("content")
(tmp_path / "dir1").mkdir()
(tmp_path / "dir1" / "file3.txt").wr... | [
{
"docstring": null,
"function_declaration": "def file_type(mode):",
"function_name": "file_type",
"parameter_list": "(mode)"
},
{
"docstring": null,
"function_declaration": "def human_readable_permissions(mode):",
"function_name": "human_readable_permissions",
"parameter_list": ... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport stat\n\ndef generate_directory_summary(directory_path: str) -> dict:\n file_counts = {\n \"Directories\": 0,\n \"Regular files\": 0,\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025571",
"row_id": 25571,
"seed_ids": "[373]"
} | 0.600941 | Docs: Python310_25571 | I | [
"file_type",
"human_readable_permissions",
"generate_directory_summary"
] | 3 | [
[
"generate_directory_summary",
"file_type"
],
[
"generate_directory_summary",
"human_readable_permissions"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f13d32916c3fdd68d6a4e53e0474df930c8ba68c | 002c45c9d3eb3f253460f3504272ed6ad680687f | |||
v1.0 | instruct | Docs | Docs: Pytorch_25584_I | #### Objective:
Demonstrate your understanding of PyTorch's block mask utilities by implementing a customized flexible attention mechanism.
#### Problem Statement:
Implement a function `custom_flex_attention` that takes an input tensor and applies a flexible attention mechanism with a custom block mask. The function s... | import torch
def create_block_mask(shape):
return torch.zeros(shape)
def create_nested_block_mask(shape):
return torch.eye(shape[0], shape[1])
def noop_mask(shape):
return torch.ones(shape)
def and_masks(mask1, mask2):
return torch.logical_and(mask1, mask2).float()
def or_masks(mask1, mask2):
r... | import torch
from solution import custom_flex_attention
def test_custom_flex_attention_block_mask():
input_tensor = torch.ones((10, 5))
mask_type = "block"
output_tensor = custom_flex_attention(input_tensor, mask_type)
expected_tensor = torch.zeros((10, 5))
assert torch.equal(output_tensor, expecte... | [
{
"docstring": null,
"function_declaration": "def create_block_mask(shape):",
"function_name": "create_block_mask",
"parameter_list": "(shape)"
},
{
"docstring": null,
"function_declaration": "def create_nested_block_mask(shape):",
"function_name": "create_nested_block_mask",
"pa... | [
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\n\ndef create_block_mask():\n \"\"\"Example block mask utility function.\"\"\"\n # Example implementation, replace with actual logic\n return torc... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025584",
"row_id": 25584,
"seed_ids": "[0]"
} | 0.425268 | Docs: Pytorch_25584 | I | [
"create_block_mask",
"create_nested_block_mask",
"noop_mask",
"and_masks",
"or_masks",
"flex_attention",
"custom_flex_attention"
] | 7 | [
[
"custom_flex_attention",
"and_masks"
],
[
"custom_flex_attention",
"create_block_mask"
],
[
"custom_flex_attention",
"create_nested_block_mask"
],
[
"custom_flex_attention",
"flex_attention"
],
[
"custom_flex_attention",
"noop_mask"
]
] | 5 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 8843dea2e879134221316e1e0d9ccedb52c04ccb | a767fecb5a7365e0b7ea28c1898f2b4f54f09d8f | |||
v1.0 | instruct | Docs | Docs: Python310_25585_I | ### Custom Codec Implementation and Error Handling
**Objective**: Implement a custom codec for a hypothetical encoding and additionally, design a custom error handling strategy for any encoding errors encountered during the use of this codec.
**Task 1**: Custom Codec Implementation
Write a Python function `custom_en... | def custom_encode(input_string: str) -> bytes:
"""
Function to encode an input string where each character is replaced by its Unicode code point shifted by 3 positions.
"""
encoded_bytes = bytearray()
for char in input_string:
try:
encoded_char = chr(ord(char) + 3)
en... | from solution import custom_encode, custom_decode
def test_custom_encode():
assert custom_encode("HELLO") == b'KHOOR'
assert custom_encode("WORLD") == b'ZRUOG'
assert custom_encode("a") == b'd'
def test_custom_decode():
assert custom_decode(b'KHOOR') == "HELLO"
assert custom_decode(b'ZRUOG') == "W... | [
{
"docstring": "Function to encode an input string where each character is replaced by its Unicode code point shifted by 3 positions.",
"function_declaration": "def custom_encode(input_string):",
"function_name": "custom_encode",
"parameter_list": "(input_string)"
},
{
"docstring": "Function... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def custom_encode(input_string: str) -> bytes:\n \"\"\"\n Function to encode an input string where each character is replaced by its Unicode code point shifted by... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00025585",
"row_id": 25585,
"seed_ids": "[47]"
} | 0.680181 | Docs: Python310_25585 | I | [
"custom_encode",
"custom_decode",
"handle_encoding_error"
] | 3 | [
[
"custom_encode",
"handle_encoding_error"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6d6413f81a14c6be34dd76984b93e5a43b5663e2 | 64eb5834a6c12ca98a1d52a3c6643f75e1aab586 | |||
v1.0 | instruct | Docs | Docs: Python310_25608_I | ### Task
You have been provided with a Python application tracking system that logs events and exceptions in a simplistic manner. Your task is to enhance this system utilizing functionalities from the `sys` module, particularly focusing on custom exception handling and profiling.
### Requirements
1. **Custom Excepti... | import sys
import time
import traceback
ERROR_LOG_FILE = 'error_log.txt'
PROFILE_LOG_FILE = 'profile_log.txt'
def custom_excepthook(exc_type, exc_value, exc_traceback):
with open(ERROR_LOG_FILE, 'a') as log_file:
log_file.write(f"Exception type: {exc_type}\n")
log_file.write(f"Exception value: {ex... | import os
import sys
from solution import custom_excepthook, profile_func, function_a, function_b
def test_custom_excepthook():
# Simulate an exception
try:
raise KeyError("Test key error")
except KeyError:
ex_type, ex_value, ex_tb = sys.exc_info()
custom_excepthook(ex_type, ex_valu... | [
{
"docstring": null,
"function_declaration": "def custom_excepthook(exc_type, exc_value, exc_traceback):",
"function_name": "custom_excepthook",
"parameter_list": "(exc_type, exc_value, exc_traceback)"
},
{
"docstring": null,
"function_declaration": "def profile_func(frame, event, arg):"... | [
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 sys\nimport time\nimport traceback\n\nERROR_LOG_FILE = 'error_log.txt'\nPROFILE_LOG_FILE = 'profile_log.txt'\n\ndef custom_excepthook(exc_type, exc_value, exc_tr... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00025608",
"row_id": 25608,
"seed_ids": "[348]"
} | 0.554822 | Docs: Python310_25608 | I | [
"custom_excepthook",
"profile_func",
"function_a",
"function_b"
] | 4 | [
[
"function_a",
"function_b"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c7c136a5e5bd7921ec84446a06106b957807d2e9 | fa53b907bf7a07017312b21974d44e73241c71c2 | |||
v1.0 | instruct | Docs | Docs: Python310_25610_I | ### Question: Handling Nested Functions and Exception Propagation
You're required to implement a suite of nested functions that demonstrate the understanding of name resolution, binding rules, and exception handling in Python.
#### Specifications:
1. Implement a function `calculate_total` that takes a list of number... | def calculate_total(numbers):
"""
Takes a list of numbers and returns their sum.
"""
total = 0 # Initialize total
def add_to_total(number):
nonlocal total # Ensure that we modify the 'total' variable from the enclosing scope
if not isinstance(number, (int, float)):
rai... | from solution import calculate_total, safe_calculate
def test_calculate_total_all_numbers():
assert calculate_total([1, 2, 3, 4]) == 10
assert calculate_total([1.5, 2.5, 3.5]) == 7.5
assert calculate_total([-1, -2, -3]) == -6
def test_calculate_total_mixed_types():
try:
calculate_total([1, 'tw... | [
{
"docstring": "Takes a list of numbers and returns their sum.",
"function_declaration": "def calculate_total(numbers):",
"function_name": "calculate_total",
"parameter_list": "(numbers)"
},
{
"docstring": "Safely calculates the total of a list of numbers by handling exceptions.",
"funct... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_total(numbers):\n total = 0\n \n def add_to_total(number):\n nonlocal total\n total += number\n \n for num in numbers:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025610",
"row_id": 25610,
"seed_ids": "[94]"
} | 0.634677 | Docs: Python310_25610 | I | [
"calculate_total",
"safe_calculate"
] | 2 | [
[
"safe_calculate",
"calculate_total"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6c8b294052a4e618151ecf3f1c52628f37da6abe | a0b67f42758adf369c7d701117c1582b89cb07eb | |||
v1.0 | instruct | Docs | Docs: Python310_25631_I | #### Objective:
Implement a function using `concurrent.futures` to update and process a list of numbers in parallel, demonstrating your understanding of both `ThreadPoolExecutor` and `ProcessPoolExecutor`.
#### Problem Description:
You are provided with a list of numbers, `numbers`, and your task is to perform two ope... | import concurrent.futures
import math
from typing import List
def increment_numbers(numbers: List[int], increment: int, max_workers: int) -> List[int]:
"""
Increment each number in the list by the given increment value using ThreadPoolExecutor.
"""
def increment_fn(n):
return n + increment
... | def test_increment_numbers():
numbers = [1, 2, 3, 4, 5]
increment = 10
max_workers = 3
result = increment_numbers(numbers, increment, max_workers)
assert result == [11, 12, 13, 14, 15]
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False... | [
{
"docstring": "Increment each number in the list by the given increment value using ThreadPoolExecutor.",
"function_declaration": "def increment_numbers(numbers, increment, max_workers):",
"function_name": "increment_numbers",
"parameter_list": "(numbers, increment, max_workers)"
},
{
"docs... | [
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 concurrent.futures\nimport math\n\ndef increment_numbers(numbers, increment, max_workers):\n def increment_fn(n):\n return n + increment\n\n with co... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00025631",
"row_id": 25631,
"seed_ids": "[347]"
} | 0.532568 | Docs: Python310_25631 | I | [
"increment_numbers",
"is_prime",
"check_prime_numbers",
"process_numbers"
] | 4 | [
[
"check_prime_numbers",
"is_prime"
],
[
"process_numbers",
"check_prime_numbers"
],
[
"process_numbers",
"increment_numbers"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 4eef5dd8ffe79c4c38cffc7743664056e65de825 | f2391bb9881feb4ac56e4f47cd5a5e118b684609 | |||
v1.0 | instruct | Docs | Docs: Python310_25701_I | You are working on an email client application and need to parse, format, and validate email addresses from various email headers. You are required to implement a function that:
1. Extracts all recipients from 'To', 'Cc', and any 'Resent-To' and 'Resent-Cc' fields provided.
2. Formats these extracted email addresses in... | import email.utils
import re
def is_valid_email(email):
"""Check if the email address is valid as per RFC 2822."""
pattern = re.compile(
r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
)
return re.match(pattern, email) is not None
def format_email_recipients(headers):
"""
Extract... | from solution import format_email_recipients
def test_format_email_recipients_with_mixed_valid_and_invalid_emails():
headers = {
'To': ['John Doe <john.doe@example.com>', 'InvalidEmail <invalid-email>'],
'Cc': ['Jane <jane.doe@sample.com>'],
'Resent-To': ['admin@domain.org'],
'Resen... | [
{
"docstring": "Check if the email address is valid as per RFC 2822.",
"function_declaration": "def is_valid_email(email):",
"function_name": "is_valid_email",
"parameter_list": "(email)"
},
{
"docstring": "Extracts recipients from 'To', 'Cc', 'Resent-To', and 'Resent-Cc' fields, validates,\... | [
0,
0,
0,
1,
0,
1,
1,
0,
1
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\nfrom email.utils import getaddresses, parseaddr\n\ndef is_valid_email(email: str) -> bool:\n \"\"\"\n Validates an email address using a regex pattern ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00025701",
"row_id": 25701,
"seed_ids": "[215]"
} | 0.596139 | Docs: Python310_25701 | I | [
"is_valid_email",
"format_email_recipients"
] | 2 | [
[
"format_email_recipients",
"is_valid_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 969c20f8e5184c89a100754cae9c1272dd55838e | 968ae3b393ae0eb1f748b208946180310f684d48 | |||
v1.0 | instruct | Docs | Docs: Python310_25715_I | ### Parallel Computation with `concurrent.futures`
You are required to implement a function that performs a computationally intensive task on a list of integers using the `concurrent.futures` module. The goal is to utilize parallel processing to improve performance.
#### Task Description
Write a function `compute_squ... | from typing import List
import concurrent.futures
def square(n: int) -> int:
"""
Returns the square of the input number.
"""
return n * n
def compute_squares(arr: List[int], num_workers: int) -> List[int]:
"""
Given a list of integers and a number of workers, compute the squares
of the int... | from solution import compute_squares
def test_compute_squares_small_list():
arr = [1, 2, 3, 4, 5]
num_workers = 2
expected = [1, 4, 9, 16, 25]
assert sorted(compute_squares(arr, num_workers)) == sorted(expected)
def test_compute_squares_large_list():
arr = list(range(1, 101))
num_workers = 4
... | [
{
"docstring": "Returns the square of the input number.",
"function_declaration": "def square(n):",
"function_name": "square",
"parameter_list": "(n)"
},
{
"docstring": "Given a list of integers and a number of workers, compute the squares\nof the integers using parallel processing.",
"f... | [
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 typing import List\nimport concurrent.futures\n\ndef compute_squares(arr: List[int], num_workers: int) -> List[int]:\n def square(x):\n return x * x\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025715",
"row_id": 25715,
"seed_ids": "[224]"
} | 0.586866 | Docs: Python310_25715 | I | [
"square",
"compute_squares"
] | 2 | [
[
"compute_squares",
"square"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 38c72aaf0fcab643b9966530e48047ac58ad1201 | b57b8ae08a31fb91171f8bae2ce8b9225e397c03 | |||
v1.0 | instruct | Docs | Docs: Python310_25808_I | ## Coding Assessment Question
### Objective:
Demonstrate your understanding of process-based parallelism using the `multiprocessing` module in Python by implementing a program that creates multiple processes to compute the results and shares the results using inter-process communication.
### Problem Statement:
You ar... | from multiprocessing import Process, Queue, current_process
# Function to compute square of a number
def compute(n):
return n * n
# Worker function to process tasks from the task queue and store results in the result queue
def worker(task_queue, result_queue):
while True:
task = task_queue.get()
... | import pytest
from solution import compute, main
def test_compute():
assert compute(1) == 1
assert compute(2) == 4
assert compute(3) == 9
assert compute(4) == 16
assert compute(5) == 25
assert compute(10) == 100
assert compute(20) == 400
# Testing main function by capturing stdout
def test... | [
{
"docstring": null,
"function_declaration": "def compute(n):",
"function_name": "compute",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def worker(task_queue, result_queue):",
"function_name": "worker",
"parameter_list": "(task_queue, result_queue)"
... | [
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 multiprocessing import Process, Queue, current_process\nimport time\n\n# Function to compute square of a number\ndef compute(n):\n return n * n\n\n# Worker func... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025808",
"row_id": 25808,
"seed_ids": "[338]"
} | 0.666555 | Docs: Python310_25808 | I | [
"compute",
"worker",
"main"
] | 3 | [
[
"worker",
"compute"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b062bcf5e8922730ce42f4ccf2b7aeac0706ea8f | e73cfb5e5b01203d680d912de7cab0bae4505b63 | |||
v1.0 | instruct | Docs | Docs: Python310_25822_I | ### Custom Exception Handling and Chaining in Python
#### Objective:
Design classes and functions that leverage custom exceptions by inheriting from built-in exceptions. Implement a function that raises and handles these custom exceptions while demonstrating exception chaining and context.
#### Problem Statement:
You... | class InvalidOperationError(Exception):
"""
Custom exception for invalid operations where the input is not within the expected range.
"""
pass
class OperationTimeoutError(TimeoutError):
"""
Custom exception for operations that take too long to complete.
"""
pass
def perform_operation(n... | import pytest
from solution import InvalidOperationError, OperationTimeoutError, perform_operation, execute
def test_perform_operation_negative():
with pytest.raises(InvalidOperationError):
perform_operation(-1)
def test_perform_operation_timeout():
with pytest.raises(OperationTimeoutError):
p... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class InvalidOperationError(Exception):\n \"\"\"\n Exception raised for invalid operations.\n \"\"\"\n pass\n\nclass OperationTimeoutError(TimeoutError):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00025822",
"row_id": 25822,
"seed_ids": "[256]"
} | 0.510735 | Docs: Python310_25822 | I | [
"perform_operation",
"execute"
] | 2 | [
[
"execute",
"perform_operation"
]
] | 1 | [] | false | [
"InvalidOperationError",
"OperationTimeoutError"
] | true | pytest | true | [] | true | f7bf477232fd07116f5b66a310f632457537917e | e0509ba56a99bb4684486b30764d7dd71cc99278 | |||
v1.0 | instruct | Docs | Docs: Python310_25840_I | **Multiprocessing in Python: Task Execution and Synchronization**
**Objective:**
To implement a multiprocessing solution that distributes tasks across multiple processes and ensures correct synchronization when accessing a shared resource.
**Background:**
You have been tasked to parallelize a computation-heavy task ... | import multiprocessing
from typing import List
import math
def generate_primes(start: int, end: int) -> List[int]:
"""
Returns a list of prime numbers between start and end (inclusive).
"""
primes = []
for num in range(start, end + 1):
if num > 1:
is_prime = True
for... | from solution import generate_primes, worker, main
import multiprocessing
def test_generate_primes():
assert generate_primes(10, 20) == [11, 13, 17, 19]
assert generate_primes(1, 10) == [2, 3, 5, 7]
assert generate_primes(0, 2) == [2]
assert generate_primes(20, 30) == [23, 29]
def test_worker():
m... | [
{
"docstring": "Returns a list of prime numbers between start and end (inclusive).",
"function_declaration": "def generate_primes(start, end):",
"function_name": "generate_primes",
"parameter_list": "(start, end)"
},
{
"docstring": "Worker function to retrieve intervals from task_queue, gene... | [
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 multiprocessing\nfrom typing import List\nimport math\n\ndef generate_primes(start: int, end: int) -> List[int]:\n \"\"\"\n Returns a list of prime numbers... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00025840",
"row_id": 25840,
"seed_ids": "[338]"
} | 0.611346 | Docs: Python310_25840 | I | [
"generate_primes",
"worker",
"main"
] | 3 | [
[
"worker",
"generate_primes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 05d210147f9da7ace9582ad9e5899ac40c4523d4 | bf3d5f9dac745d8e07604891c1fdeb9353269c50 | |||
v1.0 | instruct | Docs | Docs: Pytorch_25938_I | ### Question: Implement a Distributed Parameter Server with RPC in PyTorch
You are tasked with implementing a simple distributed training setup using PyTorch's Distributed RPC Framework. Specifically, you will create a parameter server and a set of workers that will each perform computations and update the parameters ... | import os
import torch
import torch.nn as nn
import torch.optim as optim
import torch.distributed.rpc as rpc
from torch.distributed.rpc import RRef
from concurrent.futures import ThreadPoolExecutor
global_model = nn.Linear(10, 2) # Example model
def get_model():
return global_model
def update_parameters(worker_... | def test_rpc_initialization():
import os
os.system("python rpc_distributed_training.py 100")
def test_model_parameter_shape():
import torch
global_model = torch.nn.Linear(10, 2)
assert list(global_model.parameters())[0].shape == torch.Size([2, 10])
assert list(global_model.parameters())[1].shap... | [
{
"docstring": null,
"function_declaration": "def get_model():",
"function_name": "get_model",
"parameter_list": "()"
},
{
"docstring": "Update parameters using gradients received from worker nodes ",
"function_declaration": "def update_parameters(worker_id, gradients):",
"function_n... | [
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport torch\nimport torch.distributed.rpc as rpc\nfrom torch import nn, optim\n\nclass ParameterServer(nn.Module):\n def __init__(self):\n super(P... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00025938",
"row_id": 25938,
"seed_ids": "[36]"
} | 0.374043 | Docs: Pytorch_25938 | I | [
"get_model",
"update_parameters",
"parameter_server",
"worker",
"main"
] | 5 | [
[
"worker",
"update_parameters"
]
] | 1 | [] | false | [] | false | pytest | false | [
"torch"
] | false | 607d649912979aaec92583ed0391e1fe5aee4dc4 | 1d926d4cdc845dde96dee5944e0e2851ea428741 | |||
v1.0 | instruct | Docs | Docs: Python310_25941_I | ### Asynchronous File Processing
**Objective:**
Implement an asynchronous function to process multiple files concurrently using the asyncio library in Python. This exercise will test your understanding of coroutines, task creation, and concurrent execution.
**Problem Statement:**
You are given a list of file paths,... | import asyncio
from typing import List
async def read_file(file_path: str) -> int:
"""
A coroutine that reads a file and returns the number of lines it contains.
"""
line_count = 0
async with aiofiles.open(file_path, 'r') as file:
async for _ in file:
line_count += 1
return ... | import os
import tempfile
import pytest
import asyncio
from solution import read_file, process_files
@pytest.fixture
def create_temp_files():
# Create temporary files for testing
temp_files = []
file_contents = [
"Line1\nLine2\nLine3\n",
"Line1\nLine2\n",
"",
"Line1\n"
]... | [] | [
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\nasync def read_file(file_path: str) -> int:\n \"\"\"\n A coroutine that reads a file and returns the number of lines it contains.\n \"\"\"\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00025941",
"row_id": 25941,
"seed_ids": "[317]"
} | 0.56695 | Docs: Python310_25941 | I | [
"read_file",
"process_files"
] | 2 | [
[
"process_files",
"read_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 77ed5788fc1e95fe500af3c0cdc6b27a8ef9ea16 | 55a20ebeabdda4810827cc22e3e3acb91940cca0 | |||
v1.0 | instruct | Docs | Docs: Python310_26014_I | ### Event Scheduler Implementation
You are tasked with creating a lightweight event-based notification system that uses Python's `sched` module. The system needs to handle different types of notifications at specified times or after certain delays.
#### Requirements
1. **Functions to Schedule Events**:
- **Sched... | import sched
import time
def schedule_notification_at(scheduler, notification_time, message):
"""
Schedule a notification event at an absolute time.
Args:
- scheduler: An instance of sched.scheduler.
- notification_time: A float representing the absolute time (e.g., time.time() + 60 for 60 sec... | import pytest
import sched
import time
import io
import sys
from solution import schedule_notification_at, schedule_notification_in, notification_scheduler
def capture_output(func, *args):
old_stdout = sys.stdout
new_stdout = io.StringIO()
sys.stdout = new_stdout
func(*args)
sys.stdout = old_std... | [
{
"docstring": "Schedule a notification event at an absolute time.\n\nArgs:\n- scheduler: An instance of sched.scheduler.\n- notification_time: A float representing the absolute time (e.g., time.time() + 60 for 60 seconds from now).\n- message: A string message to display when the notification is triggered.\n\n... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sched\nimport time\n\ndef schedule_notification_at(scheduler, notification_time, message):\n \"\"\"\n Schedule a notification event at an absolute time.\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00026014",
"row_id": 26014,
"seed_ids": "[180]"
} | 0.593127 | Docs: Python310_26014 | I | [
"schedule_notification_at",
"schedule_notification_in",
"notification_scheduler"
] | 3 | [
[
"notification_scheduler",
"schedule_notification_at"
],
[
"notification_scheduler",
"schedule_notification_in"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | bccbacc9a5f957943f431ea872f45a8e4660650c | caa794ea05485ea2d0f8e5bd7e0541b9efa22c76 | |||
v1.0 | instruct | Docs | Docs: Python310_26023_I | ### Function Call Tracing with SystemTap and DTrace in CPython
**Objective:**
Implement a Python script that monitors the call and return of specific functions using simulated markers. The goal is to emulate a simplified version of the DTrace/SystemTap functionality described in the provided documentation.
**Task:**
... | import time
import inspect
def trace_function(func):
def wrapper(*args, **kwargs):
filename = inspect.getfile(func)
funcname = func.__name__
lineno_start = func.__code__.co_firstlineno
timestamp_start = int(time.time() * 1000)
# Log function entry
print(f"{t... | from solution import trace_function, sample_function_1, sample_function_2
def test_trace_function(capsys):
sample_function_1()
captured = capsys.readouterr()
assert "function-entry" in captured.out
assert "function-return" in captured.out
sample_function_2(10)
captured = capsys.readouterr()
... | [
{
"docstring": null,
"function_declaration": "def trace_function(func):",
"function_name": "trace_function",
"parameter_list": "(func)"
},
{
"docstring": null,
"function_declaration": "def sample_function_1():",
"function_name": "sample_function_1",
"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 time\nimport inspect\nfrom functools import wraps\n\ndef trace_function(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n filename = inspect.g... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026023",
"row_id": 26023,
"seed_ids": "[79]"
} | 0.543372 | Docs: Python310_26023 | I | [
"trace_function",
"sample_function_1",
"sample_function_2"
] | 3 | [
[
"sample_function_2",
"sample_function_1"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 10e0311ff23e8190e1d15600a39622bf51fd7edc | c197b6b09da68182e103799f33b6c82eec9ed379 | |||
v1.0 | instruct | Docs | Docs: Python310_26045_I | **Context Management with `contextvars` in Asynchronous Programming**
### Problem Statement
Implement a small program to demonstrate the usage of `contextvars` and how context can be managed manually using the `copy_context()` function and `Context` class in Python. The program should simulate an asynchronous logging... | import asyncio
import contextvars
# Step 1: Declare the ContextVar
request_id_var = contextvars.ContextVar('request_id')
# Step 2: Implement the log_message function
def log_message(message: str) -> str:
request_id = request_id_var.get()
return f"[Request ID: {request_id}] {message}"
# Step 3: Asynchronous l... | import asyncio
from solution import async_log_messages
def test_log_messages():
# Define test log entries
log_entries = [(1, "First log message"), (2, "Second log message")]
# Get results by running the async function
results = asyncio.run(async_log_messages(log_entries))
# Verify the res... | [
{
"docstring": null,
"function_declaration": "def log_message(message):",
"function_name": "log_message",
"parameter_list": "(message)"
}
] | [
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 contextvars\n\n# Step 1: Declare the ContextVar\nrequest_id_var = contextvars.ContextVar('request_id')\n\n# Step 2: Implement the log_message fun... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026045",
"row_id": 26045,
"seed_ids": "[392]"
} | 0.514255 | Docs: Python310_26045 | I | [
"log_message",
"async_log_messages"
] | 2 | [
[
"async_log_messages",
"log_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ba6664fd4438982810f7e82b72adc8f1e7811bcd | dc7e26f2d5af567a52894bea775325b7d21e311b | |||
v1.0 | instruct | Docs | Docs: Python310_26115_I | **Task**: Create a Python module that simulates a lightweight version of function tracing similar to what can be achieved using DTrace or SystemTap markers. Your module should be able to monitor function entries, function returns, and garbage collection cycles.
**Requirements**:
1. **Function Entry and Return**:
- ... | import gc
import time
from functools import wraps
def trace_function(func):
@wraps(func)
def wrapper(*args, **kwargs):
filename = func.__code__.co_filename
func_name = func.__name__
lineno = func.__code__.co_firstlineno
timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(... | import gc
import time
from solution import trace_function, trace_gc_events, example_function, another_function
def test_trace_function_decorator(capsys):
@trace_function
def test_func():
pass
test_func()
captured = capsys.readouterr()
assert "function-entry" in captured.out
assert... | [
{
"docstring": null,
"function_declaration": "def trace_function(func):",
"function_name": "trace_function",
"parameter_list": "(func)"
},
{
"docstring": null,
"function_declaration": "def trace_gc_events():",
"function_name": "trace_gc_events",
"parameter_list": "()"
},
{
... | [
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 gc\nimport time\nfrom functools import wraps\n\ndef trace_function(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n filename = func.__code__.... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00026115",
"row_id": 26115,
"seed_ids": "[79]"
} | 0.536958 | Docs: Python310_26115 | I | [
"trace_function",
"trace_gc_events",
"example_function",
"another_function"
] | 4 | [
[
"another_function",
"example_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9197d097e0509ffa0c8528b5ff373643397e40c6 | 96798bf4981fa94e27a6d80d5ab6b761cad158ca | |||
v1.0 | instruct | Docs | Docs: Python310_26131_I | ### Secure Document Verification Using `hashlib`
Implement a Python program that verifies the integrity of documents by generating and comparing their secure hash values using the `hashlib` module.
Your task is to implement two core functions:
1. `generate_file_hash(filepath: str, algorithm: str) -> str`: This functi... | import hashlib
def generate_file_hash(filepath: str, algorithm: str) -> str:
"""
Generates a secure hash of the file using the specified algorithm.
Parameters:
filepath (str): Path to the file to be hashed.
algorithm (str): Hashing algorithm to use.
Returns:
str: Hexadecimal representatio... | import pytest
from solution import generate_file_hash, verify_file_integrity
def test_generate_file_hash():
assert generate_file_hash('nonexistentfile.txt', 'sha256') == None # File does not exist
assert generate_file_hash('document1.txt', 'nonexistent_algorithm') == None # Unsupported algorithm
# Creat... | [
{
"docstring": "Generates a secure hash of the file using the specified algorithm.\n\nParameters:\nfilepath (str): Path to the file to be hashed.\nalgorithm (str): Hashing algorithm to use.\n\nReturns:\nstr: Hexadecimal representation of the file's hash.",
"function_declaration": "def generate_file_hash(fil... | [
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 hashlib\n\ndef generate_file_hash(filepath: str, algorithm: str) -> str:\n \"\"\"\n Generates a secure hash of the file using the specified algorithm.\n\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00026131",
"row_id": 26131,
"seed_ids": "[225]"
} | 0.749396 | Docs: Python310_26131 | I | [
"generate_file_hash",
"verify_file_integrity"
] | 2 | [
[
"verify_file_integrity",
"generate_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 58d3d07429922b20827d6feb6c5fbed883a19bf6 | 2facd9aec0f04409db100d7791c70c23152a9db3 | |||
v1.0 | instruct | Docs | Docs: Python310_26146_I | **Parallel Data Processing with Threading and Multiprocessing**
In this task, you are required to process a large dataset using both multi-threading and multi-processing techniques. The dataset consists of numerical data points (integers) that need to be processed concurrently to improve performance.
### Task Descrip... | import os
from threading import Thread
from multiprocessing import Process, Queue
import time
def process_data(data_point: int) -> int:
"""
Function to process a single data point.
Here, we simply return the square of the data point.
"""
return data_point * data_point
def worker_threading(data_ch... | from solution import process_data, threading_process, multiprocessing_threading_process
import pytest
def test_process_data():
assert process_data(2) == 4
assert process_data(-3) == 9
assert process_data(0) == 0
def test_threading_process():
data = [1, 2, 3, 4, 5]
n = 2
result = threading_proc... | [
{
"docstring": "Function to process a single data point.\nHere, we simply return the square of the data point. ",
"function_declaration": "def process_data(data_point):",
"function_name": "process_data",
"parameter_list": "(data_point)"
},
{
"docstring": "Worker function to process data chun... | [
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 os\nfrom threading import Thread\nfrom multiprocessing import Process, Queue, current_process\nimport time\n\ndef process_data(data_point: int) -> int:\n \"\"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026146",
"row_id": 26146,
"seed_ids": "[206]"
} | 0.491899 | Docs: Python310_26146 | I | [
"process_data",
"worker_threading",
"threading_process",
"worker_multiprocessing",
"multiprocessing_threading_process",
"main"
] | 6 | [
[
"worker_threading",
"process_data"
]
] | 1 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 85ef6a246e364fc6c04cacdbc46e2ae0f0788081 | 8d72cca1a18108d5a45e956879bbd521178c3f7b | |||
v1.0 | instruct | Docs | Docs: Python310_26183_I | ## Coding Assessment Question
### Objective:
Design and implement a Python application using the `tkinter.tix` module that demonstrates the use of various widgets to create a File Manager and Viewer interface.
### Description:
You are tasked with creating a basic File Manager application using the `tkinter.tix` modul... | import os
import tkinter.tix as tix
from tkinter import messagebox
from tkinter import filedialog
import time
def display_file_details(file_path):
try:
file_stats = os.stat(file_path)
file_size = file_stats.st_size
creation_date = time.ctime(file_stats.st_ctime)
detail_msg ... | import pytest
from solution import display_file_details # Assuming the filename is solution.py
import os
import tempfile
import time
def test_display_file_details_creation():
with tempfile.NamedTemporaryFile(delete=False) as tf:
try:
file_path = tf.name
file_stats = os.stat(file_pa... | [
{
"docstring": null,
"function_declaration": "def display_file_details(file_path):",
"function_name": "display_file_details",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def on_directory_selection(event):",
"function_name": "on_directory_selection... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nfrom tkinter import Tk, Toplevel, messagebox, LEFT, BOTH, YES, RIGHT, END\nfrom tkinter.tix import DirTree, Tree, NoteBook, Balloon, PopupMenu\nimport time\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00026183",
"row_id": 26183,
"seed_ids": "[357]"
} | 0.389234 | Docs: Python310_26183 | I | [
"display_file_details",
"on_directory_selection",
"load_directory_tree",
"setup_ui",
"on_file_right_click",
"get_parent_directory"
] | 6 | [
[
"on_directory_selection",
"load_directory_tree"
],
[
"on_file_right_click",
"display_file_details"
],
[
"on_file_right_click",
"get_parent_directory"
],
[
"setup_ui",
"on_directory_selection"
],
[
"setup_ui",
"on_file_right_click"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | a8a1578359c1626e9e92fa62a8e0aab91c9617c3 | cb52eaf3bcdb34f483b23b3d26e51cc8e5d97e5e | |||
v1.0 | instruct | Docs | Docs: Scikit_26264_I | **Coding Assessment Question**
### Question
You are provided with a dataset containing features and target values for predicting house prices. Your task is to perform the following tasks using `scikit-learn`:
1. Preprocess the given data to handle any missing values.
2. Fit a `LinearRegression` model to the preproces... | import pandas as pd
from sklearn.linear_model import LinearRegression, RidgeCV
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.impute import SimpleImputer
def preprocess_data(filepath):
"""
Load and preprocess the dataset.
Parameters:
fi... | import pandas as pd
import numpy as np
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from solution import evaluate_models
# Create a synthetic dataset for testing
def create_test_data():
X, y = make_regression(n_samples=100, n_features=5, noise=0.1, random_state... | [
{
"docstring": "Load and preprocess the dataset.\n\nParameters:\nfilepath (str): Path to the dataset CSV file\n\nReturns:\nX (pd.DataFrame): Preprocessed features\ny (pd.Series): Target values",
"function_declaration": "def preprocess_data(filepath):",
"function_name": "preprocess_data",
"parameter_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nfrom sklearn.linear_model import LinearRegression, RidgeCV\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import tra... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026264",
"row_id": 26264,
"seed_ids": "[53]"
} | 0.675968 | Docs: Scikit_26264 | I | [
"preprocess_data",
"evaluate_models"
] | 2 | [
[
"evaluate_models",
"preprocess_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | 290deb08bd5144f7e9692a2df89e5338820f4680 | d8125a174a0ac28d7c9d44658a054af5414cf073 | |||
v1.0 | instruct | Docs | Docs: Scikit_26268_I | ## Problem Statement
You are given a dataset containing features of various houses along with their prices and sale categories. Your task is to implement a decision tree model to perform the following:
1. Predict the `category` (high, medium, low) of houses based on the given input features.
2. Predict the `price` of ... | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.metrics import accuracy_score, mean_squared_error
def prepare_data(file_path):
# Load dataset
data = pd.read_csv(file_path)
# Encode the 'categor... | import pytest
import pandas as pd
from sklearn.metrics import accuracy_score, mean_squared_error
from solution import prepare_data, train_and_evaluate
@pytest.fixture
def sample_data(tmpdir):
# Create a temporary CSV file with sample house data
data = {
'area': [1500, 2000, 2500],
'bedrooms': [... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\nfrom sklearn.metrics ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00026268",
"row_id": 26268,
"seed_ids": "[50]"
} | 0.655314 | Docs: Scikit_26268 | I | [
"prepare_data",
"train_and_evaluate"
] | 2 | [
[
"train_and_evaluate",
"prepare_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas",
"sklearn"
] | false | 394f7e0cd209236bc22a0f696cbc3d84b6cc3f5f | 835fe161b5453d2c72418acff7494f6db743b7b1 | |||
v1.0 | instruct | Docs | Docs: Python310_26277_I | **Title:** Analyzing Function Performance with Timeit
**Objective:**
To assess the student's understanding of the `timeit` module by requiring them to implement functions that utilize `timeit.timeit()` and `timeit.repeat()` to compare the performance of different implementations of a function.
**Problem Statement:**
... | import timeit
def reverse_with_slicing(lst):
"""
Reverses a list using slicing.
"""
return lst[::-1]
def reverse_with_loop(lst):
"""
Reverses a list using a for-loop.
"""
reversed_list = []
for item in lst:
reversed_list.insert(0, item)
return reversed_list
def compare... | from solution import reverse_with_slicing, reverse_with_loop, compare_performance
def test_reverse_with_slicing():
assert reverse_with_slicing([1, 2, 3]) == [3, 2, 1]
assert reverse_with_slicing([]) == []
assert reverse_with_slicing([1]) == [1]
assert reverse_with_slicing([1, 2, 3, 4, 5]) == [5, 4, 3, ... | [
{
"docstring": "Reverses a list using slicing.",
"function_declaration": "def reverse_with_slicing(lst):",
"function_name": "reverse_with_slicing",
"parameter_list": "(lst)"
},
{
"docstring": "Reverses a list using a for-loop.",
"function_declaration": "def reverse_with_loop(lst):",
... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import timeit\n\ndef reverse_with_slicing(lst):\n \"\"\"\n Reverses a list using slicing.\n \"\"\"\n return lst[::-1]\n\ndef reverse_with_loop(lst):\n \"... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00026277",
"row_id": 26277,
"seed_ids": "[328]"
} | 0.4798 | Docs: Python310_26277 | I | [
"reverse_with_slicing",
"reverse_with_loop",
"compare_performance"
] | 3 | [
[
"compare_performance",
"reverse_with_loop"
],
[
"compare_performance",
"reverse_with_slicing"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2f4997124c3b48eabc26ba984206ba6611860eb5 | 15305180f1843f96aac5e8df381ea402c5d15276 | |||
v1.0 | instruct | Docs | Docs: Python310_26278_I | ### URL Management and Handling
You are tasked with creating a Python function to retrieve and process data from a set of URLs. To achieve this, implement three functions: `fetch_url`, `parse_url`, and `check_robots`.
#### Functions Description:
1. **`fetch_url(url: str) -> str`**
This function takes a URL as an... | import urllib.request
import urllib.parse
import urllib.error
def fetch_url(url: str) -> str:
"""
Fetches the content of a given URL.
Args:
url (str): The URL to fetch.
Returns:
str: The content of the URL.
Raises:
Exception: If there is an error fetching the URL content.... | from solution import fetch_url, parse_url, check_robots
import pytest
def test_fetch_url_valid():
# We'll use httpbin.org for testing, which is a website designed for HTTP testing
content = fetch_url("http://httpbin.org/get")
assert '"url": "http://httpbin.org/get"' in content
def test_fetch_url_invalid()... | [
{
"docstring": "Fetches the content of a given URL.\n\nArgs:\nurl (str): The URL to fetch.\n\nReturns:\nstr: The content of the URL.\n\nRaises:\nException: If there is an error fetching the URL content.",
"function_declaration": "def fetch_url(url):",
"function_name": "fetch_url",
"parameter_list": ... | [
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 urllib.request\nimport urllib.robotparser\nfrom urllib.parse import urlparse, ParseResult\n\ndef fetch_url(url: str) -> str:\n \"\"\"\n Fetches the content... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00026278",
"row_id": 26278,
"seed_ids": "[291]"
} | 0.692678 | Docs: Python310_26278 | I | [
"fetch_url",
"parse_url",
"check_robots"
] | 3 | [
[
"check_robots",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 67a361e8432b87a6ceb458a77874e35a0b6d4768 | 7c53683c936321d130331469445190447eb98b16 | |||
v1.0 | instruct | Docs | Docs: Pytorch_26411_I | #### Objective:
Demonstrate your understanding of the MPS backend in PyTorch by writing code to implement a simple neural network, move it to the MPS device, and perform operations with tensors on the MPS device.
#### Problem Statement:
1. Ensure the MPS backend is available on the running system.
2. Create a simple f... | import torch
import torch.nn as nn
def check_mps_device():
"""
Check if the MPS device is available.
"""
return torch.backends.mps.is_available()
class SimpleNet(nn.Module):
def __init__(self):
super(SimpleNet, self).__init__()
self.fc1 = nn.Linear(10, 50)
self.relu = nn.Re... | import pytest
import torch
from solution import check_mps_device, SimpleNet, move_to_device, forward_pass
def test_check_mps_device():
# Check if the function returns a boolean
assert isinstance(check_mps_device(), bool)
def test_move_to_device():
model = SimpleNet()
model = move_to_device(model)
... | [] | [
1,
1,
1,
0,
1,
1,
1,
0,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\n\ndef check_mps_device():\n \"\"\"\n Checks if the MPS device is available.\n Returns:\n bool: True if MPS is avail... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00026411",
"row_id": 26411,
"seed_ids": "[167]"
} | 0.466417 | Docs: Pytorch_26411 | I | [
"check_mps_device",
"move_to_device",
"forward_pass"
] | 3 | [
[
"forward_pass",
"check_mps_device"
],
[
"move_to_device",
"check_mps_device"
]
] | 2 | [] | false | [
"SimpleNet"
] | true | pytest | true | [
"torch"
] | false | 3f63eaa992d9e5fdbb1faef70af323a38aabcf8f | dc09950673dc9593e01891ee1608c8be9a0b1508 | |||
v1.0 | instruct | Docs | Docs: Pytorch_26425_I | **Student Question:**
### Tensor Operations Testing with PyTorch
In this assessment, you are required to write a function that performs a series of tensor operations and subsequently validates the correctness of these operations using PyTorch's testing utilities.
#### Task
1. Create a function `tensor_operations(n:... | import torch
def tensor_operations(n: int) -> torch.Tensor:
if n <= 0:
raise ValueError("The size of the tensor must be a positive integer.")
torch.manual_seed(0)
a = torch.randn(n)
b = torch.rand(n)
c = a**2 + b
return c
def validate_operations(n: int) -> None:
if n ... | import pytest
from solution import tensor_operations, validate_operations
def test_tensor_operations_positive_size():
c = tensor_operations(5)
assert c.size(0) == 5
def test_tensor_operations_invalid_size():
with pytest.raises(ValueError):
tensor_operations(0)
with pytest.raises(ValueError):
... | [
{
"docstring": null,
"function_declaration": "def tensor_operations(n):",
"function_name": "tensor_operations",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def validate_operations(n):",
"function_name": "validate_operations",
"parameter_list": "(n)"
... | [
1,
1,
1,
0,
0,
0,
1,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef tensor_operations(n: int) -> torch.Tensor:\n if n <= 0:\n raise ValueError(\"The size of the tensor must be a positive integer.\")\n \n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00026425",
"row_id": 26425,
"seed_ids": "[128]"
} | 0.582739 | Docs: Pytorch_26425 | I | [
"tensor_operations",
"validate_operations"
] | 2 | [
[
"validate_operations",
"tensor_operations"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 8887319e11348dae2b50fbef2eb7fcd8c07ac6b5 | 944b8a383fae52b402a5699a756a0f5d8205da94 | |||
v1.0 | instruct | Docs | Docs: Pytorch_26552_I | #### Objective
Your task is to demonstrate your understanding of the PyTorch MPS backend by performing the following steps:
1. Check if the MPS backend is available on your system.
2. If available, create a tensor on the MPS device and perform some basic operations.
3. Define a simple neural network model and move it... | import torch
import torch.nn as nn
def check_mps_availability():
"""
Check if the MPS backend is available (enabled and supported).
Returns:
bool: True if MPS is available, False otherwise.
"""
return torch.backends.mps.is_available() and torch.backends.mps.is_built()
def create_mps_tens... | import pytest
import torch
from solution import check_mps_availability, create_mps_tensor, SimpleModel, move_model_to_device, predict_with_model
def test_check_mps_availability():
# This test simply checks the availability function.
# It won't assert anything specific because the availability depends on the s... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\n\ndef check_mps_availability():\n \"\"\"\n Check if the MPS backend is available (enabled and supported).\n\n Returns:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00026552",
"row_id": 26552,
"seed_ids": "[167]"
} | 0.469498 | Docs: Pytorch_26552 | I | [
"check_mps_availability",
"create_mps_tensor",
"move_model_to_device",
"predict_with_model"
] | 4 | [
[
"create_mps_tensor",
"check_mps_availability"
],
[
"move_model_to_device",
"check_mps_availability"
]
] | 2 | [] | false | [
"SimpleModel"
] | true | pytest | true | [
"torch"
] | false | bfb022108266b4863ab7b04189b3ee1e768edf5e | f4867d53702ee28da0fc66d0a04cb570c951a06e | |||
v1.0 | instruct | Docs | Docs: Python310_26564_I | ## Question: Priority Task Scheduler with Dynamic Updates
### Objective:
Implement a priority task scheduler that allows you to add tasks with priorities, update task priorities, remove tasks, and retrieve tasks in priority order. You need to maintain the heap invariant efficiently while handling these operations.
##... | from heapq import heappush, heappop
import itertools
REMOVED = '<removed-task>' # placeholder for a removed task
counter = itertools.count() # unique sequence count
def add_task(pq, entry_finder, task, priority=0):
"""
Add a new task or update the priority of an existing task.
:param pq: list, the prior... | from solution import add_task, remove_task, pop_task
def test_add_and_pop_task():
pq = []
entry_finder = {}
# Add tasks
add_task(pq, entry_finder, 'task1', priority=5)
add_task(pq, entry_finder, 'task2', priority=3)
add_task(pq, entry_finder, 'task3', priority=4)
# Pop tasks in priori... | [
{
"docstring": "Add a new task or update the priority of an existing task.\n:param pq: list, the priority queue (heap)\n:param entry_finder: dict, mapping of tasks to entries\n:param task: the task to add or update\n:param priority: the priority of the task",
"function_declaration": "def add_task(pq, entry_... | [
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 heapq import heappush, heappop\nimport itertools\n\nREMOVED = '<removed-task>' # placeholder for a removed task\ncounter = itertools.count() # unique sequence co... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026564",
"row_id": 26564,
"seed_ids": "[241]"
} | 0.548352 | Docs: Python310_26564 | I | [
"add_task",
"remove_task",
"pop_task"
] | 3 | [
[
"add_task",
"remove_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1f92baa414c7a3dbb76b88d806903710a828d003 | 4c71cd60d2fbefaad1d9f37fa29c50b2ffd61170 | |||
v1.0 | instruct | Docs | Docs: Python310_26613_I | #### Complex Number Operations
You are required to implement functions to perform various operations on complex numbers using the given C API for complex numbers (`Py_complex`) and their corresponding Python object (`PyComplexObject`). Using this API, write functions in Python that:
1. **Convert a complex number from... | import ctypes
class Py_complex(ctypes.Structure):
_fields_ = [("real", ctypes.c_double), ("imag", ctypes.c_double)]
def convert_to_c(py_num: complex) -> Py_complex:
return Py_complex(py_num.real, py_num.imag)
def convert_to_py(c_num: Py_complex) -> complex:
return complex(c_num.real, c_num.imag)
def c_a... | from solution import (
convert_to_c, convert_to_py, c_addition,
c_subtraction, c_multiplication, c_division,
c_exponentiation, c_negation, Py_complex
)
def test_convert_to_c():
py_num = 1 + 2j
c_num = convert_to_c(py_num)
assert c_num.real == 1
assert c_num.imag == 2
def test_convert_to_... | [] | [
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 ctypes\n\nclass Py_complex(ctypes.Structure):\n _fields_ = [(\"real\", ctypes.c_double), (\"imag\", ctypes.c_double)]\n\ndef convert_to_c(py_num: complex) -> ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00026613",
"row_id": 26613,
"seed_ids": "[1]"
} | 0.648556 | Docs: Python310_26613 | I | [
"convert_to_c",
"convert_to_py",
"c_addition",
"c_subtraction",
"c_multiplication",
"c_division",
"c_exponentiation",
"c_negation"
] | 8 | [
[
"c_addition",
"convert_to_c"
],
[
"c_addition",
"convert_to_py"
],
[
"c_division",
"convert_to_c"
],
[
"c_division",
"convert_to_py"
],
[
"c_multiplication",
"convert_to_c"
],
[
"c_multiplication",
"convert_to_py"
],
[
"c_negation",
"... | 10 | [] | false | [
"Py_complex"
] | true | pytest | true | [] | true | d83b59515bd552a1fdb25ab4332f8e60ff5fc557 | 1a43aa43b3105bb46e874c2f30b2b0fe6dd7b6bd | |||
v1.0 | instruct | Docs | Docs: Python310_26710_I | ### Question: Custom Exception Handling and Manipulation
#### Objective:
Write a Python program that demonstrates a deep understanding of custom exception creation and handling, including setting custom messages, associating additional context, and correctly managing error states.
#### Requirements:
1. **Define a Cu... | import warnings
import traceback
import sys
class CustomError(Exception):
"""Custom exception class with additional context."""
def __init__(self, message, context):
super().__init__(message)
self.context = context
def raise_custom_exception(message, context):
"""
Function to rais... | import warnings
from solution import CustomError, raise_custom_exception, handle_exception
def test_custom_error_attributes():
try:
raise_custom_exception('Test error', {'key': 'value'})
except CustomError as e:
assert str(e) == 'Test error'
assert e.context == {'key': 'value'}
def tes... | [] | [
0,
0,
0,
0,
0,
1,
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 warnings\nimport traceback\nimport sys\n\nclass CustomError(Exception):\n \"\"\"Custom exception class with additional context.\"\"\"\n \n def __init__(... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00026710",
"row_id": 26710,
"seed_ids": "[33]"
} | 0.412882 | Docs: Python310_26710 | I | [
"raise_custom_exception",
"handle_exception"
] | 2 | [
[
"handle_exception",
"raise_custom_exception"
]
] | 1 | [] | false | [
"CustomError"
] | true | pytest | true | [] | true | 5b3276c410c7915c5fd73fe722df6d2bd945e08f | 6c4e3d7950b729dca076aae6f585a2189c13879b | |||
v1.0 | instruct | Docs | Docs: Python310_26735_I | ### Question:
You are required to create a Python program that uses the "signal" module to handle asynchronous events. Specifically, the program should simulate a long-running calculation and be able to handle user interruptions or timeouts gracefully. The program should include functionality that demonstrates various... | import signal
import time
import threading
import os
# Define signal handlers
def handle_sigint(signum, frame):
print("Received SIGINT (Ctrl+C), exiting gracefully.")
signal.alarm(0) # Disable any scheduled alarm
os._exit(0)
def handle_sigterm(signum, frame):
print("Received SIGTERM, cleaning up.")
... | import signal
import os
import pytest
from solution import setup_signal_handlers, handle_sigint, handle_sigterm, handle_sigalrm
def test_sigint_handler(monkeypatch):
with pytest.raises(SystemExit):
handle_sigint(signal.SIGINT, None)
def test_sigterm_handler(monkeypatch):
with pytest.raises(SystemExit)... | [
{
"docstring": null,
"function_declaration": "def handle_sigint(signum, frame):",
"function_name": "handle_sigint",
"parameter_list": "(signum, frame)"
},
{
"docstring": null,
"function_declaration": "def handle_sigterm(signum, frame):",
"function_name": "handle_sigterm",
"parame... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import signal\nimport time\nimport threading\nimport os\n\n# Define signal handlers\ndef handle_sigint(signum, frame):\n print(\"Received SIGINT (Ctrl+C), exiting gr... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00026735",
"row_id": 26735,
"seed_ids": "[253]"
} | 0.553423 | Docs: Python310_26735 | I | [
"handle_sigint",
"handle_sigterm",
"handle_sigalrm",
"setup_signal_handlers",
"long_running_calculation",
"main_thread_function"
] | 6 | [
[
"main_thread_function",
"long_running_calculation"
],
[
"main_thread_function",
"setup_signal_handlers"
],
[
"setup_signal_handlers",
"handle_sigalrm"
],
[
"setup_signal_handlers",
"handle_sigint"
],
[
"setup_signal_handlers",
"handle_sigterm"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | d6b75636576b7e47f3d7456a1a10e32e0258f984 | 1d300aadf1fab4feb74b1cd71155d05d3612c55d | |||
v1.0 | instruct | Docs | Docs: Python310_26820_I | You are tasked to implement a custom JSON serialization and deserialization system in Python for a complex library management system. The system involves serializing and deserializing instances of various classes to and from JSON format. The classes involved are `Book`, `Author`, and `Library`.
1. **Class Definitions:... | import json
class Author:
def __init__(self, name, birth_year):
if not name or not isinstance(name, str):
raise ValueError("Invalid name")
if not (1000 <= birth_year <= 9999):
raise ValueError("Invalid birth year")
self.name = name
self.birth_year = birth_yea... | import pytest
from solution import Author, Book, Library, LibraryEncoder, save_library_to_file, load_library_from_file
def test_author_creation():
author = Author(name="J.K. Rowling", birth_year=1965)
assert author.name == "J.K. Rowling"
assert author.birth_year == 1965
def test_book_creation():
autho... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\n\nclass Author:\n def __init__(self, name, birth_year):\n if not name or not isinstance(name, str):\n raise ValueError(\"Invalid name\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00026820",
"row_id": 26820,
"seed_ids": "[159]"
} | 0.524702 | Docs: Python310_26820 | I | [
"as_author",
"as_book",
"as_library",
"save_library_to_file",
"load_library_from_file"
] | 5 | [
[
"as_book",
"as_author"
],
[
"as_library",
"as_book"
]
] | 2 | [] | false | [
"Author",
"Book",
"Library",
"LibraryEncoder"
] | true | pytest | true | [] | true | 91d8d0595a0bc6f83a483f4f54626192cf16e81b | 3fa0e622afb46e6a66b13230afb27e3aa9d869a7 | |||
v1.0 | instruct | Docs | Docs: Python310_26826_I | **Objective**:
Implement a Python function using the `zipfile` module to create, update, and extract ZIP archives with various compression methods. The function should include error handling for common pitfalls related to ZIP archives.
**Task**:
Write a function `process_zipfile(zip_path, operation, files=[], target_d... | import zipfile
from typing import List
import os
def process_zipfile(zip_path: str, operation: str, files: List[str] = [], target_dir: str = None, compression=zipfile.ZIP_STORED, password: bytes = None) -> None:
# Check for valid compression method
valid_compressions = [zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED... | import os
import zipfile
import pytest
from solution import process_zipfile
TEST_ZIP_FILE = 'test.zip'
TEST_FILES = ['test1.txt', 'test2.txt']
EXTRACT_DIR = 'extracted_files'
# Prepare environment
@pytest.fixture(scope="module", autouse=True)
def setup_teardown():
# Create test files
for file in TEST_FILES:
... | [
{
"docstring": null,
"function_declaration": "def process_zipfile(zip_path, operation, files=[], target_dir=None, compression=zipfile.ZIP_STORED, password=None):",
"function_name": "process_zipfile",
"parameter_list": "(zip_path, operation, files=[], target_dir=None, compression=zipfile.ZIP_STORED, ... | [
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 zipfile\nfrom typing import List\nimport os\n\ndef process_zipfile(zip_path: str, operation: str, files: List[str] = [], target_dir: str = None, compression=zipf... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026826",
"row_id": 26826,
"seed_ids": "[242]"
} | 0.768347 | Docs: Python310_26826 | I | [
"process_zipfile",
"safe_extract"
] | 2 | [
[
"process_zipfile",
"safe_extract"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f2a777eb21e511a8cd9ec8dba2d6fa9a70d38c0b | 28d110ad989b17ab17bee2130deb797bce849004 | |||
v1.0 | instruct | Docs | Docs: Seaborn_26873_I | You are given a dataset of daily temperatures recorded in two different cities over one month. Your task is to visualize the central tendency of the temperatures using seaborn and to represent the spread and uncertainty using error bars.
### Dataset
The dataset is a CSV file with the following columns:
- **date**: The... | import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
def read_and_preprocess(file_path):
# Read the dataset from the CSV file
data = pd.read_csv(file_path)
# No additional preprocessing steps required
return data
def plot_central_tendency_with_error_bars(file... | import pandas as pd
import numpy as np
def test_read_and_preprocess():
# Create a sample dataset
data = pd.DataFrame({
'date': ['2023-01-01', '2023-01-01', '2023-01-02', '2023-01-02'],
'city': ['CityA', 'CityB', 'CityA', 'CityB'],
'temperature': [20, 25, 19, 24]
})
temp_file_pat... | [
{
"docstring": null,
"function_declaration": "def read_and_preprocess(file_path):",
"function_name": "read_and_preprocess",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def plot_central_tendency_with_error_bars(file_path):",
"function_name": "plot_... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.stats import bootstrap\n\ndef plot_temperature_data(file_pat... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00026873",
"row_id": 26873,
"seed_ids": "[0]"
} | 0.674019 | Docs: Seaborn_26873 | I | [
"read_and_preprocess",
"plot_central_tendency_with_error_bars"
] | 2 | [
[
"plot_central_tendency_with_error_bars",
"read_and_preprocess"
]
] | 1 | [] | false | [] | false | pytest | false | [
"matplotlib",
"numpy",
"pandas",
"seaborn"
] | false | 503160fa506866e6ca8618d4e68f285c490d58d4 | 647e9b79fc064b27b5d189d8e6bb2e7e61ebb11a | |||
v1.0 | instruct | Docs | Docs: Python310_26920_I | ### Telnet Client Implementation and Custom Interaction
#### Background
You are requested to implement a Python module that interacts with a Telnet server using the `telnetlib` package. The tasks will involve connecting to the server, performing simple commands, and handling custom Telnet options using callbacks. Thi... | import telnetlib
def connect_to_server(host: str, port: int, timeout: int) -> telnetlib.Telnet:
try:
tn = telnetlib.Telnet(host, port, timeout)
return tn
except Exception as e:
print(f"Failed to connect to server: {e}")
return None
def login(tn: telnetlib.Telnet, username: str,... | import pytest
from solution import connect_to_server, login, execute_command, set_custom_option_callback, interactive_session
import telnetlib
from unittest.mock import Mock, patch
def test_connect_to_server_success():
with patch("solution.telnetlib.Telnet") as mock_telnet:
mock_telnet.return_value = Mock(... | [
{
"docstring": null,
"function_declaration": "def connect_to_server(host, port, timeout):",
"function_name": "connect_to_server",
"parameter_list": "(host, port, timeout)"
},
{
"docstring": null,
"function_declaration": "def login(tn, username, password):",
"function_name": "login",
... | [
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 telnetlib\n\ndef connect_to_server(host: str, port: int, timeout: int) -> telnetlib.Telnet:\n try:\n tn = telnetlib.Telnet(host, port, timeout)\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00026920",
"row_id": 26920,
"seed_ids": "[217]"
} | 0.548762 | Docs: Python310_26920 | I | [
"connect_to_server",
"login",
"execute_command",
"custom_option_callback",
"set_custom_option_callback",
"interactive_session"
] | 6 | [
[
"interactive_session",
"connect_to_server"
],
[
"interactive_session",
"execute_command"
],
[
"interactive_session",
"login"
],
[
"interactive_session",
"set_custom_option_callback"
],
[
"set_custom_option_callback",
"custom_option_callback"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | f76927bc44e7316f0637f35be3d3c637d27f26a1 | d7ce0cdffd33ced22bde7318626b4d63b1c419b2 | |||
v1.0 | instruct | Docs | Docs: Scikit_26927_I | **Problem: Parallelizing Model Training with scikit-learn and joblib**
**Context**: You are tasked with implementing a machine learning model to classify a dataset. The training of this model is computationally intensive and can benefit from parallel processing to improve runtime performance.
**Task**:
1. Load the di... | import time
from sklearn.datasets import load_digits
from sklearn.ensemble import RandomForestClassifier
import matplotlib.pyplot as plt
def train_model(n_jobs):
"""
Trains a RandomForestClassifier on the digits dataset with the specified number of jobs.
Parameters:
n_jobs (int): Number of paralle... | import pytest
from solution import train_model
def test_train_model_single_job():
training_time = train_model(1)
assert training_time > 0
def test_train_model_multiple_jobs():
for n_jobs in [2, 4, 8]:
training_time = train_model(n_jobs)
assert training_time > 0
def test_train_model_compar... | [
{
"docstring": "Trains a RandomForestClassifier on the digits dataset with the specified number of jobs.\n\nParameters:\nn_jobs (int): Number of parallel jobs to run\n\nReturns:\nfloat: Training time in seconds",
"function_declaration": "def train_model(n_jobs):",
"function_name": "train_model",
"pa... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nfrom sklearn.datasets import load_digits\nfrom sklearn.ensemble import RandomForestClassifier\nimport matplotlib.pyplot as plt\n\ndef train_model(n_jobs):\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026927",
"row_id": 26927,
"seed_ids": "[65]"
} | 0.540773 | Docs: Scikit_26927 | I | [
"train_model",
"evaluate_parallelism"
] | 2 | [
[
"evaluate_parallelism",
"train_model"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"sklearn"
] | false | 9ca25d66cea68428e682f4ac36707797ed1b9c6c | cdca6ecc5ed6526384d4933972ac4a923ffb608e | |||
v1.0 | instruct | Docs | Docs: Scikit_26928_I | **Objective:** Demonstrate your understanding of Support Vector Machines (SVM) using the `scikit-learn` library by implementing, tuning, and evaluating SVM models on a real-world dataset.
**Problem:**
You are given the Iris dataset, a famous dataset in the machine learning community. Your task is to:
1. Load the datas... | from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.svm import SVC, LinearSVC, NuSVC
from sklearn.metrics import accuracy_score
import numpy as np
# Load and split the data
def load_and_split_data(test_size: float = 0.3, random_state: int = 42):
ir... | import pytest
from solution import (
load_and_split_data, train_svc_rbf, train_linear_svc,
train_nusvc_polynomial, evaluate_model, tune_svc_rbf, compare_models
)
def test_load_and_split_data():
X_train, X_test, y_train, y_test = load_and_split_data()
assert X_train.shape[0] > 0
assert X_test.shap... | [
{
"docstring": null,
"function_declaration": "def load_and_split_data(test_size=0.3, random_state=42):",
"function_name": "load_and_split_data",
"parameter_list": "(test_size=0.3, random_state=42)"
},
{
"docstring": null,
"function_declaration": "def train_svc_rbf(X_train, y_train):",
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.svm import SVC, LinearSVC, ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026928",
"row_id": 26928,
"seed_ids": "[31]"
} | 0.608245 | Docs: Scikit_26928 | I | [
"load_and_split_data",
"train_svc_rbf",
"train_linear_svc",
"train_nusvc_polynomial",
"evaluate_model",
"tune_svc_rbf",
"compare_models"
] | 7 | [
[
"compare_models",
"evaluate_model"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | f0a7e0ad2cd79a458228ffa12c726cbe4e9f34ce | 45f4dcd250b7908cc6da5db90ae12c8c11c2a652 | |||
v1.0 | instruct | Docs | Docs: Python310_26948_I | ### Python Coding Assessment Question
**Objective**: Demonstrate the understanding and capability to use the `importlib` package for custom module importation and reloading in Python.
**Problem Statement**:
You are required to create a Python script that manages the dynamic import and re-importing of a module using ... | import importlib
def dynamic_import(module_name, package_name=None):
"""
Dynamically imports a module using its name.
:param module_name: Absolute or relative name of the module to import.
:param package_name: Name of the package to resolve relative module names, default is None.
:return: The ... | import pytest
import importlib
from solution import dynamic_import, reload_module, check_and_reload
def test_dynamic_import():
math_module = dynamic_import("math")
assert math_module is not None
assert hasattr(math_module, "sqrt")
def test_dynamic_import_invalid_module():
module = dynamic_import("some... | [
{
"docstring": "Dynamically imports a module using its name.\n\n:param module_name: Absolute or relative name of the module to import.\n:param package_name: Name of the package to resolve relative module names, default is None.\n:return: The imported module or None if an error occurred.",
"function_declarat... | [
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 importlib\n\ndef dynamic_import(module_name, package_name=None):\n \"\"\"\n Dynamically imports a module using its name.\n \n :param module_name: Abs... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00026948",
"row_id": 26948,
"seed_ids": "[218]"
} | 0.595771 | Docs: Python310_26948 | I | [
"dynamic_import",
"reload_module",
"check_and_reload"
] | 3 | [
[
"check_and_reload",
"reload_module"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8ccc535f3104ebda840612940aa497bbaf7262a6 | 796e949632f85040f22c6f333e118eb22a29078b | |||
v1.0 | instruct | Docs | Docs: Python310_26963_I | ### Objective: Implement Custom Memory Management in Python
Python's memory management system offers interfaces for allocating and deallocating memory across different domains: raw, mem, and object. Understanding and utilizing these can be crucial for performance optimization and debugging in memory-intensive applicat... | import ctypes
from sys import getsizeof
# Wrapper for managing raw memory (emulates raw malloc and calloc)
class RawMemoryManager:
def __init__(self):
self.memories = {}
def allocate(self, size):
if size <= 0:
return None
ptr = ctypes.create_string_buffer(size)
... | import ctypes
from solution import allocate_raw, allocate_mem, allocate_obj, custom_raw_malloc, custom_raw_calloc, custom_raw_free
def test_allocate_raw():
addr = allocate_raw(100)
assert addr is not None
assert addr > 0
custom_raw_free(addr) # Free the allocated memory
addr_zero = allocate_raw(0... | [] | [
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 ctypes\n\ndef custom_raw_malloc(size):\n \"\"\"\n Allocate size bytes of raw memory.\n \"\"\"\n if size <= 0:\n return None\n try:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026963",
"row_id": 26963,
"seed_ids": "[46]"
} | 0.481414 | Docs: Python310_26963 | I | [
"custom_raw_malloc",
"custom_raw_calloc",
"custom_raw_free",
"custom_mem_malloc",
"custom_obj_malloc",
"allocate_raw",
"allocate_mem",
"allocate_obj"
] | 8 | [
[
"allocate_mem",
"custom_mem_malloc"
],
[
"allocate_obj",
"custom_obj_malloc"
],
[
"allocate_raw",
"custom_raw_malloc"
]
] | 3 | [] | false | [
"RawMemoryManager"
] | true | pytest | true | [] | true | 5de94d2b8b23e86f341543b540862ac4703aa4d0 | 9c342e13fd35a99c9b88f1c06e4b85b6628c98ae | |||
v1.0 | instruct | Docs | Docs: Python310_26995_I | ### Question
#### Implementing Parallel Task Execution with `concurrent.futures`
Given a list of URLs and a function to download the content from each URL, use both `ThreadPoolExecutor` and `ProcessPoolExecutor` to download the content asynchronously. Measure and compare the performance of both approaches in terms of... | import concurrent.futures
import requests
from typing import List, Tuple
def fetch_url(url: str, timeout: int) -> Tuple[str, bytes]:
"""
Downloads content from the specified URL.
:param url: URL to download content from
:param timeout: Timeout for the request
:return: A tuple containing the UR... | from solution import fetch_urls_with_threads, fetch_urls_with_processes
import time
urls = ["http://www.foxnews.com/", "http://www.cnn.com/", "http://europe.wsj.com/", "http://www.bbc.co.uk/"]
timeout = 10
def test_fetch_urls_with_threads():
start = time.time()
results = fetch_urls_with_threads(urls, timeout)... | [
{
"docstring": "Downloads content from the specified URL.\n\n:param url: URL to download content from\n:param timeout: Timeout for the request\n:return: A tuple containing the URL and the content bytes",
"function_declaration": "def fetch_url(url, timeout):",
"function_name": "fetch_url",
"parameter... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed\nfrom typing import List, Tuple\n\ndef fetch_url(url: str, timeout... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00026995",
"row_id": 26995,
"seed_ids": "[347]"
} | 0.480795 | Docs: Python310_26995 | I | [
"fetch_url",
"fetch_urls_with_threads",
"fetch_urls_with_processes"
] | 3 | [
[
"fetch_urls_with_processes",
"fetch_url"
],
[
"fetch_urls_with_threads",
"fetch_url"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 9abc1f08bebd970f8922c509a2f82747c2a0c954 | 1f2e0e824e8b51d941d1406bbae79efa3553fc4c | |||
v1.0 | instruct | Docs | Docs: Python310_26997_I | #### Objective:
You are required to create a Python program using the `curses` and `curses.panel` modules. The program should create multiple panels, allow them to be manipulated by the user, and display the current state of the panels on the screen.
#### Task:
Implement a function `manage_panels(n: int)` that creates... | import curses
import curses.panel
def manage_panels(stdscr, n):
if n < 1 or n > 10:
return # input constraint
curses.curs_set(0)
stdscr.keypad(1)
stdscr.timeout(100)
panels = []
height, width = 10, 10
for i in range(n):
win = curses.newwin(height, width, i * 3, i * 3)
... | # Due to the interactive and graphical nature of curses, automated tests are not practical in the traditional way.
# Typically, you'd test this manually. However, we can define a few basic tests checking the function signature and constraints inside pytest.
def test_manage_panels_signature():
from solution import ... | [
{
"docstring": null,
"function_declaration": "def manage_panels(stdscr, n):",
"function_name": "manage_panels",
"parameter_list": "(stdscr, n)"
},
{
"docstring": null,
"function_declaration": "def move_panel(key, win):",
"function_name": "move_panel",
"parameter_list": "(key, win... | [
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 curses\nimport curses.panel\n\ndef manage_panels(n):\n def create_panel(stdscr, num, y, x):\n win = curses.newwin(10, 10, y, x)\n win.box()\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00026997",
"row_id": 26997,
"seed_ids": "[157]"
} | 0.430821 | Docs: Python310_26997 | I | [
"manage_panels",
"move_panel"
] | 2 | [
[
"manage_panels",
"move_panel"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a67d1b86cffa8fb6d20c8b7347ea0e009acdb171 | 5b51fa8c0acd1feb196f27d8214c4131cd033ded | |||
v1.0 | instruct | Docs | Docs: Pytorch_27040_I | #### Objective:
The goal of this assessment is to evaluate your understanding of the `torch.futures` package and your ability to work with asynchronous operations in PyTorch.
#### Problem Statement:
You are given an asynchronous task that processes data chunks and returns the processed result as a Future object. Your ... | import torch
import asyncio
from torch.futures import Future, collect_all
from typing import List
async def process_data_chunk(chunk: int) -> int:
"""
Simulates an asynchronous data processing task.
This function should return a Future object that completes after a delay
and returns the processed data ... | import pytest
import asyncio
from solution import process_data_chunk, process_and_aggregate_data
@pytest.mark.asyncio
async def test_process_data_chunk():
result = await process_data_chunk(3)
assert result == 9
@pytest.mark.asyncio
async def test_process_and_aggregate_data():
data_chunks = [1, 2, 3, 4]
... | [] | [
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 torch\nimport asyncio\nfrom torch.futures import Future, collect_all\nfrom typing import List\n\nasync def process_data_chunk(chunk: int) -> int:\n \"\"\"\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00027040",
"row_id": 27040,
"seed_ids": "[53]"
} | 0.438964 | Docs: Pytorch_27040 | I | [
"process_data_chunk",
"process_and_aggregate_data"
] | 2 | [
[
"process_and_aggregate_data",
"process_data_chunk"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 7c06729c1c22262ec7ef95c956a5129f04d6c566 | 8921b2c7a448cdc6433d968e985831fd4faeb8ef | |||
v1.0 | instruct | Docs | Docs: Python310_27081_I | ### Advanced SQLite Database with Python `sqlite3` Module
#### Objective
In this exercise, you will demonstrate your understanding of the `sqlite3` module by creating and managing a SQLite database. You will perform tasks including database creation, data insertion, custom query execution, and implementing custom beha... | import sqlite3
def create_database():
"""
Creates the 'school.db' SQLite database and the required tables.
"""
con = sqlite3.connect("school.db")
cur = con.cursor()
# Create students table
cur.execute("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
... | import sqlite3
import pytest
from solution import create_database, insert_data, get_student_details, initials, CourseCredits
def test_create_database():
create_database()
con = sqlite3.connect("school.db")
cur = con.cursor()
cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='stude... | [] | [
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 sqlite3\n\ndef create_database():\n \"\"\"\n Creates the 'school.db' SQLite database and the required tables.\n \"\"\"\n con = sqlite3.connect(\"scho... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00027081",
"row_id": 27081,
"seed_ids": "[103]"
} | 0.609849 | Docs: Python310_27081 | I | [
"create_database",
"insert_data",
"custom_age_collation",
"get_student_details",
"initials"
] | 5 | [
[
"get_student_details",
"custom_age_collation"
]
] | 1 | [] | false | [
"CourseCredits"
] | true | pytest | true | [] | true | bbac27aef152be7c867b66d8b5104338e6092d8f | 412ac557cf372e868859ed6bc42b734f37c112c1 | |||
v1.0 | instruct | Docs | Docs: Python310_27124_I | ### Advanced Coding Question
#### Objective:
You are required to demonstrate your understanding of the `multiprocessing.shared_memory` module by implementing a function that uses shared memory to perform efficient inter-process communication in a multiprocessing context.
#### Problem Statement:
Create a function `com... | from typing import List
import random
import multiprocessing
from multiprocessing import shared_memory
import numpy as np
def is_prime(n: int) -> bool:
"""Check if a number is prime."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
... | import pytest
from solution import compute_large_prime_sums
def test_compute_large_prime_sums():
n = 100
k = 5
results = compute_large_prime_sums(n, k)
assert isinstance(results, list)
assert all(isinstance(i, int) for i in results)
assert len(results) == multiprocessing.cpu_count()
def test_e... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Compute the sum of the largest k primes in the list.",
"function_declaration": "def largest_k_primes_sum(arr, k):",
"funct... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport random\nimport multiprocessing\nfrom multiprocessing.shared_memory import ShareableList\n\ndef is_prime(num: int) -> bool:\n if num <... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00027124",
"row_id": 27124,
"seed_ids": "[406]"
} | 0.580677 | Docs: Python310_27124 | I | [
"is_prime",
"largest_k_primes_sum",
"worker",
"compute_large_prime_sums"
] | 4 | [
[
"largest_k_primes_sum",
"is_prime"
],
[
"worker",
"largest_k_primes_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | f59369bb868945cb155b36ce2e7a3c87c0d0be5f | 810e7a0556db1280856dbaa0c3cd64ece892f83b | |||
v1.0 | instruct | Docs | Docs: Python310_27125_I | ### Python Coding Assessment
#### Objective
Demonstrate your understanding of the asyncio library by implementing an asynchronous TCP server and client system. This system should be capable of managing multiple client connections concurrently and processing client requests with a timeout mechanism.
#### Problem State... | import asyncio
import random
# Server Code
async def handle_client(reader, writer):
client_id = id(writer)
print(f'Client {client_id} connected.')
try:
while True:
data = await asyncio.wait_for(reader.read(100), timeout=10.0)
if not data:
break
me... | # Since we are dealing with asyncio and network programming, we need a more complex setup for testing.
# We will run the server and client in the same test using asyncio. We'll use pytest-asyncio for simplifying
# running the asyncio code with pytest.
import asyncio
import pytest
from solution import run_server, clien... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\n\n# Server Code\nasync def handle_client(reader, writer):\n client_id = f\"client_{id(writer)}\"\n print(f'{client_id} connected.')... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00027125",
"row_id": 27125,
"seed_ids": "[360]"
} | 0.67182 | Docs: Python310_27125 | I | [
"handle_client",
"run_server",
"client",
"main"
] | 4 | [
[
"run_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b8b0d0e8f31cbde69eae36c2978444319c001928 | a867f8e48a68b0eef3d85aec01dc7b5a3212a5de | |||
v1.0 | instruct | Docs | Docs: Python310_27270_I | You are tasked with designing a Python function to manage and process messages in different mailbox formats using the `mailbox` module. The function will move messages based on specific criteria from an mbox mailbox to a Maildir mailbox. You should implement functionality that ensures the integrity of mailbox operation... | import mailbox
import shutil
import os
def sort_and_move_messages(mbox_path: str, maildir_path: str, criteria: dict) -> None:
"""
Moves messages from mbox to Maildir based on given criteria.
Parameters:
mbox_path (str): The mbox file path.
maildir_path (str): The Maildir directory path.
cr... | import pytest
import os
import mailbox
from solution import sort_and_move_messages
@pytest.fixture
def setup_mailboxes(tmp_path):
mbox_path = tmp_path / "test.mbox"
maildir_path = tmp_path / "test_maildir"
# Create test mbox
mbox = mailbox.mbox(mbox_path)
mbox.lock()
try:
mbox.add(... | [
{
"docstring": "Moves messages from mbox to Maildir based on given criteria.\n\nParameters:\nmbox_path (str): The mbox file path.\nmaildir_path (str): The Maildir directory path.\ncriteria (dict): Criteria to match messages.",
"function_declaration": "def sort_and_move_messages(mbox_path, maildir_path, crit... | [
0,
0,
0,
1,
0,
0,
1,
1,
0
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import mailbox\n\ndef sort_and_move_messages(mbox_path: str, maildir_path: str, criteria: dict) -> None:\n \"\"\"\n Sort and move messages from an mbox format mai... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00027270",
"row_id": 27270,
"seed_ids": "[361]"
} | 0.470403 | Docs: Python310_27270 | I | [
"sort_and_move_messages",
"message_matches_criteria"
] | 2 | [
[
"sort_and_move_messages",
"message_matches_criteria"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1d5860d366535d01fdb2eb3dc51d8d0bb15ca392 | b8e4d52e803cd79f0322361442f8bbfa57e5d06a | |||
v1.0 | instruct | Docs | Docs: Python310_27313_I | **TarFile Handling and Safe Extraction**
You are required to design a Python function to handle the following tasks using the `tarfile` module:
1. Create a function named `create_tar_archive` that:
- Takes a list of filenames and an archive name as input.
- Creates a tar archive file containing the specified file... | import tarfile
import os
def create_tar_archive(file_list, archive_name):
"""
Create a tar archive containing the files in the file_list using gzip compression.
"""
with tarfile.open(archive_name, "w:gz") as tar:
for filename in file_list:
tar.add(filename, arcname=os.path.basename(... | import os
import pytest
from solution import create_tar_archive, list_tar_archive_contents, safe_extract_tar_archive
def test_create_tar_archive(tmpdir):
# Setup
file1 = tmpdir.join("file1.txt")
file2 = tmpdir.join("file2.txt")
file1.write("Hello, World!")
file2.write("Hello, Python!")
archive_... | [
{
"docstring": "Create a tar archive containing the files in the file_list using gzip compression.",
"function_declaration": "def create_tar_archive(file_list, archive_name):",
"function_name": "create_tar_archive",
"parameter_list": "(file_list, archive_name)"
},
{
"docstring": "List the co... | [
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 os\nimport tarfile\n\ndef create_tar_archive(filenames, archive_name):\n \"\"\"\n Creates a tar archive file containing the specified files with gzip compr... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00027313",
"row_id": 27313,
"seed_ids": "[163]"
} | 0.678246 | Docs: Python310_27313 | I | [
"create_tar_archive",
"list_tar_archive_contents",
"is_within_directory",
"safe_extract_tar_archive"
] | 4 | [
[
"safe_extract_tar_archive",
"is_within_directory"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ce938b11b787ef7cc336f780b4995030a6c302f8 | 8187e89d977cb7bd50c233f73f7aa84098383046 | |||
v1.0 | instruct | Docs | Docs: Python310_27327_I | **Question: File Tree Processing Using `pathlib`**
You have been given the task of creating a Python script that processes files and directories in a specified directory tree. The script should perform the following tasks:
1. List all the directories at the top level of the given directory.
2. Recursively list all th... | from pathlib import Path
def process_directory_tree(base_directory: str):
base_path = Path(base_directory)
# List all directories at the top level
top_level_directories = [str(p) for p in base_path.iterdir() if p.is_dir()]
# Print top-level directories
print("Top level directories:")
... | import pytest
import os
from pathlib import Path
from solution import process_directory_tree, count_lines_of_code
def setup_module(module):
# Create a test directory structure
os.makedirs('test_dir/dir1', exist_ok=True)
os.makedirs('test_dir/dir2', exist_ok=True)
with open('test_dir/dir1/file1.py', 'w'... | [
{
"docstring": null,
"function_declaration": "def process_directory_tree(base_directory):",
"function_name": "process_directory_tree",
"parameter_list": "(base_directory)"
},
{
"docstring": null,
"function_declaration": "def count_lines_of_code(file_path):",
"function_name": "count_l... | [
0,
0,
1,
0,
0,
0,
1,
0,
1
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from pathlib import Path\n\ndef process_directory_tree(base_directory: str):\n base_path = Path(base_directory)\n\n # List all the directories at the top level\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00027327",
"row_id": 27327,
"seed_ids": "[132]"
} | 0.621021 | Docs: Python310_27327 | I | [
"process_directory_tree",
"count_lines_of_code"
] | 2 | [
[
"process_directory_tree",
"count_lines_of_code"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d738675cef1cfb72acc0c86b0f1fe6f50124e065 | 8a35a75cc76652080a0824da13fd6aec699d1831 | |||
v1.0 | instruct | Docs | Docs: Python310_27328_I | **Coding Assessment Question: Advanced Python Runtime Services**
### Objective:
Design and implement a Python function that utilizes data classes, context managers, and inspection tools to manage, analyze, and manipulate objects safely and effectively.
### Problem Statement:
Create a function named `manage_data_obje... | from dataclasses import dataclass, field
from contextlib import contextmanager
import inspect
@dataclass(frozen=True)
class DataObject:
name: str
value: int
metadata: dict = field(default_factory=dict)
@contextmanager
def DataObjectManager(data_object: DataObject):
try:
# Ensure the metadata i... | from solution import manage_data_objects
def test_manage_data_objects_basic():
result = manage_data_objects("Sample", 42, {"key": "value"})
assert result == ("DataObject(name='Sample', value=42, metadata={'key': 'value'})", {"key": "value"})
def test_manage_data_objects_empty_metadata():
result = manage_d... | [] | [
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 dataclasses import dataclass, field\nfrom contextlib import contextmanager\nimport inspect\n\n@dataclass(frozen=True)\nclass DataObject:\n name: str\n value:... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00027328",
"row_id": 27328,
"seed_ids": "[146]"
} | 0.46251 | Docs: Python310_27328 | I | [
"DataObjectManager",
"manage_data_objects"
] | 2 | [
[
"manage_data_objects",
"DataObjectManager"
]
] | 1 | [] | false | [
"DataObject"
] | true | pytest | true | [] | true | 31dbbf3aba56aa6e2aa9e6d696d0af0edd896b58 | e5f7242e8ee6f12a5247437c2e19c61a6ad5856c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.