version stringclasses 1
value | style stringclasses 2
values | subset stringclasses 12
values | question_id stringlengths 9 23 | question stringlengths 27 8.13k | solution stringlengths 99 5.97k | test stringlengths 105 4.45k | test_info listlengths 0 13 | gpt_pass_sequence listlengths 1 10 | gpt_pass_trial_num int64 1 10 | gpt_difficulty stringclasses 3
values | gpt_pass_percentage float64 0.1 1 | trials dict | chosen_trial stringclasses 10
values | metadata dict | benchmark_similarity float64 0.16 0.93 | benchmark_instruction stringclasses 1
value | benchmark_task_id stringclasses 1
value | filter_reason stringclasses 1
value | base_id stringlengths 7 21 | variant stringclasses 2
values | top_function_names listlengths 2 13 | n_top_functions int64 2 13 | helper_call_edges listlengths 1 16 | n_helper_call_edges int64 1 16 | harness_functions listlengths 0 3 | structural_wrapper bool 1
class | class_names listlengths 0 5 | has_class bool 2
classes | test_kind stringclasses 1
value | test_has_solution_import bool 2
classes | third_party_imports listlengths 0 5 | stdlib_only bool 2
classes | question_norm_sha1 stringlengths 40 40 | solution_ast_sha1 stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v1.0 | complete | Docs | Docs: Python310_25394_C | import signal
from typing import Callable, Any
class TimeoutError(Exception):
"""Custom Timeout Exception."""
pass
def handler_sigint(signum, frame):
""" Custom handler for SIGINT (Ctrl+C) signal """
pass
def handler_sigalrm(signum, frame):
""" Custom handler for SIGALRM (timer alarm) signal """
... | 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": "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.\n\n### Requirements\n\n1. **Operation Timeout**: Impl... | 0.554748 | Docs: Python310_25394 | C | [
"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 | b1cdf6d8ec8757e56fb1a932f789fc9198293edd | 08011cb81764a830093a749275878cf8488d02d5 | |||
v1.0 | complete | Docs | Docs: Scikit_25429_C | import numpy as np
from sklearn.cross_decomposition import PLSRegression
def generate_data(seed=0):
"""Generate synthetic dataset for X and Y
containing 100 samples with 20 features and 10 targets respectively.
"""
pass
def pls_fit_transform(X, Y, n_components=5):
"""Fit PLS Regression model with ... | 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": "### Question\n\nIn 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.\n\n#### Task\n\n1. **Generate a Synthetic Dataset:**\n - Create two random matrices, `X... | 0.682679 | Docs: Scikit_25429 | C | [
"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 | d0ca58de46e95532f697e02628074ac674affaf2 | a60b4e6fd7854e03ed9c2c66a63da62695ceea87 | |||
v1.0 | complete | Docs | Docs: Seaborn_25502_C | import seaborn.objects as so
import seaborn as sns
import pandas as pd
def visualize_healthexp():
"""
Load and preprocess the health expenditure dataset, then generate and display the following visualizations using Seaborn's objects interface:
1. Faceted Area Plots by Country: An area plot showing health ... | 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": "### Question\n\nYou are provided with a dataset `healthexp` containing health expenditure data from various countries over the years. Your task is to write a function that:\n1. Loads and preprocesses the dataset.\n2. Generates a set of visualizations using Seaborn's objects interface (`so`)... | 0.703735 | Docs: Seaborn_25502 | C | [
"preprocess_data",
"visualize_healthexp"
] | 2 | [
[
"visualize_healthexp",
"preprocess_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas",
"seaborn"
] | false | e8f26320d175e552578cb5ad85c7441d1f8711ff | 2d20d05fa908af699caefeff751480f05e160635 | |||
v1.0 | complete | Docs | Docs: Python310_25475_C | # my_script.py
def start():
"""The entry point which calls other functions"""
print("Start function called")
function_a()
function_b()
def function_a():
"""A function that performs some computations."""
print("Function A called")
dummy_a()
def function_b():
"""Another function tha... | # 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": "#### Monitoring Python Function Executions with SystemTap\n\nYou 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 de... | 0.525786 | Docs: Python310_25475 | C | [
"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 | a4a00063ae0a2c2461c0c4536f1741e8513bd21b | a2204d351e0b33dee0cfed3a182dce4bec888805 | |||
v1.0 | complete | Docs | Docs: Pytorch_25365_C | import torch
import torch.nn as nn
import torch.optim as optim
def check_mps_availability():
""" Check whether MPS backend is available.
Return the MPS device if available, otherwise raise a RuntimeError.
"""
if not torch.backends.mps.is_available():
if not torch.backends.mps.is_built():
... | 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": "### Question: Implement and Train a Simple Neural Network on the MPS Device\n\n**Problem Description:**\n\nYou 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... | 0.583533 | Docs: Pytorch_25365 | C | [
"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 | 4d5d9af183e273119baf3afd3a4d4591150adb50 | 01ee38566e70c54d9dabd47ab9768eb04c5614b2 | |||
v1.0 | complete | Docs | Docs: Pytorch_25150_C | import torch
def my_custom_compress_hook(state, bucket):
""" Custom hook that compresses gradients by dividing by 2.
Args:
state: State of the process.
bucket: Gradients in the bucket.
Returns:
Compressed gradients.
"""
tensors = [tensor / 2 for tensor in bucket.buffer()]
... | 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": "### Question: Implementing and Using Custom DDP Communication Hook in PyTorch\n\n#### Objective:\nDemonstrate your understanding of PyTorch’s `DistributedDataParallel` (DDP) and communication hooks by implementing a custom gradient compression hook and using it in a distributed training set... | 0.520053 | Docs: Pytorch_25150 | C | [
"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 | a7313d726500057efae40eef8ba8260f00bce9d3 | 064f27dcb762fc67db64d8fd03c7fcc042630a8f | |||
v1.0 | complete | Docs | Docs: Python310_25715_C | from typing import List
import concurrent.futures
def compute_squares(arr: List[int], num_workers: int) -> List[int]:
"""
Given a list of integers `arr` and a number of workers `num_workers`,
compute the squares of the integers using parallel processing.
>>> compute_squares([1, 2, 3, 4, 5], 3)
... | 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": "### Parallel Computation with `concurrent.futures`\n\nYou 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.\n\n#### Task Descript... | 0.639957 | Docs: Python310_25715 | C | [
"square",
"compute_squares"
] | 2 | [
[
"compute_squares",
"square"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5ad9de8aebbd7245736dd8750decf0ec4df35c0e | b57b8ae08a31fb91171f8bae2ce8b9225e397c03 | |||
v1.0 | complete | Docs | Docs: Python310_24652_C | 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 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": "#### Objective\nImplement serialization and deserialization of a custom configuration using the `marshal` module and ensure proper handling of unsupported types.\n\n#### Question\nYou are given a task to serialize and deserialize a Python dictionary using the `marshal` module. The dictionar... | 0.550133 | Docs: Python310_24652 | C | [
"handle_unsupported_types",
"serialize_configuration",
"deserialize_configuration"
] | 3 | [
[
"serialize_configuration",
"handle_unsupported_types"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 93abb2732f12ca5bbb3dd5d10674f276e780faca | 71abab3983bcbfd3260a9a1ca15068eb69830751 | |||
v1.0 | complete | Docs | Docs: Python310_25631_C | from typing import List
import concurrent.futures
import math
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.
>>> increment_numbers([1, 2, 3], 5, 2)
[6, 7, 8]
"""
pa... | 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": "#### Objective:\nImplement a function using `concurrent.futures` to update and process a list of numbers in parallel, demonstrating your understanding of both `ThreadPoolExecutor` and `ProcessPoolExecutor`.\n\n#### Problem Description:\nYou are provided with a list of numbers, `numbers`, an... | 0.621952 | Docs: Python310_25631 | C | [
"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 | cefe13fc9ae74d840037ef29774611376f336f5b | f2391bb9881feb4ac56e4f47cd5a5e118b684609 | |||
v1.0 | complete | Docs | Docs: Scikit_25493_C | 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 incremental_text_classification(file_path, mini_batch_size):
"""
Perform incremental text classification on data streamed from... | 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": "#### Objective:\nThe 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.\n\n#### Ta... | 0.544257 | Docs: Scikit_25493 | C | [
"parse_line",
"incremental_text_classification"
] | 2 | [
[
"incremental_text_classification",
"parse_line"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 8fde7868dca15098135f49bfb89f63a40f0645dc | c206044913c3c953fcc9b7fb884bcca070c16842 | |||
v1.0 | complete | Docs | Docs: Python310_25610_C | def calculate_total(numbers):
"""
Takes a list of numbers and returns their sum.
"""
def safe_calculate(numbers):
"""
Safely calculates the total of a list of numbers by handling exceptions.
"""
# Test cases
from solution import calculate_total, safe_calculate
def test_calculate_total_all_num... | 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": "### Question: Handling Nested Functions and Exception Propagation\n\nYou're required to implement a suite of nested functions that demonstrate the understanding of name resolution, binding rules, and exception handling in Python.\n\n#### Specifications:\n\n1. Implement a function `calculate... | 0.628742 | Docs: Python310_25610 | C | [
"calculate_total",
"safe_calculate"
] | 2 | [
[
"safe_calculate",
"calculate_total"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 87b5dc640511844f4f90cf2812ffce3152f2eebd | a0b67f42758adf369c7d701117c1582b89cb07eb | |||
v1.0 | complete | Docs | Docs: Python310_25490_C | import concurrent.futures
import urllib.request
from typing import List, Dict, Union
def check_urls_status(urls: List[str], timeout: float, max_workers: int) -> Dict[str, Union[int, str]]:
""" Check the status of a list of URLs concurrently.
Args:
urls (List[str]): A list of URL strings to check.
... | 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": "URL Status Checker with Timeout\n\nYou 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... | 0.672949 | Docs: Python310_25490 | C | [
"check_url",
"check_urls_status"
] | 2 | [
[
"check_urls_status",
"check_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ef7114bd92f9e87c397f33154305170ea3d994ef | 47125b1e8c825560030ba144ce22a3526699a419 | |||
v1.0 | complete | Docs | Docs: Python310_25608_C | 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):
""" Custom exception handler to log uncaught exceptions to a file.
Args:
- exc_type: The type of the exception.
- exc_value: The valu... | 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": "### Task\n\nYou 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.\n\n### ... | 0.57207 | Docs: Python310_25608 | C | [
"custom_excepthook",
"profile_func",
"function_a",
"function_b"
] | 4 | [
[
"function_a",
"function_b"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a276481b9663623f6f07b5fa7cac158d5a9183c0 | fa53b907bf7a07017312b21974d44e73241c71c2 | |||
v1.0 | complete | Docs | Docs: Python310_25232_C | import turtle
def mandelbrot(c, max_iter):
"""
Determine the iteration count for a point in the Mandelbrot Set.
"""
pass
def draw_mandelbrot(width: int, height: int, x_center: float, y_center: float, zoom: float, max_iter: int) -> None:
"""
Visualize the Mandelbrot Set using turtle graphics.
... | 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": "### Advanced Turtle Graphics: Mandelbrot Set Visualization\n\n#### Objective:\nCreate 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... | 0.447579 | Docs: Python310_25232 | C | [
"mandelbrot",
"draw_mandelbrot"
] | 2 | [
[
"draw_mandelbrot",
"mandelbrot"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 05257bd4e968379a87bec8f49e50da6fa8eb53dc | 6247221ca8562609f1b3f565dc1b70b9cd9fffe3 | |||
v1.0 | complete | Docs | Docs: Python310_25476_C | from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from collections import Counter
from typing import List
def read_file(file_path: str) -> str:
"""Reads the content of a file and returns its text"""
pass
def count_words(text: str) -> Counter:
"""Counts the occurrences of each word in ... | 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": "### Asynchronous File Processing with `concurrent.futures`\n\n#### Objective:\nWrite 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 ... | 0.5861 | Docs: Python310_25476 | C | [
"read_file",
"count_words",
"process_files"
] | 3 | [
[
"process_files",
"count_words"
],
[
"process_files",
"read_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ac01bc9b10c856333dd7e4316db474ffd6beeac1 | a857ed1769e7aa3babac98723d918c56cf179c36 | |||
v1.0 | complete | Docs | Docs: Python310_25448_C | from contextlib import ExitStack
import logging
from typing import List, Callable, Tuple, Type
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.
"""
pass
def release_resource(resou... | 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": "**Context Management with `contextlib`**\n\n**Objective:** \nThe 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 ... | 0.487225 | Docs: Python310_25448 | C | [
"acquire_resource",
"release_resource",
"condition_function",
"manage_resources"
] | 4 | [
[
"manage_resources",
"acquire_resource"
],
[
"manage_resources",
"release_resource"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e1618e3251aa1afdbaa22b3f819dad594d05d099 | fde5020d5b9a2c51f3fde20a2e707604ed2749f7 | |||
v1.0 | complete | Docs | Docs: Python310_25295_C | import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import List, Tuple, Union, Dict
def fetch_urls_concurrently(urls: List[str], max_workers: int) -> List[Tuple[str, Union[Dict, None]]]:
"""Fetch the content of each URL concurrently and return a list of tuples containing the... | 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": "#### Background:\nYou 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 re... | 0.565716 | Docs: Python310_25295 | C | [
"fetch_url",
"fetch_urls_concurrently"
] | 2 | [
[
"fetch_urls_concurrently",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 758f8e318e5b281e01a2052d7d4251996dc65101 | f56c3c3a7426abc06977e3902822895a69ceae27 | |||
v1.0 | complete | Docs | Docs: Python310_25808_C | from multiprocessing import Process, Queue, current_process
def compute(n):
""" Compute the square of a number.
>>> compute(2)
4
>>> compute(3)
9
"""
pass
def worker(task_queue, result_queue):
""" Worker function to process tasks from the task queue and store results in the result... | 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": "## Coding Assessment Question\n\n### Objective:\nDemonstrate 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... | 0.67793 | Docs: Python310_25808 | C | [
"compute",
"worker",
"main"
] | 3 | [
[
"worker",
"compute"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | af92f6f86766319cef8c6a97ae32c9a55912cc08 | e73cfb5e5b01203d680d912de7cab0bae4505b63 | |||
v1.0 | complete | Docs | Docs: Python310_26045_C | 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:
""" Log a message with a context-specific request ID.
>>> log_message("Test message")
'[Request ID: <r... | 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": "**Context Management with `contextvars` in Asynchronous Programming**\n\n### Problem Statement\n\nImplement 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... | 0.493025 | Docs: Python310_26045 | C | [
"log_message",
"async_log_messages"
] | 2 | [
[
"async_log_messages",
"log_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d45cdc0578ccea9712acbc07fb54477f98c0e0ed | dc7e26f2d5af567a52894bea775325b7d21e311b | |||
v1.0 | complete | Docs | Docs: Python310_25281_C | from trace import Trace
def quicksort(nums):
"""
Implementation of the quicksort algorithm.
>>> quicksort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
>>> quicksort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
>>> quicksort([3, 1, 4, 1, 5]) == [1, 1, 3, 4, 5]
>>> quicksort([3, 3, 3, 3, 3]) == [3, 3, 3, 3, 3]
... | 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": "### Objective\nWrite 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.\n\n### R... | 0.497889 | Docs: Python310_25281 | C | [
"quicksort",
"run_trace"
] | 2 | [
[
"run_trace",
"quicksort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8a78496c95e8dd083449b6428a17da9deb7c6524 | 0b376308515ea4f6c052875bee211274bea6c102 | |||
v1.0 | complete | Docs | Docs: Python310_25840_C | import multiprocessing
from typing import List
def generate_primes(start: int, end: int) -> List[int]:
"""
Returns a list of prime numbers between start and end (inclusive).
>>> generate_primes(10, 20)
[11, 13, 17, 19]
>>> generate_primes(1, 10)
[2, 3, 5, 7]
>>> generate_primes(0, 2)
[2... | 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": "**Multiprocessing in Python: Task Execution and Synchronization**\n\n**Objective:** \nTo implement a multiprocessing solution that distributes tasks across multiple processes and ensures correct synchronization when accessing a shared resource.\n\n**Background:**\nYou have been tasked to pa... | 0.568095 | Docs: Python310_25840 | C | [
"generate_primes",
"worker",
"main"
] | 3 | [
[
"worker",
"generate_primes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8e0c8c323c173809e1c3e002e5da96f5443585ff | bf3d5f9dac745d8e07604891c1fdeb9353269c50 | |||
v1.0 | complete | Docs | Docs: Python310_25941_C | 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.
"""
pass
async def process_files(file_paths: List[str]) -> List[int]:
"""
Process multiple files concurrently and return the number ... | 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": "### Asynchronous File Processing\n\n**Objective:**\n\nImplement 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.\n\n**Problem Statement:**\n... | 0.602601 | Docs: Python310_25941 | C | [
"read_file",
"process_files"
] | 2 | [
[
"process_files",
"read_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 96c745fdd67aee08dbf02c67f6cd6b4a6ed25df7 | 55a20ebeabdda4810827cc22e3e3acb91940cca0 | |||
v1.0 | complete | Docs | Docs: Pytorch_25584_C | import torch
def custom_flex_attention(input_tensor: torch.Tensor, mask_type: str) -> torch.Tensor:
"""
Apply a flexible attention mechanism with a custom block mask on the input tensor.
Parameters:
input_tensor (torch.Tensor): A 2D tensor of shape (N, D).
mask_type (str): A string representi... | 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": "#### Objective:\nDemonstrate your understanding of PyTorch's block mask utilities by implementing a customized flexible attention mechanism.\n\n#### Problem Statement:\nImplement a function `custom_flex_attention` that takes an input tensor and applies a flexible attention mechanism with a ... | 0.400506 | Docs: Pytorch_25584 | C | [
"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 | 03ff2e713a6464b92fb0b43ea23f027717a31b1b | a767fecb5a7365e0b7ea28c1898f2b4f54f09d8f | |||
v1.0 | complete | Docs | Docs: Pytorch_25555_C | import torch
from torch.nn.attention.flex_attention import BlockMask, create_block_mask, create_nested_block_mask, noop_mask
def block_attention(sequence: torch.Tensor, mask_type: str, block_size: int) -> torch.Tensor:
""" Compute the attention weighted sum of a sequence with the help of block masks.
>>> seq_l... | 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": "## Coding Assessment Question\n\n### Objective:\nImplement an attention mechanism using PyTorch with block masks, focusing on the functions and class in the `torch.nn.attention.flex_attention` module.\n\n### Problem Statement:\nYou are provided with a sequence of data and need to apply an a... | 0.510237 | Docs: Pytorch_25555 | C | [
"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 | 3a8e624f6104c8674be74a41bee48d0c5f45ee04 | 11c209268eb6901985d25e833cc1a5e8ceafc0fe | |||
v1.0 | complete | Docs | Docs: Python310_26014_C | 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 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": "### Event Scheduler Implementation\n\nYou 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. \n\n#### Requirements\n\n1. **Functions... | 0.545698 | Docs: Python310_26014 | C | [
"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 | 2af93f0ef5f7e7632d1666aeaf681122adf1c488 | caa794ea05485ea2d0f8e5bd7e0541b9efa22c76 | |||
v1.0 | complete | Docs | Docs: Python310_25237_C | import hmac
import hashlib
from typing import str
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 secr... | 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": "### Question: Implement and Use Custom HMAC-Based Authentication\n\n**Objective:**\nYour 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 provide... | 0.876954 | Docs: Python310_25237 | C | [
"generate_hmac",
"verify_hmac"
] | 2 | [
[
"verify_hmac",
"generate_hmac"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7de80f3753519b46dbd98637c93da935434a06d7 | 01793b8080ade452625d1df45ea36a8adde007db | |||
v1.0 | complete | Docs | Docs: Python310_25701_C | import email.utils
def format_email_recipients(headers: dict) -> str:
"""
Extracts recipients from 'To', 'Cc', 'Resent-To', and 'Resent-Cc' fields, validates,
and formats them into a single string suitable for display.
>>> headers = {
>>> 'To': ['John Doe <john.doe@example.com>', 'InvalidEmail ... | 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": "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:\n1. Extracts all recipients from 'To', 'Cc', and any 'Resent-To' and 'Resent-Cc' fields provided.\n2. Formats the... | 0.604701 | Docs: Python310_25701 | C | [
"is_valid_email",
"format_email_recipients"
] | 2 | [
[
"format_email_recipients",
"is_valid_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 34b1eaa52e95c05045136dff99c5f131eb3b0cc4 | 968ae3b393ae0eb1f748b208946180310f684d48 | |||
v1.0 | complete | Docs | Docs: Python310_25822_C | 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... | 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": "### Custom Exception Handling and Chaining in Python\n\n#### Objective:\nDesign 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 conte... | 0.549678 | Docs: Python310_25822 | C | [
"perform_operation",
"execute"
] | 2 | [
[
"execute",
"perform_operation"
]
] | 1 | [] | false | [
"InvalidOperationError",
"OperationTimeoutError"
] | true | pytest | true | [] | true | 1e3b46e429156aae5b66ca58f2477fdc12082d43 | e0509ba56a99bb4684486b30764d7dd71cc99278 | |||
v1.0 | complete | Docs | Docs: Python310_25383_C | import shutil
import os
def get_directory_size(directory: str) -> int:
"""Calculate the total size of a directory."""
pass
def backup_and_cleanup(source_dir: str, backup_dir: str, archive_name: str) -> str:
"""Backup a specified directory by creating a compressed archive of it, verify the backup,
and... | 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": "**Question**: You are tasked with designing a file backup script using the `shutil` module. The script should:\n- Backup a specified directory by creating a compressed archive of it.\n- Verify that the backup was successful by checking the size of the original directory and the archive.\n- ... | 0.717441 | Docs: Python310_25383 | C | [
"get_directory_size",
"backup_and_cleanup"
] | 2 | [
[
"backup_and_cleanup",
"get_directory_size"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b8ed87a41e79a18bd962768e0ba0ec2c160a37cf | 97eea75dc0be6f955086a9386a827ac37c5b55b1 | |||
v1.0 | complete | Docs | Docs: Python310_25571_C | import os
import stat
def file_type(mode):
# Helper function to determine file type
pass
def human_readable_permissions(mode):
# Helper function to convert file mode to human-readable permissions
pass
def generate_directory_summary(directory_path: str) -> dict:
""" Traverse a given directory and ... | 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": "#### Objective\n\nWrite 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.\n\n#### Input\n- A string `directory_path` represen... | 0.588668 | Docs: Python310_25571 | C | [
"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 | 0bbcf943eedfbefa85b988c35205c779948955a1 | 002c45c9d3eb3f253460f3504272ed6ad680687f | |||
v1.0 | complete | Docs | Docs: Python310_26023_C | import time
import inspect
def trace_function(func):
""" Decorator that logs the call details of the wrapped function, including function name, filename, and line number, when it is invoked and when it returns.
"""
@trace_function
def sample_function_1():
print("Executing function 1")
@trace_fun... | 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": "### Function Call Tracing with SystemTap and DTrace in CPython\n\n**Objective:**\nImplement 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 pro... | 0.66769 | Docs: Python310_26023 | C | [
"trace_function",
"sample_function_1",
"sample_function_2"
] | 3 | [
[
"sample_function_2",
"sample_function_1"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2effedc8bf79b7624289f4b512d761d1b0f97c58 | c197b6b09da68182e103799f33b6c82eec9ed379 | |||
v1.0 | complete | Docs | Docs: Python310_25421_C | import re
import difflib
from typing import List, Dict, Any
def process_documents(documents: List[str]) -> Dict[str, Any]:
"""Process a list of text documents and extract emails and phone numbers, and compute similarity scores.
Args:
documents (List[str]): A list of text documents.
Returns:
Dict[... | 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": "### Python Coding Assessment Question\n\n#### Problem Description\n\nYou 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 addresse... | 0.624159 | Docs: Python310_25421 | C | [
"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 | 4e23b0cbe3447384f31b8375512ce0c87a2a5c8f | 4741d77aa479b9f7153e86bf5bd0a98c32f73bb2 | |||
v1.0 | complete | Docs | Docs: Scikit_26264_C | 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
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": "**Coding Assessment Question**\n\n### Question\nYou 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`:\n\n1. Preprocess the given data to handle any missing values.\n2. Fit a `Linea... | 0.788741 | Docs: Scikit_26264 | C | [
"preprocess_data",
"evaluate_models"
] | 2 | [
[
"evaluate_models",
"preprocess_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | 657f6be85c1d20008d6e1718912bc865876f19ce | d8125a174a0ac28d7c9d44658a054af5414cf073 | |||
v1.0 | complete | Docs | Docs: Pytorch_25938_C | 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_... | 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": "### Question: Implement a Distributed Parameter Server with RPC in PyTorch\n\nYou 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 computat... | 0.507458 | Docs: Pytorch_25938 | C | [
"get_model",
"update_parameters",
"parameter_server",
"worker",
"main"
] | 5 | [
[
"worker",
"update_parameters"
]
] | 1 | [] | false | [] | false | pytest | false | [
"torch"
] | false | f9462094421b2873149593e575c6dc15beb7df9a | 1d926d4cdc845dde96dee5944e0e2851ea428741 | |||
v1.0 | complete | Docs | Docs: Python310_26183_C | import os
import tkinter.tix as tix
from tkinter import messagebox
from tkinter import filedialog
import time
def display_file_details(file_path):
""" Display details about the selected file.
"""
# Implementation here
def on_directory_selection(event):
""" Handle directory selection event.
"""
... | 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": "## Coding Assessment Question\n\n### Objective:\nDesign 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.\n\n### Description:\nYou are tasked with creating a basic File Manager applic... | 0.407339 | Docs: Python310_26183 | C | [
"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 | 22efce59dc2da2308a8c5c119d5fc977f3d33831 | cb52eaf3bcdb34f483b23b3d26e51cc8e5d97e5e | |||
v1.0 | complete | Docs | Docs: Scikit_26268_C | 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: str):
""" Load and preprocess the house dataset.
Args:
file_pat... | 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": "## Problem Statement\n\nYou 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:\n1. Predict the `category` (high, medium, low) of houses based on the given input feat... | 0.734099 | Docs: Scikit_26268 | C | [
"prepare_data",
"train_and_evaluate"
] | 2 | [
[
"train_and_evaluate",
"prepare_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas",
"sklearn"
] | false | e28d9135bc6c116866748b4660d07679bea7ffb3 | 835fe161b5453d2c72418acff7494f6db743b7b1 | |||
v1.0 | complete | Docs | Docs: Scikit_25048_C | 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... | 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": "**Question: Implementing and Comparing SVM Classifiers for Multiclass Classification**\n\n**Objective:**\nDemonstrate understanding of scikit-learn's SVM classifiers by implementing and comparing different SVM strategies for a multiclass classification problem.\n\n**Task:**\n1. Load a datas... | 0.726341 | Docs: Scikit_25048 | C | [
"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 | 84b8e4a476fe34682ae3a5f5f31a686d3d7753c8 | 75f9eefea132d4b07136d3adaefada6523c44720 | |||
v1.0 | complete | Docs | Docs: Pytorch_26411_C | import torch
import torch.nn as nn
def check_mps_device():
"""
Check if the MPS device is available.
"""
pass
class SimpleNet(nn.Module):
def __init__(self):
super(SimpleNet, self).__init__()
self.fc1 = nn.Linear(10, 50)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(50... | 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": "#### Objective:\nDemonstrate 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.\n\n#### Problem Statement:\n1. Ensure the MPS backend is available on the run... | 0.524043 | Docs: Pytorch_26411 | C | [
"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 | 3a77bb05e70a4c03f0936ebdd240e99b60318211 | dc09950673dc9593e01891ee1608c8be9a0b1508 | |||
v1.0 | complete | Docs | Docs: Python310_26146_C | 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.
>>> process_data(2) == 4
>>> process_data(-3) == 9
>>> proces... | 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": "**Parallel Data Processing with Threading and Multiprocessing**\n\nIn 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... | 0.565081 | Docs: Python310_26146 | C | [
"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 | ed7fd5db47a82183b3c3e4221fe782e96d1380b9 | 8d72cca1a18108d5a45e956879bbd521178c3f7b | |||
v1.0 | complete | Docs | Docs: Pytorch_26425_C | import torch
def tensor_operations(n: int) -> torch.Tensor:
""" Perform tensor operations involving normal and uniform distributions.
Args:
n (int): Size of the tensors to be generated.
Returns:
torch.Tensor: Tensor resulting from the operations.
"""
if n <= 0:
raise ValueE... | 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": "**Student Question:**\n\n### Tensor Operations Testing with PyTorch\n\nIn 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.\n\n#### Task\n\n1. Cr... | 0.648012 | Docs: Pytorch_26425 | C | [
"tensor_operations",
"validate_operations"
] | 2 | [
[
"validate_operations",
"tensor_operations"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 6e5a6069e86e55448c062414763ce2167ccc153a | 944b8a383fae52b402a5699a756a0f5d8205da94 | |||
v1.0 | complete | Docs | Docs: Python310_26277_C | import timeit
def reverse_with_slicing(lst):
"""Reverses a list using slicing.
>>> reverse_with_slicing([1, 2, 3])
[3, 2, 1]
>>> reverse_with_slicing([])
[]
>>> reverse_with_slicing([1])
[1]
>>> reverse_with_slicing([1, 2, 3, 4, 5])
[5, 4, 3, 2, 1]
"""
# Your code here
def ... | 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": "**Title:** Analyzing Function Performance with Timeit\n\n**Objective:**\nTo 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 fu... | 0.502627 | Docs: Python310_26277 | C | [
"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 | 6034125b5327b65bfae8ed0e20bcc50451d73e4f | 15305180f1843f96aac5e8df381ea402c5d15276 | |||
v1.0 | complete | Docs | Docs: Python310_26131_C | 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 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": "### Secure Document Verification Using `hashlib`\nImplement a Python program that verifies the integrity of documents by generating and comparing their secure hash values using the `hashlib` module. \n\nYour task is to implement two core functions:\n1. `generate_file_hash(filepath: str, alg... | 0.758773 | Docs: Python310_26131 | C | [
"generate_file_hash",
"verify_file_integrity"
] | 2 | [
[
"verify_file_integrity",
"generate_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cd04d345b1e4c0dca33310397f5236f00ee8f04c | 2facd9aec0f04409db100d7791c70c23152a9db3 | |||
v1.0 | complete | Docs | Docs: Python310_26115_C | import time
from functools import wraps
def trace_function(func):
"""
Decorator to trace function entry and return.
Args:
func (callable): The function to be decorated.
Returns:
callable: The wrapped function with tracing.
Example:
>>> @trace_function
... ... | 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": "**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.\n\n**Requirements**:\n1. **Fu... | 0.578617 | Docs: Python310_26115 | C | [
"trace_function",
"trace_gc_events",
"example_function",
"another_function"
] | 4 | [
[
"another_function",
"example_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b96d87bd0b6fb1aa80b759ac2bb24d9c1035a471 | 96798bf4981fa94e27a6d80d5ab6b761cad158ca | |||
v1.0 | complete | Docs | Docs: Pytorch_26552_C | 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.
"""
pass
def create_mps_tensor(size):
"""
Create a tensor of the specified size filled wit... | 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": "#### Objective\n\nYour task is to demonstrate your understanding of the PyTorch MPS backend by performing the following steps:\n\n1. Check if the MPS backend is available on your system.\n2. If available, create a tensor on the MPS device and perform some basic operations.\n3. Define a simp... | 0.522915 | Docs: Pytorch_26552 | C | [
"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 | b3db1829ccaa98948c0174aa0abcb6fd9bd3929a | f4867d53702ee28da0fc66d0a04cb570c951a06e | |||
v1.0 | complete | Docs | Docs: Python310_26735_C | import signal
import time
import threading
# Define signal handlers
def handle_sigint(signum, frame):
"""Handle SIGINT (Ctrl+C) signal.
"""
print("Received SIGINT (Ctrl+C), exiting gracefully.")
signal.alarm(0) # Disable any scheduled alarm
exit(0)
def handle_sigterm(signum, frame):
"""Handle ... | 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": "### Question:\n\nYou 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 functi... | 0.602947 | Docs: Python310_26735 | C | [
"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 | ab9d1201216de20e8799d9c013acda4a2dabd363 | 1d300aadf1fab4feb74b1cd71155d05d3612c55d | |||
v1.0 | complete | Docs | Docs: Scikit_26927_C | 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 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": "**Problem: Parallelizing Model Training with scikit-learn and joblib**\n\n**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 perform... | 0.595942 | Docs: Scikit_26927 | C | [
"train_model",
"evaluate_parallelism"
] | 2 | [
[
"evaluate_parallelism",
"train_model"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"sklearn"
] | false | 17ed3c9d6a3f7061ec6874cfb7df452d39faabca | cdca6ecc5ed6526384d4933972ac4a923ffb608e | |||
v1.0 | complete | Docs | Docs: Python310_26710_C | 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
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": "### Question: Custom Exception Handling and Manipulation\n\n#### Objective:\nWrite 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. \n\n#... | 0.44449 | Docs: Python310_26710 | C | [
"raise_custom_exception",
"handle_exception"
] | 2 | [
[
"handle_exception",
"raise_custom_exception"
]
] | 1 | [] | false | [
"CustomError"
] | true | pytest | true | [] | true | 78a8256b8c9583f17bc27ad996808a5b1204b653 | 6c4e3d7950b729dca076aae6f585a2189c13879b | |||
v1.0 | complete | Docs | Docs: Python310_26278_C | 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.... | 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": "### URL Management and Handling\n\nYou 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`.\n\n#### Functions Description:\n\n1. **`fetch_url(url: str) -> str`**\... | 0.748223 | Docs: Python310_26278 | C | [
"fetch_url",
"parse_url",
"check_robots"
] | 3 | [
[
"check_robots",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f988d2521e7f46c2b641ce286851ca474b42be29 | 7c53683c936321d130331469445190447eb98b16 | |||
v1.0 | complete | Docs | Docs: Python310_26826_C | import zipfile
from typing import List
def process_zipfile(zip_path: str, operation: str, files: List[str] = [], target_dir: str = None, compression=zipfile.ZIP_STORED, password: bytes = None) -> None:
""" Use the zipfile module to create, update, and extract ZIP archives with various compression methods.
... | 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": "**Objective**:\nImplement 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.\n\n**Task**:\nWrite a function `process_zipfile(zip_pa... | 0.774852 | Docs: Python310_26826 | C | [
"process_zipfile",
"safe_extract"
] | 2 | [
[
"process_zipfile",
"safe_extract"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2a45dadc37f5684e392331f50ab9068563e45289 | 28d110ad989b17ab17bee2130deb797bce849004 | |||
v1.0 | complete | Docs | Docs: Seaborn_26873_C | import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
def read_and_preprocess(file_path):
""" Reads the dataset from the specified file path and preprocesses it if necessary.
>>> df = read_and_preprocess('sample_data.csv')
>>> not df.empty
True
"""
# Read ... | 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": "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.\n\n### Dataset\nThe dataset is a CSV file with the fo... | 0.730452 | Docs: Seaborn_26873 | C | [
"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 | a1498dc136cca16bfd9041408c69c166168c0ed8 | 647e9b79fc064b27b5d189d8e6bb2e7e61ebb11a | |||
v1.0 | complete | Docs | Docs: Python310_26920_C | import telnetlib
def connect_to_server(host: str, port: int, timeout: int) -> telnetlib.Telnet:
""" Connect to the given Telnet server and return the active Telnet object.
"""
# Implement connection logic here
def login(tn: telnetlib.Telnet, username: str, password: str) -> None:
""" Log into the serv... | 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": "### Telnet Client Implementation and Custom Interaction\n\n#### Background\n\nYou 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 Te... | 0.526758 | Docs: Python310_26920 | C | [
"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 | 423279d6ab4ba85c1a415f6ed6c3cc84ca50ed1f | d7ce0cdffd33ced22bde7318626b4d63b1c419b2 | |||
v1.0 | complete | Docs | Docs: Python310_26613_C | 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:
"""
Convert a Python complex number to a Py_complex C structure.
>>> convert_to_c(3+4j)
Py_complex(real=3.0, imag=4.0)
"""
pa... | 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": "#### Complex Number Operations\n\nYou 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:\n\n1... | 0.502613 | Docs: Python310_26613 | C | [
"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 | 311dbb9fcca62ed3d642468352d702698552fdb0 | 1a43aa43b3105bb46e874c2f30b2b0fe6dd7b6bd | |||
v1.0 | complete | Docs | Docs: Python310_27081_C | import sqlite3
def create_database():
"""
Creates the 'school.db' SQLite database and the required tables.
>>> create_database()
"""
pass
def insert_data():
"""
Inserts predefined data into the students and courses tables.
>>> insert_data()
"""
pass
def custom_age_collation(... | 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": "### Advanced SQLite Database with Python `sqlite3` Module\n\n#### Objective\nIn 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 executi... | 0.604055 | Docs: Python310_27081 | C | [
"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 | 2e4ea7f402d39ec496b947aa77653e04ab3296b9 | 412ac557cf372e868859ed6bc42b734f37c112c1 | |||
v1.0 | complete | Docs | Docs: Python310_27327_C | from pathlib import Path
def process_directory_tree(base_directory: str):
""" Process the files and directories in a specified directory tree.
List all the directories at the top level of the given directory, recursively list all the Python files (*.py), count the number of lines of code (LOC) excluding e... | 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": "**Question: File Tree Processing Using `pathlib`**\n\nYou 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:\n\n1. List all the directories at the top level of the given dire... | 0.627878 | Docs: Python310_27327 | C | [
"process_directory_tree",
"count_lines_of_code"
] | 2 | [
[
"process_directory_tree",
"count_lines_of_code"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 80dc28fc32cb694da9ff51654eff5eeb540ec5b2 | 8a35a75cc76652080a0824da13fd6aec699d1831 | |||
v1.0 | complete | Docs | Docs: Python310_27355_C | import mailcap
import re
from typing import List, Dict
def get_mailcap_commands(mime_types: List[str], filename: str, params: List[str]) -> Dict[str, str]:
"""
Implement a Mailcap Configuration Checker that returns command lines for handling files based on their MIME types.
>>> get_mailcap_commands([... | import mailcap
import re
def validate_filename_and_params(filename, params):
disallowed_chars = re.compile(r'[^a-zA-Z0-9_\-.,]')
if disallowed_chars.search(filename):
return False
for param in params:
if disallowed_chars.search(param):
return False
return True
... | from solution import get_mailcap_commands
def test_no_disallowed_chars():
mime_types = ['text/plain', 'video/mpeg']
filename = 'video.mp4'
params = ['width=1920', 'height=1080']
result = get_mailcap_commands(mime_types, filename, params)
assert 'text/plain' in result
assert 'video/mpeg' in... | [
{
"docstring": null,
"function_declaration": "def validate_filename_and_params(filename, params):",
"function_name": "validate_filename_and_params",
"parameter_list": "(filename, params)"
},
{
"docstring": null,
"function_declaration": "def get_mailcap_commands(mime_types, filename, para... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import mailcap\nimport re\n\ndef validate_filename_and_params(filename, params):\n disallowed_chars = re.compile(r'[^a-zA-Z0-9_\\-.,]')\n if disallowed_chars.sear... | trial_gpt4o_0 | {
"original_instruction": "### Question: Implement a Mailcap Configuration Checker\n\nYou are tasked with creating a Python function that utilizes the `mailcap` module to find appropriate command lines for handling files based on their MIME types. Your function should handle various MIME types, leverage user and syst... | 0.56799 | Docs: Python310_27355 | C | [
"validate_filename_and_params",
"get_mailcap_commands"
] | 2 | [
[
"get_mailcap_commands",
"validate_filename_and_params"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fe79bb904e14cc42c17a65c4f7d39bca0d655ca3 | ab4992e220b8c69aba6ea4fad024112941166afc | |||
v1.0 | complete | Docs | Docs: Python310_26564_C | 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 prio... | 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": "## Question: Priority Task Scheduler with Dynamic Updates\n\n### Objective:\nImplement 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 whil... | 0.568524 | Docs: Python310_26564 | C | [
"add_task",
"remove_task",
"pop_task"
] | 3 | [
[
"add_task",
"remove_task"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7da9a3035d059357a70fb8fec74f1e23d991530a | 4c71cd60d2fbefaad1d9f37fa29c50b2ffd61170 | |||
v1.0 | complete | Docs | Docs: Python310_26997_C | import curses
import curses.panel
def manage_panels(stdscr, n):
"""
Implement a function manage_panels(n: int) that creates n panels,
allowing user to perform the following operations interactively:
- Move a Panel: Using the arrow keys, move the currently selected panel.
- Switch Panels: Cycle th... | 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": "#### Objective:\nYou 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.\n\n#### Task:\nImplement a function `ma... | 0.367154 | Docs: Python310_26997 | C | [
"manage_panels",
"move_panel"
] | 2 | [
[
"manage_panels",
"move_panel"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5119afdbb5bec7a6b750f9cb6f4fb44e84b710eb | 5b51fa8c0acd1feb196f27d8214c4131cd033ded | |||
v1.0 | complete | Docs | Docs: Python310_27407_C | def convert_and_add(int_val, ulong_val, double_val):
"""
Convert inputs to Python integers and add them together.
Parameters:
int_val (int): An integer.
ulong_val (int): An unsigned long integer.
double_val (float): A double value.
Returns:
int: The sum of the converted inputs ... | def PyLong_FromLong(v):
"""
Hypothetical C-to-Python interface function to convert long to Python integer.
"""
return int(v)
def PyLong_FromUnsignedLong(v):
"""
Hypothetical C-to-Python interface function to convert unsigned long to Python integer.
"""
return int(v)
def PyLong_FromDoub... | from solution import convert_and_add
def test_convert_and_add_positive_numbers():
assert convert_and_add(10, 20, 5.5) == 35
def test_convert_and_add_with_zero():
assert convert_and_add(0, 0, 0.0) == 0
assert convert_and_add(10, 0, 0.0) == 10
assert convert_and_add(0, 20, 0.0) == 20
assert convert_... | [
{
"docstring": "Hypothetical C-to-Python interface function to convert long to Python integer.",
"function_declaration": "def PyLong_FromLong(v):",
"function_name": "PyLong_FromLong",
"parameter_list": "(v)"
},
{
"docstring": "Hypothetical C-to-Python interface function to convert unsigned l... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def PyLong_FromLong(v):\n \"\"\"\n Hypothetical C interface function that converts a C long to a Python int.\n In reality, this is simply emulated by Python's ... | trial_gpt4o_7 | {
"original_instruction": "**Objective:**\n\nWrite a Python function that interfaces with C functions to handle integers. You will be provided with a hypothetical C interface (mimicked by Python functions) for testing purposes.\n\n**Task:**\n\n1. Implement a function `convert_and_add` that takes an integer, an unsign... | 0.596293 | Docs: Python310_27407 | C | [
"PyLong_FromLong",
"PyLong_FromUnsignedLong",
"PyLong_FromDouble",
"convert_and_add"
] | 4 | [
[
"convert_and_add",
"PyLong_FromDouble"
],
[
"convert_and_add",
"PyLong_FromLong"
],
[
"convert_and_add",
"PyLong_FromUnsignedLong"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | abf3e2ef4fe8fede6f7ecf9efcc1a77c408ae242 | e2ef4a005c5105d3bb3fc6bbb87af4fb94a4a45c | |||
v1.0 | complete | Docs | Docs: Python310_27124_C | from typing import List
import random
import multiprocessing
def compute_large_prime_sums(n: int, k: int) -> List[int]:
"""Create a function that concurrently calculates and returns the sums of the largest `k` prime numbers for each subset of `n` randomly generated integers.
The function must distribute t... | 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": "### Advanced Coding Question\n\n#### Objective:\nYou 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.\n\n#### Problem... | 0.583353 | Docs: Python310_27124 | C | [
"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 | fcff13e43100348c9321b711d672356b3324c1f6 | 810e7a0556db1280856dbaa0c3cd64ece892f83b | |||
v1.0 | complete | Docs | Docs: Python310_27529_C | [Completion Task in Python]
import asyncio
import random
async def fetch(url: str) -> str:
"""
Simulate an HTTP get request to fetch content of a URL.
"""
random_delay = random.randint(1, 5)
await asyncio.sleep(random_delay)
return f"Content of {url}"
async def fetch_multiple_urls(urls: list, ... | import asyncio
import random
async def fetch(url: str) -> str:
"""
Simulate an HTTP get request to fetch content of a URL.
"""
random_delay = random.randint(1, 5)
await asyncio.sleep(random_delay)
return f"Content of {url}"
async def fetch_multiple_urls(urls: list, timeout: float) -> dict:
... | import pytest
import asyncio
from solution import fetch_multiple_urls
@pytest.mark.asyncio
async def test_fetch_multiple_urls_success():
urls = ["http://example.com", "http://example.org"]
timeout = 5.0
results = await fetch_multiple_urls(urls, timeout)
assert all(content.startswith("Content of") for c... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\n\nasync def fetch(url: str) -> str:\n \"\"\"\n Simulate an HTTP get request to fetch content of a URL.\n \"\"\"\n random_dela... | trial_gpt4o_0 | {
"original_instruction": "### Asyncio Coding Assessment Question\n\n**Objective**: To assess the student's comprehension and practical application of asyncio coroutines, task creation, concurrent execution, and advanced asyncio handling such as timeouts and cancellation.\n\n### Problem Statement\n\nYou are required ... | 0.582551 | Docs: Python310_27529 | C | [
"fetch",
"fetch_multiple_urls"
] | 2 | [
[
"fetch_multiple_urls",
"fetch"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 397c2e8423df13a9b1c23c2f593cfc5a5ca6377b | de4b4722748e892ce7a2adbb8b4aa36137d8256e | |||
v1.0 | complete | Docs | Docs: Python310_26948_C | import importlib
def dynamic_import(module_name: str, package_name: str = None):
"""
Dynamically import the specified module using `importlib.import_module`.
Args:
- module_name (str): Absolute or relative name of the module to import.
- package_name (str): Name of the package to resolve relative ... | 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": "### Python Coding Assessment Question\n\n**Objective**: Demonstrate the understanding and capability to use the `importlib` package for custom module importation and reloading in Python.\n\n**Problem Statement**:\n\nYou are required to create a Python script that manages the dynamic import ... | 0.63029 | Docs: Python310_26948 | C | [
"dynamic_import",
"reload_module",
"check_and_reload"
] | 3 | [
[
"check_and_reload",
"reload_module"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | eaefaff8422e63a65e53502e7a28a9cdc9f824c1 | 796e949632f85040f22c6f333e118eb22a29078b | |||
v1.0 | complete | Docs | Docs: Python310_27552_C | import traceback
def log_exceptions(log_file: str):
"""
Decorator that logs detailed information about any exceptions
that occur in the decorated function to a specified file.
>>> import os
>>> log_file = 'error.log'
>>> if os.path.exists(log_file):
... os.remove(log_file)
>>> @lo... | import traceback
def log_error(message: str, file: str):
with open(file, 'a') as f:
f.write(message + '\n')
def log_exceptions(log_file: str):
"""
Decorator that logs detailed information about any exceptions
that occur in the decorated function to a specified file.
"""
def decorator(... | import os
import pytest
from solution import log_exceptions, log_error
# Helper to read the log content
def read_log(file):
with open(file, 'r') as f:
return f.read()
def test_zero_division_error():
log_file = 'error.log'
@log_exceptions(log_file)
def test_function():
return 1 / 0... | [
{
"docstring": null,
"function_declaration": "def log_error(message, file):",
"function_name": "log_error",
"parameter_list": "(message, file)"
},
{
"docstring": "Decorator that logs detailed information about any exceptions \nthat occur in the decorated function to a specified file.",
"... | [
0,
0,
0,
1,
1,
0,
1,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import traceback\n\ndef log_error(message: str, file: str):\n with open(file, 'a') as f:\n f.write(message + '\\n')\n\ndef log_exceptions(log_file: str):\n ... | trial_gpt4o_8 | {
"original_instruction": "You are tasked with creating a function decorator named `log_exceptions` that logs detailed information about any exceptions that occur in the decorated function. The log should include the exception type, value, and traceback. The logging should be done in a format that mimics the behavior... | 0.545171 | Docs: Python310_27552 | C | [
"log_error",
"log_exceptions"
] | 2 | [
[
"log_exceptions",
"log_error"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5107e6f32160734034ad60eb1d4177f68b029846 | 8ef7815928f399c3c29fff522c6e14913449ec36 | |||
v1.0 | complete | Docs | Docs: Python310_27449_C | from contextlib import contextmanager
from typing import List
class DatabaseConnection:
def connect(self):
"""Simulates opening a database connection."""
print("Database connection opened.")
def close(self):
"""Simulates closing a database connection."""
print("Database con... | from contextlib import contextmanager
class DatabaseConnection:
def connect(self):
print("Database connection opened.")
def close(self):
print("Database connection closed.")
def execute(self, query: str):
print(f"Executing query: {query}")
@contextmanager
def database_man... | from solution import DatabaseConnection, database_manager, run_queries
def test_database_connection_emulator(capsys):
db = DatabaseConnection()
db.connect()
db.execute("SELECT * FROM test")
db.close()
captured = capsys.readouterr()
assert captured.out == "Database connection opened.\nExecuting ... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from contextlib import contextmanager\n\nclass DatabaseConnection:\n def connect(self):\n print(\"Database connection opened.\")\n \n def close(self):\n... | trial_gpt4o_1 | {
"original_instruction": "#### Objective\nTo assess the student's ability to implement context managers for resource handling and apply advanced Python concepts in a practical scenario.\n\n#### Problem Statement\nYou are required to implement a custom context manager using the `contextlib` module that handles resour... | 0.388753 | Docs: Python310_27449 | C | [
"database_manager",
"run_queries"
] | 2 | [
[
"run_queries",
"database_manager"
]
] | 1 | [] | false | [
"DatabaseConnection"
] | true | pytest | true | [] | true | 7c9df87a79ce74c112f015e4b2014f61404f8d91 | c6f9cd6e838853000200c8011b00686f74e81a59 | |||
v1.0 | complete | Docs | Docs: Python310_27640_C | import socket
import select
def chat_server(host: str, port: int):
"""
Starts a non-blocking chat server that listens on the given host and port.
Args:
host (str): The hostname or IP address on which the server should listen.
port (int): The port number on which the server should listen.
... | import socket
import select
def chat_server(host: str, port: int):
"""
Starts a non-blocking chat server that listens on the given host and port.
Args:
host (str): The hostname or IP address on which the server should listen.
port (int): The port number on which the server should listen.
... | import socket
import threading
import time
from solution import chat_server
def start_server():
chat_server("localhost", 12345)
def test_server():
# Start the chat server in a separate thread
server_thread = threading.Thread(target=start_server)
server_thread.daemon = True
server_thread.start()
... | [
{
"docstring": "Starts a non-blocking chat server that listens on the given host and port.\n\nArgs:\n host (str): The hostname or IP address on which the server should listen.\n port (int): The port number on which the server should listen.",
"function_declaration": "def chat_server(host, port):",
... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import socket\nimport select\n\ndef chat_server(host: str, port: int):\n \"\"\"\n Starts a non-blocking chat server that listens on the given host and port.\n\n ... | trial_gpt4o_3 | {
"original_instruction": "### Coding Assessment: Chat Server Implementation with Non-Blocking Sockets\n\n#### Objective\nImplement a non-blocking chat server that can handle multiple clients simultaneously. The server should be able to broadcast messages received from any client to all connected clients.\n\n#### Req... | 0.635847 | Docs: Python310_27640 | C | [
"chat_server",
"broadcast"
] | 2 | [
[
"chat_server",
"broadcast"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7a49fa4823ad1a61adc4c560fb242d9e2f4f28da | 4af3bb0ca9853e2608c0a4f661055c0e2a0f59b3 | |||
v1.0 | complete | Docs | Docs: Python310_27125_C | import asyncio
import random
async def handle_client(reader, writer):
""" Handles a client connection, assigning a unique identifier to
the client and managing communication with the client.
"""
client_id = id(writer)
print(f'Client {client_id} connected.')
try:
while True:
... | 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": "### Python Coding Assessment\n\n#### Objective\nDemonstrate 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 timeou... | 0.647484 | Docs: Python310_27125 | C | [
"handle_client",
"run_server",
"client",
"main"
] | 4 | [
[
"run_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 64d43175e013cb01dd6f5148c1e9811a2063f603 | a867f8e48a68b0eef3d85aec01dc7b5a3212a5de | |||
v1.0 | complete | Docs | Docs: Python310_26995_C | import concurrent.futures
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 URL and the conten... | 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": "### Question\n\n#### Implementing Parallel Task Execution with `concurrent.futures`\n\nGiven 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 performan... | 0.521974 | Docs: Python310_26995 | C | [
"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 | 5614eca4cacd40410ceda55a6eb753e0f174ce50 | 1f2e0e824e8b51d941d1406bbae79efa3553fc4c | |||
v1.0 | complete | Docs | Docs: Pandas_27390_C | import pandas as pd
def visualize_titanic_data(df: pd.DataFrame) -> None:
""" Visualize various aspects of the Titanic dataset.
Generate the following plots:
1. Scatter Matrix: Show relationships between 'Age', 'Fare', 'SibSp', and 'Parch'.
2. Box Plot: Compare the fare price distribution across d... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pandas.plotting import scatter_matrix, parallel_coordinates, andrews_curves
def preprocess_data(df):
"""
Handle missing values and encode categorical variables.
"""
df['Age'].fillna(df['Age'].mean(), inplace=True)
df['Fare'... | import pytest
import pandas as pd
from solution import visualize_titanic_data, preprocess_data
def test_preprocess_data():
data = {
'PassengerId': [1, 2],
'Survived': [0, 1],
'Pclass': [3, 1],
'Name': ['A', 'B'],
'Sex': ['male', 'female'],
'Age': [22, None],
... | [
{
"docstring": "Handle missing values and encode categorical variables.",
"function_declaration": "def preprocess_data(df):",
"function_name": "preprocess_data",
"parameter_list": "(df)"
},
{
"docstring": "Generate various visualizations for the Titanic dataset.",
"function_declaration":... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nfrom pandas.plotting import scatter_matrix, parallel_coordinates, andrews_curves\nimport matplotlib.pyplot as plt\n\ndef visualize_titanic_data(df:... | trial_gpt4o_1 | {
"original_instruction": "#### Objective:\nDemonstrate your understanding of data visualization using the `pandas.plotting` module.\n\n#### Problem Statement:\nYou are given a Titanic dataset containing information about passengers. You need to visualize various aspects of this data using pandas plotting functions.\... | 0.671958 | Docs: Pandas_27390 | C | [
"preprocess_data",
"visualize_titanic_data"
] | 2 | [
[
"visualize_titanic_data",
"preprocess_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"pandas"
] | false | 855799b3bb324b28d8a26664d9352d37af0ede6e | a9903d1daecf733d995e7d380d0063c99e3230d5 | |||
v1.0 | complete | Docs | Docs: Scikit_26928_C | 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
def load_and_split_data(test_size: float = 0.3, random_state: int = 42):
"""Load the Iris dataset and... | 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": "**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.\n\n**Problem:**\nYou are given the Iris dataset, a famous dataset in the machine learning community. Yo... | 0.652025 | Docs: Scikit_26928 | C | [
"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 | 6d87af83ea46be1f5169d76098dc983b74f1dde7 | 45f4dcd250b7908cc6da5db90ae12c8c11c2a652 | |||
v1.0 | complete | Docs | Docs: Pytorch_27040_C | 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 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": "#### Objective:\nThe goal of this assessment is to evaluate your understanding of the `torch.futures` package and your ability to work with asynchronous operations in PyTorch.\n\n#### Problem Statement:\nYou are given an asynchronous task that processes data chunks and returns the processed... | 0.450383 | Docs: Pytorch_27040 | C | [
"process_data_chunk",
"process_and_aggregate_data"
] | 2 | [
[
"process_and_aggregate_data",
"process_data_chunk"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | f5b1d67871261ab0ac9759049ae35c1c16d57a4a | 8921b2c7a448cdc6433d968e985831fd4faeb8ef | |||
v1.0 | complete | Docs | Docs: Pytorch_27428_C | import torch
from torch.autograd import Function
import torch.nn as nn
import torch.autograd.functional as F
class ExpWithCustomGrad(Function):
@staticmethod
def forward(ctx, input):
"""Compute the exponential of the input tensor and save the context for backward propagation."""
ctx.save_for_ba... | import torch
from torch.autograd import Function
import torch.nn as nn
import torch.autograd.functional as F
class ExpWithCustomGrad(Function):
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
return input.exp()
@staticmethod
def backward(ctx, grad_output):
... | import pytest
import torch
from solution import ExpWithCustomGrad, SimpleModel, compute_loss
def test_custom_grad_function():
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y = ExpWithCustomGrad.apply(x)
y.sum().backward()
expected_grad = 2 * torch.exp(x)
assert torch.allclose(x.grad, e... | [] | [
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\nfrom torch.autograd import Function\nimport torch.nn as nn\nimport torch.autograd.functional as F\n\nclass ExpWithCustomGrad(Function):\n @staticmethod... | trial_gpt4o_0 | {
"original_instruction": "### PyTorch Autograd Coding Assessment\n\n#### Objective\nDemonstrate your understanding of PyTorch's autograd functionalities by implementing a custom backward function and utilizing higher-level API functions (Jacobians, Hessians).\n\n#### Problem Statement\n\nYou are required to implemen... | 0.62717 | Docs: Pytorch_27428 | C | [
"compute_loss",
"main_example"
] | 2 | [
[
"main_example",
"compute_loss"
]
] | 1 | [] | false | [
"ExpWithCustomGrad",
"SimpleModel"
] | true | pytest | true | [
"torch"
] | false | b9c6999d40ab79231c6bcb06c8f6f6810052de1e | d36e48f4fcba6565c91c7eea66ffe86c50f131b0 | |||
v1.0 | complete | Docs | Docs: Python310_27888_C | import asyncio
from typing import List
async def process_data_concurrently(urls: List[str]) -> None:
"""
Simulates concurrent fetching and processing of data from a list of URLs.
Args:
urls (List[str]): List of URLs to process.
"""
pass | import asyncio
import random
from typing import List
async def fetch_data(url: str):
print(f"Started fetching {url}")
await asyncio.sleep(random.uniform(1, 5))
print(f"Finished fetching {url}")
async def process_data(url: str):
print(f"Started processing {url}")
await asyncio.sleep(random.uniform(... | import pytest
import asyncio
from solution import process_data_concurrently
@pytest.mark.asyncio
async def test_process_data_concurrently_timeout():
urls = [
"http://example.com/resource1",
"http://example.com/resource2",
"http://example.com/resource3"
]
await process_data_concurren... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\nfrom typing import List\n\nasync def fetch_data(url: str):\n print(f\"Started fetching {url}\")\n await asyncio.sleep(random.unifor... | trial_gpt4o_2 | {
"original_instruction": "#### Objective:\nDesign a Python function that simulates a simple set of concurrent tasks using the `asyncio` package. The function should demonstrate the creation of tasks, concurrent execution, and implementing timeouts.\n\n#### Problem Statement:\nWrite an asynchronous function named `pr... | 0.517165 | Docs: Python310_27888 | C | [
"fetch_data",
"process_data",
"fetch_and_process",
"process_data_concurrently"
] | 4 | [
[
"fetch_and_process",
"fetch_data"
],
[
"fetch_and_process",
"process_data"
],
[
"process_data_concurrently",
"fetch_and_process"
]
] | 3 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 1d25c4d743e28e16470256196f5c261a68ca1013 | bcdb15160e951b759f5a15c84498756238026bc6 | |||
v1.0 | complete | Docs | Docs: Python310_27328_C | from dataclasses import dataclass, field
from contextlib import contextmanager
import inspect
@dataclass(frozen=True)
class DataObject:
"""Represents a data object with a name, value and metadata."""
name: str
value: int
metadata: dict = field(default_factory=dict)
@contextmanager
def DataObjectManage... | 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": "**Coding Assessment Question: Advanced Python Runtime Services**\n\n### Objective:\nDesign and implement a Python function that utilizes data classes, context managers, and inspection tools to manage, analyze, and manipulate objects safely and effectively.\n\n### Problem Statement:\n\nCreat... | 0.469847 | Docs: Python310_27328 | C | [
"DataObjectManager",
"manage_data_objects"
] | 2 | [
[
"manage_data_objects",
"DataObjectManager"
]
] | 1 | [] | false | [
"DataObject"
] | true | pytest | true | [] | true | 4f69ea7dc557c3ca3dea5574a8b033bc66e63deb | e5f7242e8ee6f12a5247437c2e19c61a6ad5856c | |||
v1.0 | complete | Docs | Docs: Python310_27632_C | import logging
from typing import List
async def fetch_data(session: ClientSession, url: str) -> str:
"""Fetch data from a single URL.
>>> await fetch_data(session, "http://example.com") "Data from http://example.com"
>>> await fetch_data(session, "http://invalid-url") "Invalid URL"
"""
# Your impl... | import asyncio
import logging
from typing import List
from aiohttp import ClientSession
# Configure logging
logging.basicConfig(level=logging.DEBUG)
async def fetch_data(session: ClientSession, url: str) -> str:
try:
async with session.get(url) as response:
response.raise_for_status()
... | import pytest
from solution import fetch_data_from_sources
@pytest.mark.asyncio
async def test_all_successful_requests():
sources = ["http://example.com/1", "http://example.com/2"]
expected = ["Data from http://example.com/1", "Data from http://example.com/2"]
data = await fetch_data_from_sources(sources)
... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport logging\nfrom typing import List\nfrom aiohttp import ClientSession\n\n# Configure logging\nlogging.basicConfig(level=logging.DEBUG)\n\nasync def... | trial_gpt4o_0 | {
"original_instruction": "## Coding Assessment Question\n\n### Objective\nThe goal of this exercise is to assess your understanding of the `asyncio` module in Python, especially handling concurrency, managing tasks, and enabling debugging features to catch common asynchronous programming pitfalls.\n\n### Problem Sta... | 0.616713 | Docs: Python310_27632 | C | [
"fetch_data",
"fetch_data_from_sources"
] | 2 | [
[
"fetch_data_from_sources",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 69b403f73b15c1dca89c485e471b680b72e6d4cd | dcb84c9e60772631ffe4d7550b0f21e320ee36e2 | |||
v1.0 | complete | Docs | Docs: Python310_27270_C | import mailbox
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.
criteria (dict): Criteria to m... | 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": "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 i... | 0.514066 | Docs: Python310_27270 | C | [
"sort_and_move_messages",
"message_matches_criteria"
] | 2 | [
[
"sort_and_move_messages",
"message_matches_criteria"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0108f2ec67c904e56b0901aa60939456aedcd4cc | b8e4d52e803cd79f0322361442f8bbfa57e5d06a | |||
v1.0 | complete | Docs | Docs: Python310_27672_C | def prime_generator():
"""Generates an infinite sequence of prime numbers."""
pass
# Example usage:
# gen = prime_generator()
# print(next(gen)) # Output: 2
# print(next(gen)) # Output: 3
# print(next(gen)) # Output: 5
# print(next(gen)) # Output: 7
# and so on...
# Unit tests
def prime_list_from_generato... | def is_prime(number):
"""Return True if number is a prime, else False."""
if number <= 1:
return False
if number <= 3:
return True
if number % 2 == 0 or number % 3 == 0:
return False
i = 5
while i * i <= number:
if number % i == 0 or number % (i + 2) == 0:
... | from solution import prime_generator
def prime_list_from_generator(generator, count):
"""Helper function to get a list of primes from the generator."""
return [next(generator) for _ in range(count)]
def test_first_five_primes():
gen = prime_generator()
first_five_primes = prime_list_from_generator(gen... | [
{
"docstring": "Return True if number is a prime, else False.",
"function_declaration": "def is_prime(number):",
"function_name": "is_prime",
"parameter_list": "(number)"
},
{
"docstring": "Generates an infinite sequence of prime numbers.",
"function_declaration": "def prime_generator():... | [
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 prime_generator():\n \"\"\"\n Generates an infinite sequence of prime numbers.\n \"\"\"\n def is_prime(number):\n \"\"\"Returns True if the numbe... | trial_gpt4o_1 | {
"original_instruction": "### Python Coding Assessment Question\n\n**Objective**: Demonstrate understanding of Python generators and their advanced implementations.\n\n**Problem Statement**:\nGenerators are a special class of iterators in Python which allow you to iterate through a sequence of values produced dynami... | 0.641438 | Docs: Python310_27672 | C | [
"is_prime",
"prime_generator"
] | 2 | [
[
"prime_generator",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2ef9f2f9ffec508f4ff2bd72f0eb53ca3ebccf19 | 6b34119c33d726621c1209c0d2aa981de901f7af | |||
v1.0 | complete | Docs | Docs: Python310_27732_C | def greet_user(name: str) -> str:
"""
Generate a greeting message for the user.
"""
return f"Hello, {name}!"
def calculate_square(number: int) -> int:
"""
Calculate the square of a given number.
"""
return number ** 2
def process_input(data: dict) -> dict:
"""
Process user inpu... | def greet_user(name: str) -> str:
"""
Generate a greeting message for the user.
Parameters:
name (str): The name of the user.
Returns:
str: A greeting message.
"""
return f"Hello, {name}!"
def calculate_square(number: int) -> int:
"""
Calculate the square of a given number.... | from solution import greet_user, calculate_square, process_input
def test_greet_user():
assert greet_user("Alice") == "Hello, Alice!"
assert greet_user("Bob") == "Hello, Bob!"
assert greet_user("") == "Hello, !"
def test_calculate_square():
assert calculate_square(3) == 9
assert calculate_square(0... | [
{
"docstring": "Generate a greeting message for the user.\nParameters:\nname (str): The name of the user.\n\nReturns:\nstr: A greeting message.",
"function_declaration": "def greet_user(name):",
"function_name": "greet_user",
"parameter_list": "(name)"
},
{
"docstring": "Calculate the square... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def greet_user(name: str) -> str:\n \"\"\"\n Generate a greeting message for the user.\n \"\"\"\n if not name:\n raise ValueError(\"Name cannot be em... | trial_gpt4o_1 | {
"original_instruction": "### Python Coding Assessment Question\n\n#### Objective:\n\nCreate a Python module that defines several functions and uses the `if __name__ == '__main__':` idiom to conditionally run a script. The script should include taking user input, processing it, and providing an output.\n\n#### Task:... | 0.540691 | Docs: Python310_27732 | C | [
"greet_user",
"calculate_square",
"process_input",
"main"
] | 4 | [
[
"process_input",
"calculate_square"
],
[
"process_input",
"greet_user"
]
] | 2 | [
"process_input"
] | false | [] | false | pytest | true | [] | true | 3f58a4b677e93559ed6d4cec42287e75da55e6db | f9506afaa9026bc8df27ddfe5d42ae8d720f4bd2 | |||
v1.0 | complete | Docs | Docs: Pytorch_27425_C | import torch
from torch.func import grad, vmap
def per_sample_gradients(inputs: torch.Tensor) -> torch.Tensor:
"""
Compute per-sample gradients of the function f with respect to each input tensor in the batch.
The function f is defined as f(x) = (x.sum())**2.
Args:
inputs (torch.Tensor): A b... | import torch
from torch.func import grad, vmap
def f(x):
return (x.sum())**2
def per_sample_gradients(inputs: torch.Tensor) -> torch.Tensor:
grad_f = grad(f)
per_sample_grads = vmap(grad_f)(inputs)
return per_sample_grads | from solution import per_sample_gradients
import torch
def test_per_sample_gradients_two_samples():
inputs = torch.tensor([[1.0, 2.0], [3.0, 4.0]], requires_grad=True)
result = per_sample_gradients(inputs)
expected = torch.tensor([[6.0, 6.0], [14.0, 14.0]])
assert torch.allclose(result, expected), f"Ex... | [
{
"docstring": null,
"function_declaration": "def f(x):",
"function_name": "f",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def per_sample_gradients(inputs):",
"function_name": "per_sample_gradients",
"parameter_list": "(inputs)"
}
] | [
1,
0,
0,
0,
0,
0,
1,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.func import grad, vmap\n\ndef per_sample_gradients(inputs: torch.Tensor) -> torch.Tensor:\n def f(x):\n return (x.sum())**2\n \n ... | trial_gpt4o_9 | {
"original_instruction": "**Title:** Implementing and Composing Function Transforms with torch.func\n\n**Objective:**\nYour task is to implement a function that performs gradient computation and vectorization using the `torch.func` module. You will compose the `grad` and `vmap` transforms to efficiently compute per-... | 0.568304 | Docs: Pytorch_27425 | C | [
"f",
"per_sample_gradients"
] | 2 | [
[
"per_sample_gradients",
"f"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 42f5a4c008af5238aeb55d9abdc7665165edb3e4 | d30acf1fdd3861e62b600386625943d550c9a451 | |||
v1.0 | complete | Docs | Docs: Python310_27817_C | import random
from typing import List
def generate_matrix(n: int, m: int) -> List[List[int]]:
""" Generate a matrix with dimensions n x m filled with random integers between 1 and 100.
"""
return [[random.randint(1, 100) for _ in range(m)] for _ in range(n)]
def optimized_matrix_multiplication(A: List[Lis... | import random
import numpy as np
def generate_matrix(n, m):
return [[random.randint(1, 100) for _ in range(m)] for _ in range(n)]
def optimized_matrix_multiplication(A, B):
"""
Optimized matrix multiplication using NumPy for better performance.
"""
return np.dot(A, B).tolist()
# Profiling Script:... | from solution import generate_matrix, optimized_matrix_multiplication
import numpy as np
def test_generate_matrix():
matrix = generate_matrix(3, 3)
assert len(matrix) == 3
assert len(matrix[0]) == 3
assert all(1 <= element <= 100 for row in matrix for element in row)
def test_optimized_matrix_multipli... | [
{
"docstring": null,
"function_declaration": "def generate_matrix(n, m):",
"function_name": "generate_matrix",
"parameter_list": "(n, m)"
},
{
"docstring": "Optimized matrix multiplication using NumPy for better performance.",
"function_declaration": "def optimized_matrix_multiplication(... | [
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 random\nimport numpy as np\n\ndef generate_matrix(n, m):\n return [[random.randint(1, 100) for _ in range(m)] for _ in range(n)]\n\ndef optimized_matrix_multi... | trial_gpt4o_1 | {
"original_instruction": "#### Objective\nTo assess students' understanding and application of Python's debugging and profiling tools.\n\n#### Problem Statement\n\nYou are given a Python function that performs several complex operations. Your task is to:\n1. **Optimize the Function**: Analyze the performance of the ... | 0.634703 | Docs: Python310_27817 | C | [
"generate_matrix",
"optimized_matrix_multiplication",
"profile_script",
"debug_script"
] | 4 | [
[
"debug_script",
"generate_matrix"
],
[
"debug_script",
"optimized_matrix_multiplication"
],
[
"profile_script",
"generate_matrix"
],
[
"profile_script",
"optimized_matrix_multiplication"
]
] | 4 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 78e85486480491211280784a523d615f53614faa | ed312fcbd9bffb6710378adb7cf67f5c24908b38 | |||
v1.0 | complete | Docs | Docs: Python310_27693_C | import readline
def interactive_shell():
"""
Interactive Python Shell Enhancer
This function implements a simplified version of a Python shell that supports basic history management and tab completion.
Sample Usage:
>>> print('Hello, World!')
>>> MyFunction
>>> !history
print('Hello, ... | import readline
def completer(text, state):
options = [cmd for cmd in command_history if cmd.startswith(text)]
if state < len(options):
return options[state]
else:
return None
def interactive_shell():
global command_history
command_history = []
# Enable auto-completion
... | import builtins
from solution import interactive_shell
def test_exit():
builtins.input = lambda _: "exit()"
interactive_shell() # Should terminate without any error
def test_history():
inputs = iter(["print('Hello, World!')", "MyFunction", "!history", "exit()"])
builtins.input = lambda _: next(inputs... | [
{
"docstring": null,
"function_declaration": "def completer(text, state):",
"function_name": "completer",
"parameter_list": "(text, state)"
},
{
"docstring": null,
"function_declaration": "def interactive_shell():",
"function_name": "interactive_shell",
"parameter_list": "()"
}... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import readline\n\ndef interactive_shell():\n command_history = []\n \n def completer(text, state):\n options = [cmd for cmd in command_history if cmd.s... | trial_gpt4o_5 | {
"original_instruction": "### Interactive Python Shell Enhancer\n\nYou are to implement a simplified version of a Python shell that supports basic history management and tab completion. Your task is to write a function `interactive_shell()` which reads user inputs, stores them in a history, and provides tab completi... | 0.400735 | Docs: Python310_27693 | C | [
"completer",
"interactive_shell"
] | 2 | [
[
"interactive_shell",
"completer"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 75c115b25940b987605253692539b12c1ff2812b | a54288b1f2fd5e9912c39e5faab659726b10afd4 | |||
v1.0 | complete | Docs | Docs: Python310_27764_C | from contextvars import ContextVar
from concurrent.futures import ThreadPoolExecutor
# Initialize ContextVar for user configurations
user_config_var = ContextVar('user_config', default={"theme": "default", "notifications": "enabled"})
def process_user_request(user_id: int, config_changes: dict) -> dict:
"""Simula... | from contextvars import ContextVar
from concurrent.futures import ThreadPoolExecutor
# Initialize ContextVar for user configurations
user_config_var = ContextVar('user_config', default={"theme": "default", "notifications": "enabled"})
def process_user_request(user_id: int, config_changes: dict) -> dict:
# Get the... | from solution import process_user_request, handle_multiple_requests
def test_process_user_request_single_change():
result = process_user_request(1, {"theme": "dark mode"})
assert result == {"theme": "dark mode", "notifications": "enabled"}
def test_process_user_request_multiple_changes():
result = process... | [
{
"docstring": null,
"function_declaration": "def process_user_request(user_id, config_changes):",
"function_name": "process_user_request",
"parameter_list": "(user_id, config_changes)"
},
{
"docstring": null,
"function_declaration": "def handle_multiple_requests(requests):",
"functi... | [
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 contextvars import ContextVar\nfrom concurrent.futures import ThreadPoolExecutor\n\n# Initialize ContextVar for user configurations\nuser_config_var = ContextVar('... | trial_gpt4o_2 | {
"original_instruction": "#### Context:\nYou are tasked with developing a simple tool that maintains individual user configurations in a multithreaded application. To achieve this, you will utilize `ContextVar` to store and reset user configurations during each request processing. Additionally, you will need to ensu... | 0.424127 | Docs: Python310_27764 | C | [
"process_user_request",
"handle_multiple_requests"
] | 2 | [
[
"handle_multiple_requests",
"process_user_request"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 32fd0c35e626a1b53590f7365973aebfd26baf2c | 3ee3c4fcf9254765ba8a07468e67abe80e5df7ad | |||
v1.0 | complete | Docs | Docs: Python310_28164_C | import gettext
def setup_translation(domain, localedir):
"""
Bind the domain to the given locale directory and set the domain for translations.
:param domain: The text domain (e.g., 'myapplication').
:param localedir: The directory where `.mo` files are located (e.g., '/path/to/my/language/directo... | import gettext
def setup_translation(domain, localedir):
"""
Bind the domain to the given locale directory and set the domain for translations.
:param domain: The text domain (e.g., 'myapplication').
:param localedir: The directory where `.mo` files are located (e.g., '/path/to/my/language/directory')... | import os
import gettext
from solution import setup_translation, switch_language, translate
def test_setup_translation():
# Setup a fake translation environment for testing
domain = 'test_application'
localedir = '/tmp/test_translations'
os.makedirs(localedir, exist_ok=True)
# Create a .mo fil... | [
{
"docstring": "Bind the domain to the given locale directory and set the domain for translations.\n\n:param domain: The text domain (e.g., 'myapplication').\n:param localedir: The directory where `.mo` files are located (e.g., '/path/to/my/language/directory').",
"function_declaration": "def setup_translat... | [
0,
0,
0,
0,
1,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import gettext\n\ndef setup_translation(domain, localedir):\n \"\"\"\n Bind the domain to the given locale directory and set the domain for translations.\n\n :... | trial_gpt4o_7 | {
"original_instruction": "**Problem Statement:**\n\nYou are developing a multilingual application where users can switch between multiple languages at runtime. You need to create a system that supports loading translations from `.mo` files, switching languages dynamically, and using the translations in the applicati... | 0.591715 | Docs: Python310_28164 | C | [
"setup_translation",
"switch_language",
"translate"
] | 3 | [
[
"translate",
"setup_translation"
],
[
"translate",
"switch_language"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1b7d02c4f2a30103a88d090d49b1c482cf90f163 | e7bb632f3b6cdcd18902c7254ca1a4db347082cc | |||
v1.0 | complete | Docs | Docs: Python310_28136_C | import asyncio
from typing import List, Dict
async def task_runner(i: int, future: asyncio.Future):
# Simulate a delay
await asyncio.sleep(random.randint(1, 3))
# Set the future result
future.set_result(f'Task {i} completed')
def task_callback(fut: asyncio.Future):
print(f'Completed: {fut.result()... | import asyncio
import random
from typing import List, Dict
async def task_runner(i: int, future: asyncio.Future):
# Simulate a delay
await asyncio.sleep(random.randint(1, 3))
# Set the future result
future.set_result(f'Task {i} completed')
def task_callback(fut: asyncio.Future):
print(f'Completed:... | import asyncio
import random
from solution import create_tasks, manage_tasks
def test_single_task():
async def test():
futures = await create_tasks(1)
results = await manage_tasks(futures)
assert results == {'Task 0': 'Task 0 completed'}
asyncio.run(test())
def test_multiple_tasks... | [
{
"docstring": null,
"function_declaration": "def task_callback(fut):",
"function_name": "task_callback",
"parameter_list": "(fut)"
}
] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\nfrom typing import List, Dict\n\nasync def task_runner(i: int, future: asyncio.Future):\n # Simulate a delay\n await asyncio.sleep(... | trial_gpt4o_0 | {
"original_instruction": "You are required to implement a simulation of an asynchronous task management system using the `asyncio` module and the `Future` class. The system should:\n\n1. Create multiple asynchronous tasks that perform simple computations and set their results into Future objects after a delay.\n2. I... | 0.643619 | Docs: Python310_28136 | C | [
"task_runner",
"task_callback",
"create_tasks",
"manage_tasks",
"main"
] | 5 | [
[
"create_tasks",
"task_callback"
],
[
"create_tasks",
"task_runner"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 12fd399454edd5471b8bba3d2ef0dcdf41f5e4ce | d19e71a0331365c42d699410afaf1ef8149d1cb5 | |||
v1.0 | complete | Docs | Docs: Python310_27788_C | import hashlib
import os
from typing import Tuple
def derive_key(password: str, salt: bytes, iterations: int, dklen: int) -> bytes:
"""
Derives a key from the given password and salt using PBKDF2-HMAC-SHA256.
Parameters:
password (str): The password to derive the key from.
salt (bytes): The salt t... | import os
import hashlib
def derive_key(password, salt, iterations=100000, dklen=32):
"""
Derives a key from the given password and salt using PBKDF2-HMAC-SHA256.
Parameters:
password (str): The password to derive the key from.
salt (bytes): The salt to use in the derivation.
iterations (i... | import pytest
from solution import derive_key, hash_password, verify_password
def test_derive_key():
password = "testpassword"
salt = b"randomsalt"
iterations = 100000
dklen = 32
derived_key1 = derive_key(password, salt, iterations, dklen)
derived_key2 = derive_key(password, salt, iterations, d... | [
{
"docstring": "Derives a key from the given password and salt using PBKDF2-HMAC-SHA256.\n\nParameters:\npassword (str): The password to derive the key from.\nsalt (bytes): The salt to use in the derivation.\niterations (int): The number of iterations to perform (default: 100000).\ndklen (int): The length of th... | [
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\nimport hashlib\n\ndef derive_key(password, salt, iterations=100000, dklen=32):\n \"\"\"\n Derive a secure key from a given password using PBKDF2-HMAC.\... | trial_gpt4o_2 | {
"original_instruction": "#### Objective\nImplement a secure password storage system using the `hashlib` module, focusing on key derivation, salting, and hashing. This assessment will test your understanding of fundamental and advanced concepts of Python’s `hashlib` module.\n\n#### Task\n1. Write a function `derive_... | 0.797272 | Docs: Python310_27788 | C | [
"derive_key",
"hash_password",
"verify_password"
] | 3 | [
[
"hash_password",
"derive_key"
],
[
"verify_password",
"derive_key"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b85720ec08f8357feac031b59330eeb1d50d16c1 | 69658379c2121303dd3df9475e8362a362547367 | |||
v1.0 | complete | Docs | Docs: Python310_28278_C | import cProfile
import pstats
def profile_example_function():
""" Profile the example_function and save the profiling data to a file named 'example_profile.prof' """
with cProfile.Profile() as pr:
example_function()
pr.dump_stats('example_profile.prof')
def print_profile_insights(profile_file: str... | import cProfile
import pstats
def profile_example_function():
# Profile the example_function and save the profiling data to a file
with cProfile.Profile() as pr:
example_function()
pr.dump_stats('example_profile.prof')
def print_profile_insights(profile_file: str):
# Load the profiling data
... | from solution import profile_example_function, print_profile_insights, example_function
import os
def test_profile_example_function():
# Ensure no existing profiling file before test
profile_file = 'example_profile.prof'
if os.path.exists(profile_file):
os.remove(profile_file)
# Profile th... | [
{
"docstring": null,
"function_declaration": "def profile_example_function():",
"function_name": "profile_example_function",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def print_profile_insights(profile_file):",
"function_name": "print_profile_insights",
... | [
0,
0,
0,
0,
0,
1,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cProfile\nimport pstats\n\ndef example_function():\n import time\n for i in range(5):\n time.sleep(0.1)\n for i in range(3):\n for j in ra... | trial_gpt4o_6 | {
"original_instruction": "**Question:**\n\nYou are given a Python function that executes some operations. Your task is to profile this function, analyze the profiling data, and provide a report that highlights key performance metrics.\n\n### Function to Profile\n\n```python\ndef example_function():\n import time\... | 0.518509 | Docs: Python310_28278 | C | [
"profile_example_function",
"print_profile_insights",
"example_function"
] | 3 | [
[
"profile_example_function",
"example_function"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4ac8d7d6fb022978915cfc2cde2b024bf7966f45 | 8775bd0c7dbd303e4012b6367ffa327dc2cac295 | |||
v1.0 | complete | Docs | Docs: Python310_26963_C | import ctypes
class RawMemoryManager:
""" A class for managing raw memory allocations. """
def __init__(self):
self.memories = {}
def allocate(self, size: int) -> int:
""" Allocate `size` bytes of raw memory.
Args:
size (int): The size of the memory block ... | 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": "### Objective: Implement Custom Memory Management in Python\n\nPython'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 debuggi... | 0.467739 | Docs: Python310_26963 | C | [
"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 | d5153fda23f9e2e80240d334b746d7db3e998b9c | 9c342e13fd35a99c9b88f1c06e4b85b6628c98ae | |||
v1.0 | complete | Docs | Docs: Python310_27697_C | import inspect
def analyze_module(module):
"""
Inspects a given module and extracts detailed information about its classes, functions,
and methods. Returns a nested dictionary with the structure specified in the task description.
Args:
module (ModuleType): The module to be inspected.
... | import inspect
def extract_function_info(func):
"""Extract information about a given function or method."""
return {
'doc': inspect.getdoc(func),
'signature': str(inspect.signature(func)),
'is_async': inspect.iscoroutinefunction(func)
}
def analyze_module(module):
"""
Inspe... | import inspect
from types import ModuleType
# Mock module to test analyze_module function
class MockModule:
"""Example mock module for testing purposes."""
class TestClass:
"""Example class within mock module."""
def method_a(self):
"""Example method A."""
... | [
{
"docstring": "Extract information about a given function or method.",
"function_declaration": "def extract_function_info(func):",
"function_name": "extract_function_info",
"parameter_list": "(func)"
},
{
"docstring": "Inspects a given module and extracts details about its classes, function... | [
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 inspect\n\ndef analyze_module(module):\n \"\"\"\n Analyzes the given module and extracts detailed information about its classes,\n functions, and method... | trial_gpt4o_2 | {
"original_instruction": "### Question\nYou are required to write a Python function named `analyze_module` that inspects a given Python module and extracts detailed information about its classes, functions, and methods. The information should include documentation strings, parameter lists, and identifying whether fu... | 0.602709 | Docs: Python310_27697 | C | [
"extract_function_info",
"analyze_module"
] | 2 | [
[
"analyze_module",
"extract_function_info"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | a7aa2812b8132e9221591e5ff3709ca8a6982444 | 93cb3036f17758cb5f6e85414625bcfc341c6482 | |||
v1.0 | complete | Docs | Docs: Python310_28386_C | from itertools import combinations
from functools import reduce
from typing import List
def is_prime(n: int) -> bool:
"""
Returns True if the given number n is a prime number, otherwise False.
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(4)
False
"""
# Your code here
... | from itertools import combinations
from functools import reduce
from typing import List
def is_prime(n: int) -> bool:
"""
Returns True if the given number n is a prime number, otherwise False.
"""
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
... | from solution import process_data, is_prime, sum_combinations
def test_is_prime():
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(1)
assert is_prime(13)
assert not is_prime(15)
assert is_prime(17)
def test_sum_combinations():
ass... | [
{
"docstring": "Returns True if the given number n is a prime number, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Given a list of integers, returns a list of sums of all possible combinations.",
"f... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import combinations\nfrom functools import reduce\nfrom typing import List\n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Check if the given integer i... | trial_gpt4o_2 | {
"original_instruction": "**Question: Efficient Data Processing with Itertools and Functools**\n\nYou are given a dataset of numbers, and your task is to perform a series of operations using `itertools` and `functools` to transform and analyze the data efficiently. Specifically, you need to implement a function `pro... | 0.701896 | Docs: Python310_28386 | C | [
"is_prime",
"sum_combinations",
"process_data"
] | 3 | [
[
"process_data",
"is_prime"
],
[
"process_data",
"sum_combinations"
]
] | 2 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 01a80c83390a358faa13a7b043649a5ebacd03cd | f0a2cebe4246187892e50672be952fada1340602 | |||
v1.0 | complete | Docs | Docs: Python310_28282_C | import concurrent.futures
import requests
def fetch_url_contents(url_list: list) -> dict:
""" Downloads the contents of the provided URLs in parallel and returns a dictionary
where the keys are the URLs and the values are the lengths of the content retrieved
from each URL.
The function uses the `c... | import concurrent.futures
import requests
def fetch_content(url):
try:
response = requests.get(url)
response.raise_for_status()
return url, len(response.content)
except requests.RequestException:
return url, None
def fetch_url_contents(url_list: list) -> dict:
result = {}
... | from solution import fetch_url_contents
def test_fetch_url_contents_single_url(monkeypatch):
url_list = ["http://example.com"]
responses = {
"http://example.com": "Example content."
}
def mock_requests_get(url):
class MockResponse:
def __init__(self, text):
... | [
{
"docstring": null,
"function_declaration": "def fetch_content(url):",
"function_name": "fetch_content",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def fetch_url_contents(url_list):",
"function_name": "fetch_url_contents",
"parameter_list": "(url_... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import concurrent.futures\nimport requests\n\ndef fetch_url_content(url):\n \"\"\"\n Helper function to fetch content from a single URL.\n \"\"\"\n try:\n ... | trial_gpt4o_2 | {
"original_instruction": "## Coding Assessment Question\n\n### Objective\n\nDemonstrate your understanding of parallel task execution using the `concurrent.futures` module in Python.\n\n### Problem Statement\n\nYou are provided with a list of URLs. Your task is to write a Python function that downloads the contents ... | 0.618382 | Docs: Python310_28282 | C | [
"fetch_content",
"fetch_url_contents"
] | 2 | [
[
"fetch_url_contents",
"fetch_content"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 2f6c6672282daf2f64a4ca9c373cd596ecbc9f8c | a206eefd96b66844ff8e9da8a828ab99597d8d34 | |||
v1.0 | complete | Docs | Docs: Python310_28274_C | import os
import stat
import time
def traverse_and_report(directory: str) -> None:
"""
Recursively descends the directory tree starting from 'directory'.
Gathers information about each file and subdirectory using the 'stat' module.
Generates a report in human-readable format.
For example:
... | import os
import stat
import time
def format_time(epoch_time):
"""Formats the epoch time to a human-readable format."""
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(epoch_time))
def get_file_type(mode):
"""Returns the type of the file based on the mode."""
if stat.S_ISREG(mode):
re... | from solution import traverse_and_report
from unittest.mock import patch, mock_open
import os
def test_traverse_and_report_empty_directory(tmp_path):
with patch('builtins.print') as mocked_print:
traverse_and_report(tmp_path)
mocked_print.assert_not_called()
def test_traverse_and_report_single_fil... | [
{
"docstring": "Formats the epoch time to a human-readable format.",
"function_declaration": "def format_time(epoch_time):",
"function_name": "format_time",
"parameter_list": "(epoch_time)"
},
{
"docstring": "Returns the type of the file based on the mode.",
"function_declaration": "def ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport stat\nimport time\n\ndef format_time(epoch_time):\n \"\"\"Formats the epoch time to a human-readable format.\"\"\"\n return time.strftime('%Y-%m... | trial_gpt4o_0 | {
"original_instruction": "You are tasked with writing a Python program that traverses a specific directory and generates a detailed report of all its files and subdirectories. Your program should utilize the \"stat\" module to gather this information effectively. This assignment aims to test your proficiency with fi... | 0.63053 | Docs: Python310_28274 | C | [
"format_time",
"get_file_type",
"traverse_and_report"
] | 3 | [
[
"traverse_and_report",
"format_time"
],
[
"traverse_and_report",
"get_file_type"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 86b6c871a43ac78b5e05a6e1fa0efd7c8b2640f5 | 85c4ce4b060aaa68f8690cc5022e9ca319fe639c | |||
v1.0 | complete | Docs | Docs: Python310_28424_C | from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from typing import List, Tuple
def check_prime_threadpool(numbers: List[int], max_workers: int) -> List[Tuple[int, bool]]:
"""Process a list of numbers to determine whether they are prime using ThreadPoolExecutor.
Args:
numbers (Li... | from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from typing import List, Tuple
def is_prime(n: int) -> bool:
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (... | from solution import check_prime_threadpool, check_prime_processpool
def test_check_prime_threadpool():
numbers = [29, 15, 18, 47, 77, 93, 97]
expected = [(29, True), (15, False), (18, False), (47, True), (77, False), (93, False), (97, True)]
assert sorted(check_prime_threadpool(numbers, max_workers=5)) ==... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def check_prime_threadpool(numbers, max_workers):",
"function_name": "check_prime_threadpool",
"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": "from typing import List, Tuple\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\nimport math\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n ... | trial_gpt4o_1 | {
"original_instruction": "### Comprehensive Python310 Coding Assessment\n\n#### Problem Statement:\nYou are required to use the `concurrent.futures` module to implement a function that processes a list of numbers to determine whether they are prime. The function should handle the task in parallel using both `ThreadP... | 0.622961 | Docs: Python310_28424 | C | [
"is_prime",
"check_prime_threadpool",
"check_prime_processpool"
] | 3 | [
[
"check_prime_processpool",
"is_prime"
],
[
"check_prime_threadpool",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3bb558bdca96301264dcc2780f1d9203b77557b3 | 2f96a48001675b4c9cd62bc8d718f8ec02695cd0 | |||
v1.0 | complete | Docs | Docs: Python310_28403_C | import os
import shutil
import zipfile
import gzip
import bz2
import argparse
def organize_files(src_dir, dst_dir):
""" Organize files in a specified directory based on their file extensions.
Handle different types of file compressions and produce a summary report of the actions performed.
The script shoul... | import os
import shutil
import zipfile
import gzip
import bz2
import argparse
def organize_files(src_dir, dst_dir):
files_processed = 0
decompressed_files = 0
file_count_by_extension = {}
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for filename in os.listdir(src_dir):
sou... | import os
import shutil
import pytest
from solution import organize_files
@pytest.fixture
def setup_test_environment(tmp_path):
src_dir = tmp_path / "source"
dst_dir = tmp_path / "destination"
os.makedirs(src_dir)
os.makedirs(dst_dir)
# Create test files
(src_dir / "test1.txt").write_text("Thi... | [
{
"docstring": null,
"function_declaration": "def organize_files(src_dir, dst_dir):",
"function_name": "organize_files",
"parameter_list": "(src_dir, dst_dir)"
},
{
"docstring": null,
"function_declaration": "def decompress_file(file_path, ext):",
"function_name": "decompress_file",
... | [
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 shutil\nimport zipfile\nimport gzip\nimport bz2\nimport argparse\n\ndef organize_files(src_dir, dst_dir):\n file_count = 0\n decompressed_count ... | trial_gpt4o_7 | {
"original_instruction": "**File Organizer Script with Command-Line Interface**\n\n**Objective**: Write a Python script that organizes files in a specified directory based on their file extensions. The script should be able to handle different types of file compressions and produce a summary report of the actions pe... | 0.75681 | Docs: Python310_28403 | C | [
"organize_files",
"decompress_file",
"print_report"
] | 3 | [
[
"organize_files",
"decompress_file"
],
[
"organize_files",
"print_report"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 538ccdffaf6d943296fbae3549aa4639f1c6d356 | 32d226940aaf630c77fe2edc7bc845a452af8b3c | |||
v1.0 | complete | Docs | Docs: Scikit_28124_C | import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.svm import SVC, LinearSVC
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.preprocessing import StandardScaler
def load_and_preprocess_data(file_path):
"""Load and preprocess the data from g... | import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.svm import SVC, LinearSVC
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.preprocessing import StandardScaler
def load_and_preprocess_data(file_path):
df = pd.read_csv(file_path)
X = df... | import pytest
from sklearn.datasets import load_iris
import pandas as pd
from tempfile import NamedTemporaryFile
from solution import load_and_preprocess_data, linear_svm_classification, rbf_svm_classification
@pytest.fixture
def iris_data():
iris = load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.f... | [
{
"docstring": null,
"function_declaration": "def load_and_preprocess_data(file_path):",
"function_name": "load_and_preprocess_data",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def linear_svm_classification(X_train, y_train, X_test, y_test):",
"f... | [
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 pandas as pd\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.metrics import accuracy_sc... | trial_gpt4o_2 | {
"original_instruction": "### SVM Classification Task\n\nYou are provided with a dataset `iris.csv`, which contains the famous Iris dataset. Your task is to implement a classification model using Support Vector Machines (SVM) from the scikit-learn library. Your solution should demonstrate the following:\n\n1. Load a... | 0.681219 | Docs: Scikit_28124 | C | [
"load_and_preprocess_data",
"linear_svm_classification",
"rbf_svm_classification",
"svm_classification"
] | 4 | [
[
"svm_classification",
"linear_svm_classification"
],
[
"svm_classification",
"load_and_preprocess_data"
],
[
"svm_classification",
"rbf_svm_classification"
]
] | 3 | [] | false | [] | false | pytest | true | [
"pandas",
"sklearn"
] | false | 48ad780bad9aaab62bbd8ef9f2c6a0f449652f0c | c34e2952fd7eff9d0c7f823b80f0474e11bba2e6 | |||
v1.0 | complete | Docs | Docs: Python310_28013_C | import hmac
import hashlib
from typing import Optional
def create_hmac(key: bytes, message: bytes, digestmod: str) -> bytes:
"""
Creates an HMAC digest using the given key, message, and digestmod algorithm.
>>> key = b'secret_key'
>>> message = b'This is a message'
>>> digestmod = 'sha256'
... | import hmac
import hashlib
def create_hmac(key: bytes, message: bytes, digestmod: str) -> bytes:
"""
Creates an HMAC digest using the given key, message, and digestmod algorithm.
"""
hmac_obj = hmac.new(key, message, digestmod=getattr(hashlib, digestmod))
return hmac_obj.digest()
def verify_hmac(k... | import hmac
import hashlib
from solution import create_hmac, verify_hmac, update_hmac, secure_compare
def test_create_hmac():
key = b'secret_key'
message = b'This is a message'
digestmod = 'sha256'
expected_hmac = hmac.new(key, message, digestmod=hashlib.sha256).digest()
assert create_hmac(key, mes... | [
{
"docstring": "Creates an HMAC digest using the given key, message, and digestmod algorithm.",
"function_declaration": "def create_hmac(key, message, digestmod):",
"function_name": "create_hmac",
"parameter_list": "(key, message, digestmod)"
},
{
"docstring": "Verifies an HMAC digest using ... | [
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\n\ndef create_hmac(key: bytes, message: bytes, digestmod: str) -> bytes:\n \"\"\"\n Create an HMAC digest for a given key and message ... | trial_gpt4o_2 | {
"original_instruction": "### Coding Challenge\n\n**Objective:** Implement a message authentication system using HMAC. Your task is to write several functions to simulate the process of creating and verifying message digests using secret keys.\n\n#### Functions to Implement:\n\n1. **`create_hmac(key: bytes, message:... | 0.84056 | Docs: Python310_28013 | C | [
"create_hmac",
"verify_hmac",
"update_hmac",
"secure_compare"
] | 4 | [
[
"verify_hmac",
"create_hmac"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b230e3f5e304b9c2af5e69222a4217b6efe67d63 | 685ea88ac07ee96e41e3df48282093fca57f3938 | |||
v1.0 | complete | Docs | Docs: Python310_28215_C | import asyncio
from typing import List, Dict, Any
async def run_commands(commands: List[str]) -> List[Dict[str, Any]]:
"""Runs multiple shell commands asynchronously and captures their outputs concurrently.
Args:
commands (List[str]): A list of shell commands to be executed.
Returns:
List... | import asyncio
from typing import List, Dict, Any
async def run_command(command: str) -> Dict[str, Any]:
"""
Runs a single command and captures its output.
"""
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIP... | import asyncio
from solution import run_commands
def test_run_commands():
commands = [
'echo "Hello, World!"',
'ls /nonexistent_directory',
'sleep 1; echo "Done"'
]
# Running the commands
result = asyncio.run(run_commands(commands))
# Expected results
expected ... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Dict, Any\n\nasync def run_single_command(command: str) -> Dict[str, Any]:\n proc = await asyncio.create_subprocess_shell(\n... | trial_gpt4o_2 | {
"original_instruction": "## Question: Managing Multiple Subprocesses in Parallel\n\n### Objective\nYou need to create a function that runs multiple shell commands asynchronously and captures their outputs concurrently using asyncio.\n\n### Task\n1. Write an asynchronous function `run_commands(commands: List[str]) -... | 0.681278 | Docs: Python310_28215 | C | [
"run_command",
"run_commands"
] | 2 | [
[
"run_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d4006f5f3641463500846d01e318e1e3a8fd97f1 | 796ff35aef5a134cd0d27f4e35c916fe4bcbde80 | |||
v1.0 | complete | Docs | Docs: Python310_28627_C | from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.client import ServerProxy
# Server-side implementation
def add_numbers(x, y):
"""
Returns the sum of x and y.
"""
return x + y
def start_server():
"""
Starts the XML-RPC server at localhost:8000 which has the add_numbers function
reg... | # Server-side implementation
from xmlrpc.server import SimpleXMLRPCServer
def add_numbers(x, y):
"""
Returns the sum of x and y.
"""
return x + y
def start_server():
server = SimpleXMLRPCServer(("localhost", 8000))
print("Server started at localhost:8000")
server.register_function(add_numb... | # Unit tests for the add_numbers function in the server
from solution import add_numbers
def test_add_numbers_positive():
assert add_numbers(2, 3) == 5
def test_add_numbers_with_zero():
assert add_numbers(0, 5) == 5
assert add_numbers(5, 0) == 5
def test_add_numbers_negative():
assert add_numbers(-1,... | [
{
"docstring": "Returns the sum of x and y.",
"function_declaration": "def add_numbers(x, y):",
"function_name": "add_numbers",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def start_server():",
"function_name": "start_server",
"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": "# Server-side implementation\nfrom xmlrpc.server import SimpleXMLRPCServer\n\ndef add_numbers(x, y):\n \"\"\"\n Function to add two numbers and return the result.... | trial_gpt4o_1 | {
"original_instruction": "### XML-RPC Communication: Client-Server Implementation\n\n**Objective:** \nYour task is to implement an XML-RPC server and a corresponding client to demonstrate your understanding of remote procedure calls using Python's `xmlrpc` package. The communication should involve at least one func... | 0.44017 | Docs: Python310_28627 | C | [
"add_numbers",
"start_server",
"main"
] | 3 | [
[
"start_server",
"add_numbers"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ae33574f98d9d9a214f55cb5aa4658b6e6baffd8 | 3f8a6259d37fdecb01dbd0e192bfd4e5273c726b | |||
v1.0 | complete | Docs | Docs: Python310_27911_C | import concurrent.futures
import math
from typing import List, Dict
def compute_factorials(numbers: List[int], use_threads: bool = True) -> Dict[int, int]:
""" Compute the factorials of a list of numbers concurrently.
Parameters:
numbers (List[int]): A list of integers (1 <= numbers[i] <= 20)
use_... | import concurrent.futures
import math
from typing import List, Dict
def factorial(num: int) -> int:
return math.factorial(num)
def compute_factorials(numbers: List[int], use_threads: bool = True) -> Dict[int, int]:
result = {}
executor_class = concurrent.futures.ThreadPoolExecutor if use_threads else... | from solution import compute_factorials
def test_factorials_with_threads():
numbers = [5, 10, 15]
result = compute_factorials(numbers, use_threads=True)
expected = {5: 120, 10: 3628800, 15: 1307674368000}
assert result == expected
def test_factorials_with_processes():
numbers = [5, 10, 15]
res... | [] | [
0,
0,
0,
1,
1,
0,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict\nimport concurrent.futures\nfrom math import factorial\n\ndef compute_factorials(numbers: List[int], use_threads: bool = True) -> Dict[int... | trial_gpt4o_4 | {
"original_instruction": "### Question: Parallel Task Execution with `concurrent.futures`\n\nYou are a software engineer at a company that processes large datasets. One of your tasks is to implement an efficient solution to calculate the factorial of a list of numbers concurrently, leveraging both multithreading and... | 0.822698 | Docs: Python310_27911 | C | [
"factorial",
"compute_factorials"
] | 2 | [
[
"compute_factorials",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2a9235ac79011eae3c6f2bc7d05dfc3889264a20 | 5101e31de9b79cee7dea3dd12be0d29387f1d8c7 | |||
v1.0 | complete | Docs | Docs: Scikit_27726_C | import numpy as np
from typing import Tuple, Dict
def kmeans_clustering(X: np.ndarray, n_clusters: int, init: str, max_iter: int, random_state: int) -> Tuple[np.ndarray, np.ndarray, float]:
"""
Perform K-Means clustering on the dataset X.
Parameters:
- X (np.ndarray): Dataset of shape (n_samples, ... | import numpy as np
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn import metrics
from typing import Tuple, Dict
def kmeans_clustering(X: np.ndarray, n_clusters: int, init: str, max_iter: int, random_state: int) -> Tuple[np.ndarray, np.ndarray, float]:
"""
Perform K-Means ... | import numpy as np
from sklearn.datasets import load_iris
from sklearn.datasets import make_blobs
from sklearn.preprocessing import StandardScaler
from solution import kmeans_clustering, evaluate_clustering
def test_kmeans_clustering():
X, _ = make_blobs(n_samples=100, centers=3, n_features=2, random_state=42)
... | [
{
"docstring": "Perform K-Means clustering on the dataset X.\n\nParameters:\n- X (np.ndarray): Dataset of shape (n_samples, n_features).\n- n_clusters (int): Number of clusters.\n- init (str): Initialization method, either 'random' or 'k-means++'.\n- max_iter (int): Maximum number of iterations.\n- random_state... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import adjusted_rand_score, normalized_mutual_info_s... | trial_gpt4o_2 | {
"original_instruction": "**Question: Implementing and Analyzing K-Means Clustering on Synthetic and Real Datasets**\n\n### Objective:\nTo assess the understanding of K-Means clustering, data preprocessing, dimensionality reduction, and evaluation metrics in the scikit-learn package.\n\n### Task:\n1. **Implement K-M... | 0.867614 | Docs: Scikit_27726 | C | [
"kmeans_clustering",
"evaluate_clustering"
] | 2 | [
[
"evaluate_clustering",
"kmeans_clustering"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | fd6c4b3ad5a601da1537020cbefd20a40f7ea8db | a6beefbc605e3cab5a1c02d7935a16bb663f9183 | |||
v1.0 | complete | Docs | Docs: Python310_28738_C | import zipapp
import os
from typing import Optional
def bundle_project_to_zipapp(source_dir: str, output_file: str, interpreter: Optional[str], main_function: str, compress: bool = False):
"""
Bundles a given Python project directory into an executable zip archive.
Args:
source_dir (str): Path... | import os
import zipapp
def create_main_py(source_dir, main_function):
main_py_path = os.path.join(source_dir, "__main__.py")
module, func = main_function.split(":")
main_py_content = f"""
if __name__ == '__main__':
from {module} import {func}
{func}()
"""
with open(main_py_path, "w") as f:
... | import os
import zipapp
from solution import bundle_project_to_zipapp
def test_bundle_project_to_zipapp():
source_dir = "test_project"
output_file = "test_project.pyz"
interpreter = "/usr/bin/env python3"
main_function = "test_module:test_function"
# Setup: Create a test project directory with... | [
{
"docstring": null,
"function_declaration": "def create_main_py(source_dir, main_function):",
"function_name": "create_main_py",
"parameter_list": "(source_dir, main_function)"
},
{
"docstring": "Bundles a given Python project directory into an executable zip archive.\n\nArgs:\n source_d... | [
1,
0,
1,
0,
1,
0,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport zipapp\nfrom typing import Optional\n\ndef bundle_project_to_zipapp(source_dir: str, output_file: str, interpreter: Optional[str], main_function: str,... | trial_gpt4o_4 | {
"original_instruction": "As an advanced Python programmer, you are required to create a tool that automates the process of bundling a given Python project directory into an executable zip archive. This tool must also add a specified Python interpreter shebang line and handle potential compression of the archive.\n\... | 0.733809 | Docs: Python310_28738 | C | [
"create_main_py",
"bundle_project_to_zipapp"
] | 2 | [
[
"bundle_project_to_zipapp",
"create_main_py"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4ed5283a8217cc26ee952aab9841bf8e091c9496 | 166dee0199167d80d7f32e94090703f511c40736 | |||
v1.0 | complete | Docs | Docs: Python310_27865_C | import re
def extract_contacts(info_string: str) -> list:
"""Extract and format contact information from a given string.
The input string is expected to contain contact information of several individuals with the following format:
- Each individual's information is separated by a semicolon `;`.
- ... | import re
def normalize_phone(phone):
# Remove everything that is not a digit
phone = re.sub(r'\D', '', phone)
# Format the phone number to 123-456-7890
return f"{phone[:3]}-{phone[3:6]}-{phone[6:]}"
def extract_contacts(info_string: str) -> list:
contacts = []
individuals = info_string.split(... | from solution import extract_contacts
def test_extract_contacts_standard_case():
info_string = "John Doe,john.doe@example.com,123-456-7890;Jane Smith,jane_smith@mail.com,(123) 456 7890"
result = extract_contacts(info_string)
assert result == [
{'name': 'John Doe', 'email': 'john.doe@example.com', '... | [
{
"docstring": null,
"function_declaration": "def normalize_phone(phone):",
"function_name": "normalize_phone",
"parameter_list": "(phone)"
},
{
"docstring": null,
"function_declaration": "def extract_contacts(info_string):",
"function_name": "extract_contacts",
"parameter_list":... | [
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 re\n\ndef normalize_phone(phone):\n # Remove everything that is not a digit\n phone = re.sub(r'\\D', '', phone)\n # Format the phone number to 123-456-7... | trial_gpt4o_0 | {
"original_instruction": "### Problem: Extract and Format Contact Information\n\nYou are given a string containing contact information of several individuals. The format of the string is as follows:\n\n- Each individual's information is separated by a semicolon `;`.\n- Each individual has a name, an email address, a... | 0.593215 | Docs: Python310_27865 | C | [
"normalize_phone",
"extract_contacts"
] | 2 | [
[
"extract_contacts",
"normalize_phone"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5f686b99ca39da67a638cdcee89d9da1e31e7563 | d3067eceba1c7b2e90756acae7524906ead4f03c | |||
v1.0 | complete | Docs | Docs: Python310_28884_C | import signal
import os
def setup_signal_handler():
""" Set up a signal handler to catch SIGUSR1 and perform a custom action when the signal is received.
The custom action is to print "User-defined signal received".
Example:
>>> setup_signal_handler()
User-defined signal received
""" | import signal
import os
def signal_handler(signum, frame):
print("User-defined signal received")
def setup_signal_handler():
# Set up the signal handler for SIGUSR1
signal.signal(signal.SIGUSR1, signal_handler)
# Sending SIGUSR1 to the current process
os.kill(os.getpid(), signal.SIGUSR1) | import signal
import os
import subprocess
def test_signal_handler(capsys):
# Function to call within a subprocess to avoid interference with pytest execution
setup_signal_handler()
# Capture output
captured = capsys.readouterr()
assert "User-defined signal received" in captured.out | [
{
"docstring": null,
"function_declaration": "def signal_handler(signum, frame):",
"function_name": "signal_handler",
"parameter_list": "(signum, frame)"
},
{
"docstring": null,
"function_declaration": "def setup_signal_handler():",
"function_name": "setup_signal_handler",
"param... | [
1,
1,
0,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import signal\nimport os\n\ndef signal_handler(signum, frame):\n print(\"User-defined signal received\")\n\ndef setup_signal_handler():\n # Setting up the signal ... | trial_gpt4o_9 | {
"original_instruction": "You are tasked with implementing a signal handling mechanism in Python. Your objective is to create a function that sets up a signal handler to catch a user-defined signal (`SIGUSR1`) and perform a custom action when this signal is received.\n\n### Function Signature\n```python\ndef setup_s... | 0.431477 | Docs: Python310_28884 | C | [
"signal_handler",
"setup_signal_handler"
] | 2 | [
[
"setup_signal_handler",
"signal_handler"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 3d1d3a01e07a63cd3eb0b9b6055ce84f0b0c454d | afd00ea755d5e9c75de1bb7957da2a7163e78f24 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.