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: Scikit_28625_C | import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import brier_score_loss
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
def plot_calibration_curve(y_true, probas_p... | import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import brier_score_loss
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
def plot_calibration_curve(y_true, probas_p... | import pandas as pd
import numpy as np
from sklearn.datasets import make_classification
from solution import evaluate_model_calibration
def test_evaluate_model_calibration(tmp_path):
# Creating a temporary data file
X, y = make_classification(n_samples=100, n_features=20, n_informative=2, n_redundant=10, rando... | [
{
"docstring": "Plot a calibration curve using the true labels and predicted probabilities. ",
"function_declaration": "def plot_calibration_curve(y_true, probas_pred, label, ax):",
"function_name": "plot_calibration_curve",
"parameter_list": "(y_true, probas_pred, label, ax)"
},
{
"docstrin... | [
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 numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.calibration import CalibratedClassifierCV\nfrom sklearn.metri... | trial_gpt4o_8 | {
"original_instruction": "You are given a binary classification task with a dataset containing feature vectors and corresponding binary labels. Your objective is to train a classifier, evaluate its probability calibration, and improve it if necessary. Follow the steps below to complete this task:\n\n#### Step-by-Ste... | 0.663946 | Docs: Scikit_28625 | C | [
"plot_calibration_curve",
"evaluate_model_calibration"
] | 2 | [
[
"evaluate_model_calibration",
"plot_calibration_curve"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"pandas",
"sklearn"
] | false | 2c2fd91b11f37e1f088be073c86c788560706d86 | ff59ac7bc2ab7cae17e7681abb60ee6b8cc8e154 | |||
v1.0 | complete | Docs | Docs: Python310_28129_C | import math
from typing import List
def calculate_mean(numbers: List[float]) -> float:
"""
Calculate the mean (average) of a given list of numbers.
>>> calculate_mean([1.0, 2.0, 3.0, 4.0, 5.0])
3.0
>>> calculate_mean([10.0, 20.0, 30.0])
20.0
>>> calculate_mean([0.0, 0.0, 0.0])
0.0
... | import math
from typing import List
def calculate_mean(numbers: List[float]) -> float:
"""
Calculate the mean (average) of a given list of numbers.
"""
return sum(numbers) / len(numbers)
def calculate_std_deviation(numbers: List[float]) -> float:
"""
Calculate the standard deviation of a given... | import pytest
from solution import (calculate_mean, calculate_std_deviation, calculate_combination,
calculate_hypotenuse, degrees_to_radians)
def test_calculate_mean():
assert calculate_mean([1.0, 2.0, 3.0, 4.0, 5.0]) == 3.0
assert calculate_mean([10.0, 20.0, 30.0]) == 20.0
assert cal... | [
{
"docstring": "Calculate the mean (average) of a given list of numbers.",
"function_declaration": "def calculate_mean(numbers):",
"function_name": "calculate_mean",
"parameter_list": "(numbers)"
},
{
"docstring": "Calculate the standard deviation of a given list of numbers.",
"function_... | [
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 math\nfrom typing import List\n\ndef calculate_mean(numbers: List[float]) -> float:\n \"\"\"\n Returns the mean (average) of a given list of numbers.\n ... | trial_gpt4o_7 | {
"original_instruction": "### Advanced Coding Assessment: Custom Statistical Calculator\n\n**Objective**: Demonstrate your understanding of the Python `math` module by creating a custom statistical calculator that performs various computations based on given data.\n\n**Problem Statement**:\n\nYou need to implement a... | 0.682295 | Docs: Python310_28129 | C | [
"calculate_mean",
"calculate_std_deviation",
"calculate_combination",
"calculate_hypotenuse",
"degrees_to_radians"
] | 5 | [
[
"calculate_std_deviation",
"calculate_mean"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ac14bb7de9e72ae8d3da2ad2ee57092d21fe4ddf | 881d01517261b3f8984f9e2665387c4939f2cdd2 | |||
v1.0 | complete | Docs | Docs: Python310_28776_C | import asyncio
import logging
from concurrent.futures import ThreadPoolExecutor
def perform_calculations(n):
""" Calculate the sum of squares from 1 to n.
>>> perform_calculations(5)
55
"""
# Implementation needed
async def schedule_calculations(n_vals, loop):
""" Schedule the execution of per... | import asyncio
import logging
from concurrent.futures import ThreadPoolExecutor
# Function to perform CPU-bound calculations
def perform_calculations(n):
logging.debug(f"Performing calculations for n={n}")
return sum(i*i for i in range(1, n+1))
# Function to schedule calculations asynchronously
async def sche... | import pytest
from solution import run_main, perform_calculations
def test_perform_calculations():
assert perform_calculations(5) == 55 # 1^2 + 2^2 + 3^2 + 4^2 + 5^2 = 55
@pytest.mark.asyncio
async def test_schedule_calculations():
loop = asyncio.get_event_loop()
n_vals = [1, 2, 3]
expected_results =... | [
{
"docstring": null,
"function_declaration": "def perform_calculations(n):",
"function_name": "perform_calculations",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def run_main(n_vals):",
"function_name": "run_main",
"parameter_list": "(n_vals)"
}
] | [
1,
0,
1,
1,
1,
0,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport logging\nfrom concurrent.futures import ThreadPoolExecutor\n\n# Function to perform CPU-bound calculations\ndef perform_calculations(n):\n \"\... | trial_gpt4o_9 | {
"original_instruction": "### Question:\n\nYou are tasked with developing a small application that performs CPU-intensive calculations asynchronously, while handling logging and ensuring debugging information is available. Implement the following functions based on the given constraints.\n\n- `perform_calculations(n... | 0.547287 | Docs: Python310_28776 | C | [
"perform_calculations",
"schedule_calculations",
"main",
"run_main"
] | 4 | [
[
"run_main",
"main"
],
[
"schedule_calculations",
"perform_calculations"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 26e3120232e1196f990d40106d16c62fce7f1993 | 8867359ed2a69d9e7e082c215fead90f19b12d6d | |||
v1.0 | complete | Docs | Docs: Python310_28240_C | import pty
import os
import select
def run_and_log_child_process(command: str, logfile: str, stop_keyword: str) -> int:
"""
Run a given command in an interactive child process, log all input and output to a logfile,
and terminate the session when a stop keyword is detected in the child's output.
P... | import pty
import os
import select
def read_and_log(fd, logfile, stop_keyword, timeout=0.1):
with open(logfile, "a") as log:
while True:
rlist, _, _ = select.select([fd], [], [], timeout)
if rlist:
output = os.read(fd, 1024).decode()
log.write(output)... | import os
import pytest
from solution import run_and_log_child_process
def test_run_and_log_child_process(tmpdir):
test_file = os.path.join(tmpdir, "logfile.log")
command = "echo 'test output'"
stop_keyword = "test"
exit_code = run_and_log_child_process(command, test_file, stop_keyword)
assert... | [
{
"docstring": null,
"function_declaration": "def read_and_log(fd, logfile, stop_keyword, timeout=0.1):",
"function_name": "read_and_log",
"parameter_list": "(fd, logfile, stop_keyword, timeout=0.1)"
},
{
"docstring": null,
"function_declaration": "def run_and_log_child_process(command, ... | [
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 pty\nimport os\nimport sys\n\ndef run_and_log_child_process(command: str, logfile: str, stop_keyword: str) -> int:\n \"\"\"\n Run a given command in an int... | trial_gpt4o_2 | {
"original_instruction": "You are tasked with creating a Python script that runs an interactive child process, captures its output, and logs it to a file. Additionally, implement functionality that allows the parent process to send a specific command to the child process and terminate the session once a particular k... | 0.592397 | Docs: Python310_28240 | C | [
"read_and_log",
"run_and_log_child_process"
] | 2 | [
[
"run_and_log_child_process",
"read_and_log"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ad421f1b890bffcbee44eda2797e4219b5bc00c6 | 35a08b33e65f2fc69fa94d46e76ab73c5fc9a115 | |||
v1.0 | complete | Docs | Docs: Pytorch_28196_C | import torch
def generate_tensor(method: str, size: int) -> torch.Tensor:
"""Generate a tensor with the specified method.
Args:
method: A string which can be either "A" (enable fill_uninitialized_memory)
or "B" (disable fill_uninitialized_memory).
size: Integer specifying t... | import torch
import time
def generate_tensor(method: str, size: int) -> torch.Tensor:
if method == "A":
torch.utils.deterministic.fill_uninitialized_memory = True
elif method == "B":
torch.utils.deterministic.fill_uninitialized_memory = False
else:
raise ValueError("Invalid method. ... | import torch
from solution import generate_tensor, measure_time, demonstrate_determinism
def test_generate_tensor_valid():
tensor_a = generate_tensor("A", 1000)
tensor_b = generate_tensor("B", 1000)
assert tensor_a.size(0) == 1000
assert tensor_b.size(0) == 1000
assert isinstance(tensor_a, torch.Te... | [
{
"docstring": null,
"function_declaration": "def generate_tensor(method, size):",
"function_name": "generate_tensor",
"parameter_list": "(method, size)"
},
{
"docstring": null,
"function_declaration": "def measure_time(method, size):",
"function_name": "measure_time",
"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 torch\nimport time\n\ndef generate_tensor(method: str, size: int) -> torch.Tensor:\n if method == \"A\":\n torch.utils.deterministic.fill_uninitialized... | trial_gpt4o_1 | {
"original_instruction": "**Coding Assessment Question**\n\n### Objective\nTo assess your understanding of PyTorch's handling of deterministic algorithms and uninitialized memory, you will write a script that demonstrates the use of the `fill_uninitialized_memory` attribute and measures its impact on program determi... | 0.526914 | Docs: Pytorch_28196 | C | [
"generate_tensor",
"measure_time",
"demonstrate_determinism"
] | 3 | [
[
"measure_time",
"generate_tensor"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | e48b9bac21fbd37f55c93e9a383a7c166557e9eb | 789f7226b780d573ea14cacabc3c3c3150c9190a | |||
v1.0 | complete | Docs | Docs: Python310_29095_C | import sys
import time
def profile(frame, event, arg):
"""Implement your profiler logic here."""
pass
def enable_profiling():
"""Enable profiling by setting the profile function."""
sys.setprofile(profile)
def disable_profiling():
"""Disable profiling and log the results to profile.txt.""... | import sys
import time
# Dictionary to keep track of the start time of each function call
profile_data = {}
def profile(frame, event, arg):
function_name = frame.f_code.co_name
if event == "call":
# Record the start time when a function is called
profile_data[function_name] = time.time()
... | import os
import time
import pytest
from solution import enable_profiling, disable_profiling
def test_function():
time.sleep(1)
def test_function_nested():
time.sleep(1)
test_function()
def test_no_profiling_output_exists_before_enabling():
if os.path.exists("profile.txt"):
os.remove("pro... | [
{
"docstring": null,
"function_declaration": "def profile(frame, event, arg):",
"function_name": "profile",
"parameter_list": "(frame, event, arg)"
},
{
"docstring": null,
"function_declaration": "def enable_profiling():",
"function_name": "enable_profiling",
"parameter_list": "(... | [
0,
0,
1,
0,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nimport time\n\n# Dictionary to store the start time of function calls\ncall_timings = {}\n\n# List to store the profiling information\nprofile_data = []\n\n... | trial_gpt4o_2 | {
"original_instruction": "### Coding Assessment: Implement a Custom Python Profiler using the `sys` module\n\n#### Objective\nYour task is to implement a Python profiling utility that uses the `sys.setprofile` functionality to track function call durations within a given Python script. Profiling is essential for per... | 0.532403 | Docs: Python310_29095 | C | [
"profile",
"enable_profiling",
"disable_profiling"
] | 3 | [
[
"enable_profiling",
"profile"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4c5843ac46769e007adcda44af5806f73e37d6fe | b39886a27ffcd0b7989edb536f52e8ef7a769119 | |||
v1.0 | complete | Docs | Docs: Python310_28070_C | import uuid
def generate_random_uuids(n: int) -> list:
"""Generates n random UUIDs using uuid4 and returns a list of string representations.
>>> len(generate_random_uuids(5)) == 5
True
"""
def generate_named_uuid(namespace: str, name: str, version=5) -> str:
"""Generates a UUID based on the given ... | import uuid
def generate_random_uuids(n: int) -> list:
"""
Generates n random UUIDs using uuid4 and returns a list of string representations.
"""
return [str(uuid.uuid4()) for _ in range(n)]
def generate_named_uuid(namespace: str, name: str, version=5) -> str:
"""
Generates a UUID based on the... | from solution import generate_random_uuids, generate_named_uuid, is_valid_uuid, uuid_attributes
def test_generate_random_uuids():
uuids = generate_random_uuids(5)
assert len(uuids) == 5
for u in uuids:
assert is_valid_uuid(u)
def test_generate_named_uuid_v5():
namespace = 'NAMESPACE_DNS'
n... | [
{
"docstring": "Generates n random UUIDs using uuid4 and returns a list of string representations.",
"function_declaration": "def generate_random_uuids(n):",
"function_name": "generate_random_uuids",
"parameter_list": "(n)"
},
{
"docstring": "Generates a UUID based on the given namespace and... | [
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 uuid\n\ndef generate_random_uuids(n: int) -> list:\n \"\"\"\n Generates `n` random UUIDs using uuid4.\n \"\"\"\n return [str(uuid.uuid4()) for _ in r... | trial_gpt4o_1 | {
"original_instruction": "### UUID Toolkit\n\nYou are tasked with creating a toolkit leveraging the `uuid` module to handle a variety of tasks related to UUID generation, validation, and analysis.\n\n#### Part 1: UUID Generation\n\n1. Write a function `generate_random_uuids(n: int) -> list` that generates `n` random... | 0.512035 | Docs: Python310_28070 | C | [
"generate_random_uuids",
"generate_named_uuid",
"is_valid_uuid",
"uuid_attributes"
] | 4 | [
[
"uuid_attributes",
"is_valid_uuid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ab59215e472f30991c5eaaee0532045c94e3f12c | 4136bd058bfc6ec6322564d0d23d7a528e9f5a49 | |||
v1.0 | complete | Docs | Docs: Python310_28087_C | import asyncio
async def start_chat_server(host: str, port: int):
"""
Implement an asynchronous TCP chat server that can handle multiple clients and broadcast messages to all connected clients.
Args:
host (str): The server's hostname or IP address.
port (int): The port number the server listen... | import asyncio
import sys
clients = []
async def handle_client(reader, writer):
client_addr = writer.get_extra_info('peername')
print(f"New connection from {client_addr}")
clients.append(writer)
try:
while True:
data = await reader.read(100)
if not data:
... | import asyncio
import pytest
from solution import start_chat_server, chat_client
@pytest.fixture
async def chat_server():
server_task = asyncio.create_task(start_chat_server('127.0.0.1', 8888))
await asyncio.sleep(1) # Give server time to start
yield
server_task.cancel()
@pytest.mark.asyncio
async ... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nclients = []\n\nasync def handle_client(reader, writer):\n client_address = writer.get_extra_info('peername')\n print(f\"New client connected: {... | trial_gpt4o_2 | {
"original_instruction": "## Asynchronous TCP Chat Server and Client\n\n### Objective\nImplement an asynchronous TCP chat server and client using the asyncio streams functionality in Python. The server should be able to handle multiple clients, broadcasting messages from any client to all other clients connected to ... | 0.625487 | Docs: Python310_28087 | C | [
"handle_client",
"broadcast",
"start_chat_server",
"chat_client"
] | 4 | [
[
"handle_client",
"broadcast"
],
[
"start_chat_server",
"handle_client"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d89d81fe8f51f21c29874ce85c8aa4b4cf10d4ac | 0881db1b167829d6df183182882c951ec421dfcd | |||
v1.0 | complete | Docs | Docs: Python310_28807_C | import os
from fnmatch import fnmatch
def process_manifest(file_list: list, commands: list) -> list:
"""
Processes a list of file patterns associated with commands to include and
exclude files and returns the final list of files to be included in the
distribution manifest.
Parameters:
- ... | import fnmatch
import os
def process_manifest(file_list, commands):
included_files = set()
for command_tuple in commands:
command = command_tuple[0]
patterns = command_tuple[1]
if command == "include":
for pattern in patterns:
include_files(file_list, p... | from solution import process_manifest
def test_include_exclude():
file_list = [
"src/module1.py",
"src/module2.py",
"src/data/data1.dat",
"src/data/data2.dat",
"scripts/install.sh",
"scripts/uninstall.sh",
"docs/readme.md"
]
commands = [
("inc... | [
{
"docstring": null,
"function_declaration": "def process_manifest(file_list, commands):",
"function_name": "process_manifest",
"parameter_list": "(file_list, commands)"
},
{
"docstring": null,
"function_declaration": "def include_files(file_list, pattern, included_files, base_dir=None):... | [
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport fnmatch\n\ndef process_manifest(file_list, commands):\n inclusion_set = set(file_list) # All files initially considered for inclusion\n\n for c... | trial_gpt4o_2 | {
"original_instruction": "**Objective**: Write a Python function `process_manifest` that processes a list of file patterns associated with commands to include and exclude files and returns the final list of files to be included in the distribution manifest.\n\n**Function Signature**:\n```python\ndef process_manifest... | 0.580193 | Docs: Python310_28807 | C | [
"process_manifest",
"include_files",
"exclude_files",
"prune_dir",
"graft_dir"
] | 5 | [
[
"process_manifest",
"exclude_files"
],
[
"process_manifest",
"graft_dir"
],
[
"process_manifest",
"include_files"
],
[
"process_manifest",
"prune_dir"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 913a67c734b05221de1670497ddf1e54d669095d | e3a60e8d35fed981b18c47fe880632e254ad0cf4 | |||
v1.0 | complete | Docs | Docs: Python310_28755_C | import os
import shutil
import argparse
import re
from datetime import datetime
def organize_files(input_dir, target_dir='organized_files', include_hidden=False):
"""Organizes files in the given directory based on their extensions and generates a summary report.
Args:
input_dir (str): Path to the ... | import os
import shutil
import argparse
import re
from datetime import datetime
import glob
def organize_files(input_dir, target_dir='organized_files', include_hidden=False):
if not os.path.isdir(input_dir):
raise ValueError("Input directory does not exist.")
if not os.path.exists(target_dir):
... | import os
import pytest
import shutil
from solution import organize_files
@pytest.fixture
def setup_test_environment(tmp_path):
input_dir = tmp_path / "input"
target_dir = tmp_path / "output"
input_dir.mkdir()
target_dir.mkdir()
# Create some test files
(input_dir / "file1.txt").write_text... | [
{
"docstring": null,
"function_declaration": "def organize_files(input_dir, target_dir='organized_files', include_hidden=False):",
"function_name": "organize_files",
"parameter_list": "(input_dir, target_dir='organized_files', include_hidden=False)"
},
{
"docstring": null,
"function_decl... | [
1,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport shutil\nimport argparse\nimport datetime\n\ndef organize_files(input_dir, target_dir, include_hidden):\n \"\"\"\n Organizes files in the given i... | trial_gpt4o_6 | {
"original_instruction": "#### File Organizer and Report Generator\n\n### Objective\nDesign and implement a Python program that organizes files in a given directory based on their extensions and generates a summary report. The program should utilize features from the provided `python310` documentation, specifically ... | 0.691275 | Docs: Python310_28755 | C | [
"organize_files",
"create_summary_report"
] | 2 | [
[
"organize_files",
"create_summary_report"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dc4ffe2233a803a1e894623d97ff87267d2ee1e7 | 38da29725e50ac46ad2a4091a5c15579d65519f7 | |||
v1.0 | complete | Docs | Docs: Python310_27937_C | import hmac
import hashlib
def create_hmac(key: bytes, message: str, digestmod: str) -> str:
"""
Creates an HMAC for the given message using the provided secret key and hashing algorithm.
Params:
key (bytes): The secret key.
message (str): The message to be authenticated.
digestmod... | import hmac
import hashlib
def create_hmac(key: bytes, message: str, digestmod: str) -> str:
"""
Creates an HMAC for the given message using the provided secret key and hashing algorithm.
Params:
key (bytes): The secret key.
message (str): The message to be authenticated.
digestmod... | import pytest
from solution import create_hmac, verify_hmac
def test_create_hmac_sha256():
key = b'secret_key'
message = "authenticated_message"
digestmod = "sha256"
hmac_result = create_hmac(key, message, digestmod)
expected_result = hmac.new(key, message.encode(), digestmod).hexdigest()
... | [
{
"docstring": "Creates an HMAC for the given message using the provided secret key and hashing algorithm.\n\nParams:\n key (bytes): The secret key.\n message (str): The message to be authenticated.\n digestmod (str): The hashing algorithm (e.g., 'sha256').\n\nReturns:\n str: The hexadecimal string ... | [
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 hmac\nimport hashlib\n\ndef create_hmac(key: bytes, message: str, digestmod: str) -> str:\n \"\"\"\n Creates an HMAC for a given message using a secret key... | trial_gpt4o_5 | {
"original_instruction": "## Coding Assessment Question\n\nYour task is to implement a secure messaging system that uses the HMAC (Keyed-Hashing for Message Authentication) algorithm to ensure message integrity and authenticity. The implementation should include both the creation of HMACs for messages and their veri... | 0.821117 | Docs: Python310_27937 | C | [
"create_hmac",
"verify_hmac"
] | 2 | [
[
"verify_hmac",
"create_hmac"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 85f5de43bc0ccf21b46d436e4e5898dec722adec | de1b2c3cad716f3d5add1a09b97b771e6fd3c52a | |||
v1.0 | complete | Docs | Docs: Pytorch_28685_C | import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
from torchvision import models, datasets, transforms
from torch.optim import SGD
from torch.utils.data import DataLoader, DistributedSampler
from torch.distributed.fsdp import Fu... | import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torchvision.models import resnet50
from torchvision import datasets, transforms
from torch.optim import SGD
from torch.utils.data import DataLoader, DistributedSampler
from torch.distributed.fsdp import FullyShardedDataParallel as FSD... | import pytest
import torch
import torch.distributed as dist
from torch.multiprocessing import get_start_method, set_start_method
@pytest.fixture(scope="module")
def setup_distributed_mode():
try:
if get_start_method() != "spawn":
try:
set_start_method("spawn")
except... | [
{
"docstring": null,
"function_declaration": "def setup():",
"function_name": "setup",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def cleanup():",
"function_name": "cleanup",
"parameter_list": "()"
},
{
"docstring": null,
"function_declara... | [
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 torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom torchvision.models import resnet50\nfrom torchvision import datasets, transform... | trial_gpt4o_0 | {
"original_instruction": "**Objective:**\nImplement a PyTorch distributed training setup using the `torch.distributed.fsdp.FullyShardedDataParallel` class. Utilize mixed precision and CPU offloading to demonstrate advanced functionalities provided by the `torch.distributed.fsdp` module.\n\n**Problem Statement:**\n\n... | 0.475494 | Docs: Pytorch_28685 | C | [
"setup",
"cleanup",
"train"
] | 3 | [
[
"train",
"cleanup"
],
[
"train",
"setup"
]
] | 2 | [] | false | [] | false | pytest | false | [
"torch",
"torchvision"
] | false | 368c7202f91cdd034499d302c432ac43bfe050b6 | 4561ae1a0e2294d08bc0264b03f9602780511d08 | |||
v1.0 | complete | Docs | Docs: Python310_28882_C | import csv
def register_my_dialect():
"""
Registers a custom CSV dialect with the specified formatting parameters.
"""
pass # Implement this function
def unregister_my_dialect():
"""
Unregisters the custom CSV dialect.
"""
pass # Implement this function
def process_csv(input_file, o... | import csv
def register_my_dialect():
"""
Registers a custom CSV dialect with the specified formatting parameters.
"""
csv.register_dialect(
'my_dialect',
delimiter=';',
quotechar='"',
quoting=csv.QUOTE_MINIMAL
)
def unregister_my_dialect():
"""
Unregisters ... | import csv
import os
from solution import process_csv, register_my_dialect, unregister_my_dialect
def setup_module(module):
with open("input.csv", "w", newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["name", "age", "city"])
writer.writerow(["Alice", "17", "new york"])
... | [
{
"docstring": "Registers a custom CSV dialect with the specified formatting parameters.",
"function_declaration": "def register_my_dialect():",
"function_name": "register_my_dialect",
"parameter_list": "()"
},
{
"docstring": "Unregisters the custom CSV dialect.",
"function_declaration":... | [
1,
1,
1,
0,
1,
0,
1,
0,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\n\ndef register_my_dialect():\n \"\"\"\n Registers a custom CSV dialect with the specified formatting parameters.\n \"\"\"\n csv.register_dialect... | trial_gpt4o_0 | {
"original_instruction": "**CSV File Processing with Custom Dialects**\n\nYou are required to create a Python script that reads data from an existing CSV file, processes the data, and writes the processed data to a new CSV file using custom dialects. Follow the guidelines below to accomplish this task:\n\n1. **Readi... | 0.693745 | Docs: Python310_28882 | C | [
"register_my_dialect",
"unregister_my_dialect",
"process_csv"
] | 3 | [
[
"process_csv",
"register_my_dialect"
],
[
"process_csv",
"unregister_my_dialect"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7719004ca64a13b56d26846929da650827118f67 | f6d07c660e1830b2ec92fd3325c4ced426066351 | |||
v1.0 | complete | Docs | Docs: Python310_26820_C | import json
class Author:
def __init__(self, name, birth_year):
""" Initialize an Author instance with name and birth_year.
Args:
name (str): The name of the author.
birth_year (int): The birth year of the author (1000-9999).
"""
if not name or not isinstance... | import json
class Author:
def __init__(self, name, birth_year):
if not name or not isinstance(name, str):
raise ValueError("Invalid name")
if not (1000 <= birth_year <= 9999):
raise ValueError("Invalid birth year")
self.name = name
self.birth_year = birth_yea... | import pytest
from solution import Author, Book, Library, LibraryEncoder, save_library_to_file, load_library_from_file
def test_author_creation():
author = Author(name="J.K. Rowling", birth_year=1965)
assert author.name == "J.K. Rowling"
assert author.birth_year == 1965
def test_book_creation():
autho... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import json\n\nclass Author:\n def __init__(self, name, birth_year):\n if not name or not isinstance(name, str):\n raise ValueError(\"Invalid name\... | trial_gpt4o_0 | {
"original_instruction": "You are tasked to implement a custom JSON serialization and deserialization system in Python for a complex library management system. The system involves serializing and deserializing instances of various classes to and from JSON format. The classes involved are `Book`, `Author`, and `Libra... | 0.520499 | Docs: Python310_26820 | C | [
"as_author",
"as_book",
"as_library",
"save_library_to_file",
"load_library_from_file"
] | 5 | [
[
"as_book",
"as_author"
],
[
"as_library",
"as_book"
]
] | 2 | [] | false | [
"Author",
"Book",
"Library",
"LibraryEncoder"
] | true | pytest | true | [] | true | 764adf55b681b13a5f101bf536a388dead4a53ca | 3fa0e622afb46e6a66b13230afb27e3aa9d869a7 | |||
v1.0 | complete | Docs | Docs: Python310_28553_C | import asyncio
async def fetch_and_process() -> str:
""" Demonstrates the ability to perform multiple asynchronous tasks concurrently and synchronize their results.
- `fetch_data_source_1`: Takes 2 seconds to fetch data.
- `fetch_data_source_2`: Takes 3 seconds to fetch data.
- `fetch_data_source_... | import asyncio
async def fetch_data_source_1():
await asyncio.sleep(2)
return 'Data from source 1'
async def fetch_data_source_2():
await asyncio.sleep(3)
return 'Data from source 2'
async def fetch_data_source_3():
await asyncio.sleep(1)
return 'Data from source 3'
async def fetch_and_proce... | import asyncio
from solution import fetch_and_process
def test_fetch_and_process():
result = asyncio.run(fetch_and_process())
assert result == 'Data from source 1, Data from source 2, Data from source 3'
def test_fetch_and_process_runs_concurrently():
import time
start_time = time.time()
result =... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def fetch_data_source_1():\n await asyncio.sleep(2)\n return 'Data from source 1'\n\nasync def fetch_data_source_2():\n await asyncio.s... | trial_gpt4o_2 | {
"original_instruction": "### AsyncIO Tasks and Synchronization\n\n**Objective:**\nImplement a function that demonstrates the ability to perform multiple asynchronous tasks concurrently and synchronize their results.\n\n**Task:**\nWrite an asynchronous function `fetch_and_process` that simulates fetching data from t... | 0.528976 | Docs: Python310_28553 | C | [
"fetch_data_source_1",
"fetch_data_source_2",
"fetch_data_source_3",
"fetch_and_process"
] | 4 | [
[
"fetch_and_process",
"fetch_data_source_1"
],
[
"fetch_and_process",
"fetch_data_source_2"
],
[
"fetch_and_process",
"fetch_data_source_3"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 6197a136527e8da483fd4cc99536f7951a9fec7c | 6b3d3b487608192ddb4abdd10bf60130a625e9ea | |||
v1.0 | complete | Docs | Docs: Python310_29084_C | # chat_server.py
import socket
import selectors
def main():
"""
Starts a chat server that can handle multiple clients.
The server listens on localhost and port 12345 for incoming connections.
It uses non-blocking sockets and multiplexing to handle multiple clients simultaneously.
Received message... | # chat_server.py
import socket
import selectors
# Create a selector object
sel = selectors.DefaultSelector()
clients = {}
HOST = 'localhost'
PORT = 12345
def accept(sock):
conn, addr = sock.accept() # Should be ready to read
print('Connected by', addr)
conn.setblocking(False)
sel.register(conn, sel... | # test_chat.py
import socket
import threading
import time
# Test the server setup by attempting to create a connection
def test_server_setup():
server_thread = threading.Thread(target=run_server)
server_thread.daemon = True
server_thread.start()
time.sleep(1) # Wait a moment for the server to start
... | [
{
"docstring": null,
"function_declaration": "def accept(sock):",
"function_name": "accept",
"parameter_list": "(sock)"
},
{
"docstring": null,
"function_declaration": "def read(conn):",
"function_name": "read",
"parameter_list": "(conn)"
},
{
"docstring": null,
"func... | [
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": "# chat_server.py\nimport socket\nimport selectors\n\nsel = selectors.DefaultSelector()\n\ndef accept(sock, mask):\n conn, addr = sock.accept() # Should be ready\n ... | trial_gpt4o_3 | {
"original_instruction": "### Question\n\nYou are tasked with designing a simple chat server and client using Python's `socket` module. The chat server should be capable of handling multiple clients simultaneously and allow them to send and receive messages in real-time. Implement both the server and the client.\n\n... | 0.673552 | Docs: Python310_29084 | C | [
"accept",
"read",
"broadcast",
"main",
"read",
"main"
] | 6 | [
[
"accept",
"read"
]
] | 1 | [] | false | [] | false | pytest | false | [
"chat_server"
] | false | 5d72a9b9a83646eb2bce3b28ed32fa4aaf38ecc8 | 47e22943e7ebb17e93d5c88fd3a517c3914fabc2 | |||
v1.0 | complete | Docs | Docs: Scikit_29091_C | import numpy as np
from sklearn.datasets import load_iris
from sklearn.impute import SimpleImputer, MissingIndicator
from sklearn.pipeline import FeatureUnion, make_pipeline
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
def load_data_with_missing_values():
"""... | import numpy as np
from sklearn.datasets import load_iris
from sklearn.impute import SimpleImputer, MissingIndicator
from sklearn.pipeline import FeatureUnion, make_pipeline
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
# Load the Iris dataset and introduce missin... | from solution import load_data_with_missing_values, create_pipeline, train_and_evaluate
def test_load_data_with_missing_values():
X, y = load_data_with_missing_values()
assert X.shape == (150, 4)
assert y.shape == (150,)
assert np.isnan(X).sum() > 0
def test_create_pipeline():
pipeline = create_pi... | [
{
"docstring": null,
"function_declaration": "def load_data_with_missing_values():",
"function_name": "load_data_with_missing_values",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def create_pipeline():",
"function_name": "create_pipeline",
"parameter_l... | [
0,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"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.impute import SimpleImputer, MissingIndicator\nfrom sklearn.pipeline import FeatureUnion, make_... | trial_gpt4o_9 | {
"original_instruction": "Using the scikit-learn library, you are required to design a data preprocessing pipeline to handle missing data and perform a classification task. \n\n## Dataset\nYou will use the iris dataset and simulate missing values.\n\n## Tasks\n1. **Load the Iris Dataset**: Load the Iris dataset and ... | 0.606359 | Docs: Scikit_29091 | C | [
"load_data_with_missing_values",
"create_pipeline",
"train_and_evaluate"
] | 3 | [
[
"train_and_evaluate",
"create_pipeline"
],
[
"train_and_evaluate",
"load_data_with_missing_values"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 14f14f0351ed5fa4780a00d0768f888e49ebeade | 409f38053139df62c758e431bf076dc62d3b1d83 | |||
v1.0 | complete | Docs | Docs: Python310_29248_C | def fibonacci_sequence(n):
"""
Generator to return Fibonacci sequence up to n terms
>>> list(fibonacci_sequence(5))
[0, 1, 1, 2, 3]
>>> list(fibonacci_sequence(6))
[0, 1, 1, 2, 3, 5]
"""
# Your code here
def square_sequence(seq_gen):
"""
Generator to return the square of number... | def fibonacci_sequence(n):
"""
Generator to return Fibonacci sequence up to n terms
"""
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
def square_sequence(seq_gen):
"""
Generator to return the square of numbers from the provided sequence generator
"""
for num... | from solution import fibonacci_sequence, square_sequence, sum_of_squares
def test_fibonacci_sequence():
fib_gen = fibonacci_sequence(5)
assert list(fib_gen) == [0, 1, 1, 2, 3]
def test_square_sequence():
fib_gen = fibonacci_sequence(5)
square_gen = square_sequence(fib_gen)
assert list(square_gen) ... | [
{
"docstring": "Generator to return Fibonacci sequence up to n terms",
"function_declaration": "def fibonacci_sequence(n):",
"function_name": "fibonacci_sequence",
"parameter_list": "(n)"
},
{
"docstring": "Generator to return the square of numbers from the provided sequence 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 fibonacci_sequence(n):\n \"\"\"\n Generator that yields the first n terms of the Fibonacci sequence.\n \n Parameters:\n n (int): Number of terms to g... | trial_gpt4o_2 | {
"original_instruction": "**Title:** Implementing and Using Generators in Python\n\n**Objective:**\n\nAssess your understanding of Python generators by implementing custom generator functions and using them in various scenarios. This question will test your ability to handle lazy evaluation, memory efficiency, and w... | 0.670888 | Docs: Python310_29248 | C | [
"fibonacci_sequence",
"square_sequence",
"sum_of_squares"
] | 3 | [
[
"sum_of_squares",
"fibonacci_sequence"
],
[
"sum_of_squares",
"square_sequence"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 59b5a2e0f20982fdef07530a44623b44a52c903c | 640baf552615679887c2449e062c5e38d0d4bb9d | |||
v1.0 | complete | Docs | Docs: Scikit_29165_C | import numpy as np
def train_rbm(data: np.ndarray, n_hidden: int, learning_rate: float, n_iterations: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""
Implement and train a Bernoulli Restricted Boltzmann Machine (RBM) using Stochastic Maximum Likelihood (SML).
Parameters:
data (np.n... | import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def train_rbm(data, n_hidden, learning_rate, n_iterations):
n_samples, n_visible = data.shape
# Initialize weights and biases
np.random.seed(0)
weights = np.random.randn(n_visible, n_hidden) * 0.01
visible_bias = np.zeros(n_vi... | from solution import train_rbm
import numpy as np
def test_rbm_shapes():
data = np.array([
[0, 1, 1, 0, 1],
[1, 0, 1, 1, 0],
[0, 1, 0, 1, 0],
[1, 0, 0, 1, 1]
])
n_hidden = 3
learning_rate = 0.1
n_iterations = 1000
weights, v_bias, h_bias, samples = train_rbm(data... | [
{
"docstring": null,
"function_declaration": "def sigmoid(x):",
"function_name": "sigmoid",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def train_rbm(data, n_hidden, learning_rate, n_iterations):",
"function_name": "train_rbm",
"parameter_list": "(dat... | [
1,
1,
0,
0,
0,
0,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef sigmoid(x):\n \"\"\"\n Sigmoid activation function.\n \"\"\"\n return 1.0 / (1 + np.exp(-x))\n\ndef sample_binary(prob_matrix):\n ... | trial_gpt4o_8 | {
"original_instruction": "### Question: Implementing and Training a Bernoulli Restricted Boltzmann Machine\n\n**Objective**: Implement and train a Bernoulli Restricted Boltzmann Machine (RBM) using the learning algorithm discussed — Stochastic Maximum Likelihood (SML).\n\n**Task**: Write a function `train_rbm(data, ... | 0.546612 | Docs: Scikit_29165 | C | [
"sigmoid",
"train_rbm"
] | 2 | [
[
"train_rbm",
"sigmoid"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | dbccc12814fea93e8e87e0eb9f3f5e6c35e943da | 0ad3637de1d98567bd5b1beed82a3dd259c34820 | |||
v1.0 | complete | Docs | Docs: Python310_28978_C | import aiohttp
import asyncio
from typing import List, Dict, Any
async def fetch_and_process_data(urls: List[str]) -> List[Dict[str, Any]]:
"""Fetch and process data from multiple URLs concurrently.
Args:
urls (List[str]): A list of URLs to fetch data from.
Returns:
List[Dict[str, Any]]: ... | import aiohttp
import asyncio
from typing import List, Dict, Any
async def fetch_data(session: aiohttp.ClientSession, url: str) -> Dict[str, Any]:
async with session.get(url) as response:
data = await response.json()
return {
'id': data.get('id'),
'name': data.get('name'),
... | import pytest
from typing import List, Dict, Any
import asyncio
from aiohttp import web
@pytest.mark.asyncio
async def test_fetch_and_process_data():
# Set up a mock server to provide responses
async def mock_handler(request):
return web.json_response({"id": 123, "name": "Test", "value": 456})
ap... | [] | [
1,
0,
1,
1,
1,
1,
0,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import aiohttp\nimport asyncio\nfrom typing import List, Dict, Any\n\nasync def fetch_data(url: str) -> Dict[str, Any]:\n async with aiohttp.ClientSession() as sessi... | trial_gpt4o_3 | {
"original_instruction": "**Objective:**\n\nYou are tasked with implementing a high-level asynchronous function that fetches and processes data from multiple sources concurrently. This will test your understanding of coroutines, the asyncio library, and its high-level APIs.\n\n**Question:**\n\nYou are given a list o... | 0.668797 | Docs: Python310_28978 | C | [
"fetch_data",
"fetch_and_process_data"
] | 2 | [
[
"fetch_and_process_data",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | c768dfe51f602067acfc336e038bf3f3e0cc599a | c19f9c63f04e961777200d74f69e85b1c50c1541 | |||
v1.0 | complete | Docs | Docs: Pytorch_29219_C | import torch
def batched_relu(x: torch.Tensor) -> torch.Tensor:
"""
Applies the rectified linear unit (ReLU) function to a batch of input tensors.
:param x: A 2D tensor of shape (batch_size, features).
:return: A 2D tensor of the same shape as the input, with ReLU applied element-wise.
Exampl... | import torch
from torch.func import vmap, grad
def batched_relu(x: torch.Tensor) -> torch.Tensor:
"""
Applies the rectified linear unit (ReLU) function to a batch of input tensors.
:param x: A 2D tensor of shape (batch_size, features).
:return: A 2D tensor of the same shape as the input, with ReLU app... | from solution import batched_relu, grad_batched_relu
import torch
def test_batched_relu():
x = torch.tensor([[-1.0, 2.0], [3.0, -4.0], [5.0, -6.0]])
result = batched_relu(x)
expected = torch.tensor([[0.0, 2.0], [3.0, 0.0], [5.0, 0.0]])
assert torch.equal(result, expected)
def test_grad_batched_relu():... | [
{
"docstring": "Applies the rectified linear unit (ReLU) function to a batch of input tensors.\n\n:param x: A 2D tensor of shape (batch_size, features).\n:return: A 2D tensor of the same shape as the input, with ReLU applied element-wise.",
"function_declaration": "def batched_relu(x):",
"function_name"... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef batched_relu(x: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Applies the rectified linear unit (ReLU) function to a batch of input tensors.\n\n ... | trial_gpt4o_2 | {
"original_instruction": "### Question:\n\nYou are tasked with implementing a function in PyTorch using the `torch.func` transformations, ensuring no side effects and adhering to the limitations described.\n\n**Task:**\n\n1. Implement a function `batched_relu` using `vmap` that applies a rectified linear unit (ReLU)... | 0.570625 | Docs: Pytorch_29219 | C | [
"batched_relu",
"grad_batched_relu"
] | 2 | [
[
"grad_batched_relu",
"batched_relu"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | bd56c882f508e405845f0c0ff60175304617c77b | 726903045140129470a1a932f326edb100e173a9 | |||
v1.0 | complete | Docs | Docs: Python310_28797_C | import os
import re
from typing import Any
def replace_env_vars_in_file(file_path: str) -> None:
"""
Reads the file, replaces environment variable placeholders with actual values and writes back to the file.
Placeholders are in the format ${VAR_NAME}.
"""
pass
def search_and_replace(root_dir: str,... | import os
import sys
import re
def replace_env_vars_in_file(file_path):
"""
Reads the file, replaces environment variable placeholders with actual values and writes back to the file.
Placeholders are in the format ${VAR_NAME}.
"""
with open(file_path, 'r') as file:
content = file.read()
... | import os
import tempfile
from solution import replace_env_vars_in_file, search_and_replace
def setup_test_env(directory, filename, content):
"""
Helper function to setup a test file with specified content.
"""
file_path = os.path.join(directory, filename)
with open(file_path, 'w') as file:
... | [
{
"docstring": "Reads the file, replaces environment variable placeholders with actual values and writes back to the file.\nPlaceholders are in the format ${VAR_NAME}.",
"function_declaration": "def replace_env_vars_in_file(file_path):",
"function_name": "replace_env_vars_in_file",
"parameter_list":... | [
0,
1,
1,
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 os\nimport sys\nimport re\n\ndef traverse_and_replace(directory, file_extension):\n \"\"\"\n Recursively traverse the given directory and replace environme... | trial_gpt4o_3 | {
"original_instruction": "#### Objective\nDesign a program using the `os` module to recursively search for a specific file type and replace environment variables in those files with their actual values from the system's environment.\n\n#### Problem Statement\nYou need to create a Python script named `replace_env_var... | 0.499631 | Docs: Python310_28797 | C | [
"replace_env_vars_in_file",
"search_and_replace"
] | 2 | [
[
"search_and_replace",
"replace_env_vars_in_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 65f37fa387eef93c01931b8d08a7ae74aecbcddd | 9d31c68172fe4971869ef47184dffb1ed57dd051 | |||
v1.0 | complete | Docs | Docs: Python310_28812_C | import xml.etree.ElementTree as ET
def parse_books(xml_file):
"""
Parses the given XML file and returns a list of dictionaries, each representing a book with the keys:
id, author, title, genre, price, publish_date, description.
Args:
xml_file (str): Path to the XML file.
Returns:
... | import xml.etree.ElementTree as ET
def parse_books(xml_file):
tree = ET.parse(xml_file)
root = tree.getroot()
books = []
for book in root.findall('book'):
book_data = {
'id': book.attrib['id'],
'author': book.find('author').text,
'title': book.find('title').t... | from solution import parse_books, generate_book_report
def test_parse_books():
books = parse_books('test_books.xml')
assert len(books) == 2
assert books[0]['id'] == 'bk101'
assert books[0]['title'] == "XML Developer's Guide"
assert books[1]['price'] == 5.95
def test_generate_book_report(capsys):
... | [
{
"docstring": null,
"function_declaration": "def parse_books(xml_file):",
"function_name": "parse_books",
"parameter_list": "(xml_file)"
},
{
"docstring": null,
"function_declaration": "def generate_book_report(xml_file):",
"function_name": "generate_book_report",
"parameter_lis... | [
1,
0,
0,
1,
0,
1,
0,
0,
1
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import xml.etree.ElementTree as ET\n\ndef parse_books(xml_file):\n \"\"\"\n Parse the books from the given XML file and return a list of dictionaries.\n \"\"\"... | trial_gpt4o_6 | {
"original_instruction": "## Coding Assessment Question\n\n**Problem Statement:**\n\nYou are given an XML file that contains information about various books in a catalog. Each book has the following structure:\n\n```xml\n<book id=\"bk101\">\n <author>Author Name</author>\n <title>Book Title</title>\n <genre... | 0.507504 | Docs: Python310_28812 | C | [
"parse_books",
"generate_book_report"
] | 2 | [
[
"generate_book_report",
"parse_books"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 21f89d8abf94ee92d770a4dfe2466fd5da4d2f18 | 6a87c5a4f2c9640faf105bd4edc288310c99a0c6 | |||
v1.0 | complete | Docs | Docs: Python310_29446_C | def create_cell(value):
"""Creates a new cell object containing the given value.
>>> cell = create_cell(10)
>>> get_cell_value(cell) == 10
True
"""
def get_cell_value(cell):
"""Returns the value contained in the cell.
>>> cell = create_cell("hello")
>>> get_cell_value(cell) == "hello"
... | def create_cell(value):
"""
Creates a new cell object containing the given value.
"""
class Cell:
"""Represents a simple cell to hold a single value."""
def __init__(self, value):
self.value = value
return Cell(value)
def get_cell_value(cell):
"""
Returns the va... | from solution import create_cell, get_cell_value, set_cell_value, exchange_cell_values
def test_create_and_get_cell_value():
cell = create_cell(10)
assert get_cell_value(cell) == 10
def test_set_cell_value():
cell = create_cell(10)
set_cell_value(cell, 20)
assert get_cell_value(cell) == 20
def te... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def create_cell(value):\n \"\"\"\n Creates a cell object containing the given value.\n \n Args:\n value: Any Python object.\n \n Returns:\n A ce... | trial_gpt4o_2 | {
"original_instruction": "### Advanced Python310 Coding Assessment: Working with Cell Objects\n\n#### Objective\nThis exercise is designed to test your understanding of the `PyCellObject` and its various operations. You will be required to implement a series of functions that manipulate and utilize cell objects as d... | 0.480095 | Docs: Python310_29446 | C | [
"create_cell",
"get_cell_value",
"set_cell_value",
"exchange_cell_values"
] | 4 | [
[
"exchange_cell_values",
"set_cell_value"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 27b009950f14e1d5894d435341771a13800d15cf | 3725d6022f6d8cfcfe84f50f6a81cc70877c8d2d | |||
v1.0 | complete | Docs | Docs: Python310_29500_C | import signal
import time
from datetime import datetime
def timestamp_handler(signum, frame):
""" Signal handler for SIGALRM that prints the current timestamp. """
pass
def sigint_handler(signum, frame):
""" Signal handler for SIGINT that gracefully terminates the program. """
pass
def setup_signal_h... | import signal
import time
from datetime import datetime
def timestamp_handler(signum, frame):
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
def sigint_handler(signum, frame):
print('Received SIGINT. Shutting down gracefully...')
signal.setitimer(signal.ITIMER_REAL, 0) # Disable the interval timer
... | import pytest
import signal
import subprocess
import time
def test_setup_signal_handlers():
proc = subprocess.Popen(['python3', 'solution.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Allow the process to run for a few cycles
time.sleep(7)
# Send SIGINT to the process
proc.send_sign... | [
{
"docstring": null,
"function_declaration": "def timestamp_handler(signum, frame):",
"function_name": "timestamp_handler",
"parameter_list": "(signum, frame)"
},
{
"docstring": null,
"function_declaration": "def sigint_handler(signum, frame):",
"function_name": "sigint_handler",
... | [
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 signal\nimport time\nfrom datetime import datetime\n\ndef timestamp_handler(signum, frame):\n print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n\ndef sigin... | trial_gpt4o_0 | {
"original_instruction": "**Objective:**\n\nDemonstrate your understanding of the `signal` module in Python by implementing a program that involves setting custom signal handlers and using timers.\n\nYou are required to:\n\n1. Implement a custom signal handler for `SIGALRM` that will print the current timestamp each... | 0.545789 | Docs: Python310_29500 | C | [
"timestamp_handler",
"sigint_handler",
"setup_signal_handlers",
"run_timer"
] | 4 | [
[
"setup_signal_handlers",
"sigint_handler"
],
[
"setup_signal_handlers",
"timestamp_handler"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 2cf32526704189c7f8cfc9ebba5aa66a05a3264e | 1c036608db4371b312ed91bb49619d7a5ca03177 | |||
v1.0 | complete | Docs | Docs: Python310_29110_C | import grp
def get_group_by_gid(gid: int) -> dict:
""" Returns group information as a dictionary given a group ID (gid).
>>> get_group_by_gid(1000)
{
"name": "staff",
"passwd": "",
"gid": 1000,
"members": ["alice", "bob"]
}
>>> get_group_by_gid("1000")
Traceback ... | import grp
def get_group_by_gid(gid):
"""
Returns group information as a dictionary given a group ID (gid).
"""
if not isinstance(gid, int):
raise ValueError("gid must be an integer")
try:
group = grp.getgrgid(gid)
return {
"name": group.gr_name,
... | import pytest
from unittest.mock import patch, Mock
from solution import (get_group_by_gid, get_group_by_name, get_all_groups,
filter_groups_by_member, get_users_with_multiple_groups)
@patch('grp.getgrgid')
def test_get_group_by_gid(mock_getgrgid):
mock_group = Mock(gr_name="staff", gr_pass... | [
{
"docstring": "Returns group information as a dictionary given a group ID (gid).",
"function_declaration": "def get_group_by_gid(gid):",
"function_name": "get_group_by_gid",
"parameter_list": "(gid)"
},
{
"docstring": "Returns group information as a dictionary given a group name.",
"fun... | [
1,
1,
0,
0,
1,
0,
1,
1
] | 5 | medium | 0.625 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import grp\n\ndef get_group_by_gid(gid):\n if not isinstance(gid, int):\n raise ValueError(\"gid must be an integer.\")\n try:\n group = grp.getgrgi... | trial_gpt4o_1 | {
"original_instruction": "### Unix Group Analysis Tool\n\n#### Problem Statement\n\nYou are required to implement functions to retrieve, analyze, and manipulate Unix group data using the `grp` module. The functions should cover different aspects, from fetching information about specific groups to summarizing and fil... | 0.57607 | Docs: Python310_29110 | C | [
"get_group_by_gid",
"get_group_by_name",
"get_all_groups",
"filter_groups_by_member",
"get_users_with_multiple_groups"
] | 5 | [
[
"filter_groups_by_member",
"get_all_groups"
],
[
"get_users_with_multiple_groups",
"get_all_groups"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d34603efdb634889339078a4589aadc220c699bc | 7b0ca0a2c9944e85bf3a40aa779bd36fdcf73854 | |||
v1.0 | complete | Docs | Docs: Scikit_28944_C | from typing import List, Tuple, Generator
import numpy as np
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
def stream_data(file_path: str, batch_size: int) -> Generator[Tuple[List[str], List[int]], None, None]:
"""
Generator function that reads fr... | import numpy as np
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
def stream_data(file_path, batch_size):
"""
Generator function that reads from a large file and yields mini-batches of data.
:param file_path: str, File path to the large dataset... | import os
from tempfile import NamedTemporaryFile
from solution import stream_data, train_incremental_classifier
def create_temp_file(content):
"""
Utility function to create a temporary file with the provided content.
"""
temp_file = NamedTemporaryFile(delete=False, mode='w')
temp_file.write(conte... | [
{
"docstring": "Generator function that reads from a large file and yields mini-batches of data.\n\n:param file_path: str, File path to the large dataset.\n:param batch_size: int, The number of examples per mini-batch.\n:return: generator yielding tuples (X_batch, y_batch).",
"function_declaration": "def st... | [
0,
1,
1,
1,
1,
1,
1,
0,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\n\ndef stream_data(file_path, batch_si... | trial_gpt4o_5 | {
"original_instruction": "**Out-of-Core Learning with Scikit-learn**\n\nIn this question, you will implement an out-of-core learning pipeline using scikit-learn. You need to work with a large dataset that cannot fit into memory all at once. You will build a system that streams data, extracts features using the hashi... | 0.62879 | Docs: Scikit_28944 | C | [
"stream_data",
"train_incremental_classifier"
] | 2 | [
[
"train_incremental_classifier",
"stream_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 58642fa80dc71d4b42187a937ac2ad2ead7cd1ab | e566cdedf609c68b2cfe0299e679f66cef82fff6 | |||
v1.0 | complete | Docs | Docs: Pytorch_29234_C | import torch
from torch.func import vmap, grad
def batched_cosine_similarity(batch1: torch.Tensor, batch2: torch.Tensor) -> torch.Tensor:
"""
Computes the cosine similarity between two batches of vectors using vmap for batch processing.
Parameters:
- batch1 (torch.Tensor): A tensor of shape (n, d)... | import torch
from torch.func import vmap, grad
def batched_cosine_similarity(batch1: torch.Tensor, batch2: torch.Tensor) -> torch.Tensor:
"""
Computes the cosine similarity between two batches of vectors using vmap for batch processing.
Parameters:
- batch1 (torch.Tensor): A tensor of shape (n, d)... | import torch
from solution import batched_cosine_similarity, grad_batched_cosine_similarity
def test_batched_cosine_similarity_validity():
batch1 = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
batch2 = torch.tensor([[1.0, 0.0, 0.0], [1.0, 0.0, 0.0]])
expected = torch.tensor([1.0, 0.0])
result = bat... | [
{
"docstring": "Computes the cosine similarity between two batches of vectors using vmap for batch processing.\n\nParameters:\n- batch1 (torch.Tensor): A tensor of shape (n, d) containing n vectors each of dimension d.\n- batch2 (torch.Tensor): A tensor of shape (n, d) containing n vectors each of dimension d.\... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.func import vmap, grad\n\ndef batched_cosine_similarity(batch1: torch.Tensor, batch2: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Calculate... | trial_gpt4o_2 | {
"original_instruction": "### PyTorch Coding Assessment\n\n**Objective**: Demonstrate your ability to utilize PyTorch's `torch.func` functionality, particularly focusing on `vmap` and `grad`, while adhering to the limitations and constraints described.\n\n### Question\n\nYou are to write a function `batched_cosine_s... | 0.555862 | Docs: Pytorch_29234 | C | [
"batched_cosine_similarity",
"grad_batched_cosine_similarity"
] | 2 | [
[
"grad_batched_cosine_similarity",
"batched_cosine_similarity"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 62c561caa72ef0c0e1bedbad8dc3c4920ef941dc | 5bdd5e8db81e986327ccd2c51b6aef5df5bed4eb | |||
v1.0 | complete | Docs | Docs: Python310_29250_C | import asyncio
async def handle_client(reader, writer):
""" Handle incoming client connections and echo received messages.
Args:
reader (StreamReader): Reader object for the incoming connection.
writer (StreamWriter): Writer object for the outgoing connection.
"""
try:
data = await read... | import asyncio
async def handle_client(reader, writer):
try:
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message} from {addr}")
print(f"Echoing: {message}")
writer.write(data)
awai... | import asyncio
import pytest
from solution import handle_client, start_server, run_client
@pytest.mark.asyncio
async def test_server_client_interaction():
host = '127.0.0.1'
port = 8889
message = 'Test Message'
server_task = asyncio.create_task(start_server(host, port))
await asyncio.sleep(1)... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n \"\"\"\n Handle client connections and echo received messages.\n \"\"\"\n try:\n data = ... | trial_gpt4o_1 | {
"original_instruction": "### Complex Network Application using asyncio Event Loop\n\n#### Problem Statement:\n\nYou are tasked with implementing a simplified network monitoring tool using the asyncio event loop functionalities. This tool will act as both a client and a server. The server part listens for incoming c... | 0.662532 | Docs: Python310_29250 | C | [
"handle_client",
"start_server",
"run_client",
"main"
] | 4 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 479be393e0d7bcfbdbc1349efeb47db2da0ad052 | aee922089054613239e0a8fea60a4f965ed2658f | |||
v1.0 | complete | Docs | Docs: Python310_29515_C | import os
import zipapp
from datetime import datetime
def log_message(log_file: str, message: str):
""" Log a message with a timestamp to the specified log file.
Parameters:
- log_file (str): Path for the log file.
- message (str): The log message to write.
Examples:
>>> log_message('... | import os
import zipapp
from datetime import datetime
def log_message(log_file, message):
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with open(log_file, 'a') as f:
f.write(f"{timestamp} - {message}\n")
def create_executable_archive(source, target, interpreter, compress=False, log_file='c... | import os
import pytest
from unittest.mock import patch, mock_open
from solution import create_executable_archive, log_message
def test_create_executable_archive_success(tmpdir):
source = tmpdir.mkdir("source")
source.join("__main__.py").write("print('Hello, World!')")
target = tmpdir.join("myapp.pyz")
... | [
{
"docstring": null,
"function_declaration": "def log_message(log_file, message):",
"function_name": "log_message",
"parameter_list": "(log_file, message)"
},
{
"docstring": "Create an executable Python archive from a source directory.\n\nParameters:\n- source (str): Path to the source direc... | [
0,
0,
0,
0,
0,
0,
1,
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 os\nimport zipapp\nimport logging\nfrom datetime import datetime\n\ndef create_executable_archive(source, target, interpreter, compress=False, log_file='creation... | trial_gpt4o_8 | {
"original_instruction": "You are required to implement a function that wraps the `zipapp.create_archive` functionality and adds some additional validation and logging. The function should:\n- Create an archive from a given directory, adding a shebang line with a specified Python interpreter.\n- Allow optional compr... | 0.722621 | Docs: Python310_29515 | C | [
"log_message",
"create_executable_archive"
] | 2 | [
[
"create_executable_archive",
"log_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fcdab7ab53748fc76e77528f7358f38c6bf02963 | 8ddc18e73e1e79a349a1101fbebdc7b302a0a702 | |||
v1.0 | complete | Docs | Docs: Python310_29351_C | import curses
import curses.panel
def window_manager(stdscr) -> None:
"""
Implement a multi-layer window manager using the 'curses.panel' module.
Create panels with different content and handle their visibility and stacking based on user input.
Instructions:
- Use the keys '1', '2', '3' t... | import curses
import curses.panel
def window_manager(stdscr) -> None:
curses.curs_set(0) # Hide the default cursor
stdscr.nodelay(0) # Make getch() blocking to wait for user input
max_y, max_x = stdscr.getmaxyx()
# Create windows
win1 = curses.newwin(max_y//3, max_x//3, 0, 0)
win2 = cur... | # Unit test code requires interaction which is challenging to automate.
# For testing UI components like this, end-to-end tests with a tool like 'pytest-curses' or manual testing is usually preferred.
# Here's a simple manual test guide:
# 1. Run the program.
# 2. Press '1', '2', '3' to toggle visibility of the panels... | [
{
"docstring": null,
"function_declaration": "def window_manager(stdscr):",
"function_name": "window_manager",
"parameter_list": "(stdscr)"
},
{
"docstring": null,
"function_declaration": "def toggle_visibility(panel):",
"function_name": "toggle_visibility",
"parameter_list": "(p... | [
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 curses\nimport curses.panel\n\ndef window_manager(stdscr):\n curses.curs_set(0) # Hide the default cursor\n stdscr.nodelay(1) # Make getch() non-blockin... | trial_gpt4o_2 | {
"original_instruction": "**Question: Implement a Multi-Layer Window Manager Using curses.panel**\n\n### Objective:\nYou are required to implement a multi-layer window manager using the \"curses.panel\" module. Your task involves creating multiple panels, manipulating their stack order, and handling their visibility... | 0.373767 | Docs: Python310_29351 | C | [
"window_manager",
"toggle_visibility",
"move_panel",
"main"
] | 4 | [
[
"window_manager",
"move_panel"
],
[
"window_manager",
"toggle_visibility"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 08fafef206abf9bc89369d6d6bbdd51d9e2d2f50 | f659b2ae10035a5522655eecddaf17f02467bf82 | |||
v1.0 | complete | Docs | Docs: Python310_29871_C | import asyncio
async def fetch_urls(urls: list, max_retries: int) -> dict:
""" Fetch multiple URLs concurrently with a specified number of retries.
>>> asyncio.run(fetch_urls(["http://example.com/good1", "http://example.com/good2", "http://example.com/bad"], 3))
{"http://example.com/good1": "Data from http... | import asyncio
async def fetch_data(url):
# Simulated fetch logic, replace with actual network request
await asyncio.sleep(1) # Simulate network delay
if url == "http://example.com/bad":
raise Exception(f"Failed to fetch data from {url}")
return f"Data from {url}"
async def fetch_with_retries... | import asyncio
from solution import fetch_urls
async def test_fetch_urls():
urls_to_fetch = [
"http://example.com/good1",
"http://example.com/good2",
"http://example.com/bad"
]
result = await fetch_urls(urls_to_fetch, 3)
assert result == {
"http://example.com/good1": "Da... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def fetch_data(url):\n # This is a simulated fetch function\n await asyncio.sleep(1)\n if \"bad\" in url:\n raise Exception(f\"F... | trial_gpt4o_6 | {
"original_instruction": "**Problem Statement: Concurrent Web Scraping with Retry Logic**\n\nYou are tasked with implementing a Python function using asyncio to perform concurrent web scraping. Your function will take a list of URLs to scrape concurrently and retry fetching each URL up to a specified number of times... | 0.544866 | Docs: Python310_29871 | C | [
"fetch_data",
"fetch_with_retries",
"fetch_urls"
] | 3 | [
[
"fetch_urls",
"fetch_with_retries"
],
[
"fetch_with_retries",
"fetch_data"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 993aaea955156b5d3a7b802e6fa86598f3918403 | 919ee6b13545c9df1ac2b30c72a835808ec5f141 | |||
v1.0 | complete | Docs | Docs: Python310_29559_C | import asyncio
import logging
from typing import List
async def fetch_and_process_data(url: str) -> str:
""" Fetch and process data from the given URL.
Simulates data fetching using asyncio.sleep and offloads CPU-bound processing
(calculating factorial) to a separate thread.
Args:
url (s... | import asyncio
import logging
from typing import List
def factorial(n: int) -> int:
if n == 0:
return 1
else:
return n * factorial(n-1)
async def fetch_and_process_data(url: str) -> str:
# Simulate fetching data
await asyncio.sleep(1)
# Offload CPU-bound task to a separate thr... | import asyncio
import logging
from solution import fetch_and_process_data, main
async def test_fetch_and_process_data():
url = "http://example.com"
result = await fetch_and_process_data(url)
assert "processed with factorial 3628800" in result
async def test_main():
urls = ["http://example.com/data1", ... | [
{
"docstring": null,
"function_declaration": "def factorial(n):",
"function_name": "factorial",
"parameter_list": "(n)"
}
] | [
1,
1,
1,
1,
1,
1,
0,
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 asyncio\nimport logging\nfrom typing import List\n\ndef factorial(n: int) -> int:\n if n == 0:\n return 1\n else:\n return n * factorial(n-1)... | trial_gpt4o_5 | {
"original_instruction": "**Title: Asyncio Concurrency and Debugging**\n\n**Objective**: To assess the student's understanding of asyncio's concurrency mechanisms, enabling debug mode, running blocking code in an executor, and handling potential pitfalls such as unawaited coroutines and unhandled exceptions.\n\n**Pr... | 0.520652 | Docs: Python310_29559 | C | [
"factorial",
"fetch_and_process_data",
"main"
] | 3 | [
[
"fetch_and_process_data",
"factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8ba45b030e531a707f2eff897956a39aa45a71f9 | c9498c0f0dd8ea242019155096774fb741a3bb37 | |||
v1.0 | complete | Docs | Docs: Python310_29564_C | import hashlib
def generate_file_hash(file_path: str, algorithm: str = 'sha256') -> str:
"""
Generate the hash of a file's contents using the specified algorithm.
Args:
- file_path (str): The path to the file to hash.
- algorithm (str): The hashing algorithm to use ('sha256', 'sha512', 'blake2... | import hashlib
def generate_file_hash(file_path: str, algorithm: str = 'sha256') -> str:
"""
Generate the hash of a file's contents using the specified algorithm.
Args:
- file_path (str): The path to the file to hash.
- algorithm (str): The hashing algorithm to use ('sha256', 'sha512', 'blake2... | import pytest
import os
from solution import generate_file_hash, verify_file_integrity
def create_test_file(file_path, content):
with open(file_path, 'w') as file:
file.write(content)
def test_generate_file_hash_sha256():
# Setup
file_path = 'test_file.txt'
content = "Hello, world!"
create... | [
{
"docstring": "Generate the hash of a file's contents using the specified algorithm.\n\nArgs:\n- file_path (str): The path to the file to hash.\n- algorithm (str): The hashing algorithm to use ('sha256', 'sha512', 'blake2b').\n\nReturns:\n- str: The hexadecimal representation of the file's hash.",
"functio... | [
0,
0,
1,
1,
1,
1,
1,
0,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\n\ndef generate_file_hash(file_path: str, algorithm: str = 'sha256') -> str:\n \"\"\"\n Generate the hash for a given file using the specified algo... | trial_gpt4o_9 | {
"original_instruction": "**Problem Statement:**\n\nYou are developing a secure file verification system. The system will generate a hash for each file and store these hashes in a repository. Later, when the files need to be verified, the system will re-compute the hash for each file and compare it with the stored h... | 0.722994 | Docs: Python310_29564 | C | [
"generate_file_hash",
"verify_file_integrity"
] | 2 | [
[
"verify_file_integrity",
"generate_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6236c8bfe6e3b309afd5d22b6ad5f55e0b2c3b17 | b427deda92ed829b26ac3b796bc799e97d83e3ff | |||
v1.0 | complete | Docs | Docs: Python310_28908_C | import os
from concurrent.futures import ThreadPoolExecutor
def analyze_log_files(directory_path: str) -> dict:
""" Analyzes log files in a given directory and gathers statistics.
Processes multiple log files concurrently and outputs the gathered statistics
in a structured format. Each log file contai... | import os
from concurrent.futures import ThreadPoolExecutor
def count_logs_in_file(log_file_path):
"""
Counts the number of logs and categories in a log file.
:param log_file_path: Path to the log file
:return: A dictionary with counts of log levels and total logs
"""
log_counts = {'info': 0, ... | import os
import pytest
from solution import analyze_log_files
def create_log_file(directory, filename, content):
"""
Creates a log file with the specified content.
"""
with open(os.path.join(directory, filename), 'w') as file:
file.write(content)
@pytest.fixture
def setup_log_directory(tmpdir... | [
{
"docstring": "Counts the number of logs and categories in a log file.\n\n:param log_file_path: Path to the log file\n:return: A dictionary with counts of log levels and total logs",
"function_declaration": "def count_logs_in_file(log_file_path):",
"function_name": "count_logs_in_file",
"parameter_... | [
1,
0,
1,
1,
1,
1,
1,
1,
0,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef process_log_file(file_path):\n stats = {\n 'total_logs': 0,\n 'info': 0,\n '... | trial_gpt4o_5 | {
"original_instruction": "### Question: Log File Analyzer\n\n**Objective:**\nWrite a Python program that analyzes log files to gather specific statistics. This program should process multiple log files concurrently and output the gathered statistics in a structured format.\n\n**Details:**\n\nYou are given a director... | 0.542181 | Docs: Python310_28908 | C | [
"count_logs_in_file",
"analyze_log_files"
] | 2 | [
[
"analyze_log_files",
"count_logs_in_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ff1fddcb95a5714d3ed95ce7b2ddbfc46357f415 | 9b2001b8bd8dcb679d1e3fe73c774e84766fe69f | |||
v1.0 | complete | Docs | Docs: Scikit_29728_C | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.metrics import accuracy_score, precision_score, recall_score
import numpy as np
def load_data(file_path: str):
""" Load dataset from the given CSV file path.
>>> load_data('data.csv')
(array([[...]... | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.metrics import accuracy_score, precision_score, recall_score
import numpy as np
# Load data
def load_data(file_path):
data = pd.read_csv(file_path)
X = data.iloc[:, :-1].values
y = data.iloc[:, -1]... | from solution import svm_classification
# Mocking the function for test purposes
import pandas as pd
from sklearn.datasets import make_classification
# Create a mock dataset function
def create_mock_dataset():
X, y = make_classification(n_samples=100, n_features=20, n_classes=2, random_state=42)
mock_data = p... | [
{
"docstring": null,
"function_declaration": "def load_data(file_path):",
"function_name": "load_data",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def custom_poly_kernel(X, Y):",
"function_name": "custom_poly_kernel",
"parameter_list": "(X, Y... | [
0,
0,
0,
0,
0,
1,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import svm\nfrom sklearn.metrics import accuracy_score, precision_score, recall_... | trial_gpt4o_7 | {
"original_instruction": "#### SVM Classification and Custom Kernels\n\nYou are tasked with utilizing scikit-learn's Support Vector Machine (SVM) functionality to:\n1. Perform binary classification on a given dataset.\n2. Implement and use a custom kernel for the SVM classifier.\n\n**Requirements:**\n\n1. **Binary C... | 0.659815 | Docs: Scikit_29728 | C | [
"load_data",
"custom_poly_kernel",
"svm_classification"
] | 3 | [
[
"svm_classification",
"load_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | 6d3c57c95abe05cc94fac6c37a251f1f5206d7f4 | 327efde72cb84f284ad0ef2a74e5c2ba7079267c | |||
v1.0 | complete | Docs | Docs: Pytorch_30044_C | def train_with_metrics(epochs: int) -> None:
"""
Configures metric handlers and logs metrics during a training loop.
Args:
epochs (int): Number of epochs to run the training loop.
Returns:
None: The function does not return any value.
""" | import datetime
def put_metric(name, value, handler):
"""
Mock function to put the metric using the handler
"""
handler(name, value)
def ConsoleMetricHandler(name, value):
"""
Mock ConsoleMetricHandler function
"""
print(f"[{datetime.datetime.now()}] {name}: {value}")
def NullMetr... | import io
import sys
from solution import train_with_metrics
def test_train_with_metrics():
captured_output = io.StringIO()
sys.stdout = captured_output
train_with_metrics(5)
sys.stdout = sys.__stdout__
output = captured_output.getvalue()
expected_output_lines = [
f"training_l... | [
{
"docstring": "Mock function to put the metric using the handler",
"function_declaration": "def put_metric(name, value, handler):",
"function_name": "put_metric",
"parameter_list": "(name, value, handler)"
},
{
"docstring": "Mock ConsoleMetricHandler function",
"function_declaration": "... | [
0,
1,
0,
1,
0,
0,
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 torch\nfrom torchelastic.metrics import ConsoleMetricHandler, NullMetricHandler, put_metric\n\ndef train_with_metrics(epochs: int) -> None:\n \"\"\"\n Conf... | trial_gpt4o_3 | {
"original_instruction": "### PyTorch Distributed Metrics Handler\n\n#### Objective\n\nIn this assessment, your goal is to demonstrate your understanding of metrics handling in a distributed training setup with PyTorch, using the `torchelastic` framework. You will implement a function to configure and use multiple m... | 0.561182 | Docs: Pytorch_30044 | C | [
"put_metric",
"ConsoleMetricHandler",
"NullMetricHandler",
"train_with_metrics"
] | 4 | [
[
"train_with_metrics",
"put_metric"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 972e1e740659b22058c239df094ef8ea2f465999 | 4537a48849a58844f2b3ada3e763c7a93a1ebd5b | |||
v1.0 | complete | Docs | Docs: Python310_29402_C | import socket
import threading
def start_server(server_ip, server_port):
""" Starts a chat server that listens for connections
and broadcasts messages from any client to all clients.
Usage:
>> start_server('127.0.0.1', 5000)
"""
pass
def client_program(server_ip, server_port):
""" Connect... | import socket
import threading
def broadcast_message(message, clients):
for client in clients:
try:
client.sendall(message.encode())
except:
client.close()
clients.remove(client)
def handle_client(client_socket, clients):
while True:
try:
... | import socket
import pytest
import threading
from time import sleep
def test_server_can_accept_clients():
server_ip = '127.0.0.1'
server_port = 5000
server_thread = threading.Thread(target=start_server, args=(server_ip, server_port))
server_thread.daemon = True
server_thread.start()
sleep(1) ... | [
{
"docstring": null,
"function_declaration": "def broadcast_message(message, clients):",
"function_name": "broadcast_message",
"parameter_list": "(message, clients)"
},
{
"docstring": null,
"function_declaration": "def handle_client(client_socket, clients):",
"function_name": "handle... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# chat_server.py\nimport socket\nimport select\n\ndef broadcast(server_socket, message, clients):\n for client in clients:\n if client != server_socket:\n ... | trial_gpt4o_2 | {
"original_instruction": "**Question:** Implement a simple chat server and client using the `socket` module in Python. The server should accept multiple client connections and broadcast messages sent by any client to all connected clients. Both the server and the clients should be able to run on separate machines bu... | 0.68323 | Docs: Python310_29402 | C | [
"broadcast_message",
"handle_client",
"start_server",
"client_program"
] | 4 | [
[
"handle_client",
"broadcast_message"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 97f3d2d388067c3b8de6995dc11281ece88d27f4 | e8388f481f2cca7fff88592faee78918933cad59 | |||
v1.0 | complete | Docs | Docs: Python310_29991_C | import multiprocessing
from typing import List
def is_prime(num: int) -> bool:
""" Check if a number is prime.
>>> is_prime(2)
True
>>> is_prime(4)
False
>>> is_prime(11)
True
"""
def generate_primes(n: int, num_processes: int) -> List[int]:
""" Generates prime numbers up to n ... | import multiprocessing
def is_prime(num):
"""
Checks if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
re... | import multiprocessing
from solution import is_prime, generate_primes
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(29) == True
assert is_prime(30) == False
assert is_prime(1) == False
as... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Generates prime numbers up to n using num_processes processes.",
"function_declaration": "def generate_primes(n, num_proc... | [
1,
0,
1,
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": "from multiprocessing import Pool\n\ndef is_prime(num):\n \"\"\"\n Returns True if num is a prime number else False.\n \"\"\"\n if num <= 1:\n return ... | trial_gpt4o_3 | {
"original_instruction": "Efficient Prime Number Generation using Multiprocessing\n\nIn this task, you are required to generate a list of prime numbers up to a given integer `n` efficiently by utilizing the `multiprocessing` module. This will test your ability to implement process-based parallel programming and appl... | 0.646621 | Docs: Python310_29991 | C | [
"is_prime",
"generate_primes"
] | 2 | [
[
"generate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a71ae33150ec78ca1aac623e2d56ddd9c364053e | 56974df1b63fd53d3bcedc047142e3b89ae3f450 | |||
v1.0 | complete | Docs | Docs: Python310_29839_C | import os
import stat
from netrc import netrc, NetrcParseError
class SecurityRiskAlert(Exception):
pass
def read_netrc(file=None):
"""
Initializes a netrc object from the given file. If no file is provided,
defaults to .netrc in the user's home directory.
>>> read_netrc('path/to/netrc_file') # <ne... | import os
import stat
from netrc import netrc, NetrcParseError
class SecurityRiskAlert(Exception):
pass
def read_netrc(file=None):
"""
Initializes a netrc object from the given file. If no file is provided,
defaults to .netrc in the user's home directory.
"""
if file is None:
file = os... | from solution import read_netrc, get_authenticator, assess_security, netrc_to_string, SecurityRiskAlert
import os
import stat
import pytest
from tempfile import NamedTemporaryFile
def test_read_netrc():
with NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(b"machine example.com login user1 pa... | [] | [
0,
0,
0,
0,
1,
1,
1,
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\nfrom netrc import netrc, NetrcParseError\n\ndef read_netrc(file=None):\n \"\"\"\n Initializes a netrc object. If a file path is provided, it uses that ... | trial_gpt4o_4 | {
"original_instruction": "### **Netrc File Manipulation and Security Assessment**\n\nYou are tasked with creating a Python script to read, manipulate, and enhance the security of a `.netrc` file using the `netrc` class. Your implementation should include the following functionalities:\n\n1. **Initialization and Read... | 0.452218 | Docs: Python310_29839 | C | [
"read_netrc",
"get_authenticator",
"assess_security",
"netrc_to_string"
] | 4 | [
[
"get_authenticator",
"read_netrc"
],
[
"netrc_to_string",
"read_netrc"
]
] | 2 | [] | false | [
"SecurityRiskAlert"
] | true | pytest | true | [] | true | a9e6b9e61f614f7e7fae4a426940e3ad3fce2554 | 6044993b49654cfb8eabe64855ab5176a9f2f3ef | |||
v1.0 | complete | Docs | Docs: Pytorch_30081_C | import torch
from torch.futures import Future, collect_all, wait_all
def asynchronous_computation(nums):
"""
Accepts a list of numbers and returns a list of squared numbers after a delay of 1 second for each computation using torch.futures.Future.
>>> asynchronous_computation([1, 2, 3, 4, 5])
[1, 4, ... | import torch
from torch.futures import Future, collect_all, wait_all
import time
import asyncio
def async_square(num):
"""
Asynchronous function to compute the square of a number after 1 second.
"""
async def compute_square():
await asyncio.sleep(1) # Simulating a 1-second delay
return... | from solution import asynchronous_computation
def test_asynchronous_computation():
nums = [1, 2, 3, 4, 5]
expected = [1, 4, 9, 16, 25]
assert asynchronous_computation(nums) == expected
def test_asynchronous_computation_empty():
nums = []
expected = []
assert asynchronous_computation(nums) == e... | [
{
"docstring": "Asynchronous function to compute the square of a number after 1 second.",
"function_declaration": "def async_square(num):",
"function_name": "async_square",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def asynchronous_computation(nums):",
... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.futures import Future, collect_all, wait_all\nimport time\n\ndef asynchronous_computation(nums):\n futures = []\n\n # Function to simulat... | trial_gpt4o_6 | {
"original_instruction": "#### Objective:\nDemonstrate your understanding of `torch.futures.Future` for handling asynchronous operations in PyTorch by creating and managing multiple `Future` objects.\n\n#### Task:\nWrite a Python function `asynchronous_computation` that accepts a list of numbers. For each number, it... | 0.531137 | Docs: Pytorch_30081 | C | [
"async_square",
"asynchronous_computation"
] | 2 | [
[
"asynchronous_computation",
"async_square"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | f67b36a534acef7313b60b365118603c7a97f36a | 3f314e4bcd09cb7055e262684eeb2ffcc1c879dd | |||
v1.0 | complete | Docs | Docs: Python310_30033_C | import asyncio
from typing import List, Tuple
async def process_jobs(jobs: List[Tuple[int, float]], n: int) -> None:
""" Simulate a job processing system where jobs have varying priorities and specific handling time.
Args:
jobs: A list of tuples where each tuple contains:
- priority: An intege... | import asyncio
from typing import List, Tuple
async def worker(name: str, queue: asyncio.PriorityQueue):
while True:
priority, processing_time = await queue.get()
print(f"{name} started job with priority {priority} for {processing_time} seconds")
await asyncio.sleep(processing_time)
... | import asyncio
import pytest
from solution import process_jobs
def job_processing_test():
jobs = [(1, 1.0), (2, 2.0), (1, 3.0), (3, 4.0)]
n = 2
async def run_test():
await process_jobs(jobs, n)
asyncio.run(run_test())
def test_jobs_processed_correctly():
jobs = [(1, 0.1), (2, 0.2), (1, 0... | [] | [
0,
1,
0,
1,
1,
0,
0,
0,
1
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def worker(worker_id: int, queue: asyncio.PriorityQueue):\n while True:\n job = await queue.get()\n ... | trial_gpt4o_3 | {
"original_instruction": "### Advanced Asyncio Queue Operations\n\n**Objective:**\n\nImplement a solution that demonstrates advanced usage of `asyncio.Queue` and its variants (`PriorityQueue`, `LifoQueue`). Your task is to simulate a job processing system where jobs have varying priorities and specific handling time... | 0.694212 | Docs: Python310_30033 | C | [
"worker",
"process_jobs"
] | 2 | [
[
"process_jobs",
"worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6aa479900b8928594b39c5eb462551e9b551dde4 | 8b23a5b31e755b2afa56bb5c8266813c5823ac1d | |||
v1.0 | complete | Docs | Docs: Python310_29704_C | import telnetlib
def connect_to_server(host: str, port: int, timeout: int) -> telnetlib.Telnet:
""" Connects to a Telnet server.
Args:
host (str): The server hostname or IP address.
port (int): The server port number.
timeout (int): The connection timeout in seconds.
Returns:
... | import telnetlib
import time
def connect_to_server(host: str, port: int, timeout: int) -> telnetlib.Telnet:
tn = telnetlib.Telnet()
tn.open(host, port, timeout)
return tn
def login(tn: telnetlib.Telnet, username: str, password: str) -> bool:
try:
tn.read_until(b"login: ")
tn.write(user... | from unittest.mock import Mock, patch
from solution import connect_to_server, login, execute_commands, set_debug_level, fault_tolerant_connection
@patch('telnetlib.Telnet.open')
def test_connect_to_server(mock_open):
tn = connect_to_server('localhost', 23, 10)
mock_open.assert_called_with('localhost', 23, 10)
... | [
{
"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",
... | [
0,
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import telnetlib\nimport time\n\ndef connect_to_server(host: str, port: int, timeout: int) -> telnetlib.Telnet:\n tn = telnetlib.Telnet()\n tn.open(host, port, ti... | trial_gpt4o_7 | {
"original_instruction": "<|Analysis Begin|>\n\nThe provided documentation explains the functionality of the `telnetlib` module, which is used to implement a Telnet client in Python. It discusses the `Telnet` class, its initialization, and the methods available for performing various Telnet operations. Key methods i... | 0.528933 | Docs: Python310_29704 | C | [
"connect_to_server",
"login",
"execute_commands",
"set_debug_level",
"fault_tolerant_connection"
] | 5 | [
[
"fault_tolerant_connection",
"connect_to_server"
],
[
"fault_tolerant_connection",
"execute_commands"
],
[
"fault_tolerant_connection",
"login"
],
[
"fault_tolerant_connection",
"set_debug_level"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 26e864aba8168c159e420af92128afa331ae3dae | cf5ad1d3ed9555de1e358ace24f1e4945053b740 | |||
v1.0 | complete | Docs | Docs: Python310_29699_C | import signal
class TimeoutError(Exception):
pass
def _handle_timeout(signum, frame):
raise TimeoutError("Function execution exceeded the timeout")
def run_with_timeout(func, args, timeout):
"""
Executes a function with a given timeout.
Parameters:
func (callable): The function to execut... | import signal
class TimeoutError(Exception):
pass
def _handle_timeout(signum, frame):
raise TimeoutError("Function execution exceeded the timeout")
def run_with_timeout(func, args, timeout):
"""
Executes a function with a given timeout.
Parameters:
func (callable): The function to execut... | import pytest
import time
from solution import run_with_timeout, TimeoutError
def long_running_function(x, y):
time.sleep(x)
return x + y
def quick_function(x, y):
return x + y
def test_run_with_timeout_success():
assert run_with_timeout(quick_function, (2, 3), 5) == 5
def test_run_with_timeout_exce... | [] | [
0,
0,
0,
1,
0,
1,
1,
1,
0
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import signal\n\ndef _timeout_handler(signum, frame):\n raise TimeoutError(\"Function execution exceeded the timeout\")\n\ndef run_with_timeout(func, args, timeout):... | trial_gpt4o_8 | {
"original_instruction": "**Title: Implementing a Timeout for a Long-Running Function with Signal Handling**\n\n**Objective:**\n\nImplement a function that limits the execution time of another function using the `signal` module. If the execution exceeds the specified time, an exception should be raised. This require... | 0.569514 | Docs: Python310_29699 | C | [
"_handle_timeout",
"run_with_timeout"
] | 2 | [
[
"run_with_timeout",
"_handle_timeout"
]
] | 1 | [] | false | [
"TimeoutError"
] | true | pytest | true | [] | true | 5105ace33f965e95aad54e5da1ed938c79346946 | f43e177bab903de9d116b3804379851b3d4bb54c | |||
v1.0 | complete | Docs | Docs: Pytorch_29644_C | import torch
import timeit
# Synchronous matrix multiplication
def synchronous_mm(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""
Perform synchronous matrix multiplication.
Args:
x: torch.Tensor - First matrix.
y: torch.Tensor - Second matrix.
Returns:
torch.Tensor - The re... | import torch
import timeit
# Synchronous matrix multiplication
def synchronous_mm(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""
Perform synchronous matrix multiplication.
Args:
x: torch.Tensor - First matrix.
y: torch.Tensor - Second matrix.
Returns:
torch.Tensor - The re... | import torch
from solution import synchronous_mm, asynchronous_mm
def test_synchronous_mm():
x = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
y = torch.tensor([[5.0, 6.0], [7.0, 8.0]])
expected = torch.tensor([[19.0, 22.0], [43.0, 50.0]])
result = synchronous_mm(x, y)
assert torch.allclose(result, expect... | [
{
"docstring": "Perform synchronous matrix multiplication.\n\nArgs:\nx: torch.Tensor - First matrix.\ny: torch.Tensor - Second matrix.\n\nReturns:\ntorch.Tensor - The result of matrix multiplication.",
"function_declaration": "def synchronous_mm(x, y):",
"function_name": "synchronous_mm",
"parameter... | [
1,
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport timeit\n\n# Synchronous matrix multiplication\ndef synchronous_mm(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Perform synch... | trial_gpt4o_0 | {
"original_instruction": "### PyTorch Parallel Processing Assessment\n\n#### Objective:\nImplement a function using PyTorch that demonstrates the use of both synchronous and asynchronous operations, leveraging inter-op and intra-op parallelism. You will need to configure the number of threads and measure the perform... | 0.51721 | Docs: Pytorch_29644 | C | [
"synchronous_mm",
"compute_mm",
"asynchronous_mm",
"experiment"
] | 4 | [
[
"asynchronous_mm",
"compute_mm"
],
[
"experiment",
"asynchronous_mm"
],
[
"experiment",
"synchronous_mm"
]
] | 3 | [] | false | [] | false | pytest | true | [
"torch"
] | false | e8b1a1d8afdbd2cb1251186466b3c542da5fac85 | e6b62fb9d10a374d75e08752b055ebc08851cb59 | |||
v1.0 | complete | Docs | Docs: Python310_29995_C | import warnings
from contextlib import contextmanager
def trigger_warning(warning_type: str, message: str) -> None:
"""
Triggers a warning of the specified type with a custom message.
:param warning_type: Type of warning to trigger.
:param message: Custom warning message.
"""
pass
def co... | import warnings
from contextlib import contextmanager
def trigger_warning(warning_type: str, message: str) -> None:
"""
Triggers a warning of the specified type with a custom message.
:param warning_type: Type of warning to trigger.
:param message: Custom warning message.
"""
warning_types... | import pytest
from solution import trigger_warning, configure_warning_filter, suppress_warnings, test_warning_capture
def test_trigger_warning_user():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
trigger_warning("user", "This is a user warning")
assert len... | [
{
"docstring": "Triggers a warning of the specified type with a custom message.\n\n:param warning_type: Type of warning to trigger.\n:param message: Custom warning message.",
"function_declaration": "def trigger_warning(warning_type, message):",
"function_name": "trigger_warning",
"parameter_list": ... | [
0,
1,
0,
0,
0,
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 warnings\n\ndef trigger_warning(warning_type: str, message: str) -> None:\n \"\"\"\n Triggers a warning of the specified type with the provided message.\n ... | trial_gpt4o_1 | {
"original_instruction": "### Warning Control and Testing in Python\n\n**Objective**:\nTo assess your understanding of the `warnings` module in Python, particularly how to handle, filter, and test runtime warnings.\n\n**Problem Statement**:\n\nYou are developing a Python package, and you want to ensure that your pac... | 0.530712 | Docs: Python310_29995 | C | [
"trigger_warning",
"configure_warning_filter",
"suppress_warnings",
"test_warning_capture"
] | 4 | [
[
"test_warning_capture",
"trigger_warning"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ce7cf0185fead8ff5e3300e8e21d0b8b47c64011 | 92b53b912e47695ebde43516c358af1c8f51e371 | |||
v1.0 | complete | Docs | Docs: Python310_29857_C | import crypt
import hmac
from typing import Dict
# In-memory storage for user data, simulate the database.
user_db: Dict[str, str] = {}
def register_user(username: str, password: str) -> None:
"""
Registers a new user by hashing the provided password and storing the username with the hashed password.
... | import crypt
import hmac
from typing import Dict
# In-memory storage for user data, simulate the database.
user_db: Dict[str, str] = {}
def register_user(username: str, password: str) -> None:
"""
Registers a new user by hashing the provided password and storing the username with the hashed password.
"""
... | import pytest
from solution import register_user, authenticate_user, change_password
def setup_module(module):
"""
Setup method for the test module.
"""
global user_db
user_db = {}
def test_register_and_authenticate_user():
register_user('alice', 'wonderland123')
assert authenticate_user('... | [
{
"docstring": "Registers a new user by hashing the provided password and storing the username with the hashed password.",
"function_declaration": "def register_user(username, password):",
"function_name": "register_user",
"parameter_list": "(username, password)"
},
{
"docstring": "Authentic... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import crypt\nimport hmac\n\n# In-memory user storage\nuser_store = {}\n\ndef get_strongest_available_hash():\n \"\"\"\n Returns the strongest available hash meth... | trial_gpt4o_9 | {
"original_instruction": "### Password Authentication System with Crypt Module\n\nYou are required to implement a password authentication system using the legacy `crypt` module in Python. This system should:\n1. Register new users by storing their username and hashed password.\n2. Authenticate existing users by comp... | 0.633655 | Docs: Python310_29857 | C | [
"register_user",
"authenticate_user",
"change_password"
] | 3 | [
[
"change_password",
"authenticate_user"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 52a5de3114d560e102008ee420190a8b9583ac17 | feff83769defaed4cc8325fc8b17ca1f78c6a7e7 | |||
v1.0 | complete | Docs | Docs: Python310_30203_C | import socket
import select
def setup_server(port):
"""
Create and set up the server socket to listen for incoming connections.
"""
pass
def accept_connections(server_socket, inputs):
"""
Accept new client connection and add it to the list of input sockets.
"""
pass
def broadcast_mess... | import socket
import select
def setup_server(port):
"""
Create and set up the server socket to listen for incoming connections.
"""
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('0.0.0.0'... | import socket
import threading
def test_server_startup():
"""
Test the server startup.
"""
server_thread = threading.Thread(target=run_server, args=(12345,), daemon=True)
server_thread.start()
test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
test_socket.connect(... | [
{
"docstring": "Create and set up the server socket to listen for incoming connections.",
"function_declaration": "def setup_server(port):",
"function_name": "setup_server",
"parameter_list": "(port)"
},
{
"docstring": "Accept new client connection and add it to the list of input sockets.",
... | [
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 socket\nimport select\n\ndef setup_server(port):\n server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_socket.setsockopt(socket.SOL_... | trial_gpt4o_9 | {
"original_instruction": "#### Objective\nImplement a server that can handle multiple client connections using the `select` module in Python 3.10. The server must be able to read messages from clients and broadcast these messages to all connected clients (except the sender). This will test the student's ability to m... | 0.695755 | Docs: Python310_30203 | C | [
"setup_server",
"accept_connections",
"broadcast_message",
"run_server"
] | 4 | [
[
"run_server",
"accept_connections"
],
[
"run_server",
"broadcast_message"
],
[
"run_server",
"setup_server"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 8f781308e5ffb27c5509b098f604295d41bd287f | d0d76b799bcdddd42dde93bf36f513721b418aef | |||
v1.0 | complete | Docs | Docs: Pandas_29312_C | from pandas.api.extensions import ExtensionArray, ExtensionDtype, register_extension_dtype
import numpy as np
import pandas as pd
class HalfFloatDtype(ExtensionDtype):
"""Define the HalfFloat dtype class, sub-classing ExtensionDtype"""
# Implementation of properties like name, type, and na_value
class Hal... | from pandas.api.extensions import ExtensionArray, ExtensionDtype, register_extension_dtype
import numpy as np
import pandas as pd
class HalfFloatDtype(ExtensionDtype):
name = 'HalfFloat'
type = np.float64
na_value = np.nan
@classmethod
def construct_array_type(cls):
return HalfFloatAr... | def test_half_float_array_initialization():
data = [0.5, 1.0, 2.5, np.nan]
arr = HalfFloatArray(data)
assert len(arr) == 4
assert arr[0] == 0.5
assert np.isnan(arr[3])
def test_half_float_dtype():
assert HalfFloatDtype().name == 'HalfFloat'
assert isinstance(HalfFloatDtype().na_value, floa... | [] | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from pandas.api.extensions import ExtensionArray, ExtensionDtype, register_extension_dtype\nimport numpy as np\nimport pandas as pd\n\ndef round_to_half(x):\n \"\"\"... | trial_gpt4o_5 | {
"original_instruction": "#### Objective:\nTo assess students' understanding of pandas extensions by implementing and utilizing custom ExtensionArray and associated features.\n\n#### Task:\n\nYou need to implement a custom pandas ExtensionArray to handle a simple data type and integrate it into a pandas DataFrame. T... | 0.600991 | Docs: Pandas_29312 | C | [
"generate_half_float_data",
"create_half_float_dataframe"
] | 2 | [
[
"create_half_float_dataframe",
"generate_half_float_data"
]
] | 1 | [] | false | [
"HalfFloatDtype",
"HalfFloatArray",
"HalfFloatDtype"
] | true | pytest | false | [
"numpy",
"pandas"
] | false | cc33ccea008f7a02679d4250dec314851acc1863 | 18e794b60acd74d6281574201ec7de4e54af8f83 | |||
v1.0 | complete | Docs | Docs: Python310_30026_C | import asyncio
import logging
import random
from typing import Dict
from concurrent.futures import ThreadPoolExecutor
async def fetch_data() -> int:
""" Simulate a network request by sleeping for a random number of seconds between 1 and 5
and then return a random integer between 1 and 100.
Returns:
... | import asyncio
import logging
import random
from concurrent.futures import ThreadPoolExecutor
async def fetch_data():
await asyncio.sleep(random.randint(1, 5))
return random.randint(1, 100)
def compute_factorial(n):
if n == 1:
return 1
else:
return n * compute_factorial(n - 1)
async d... | import asyncio
import logging
from solution import fetch_data, compute_factorial, process_tasks
def test_fetch_data():
loop = asyncio.get_event_loop()
result = loop.run_until_complete(fetch_data())
assert 1 <= result <= 100
def test_compute_factorial():
assert compute_factorial(1) == 1
assert comp... | [
{
"docstring": null,
"function_declaration": "def compute_factorial(n):",
"function_name": "compute_factorial",
"parameter_list": "(n)"
}
] | [
1,
1,
1,
1,
1,
0,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport logging\nimport random\nfrom concurrent.futures import ThreadPoolExecutor\n\nasync def fetch_data():\n await asyncio.sleep(random.randint(1, 5... | trial_gpt4o_0 | {
"original_instruction": "#### Objective:\nDesign and implement an asynchronous Python program that performs both network I/O operations and CPU-bound computations. The program should utilize the asyncio library effectively, ensuring proper error handling, logging, and debugging.\n\n#### Description:\n\n1. Implement... | 0.653839 | Docs: Python310_30026 | C | [
"fetch_data",
"compute_factorial",
"process_tasks"
] | 3 | [
[
"process_tasks",
"compute_factorial"
],
[
"process_tasks",
"fetch_data"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 483c93c1efc5b15c0b48622225f353df57a2798f | d74ed27020c1183f67951c83693ad08a2815ecf8 | |||
v1.0 | complete | Docs | Docs: Python310_29461_C | import heapq
import itertools
REMOVED = '<removed-task>'
def add_task(pq, task, priority, entry_finder, counter):
"""
Add a new task or update the priority of an existing task.
Arguments:
pq -- the priority queue (min-heap)
task -- the task to be added or updated
priority -- the priority of t... | import heapq
import itertools
REMOVED = '<removed-task>'
def add_task(pq, task, priority, entry_finder, counter):
"""
Add a new task or update the priority of an existing task.
"""
if task in entry_finder:
remove_task(pq, task, entry_finder)
count = next(counter)
entry = [priority, cou... | import pytest
def test_add_and_pop_task():
pq = []
entry_finder = {}
counter = itertools.count()
add_task(pq, 'task1', 1, entry_finder, counter)
add_task(pq, 'task2', 2, entry_finder, counter)
assert pop_task(pq, entry_finder) == 'task1'
assert pop_task(pq, entry_finder) == 'task2'
def t... | [
{
"docstring": "Add a new task or update the priority of an existing task.",
"function_declaration": "def add_task(pq, task, priority, entry_finder, counter):",
"function_name": "add_task",
"parameter_list": "(pq, task, priority, entry_finder, counter)"
},
{
"docstring": "Mark an existing ta... | [
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 heapq\nimport itertools\n\nREMOVED = '<removed-task>' # Placeholder for a removed task\n\ndef add_task(pq, task, priority, entry_finder, counter):\n \"\"\"\n... | trial_gpt4o_1 | {
"original_instruction": "### Custom Priority Queue Implementation\n\nYou work for a task management software development company. Your team is enhancing its core library to manage tasks with priorities using the heapq module. The requirements are as follows:\n\n1. **Add a new task** or **update the priority of an e... | 0.542715 | Docs: Python310_29461 | C | [
"add_task",
"remove_task",
"pop_task"
] | 3 | [
[
"add_task",
"remove_task"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 87c8e6cb7e9d9b998e4d8e306db1d1708488c70c | 38b97306360a989169c1c1f91f85caa41b739e1f | |||
v1.0 | complete | Docs | Docs: Python310_30397_C | import signal
def long_running_computation():
"""
Dummy function that simulates a long-running computation
"""
def limit_computation_time(time_limit: int):
"""Manages signal handling for SIGALRM and SIGINT, starts the computation,
and handles any exceptions raised due to timeout or user interrupti... | import signal
import time
def long_running_computation():
while True:
# Simulate some long-running computation
time.sleep(1)
def limit_computation_time(time_limit):
def handle_alarm(signum, frame):
raise TimeoutError("Computation timed out")
def handle_interrupt(signum, frame):
... | import multiprocessing
import os
import pytest
import time
from solution import limit_computation_time
def computation_with_timeout(time_limit):
from solution import limit_computation_time
limit_computation_time(time_limit)
def test_timeout():
p = multiprocessing.Process(target=computation_with_timeout, ... | [
{
"docstring": null,
"function_declaration": "def long_running_computation():",
"function_name": "long_running_computation",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def limit_computation_time(time_limit):",
"function_name": "limit_computation_time",
... | [
0,
1,
0,
0,
0,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import signal\n\ndef long_running_computation():\n \"\"\"\n Simulates a long-running computation by entering an infinite loop.\n \"\"\"\n while True:\n ... | trial_gpt4o_1 | {
"original_instruction": "### Python Signal Handling Assessment\n\n**Objective**: Demonstrate your understanding of Python's `signal` module by implementing signal handling in a practical scenario.\n\n### Problem Statement\n\nYou are required to implement a Python program that monitors the execution time of a long-r... | 0.56904 | Docs: Python310_30397 | C | [
"long_running_computation",
"limit_computation_time"
] | 2 | [
[
"limit_computation_time",
"long_running_computation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a3e7e7af956a487bbb528203bfaa5bc7cc544cde | a0bbe8a3b900789e67a4dfcdeb33f1d577c02f76 | |||
v1.0 | complete | Docs | Docs: Python310_29795_C | import os
import stat
import time
def file_type(mode):
"""Determine the type of the file.
Args:
mode (int): The mode of the file.
Returns:
str: The type of the file.
"""
def permissions_string(mode):
"""Convert the mode to a string representing the permissions.
A... | import os
import stat
import time
def file_type(mode):
if stat.S_ISDIR(mode):
return "Directory"
elif stat.S_ISREG(mode):
return "Regular File"
elif stat.S_ISLNK(mode):
return "Symbolic Link"
elif stat.S_ISCHR(mode):
return "Character Device"
elif stat.S_ISBLK(mode):... | from solution import directory_overview
import os
import pytest
def setup_test_directory():
if not os.path.exists('test_dir'):
os.mkdir('test_dir')
with open('test_dir/file1.txt', 'w') as f:
f.write('hello world')
with open('test_dir/file2.txt', 'w') as f:
f.write('p... | [
{
"docstring": null,
"function_declaration": "def file_type(mode):",
"function_name": "file_type",
"parameter_list": "(mode)"
},
{
"docstring": null,
"function_declaration": "def permissions_string(mode):",
"function_name": "permissions_string",
"parameter_list": "(mode)"
},
... | [
1,
1,
0,
1,
1,
1,
1,
1,
0
] | 7 | easy | 0.778 | {
"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 get_file_type(mode):\n if stat.S_ISDIR(mode):\n return \"Directory\"\n elif stat.S_ISREG(mode):\n return ... | trial_gpt4o_5 | {
"original_instruction": "### Question: Implement a Directory Overview Tool using Python `stat` Module\n\nYou are tasked with implementing a Python script that provides an overview of all files and directories within a specified directory. The overview should include file types, permissions, and other relevant attri... | 0.572022 | Docs: Python310_29795 | C | [
"file_type",
"permissions_string",
"directory_overview"
] | 3 | [
[
"directory_overview",
"file_type"
],
[
"directory_overview",
"permissions_string"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a2a79c1773a8113680deb7a96c28b1b1ceea6af7 | 8d8dbdc544c14b6191f4d5bd6821299e159678ce | |||
v1.0 | complete | Docs | Docs: Python310_30260_C | import asyncio
import random
from typing import List
async def fetch_url(url: str) -> str:
"""Simulates fetching data from a URL by sleeping for a random short duration (between 1 and 3 seconds)
and then returns a message indicating the data was retrieved from the given URL.
>>> await fetch_url("http://exa... | import asyncio
import random
from typing import List
async def fetch_url(url: str) -> str:
await asyncio.sleep(random.randint(1, 3))
return f"Data retrieved from {url}"
async def process_urls(urls: List[str]) -> List[str]:
semaphore = asyncio.Semaphore(3)
async def sem_fetch(url):
async w... | import pytest
import asyncio
import random
from solution import fetch_url, process_urls
# Patching random.randint to control the sleep time for predictability in tests
@pytest.fixture(autouse=True)
def patch_random_sleep(monkeypatch):
def mock_randint(start, end):
return 1 # Always sleep for 1 second in t... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\nfrom typing import List\n\nasync def fetch_url(url: str) -> str:\n \"\"\"\n Simulates fetching data from a URL by sleeping for a ra... | trial_gpt4o_7 | {
"original_instruction": "**Title: Asynchronous Task Execution with Synchronization Primitives**\n\n**Objective:**\nWrite a Python program using the `asyncio` library that demonstrates the management and synchronization of multiple asynchronous tasks. You will implement a function that processes a list of URLs, fetc... | 0.564374 | Docs: Python310_30260 | C | [
"fetch_url",
"process_urls",
"main"
] | 3 | [
[
"process_urls",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 53b893ed50121ee31fb6a7fda2ed1c47f9715250 | aaafc6964699e0f4b173cbe9c861cc95625adfbc | |||
v1.0 | complete | Docs | Docs: Python310_30210_C | import asyncio
import concurrent.futures
import logging
def cpu_bound_task():
"""Simulates a heavy computation by sleeping for 2 seconds and then returns a completion message."""
import time
time.sleep(2)
return "CPU-bound task complete"
async def async_callback():
"""Prints a message indicating t... | import asyncio
import concurrent.futures
import logging
def cpu_bound_task():
import time
time.sleep(2)
return "CPU-bound task complete"
async def async_callback():
print("Asynchronous callback executed")
async def perform_async_operations():
loop = asyncio.get_running_loop()
loop.set_debug(T... | import pytest
import asyncio
from solution import cpu_bound_task, async_callback, perform_async_operations
def test_cpu_bound_task():
assert cpu_bound_task() == "CPU-bound task complete"
@pytest.mark.asyncio
async def test_async_callback(capfd):
await async_callback()
captured = capfd.readouterr()
ass... | [
{
"docstring": null,
"function_declaration": "def cpu_bound_task():",
"function_name": "cpu_bound_task",
"parameter_list": "()"
}
] | [
0,
1,
0,
1,
1,
1,
0,
1,
1
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport concurrent.futures\nimport logging\nimport time\n\ndef cpu_bound_task():\n \"\"\"\n Simulates a heavy computation by sleeping for 2 seconds... | trial_gpt4o_5 | {
"original_instruction": "Using asyncio for Multithreading and Debugging\n\n#### Objective\nYou are asked to demonstrate your understanding of the asyncio library in Python, particularly focusing on multithreading, handling blocking code, and debugging. You will implement a function that performs a blocking operatio... | 0.487556 | Docs: Python310_30210 | C | [
"cpu_bound_task",
"async_callback",
"perform_async_operations"
] | 3 | [
[
"perform_async_operations",
"async_callback"
],
[
"perform_async_operations",
"cpu_bound_task"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cb944084b09ca2315e0c88e691891994fe41041b | 6a46e2bf25929c09b61a1caa02c1a3f5e319ee99 | |||
v1.0 | complete | Docs | Docs: Python310_29958_C | #!/usr/bin/python3
import cgi
import cgitb
cgitb.enable() # Enables CGI tracebacks for debugging
def html_response(message):
"""Generate an HTML response with the given message.
>>> html_response("Test message")
Content-type: text/html
...
<h2>Test message</h2>
...
"""
print("Content-... | #!/usr/bin/python3
import cgi
import cgitb
cgitb.enable() # Enables CGI tracebacks for debugging
def html_response(message):
print("Content-type: text/html\n")
print("<html><head>")
print("<title>CGI Form Response</title>")
print("</head><body>")
print(f"<h2>{message}</h2>")
print("</body></h... | def test_html_response(capsys):
html_response("Test message")
captured = capsys.readouterr()
assert "Content-type: text/html\n" in captured.out
assert "<h2>Test message</h2>" in captured.out
def test_process_form_valid_post(monkeypatch, capsys):
def mock_fieldstorage():
class MockFieldStora... | [
{
"docstring": null,
"function_declaration": "def html_response(message):",
"function_name": "html_response",
"parameter_list": "(message)"
},
{
"docstring": null,
"function_declaration": "def process_form():",
"function_name": "process_form",
"parameter_list": "()"
}
] | [
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": "#!/usr/bin/python3\n\nimport cgi\nimport cgitb\ncgitb.enable() # Enable CGI traceback for debugging\n\ndef html_response(message):\n \"\"\"\n Generates a simple ... | trial_gpt4o_9 | {
"original_instruction": "### CGI Script for Processing Form Data\n\n**Description:**\nYou are required to write a CGI (Common Gateway Interface) script using the deprecated `cgi` module in Python. This script should be capable of handling a simple HTML form submission. The form will contain fields for a user's firs... | 0.619388 | Docs: Python310_29958 | C | [
"html_response",
"process_form"
] | 2 | [
[
"process_form",
"html_response"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | f2cb702b145e0b029f2d780cb0f6da3c87cb50c7 | d5af2a13730963ab547f3e79f3ad34c168ceefe5 | |||
v1.0 | complete | Docs | Docs: Python310_30362_C | from typing import List, Dict
def process_numbers(numbers: List[int]) -> Dict[str, int]:
"""
Given a list of integers, perform the following operations concurrently:
1. Compute the sum of the squares of all numbers in the list.
2. Compute the sum of the cubes of all numbers in the list.
3. Find th... | from concurrent.futures import ThreadPoolExecutor
from typing import List, Dict
def sum_of_squares(numbers: List[int]) -> int:
return sum(x ** 2 for x in numbers)
def sum_of_cubes(numbers: List[int]) -> int:
return sum(x ** 3 for x in numbers)
def max_number(numbers: List[int]) -> int:
return max(numbers... | from solution import process_numbers
def test_process_numbers_basic():
numbers = [1, 2, 3, 4, 5]
result = process_numbers(numbers)
assert result == {
'sum_of_squares': 1**2 + 2**2 + 3**2 + 4**2 + 5**2,
'sum_of_cubes': 1**3 + 2**3 + 3**3 + 4**3 + 5**3,
'max_number': 5,
'min_n... | [
{
"docstring": null,
"function_declaration": "def sum_of_squares(numbers):",
"function_name": "sum_of_squares",
"parameter_list": "(numbers)"
},
{
"docstring": null,
"function_declaration": "def sum_of_cubes(numbers):",
"function_name": "sum_of_cubes",
"parameter_list": "(numbers... | [
1,
1,
0,
1,
0,
1,
0,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import concurrent.futures\nfrom typing import List, Dict\n\ndef compute_sum_of_squares(numbers):\n return sum(x**2 for x in numbers)\n\ndef compute_sum_of_cubes(numb... | trial_gpt4o_5 | {
"original_instruction": "### Question: Concurrent Number Processing\n\nGiven a list of integers, design a Python program to perform the following operations concurrently using the `concurrent.futures` module. Your task is to implement a function `process_numbers(numbers: List[int]) -> Dict[str, int]` that performs ... | 0.659377 | Docs: Python310_30362 | C | [
"sum_of_squares",
"sum_of_cubes",
"max_number",
"min_number",
"process_numbers"
] | 5 | [
[
"process_numbers",
"max_number"
],
[
"process_numbers",
"min_number"
],
[
"process_numbers",
"sum_of_cubes"
],
[
"process_numbers",
"sum_of_squares"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | a4ae2d6f509d827e052b24e5902af30e3bdb7bde | 6987fcdbefc030e8e6e8732a87f125bcc424a380 | |||
v1.0 | complete | Docs | Docs: Python310_30500_C | import time
import concurrent.futures
def fetch_data(task_id):
"""
Simulates fetching data for a given task_id.
"""
print(f"Fetching data for task {task_id}")
time.sleep(1)
return f"Data for task {task_id}"
def process_data(data):
"""
Simulates processing the fetched data.
"""
... | import time
import concurrent.futures
def fetch_data(task_id):
"""
Simulates fetching data for a given task_id.
"""
print(f"Fetching data for task {task_id}")
time.sleep(1)
return f"Data for task {task_id}"
def process_data(data):
"""
Simulates processing the fetched data.
"""
... | import pytest
from solution import process_tasks_concurrently
def test_process_tasks_using_threads(capfd):
task_ids = [1, 2, 3]
process_tasks_concurrently(task_ids, use_threads=True)
captured = capfd.readouterr()
assert all(f"Fetching data for task {i}" in captured.out for i in task_ids)
assert all... | [] | [
1,
1,
0,
1,
1,
0,
0,
1,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed\n\ndef fetch_data(task_id):\n print(f\"Fetching data for task {task... | trial_gpt4o_3 | {
"original_instruction": "**Challenging Python Coding Assessment**\n\nYou are tasked with implementing a concurrent system for processing a number of independent tasks using Python's `concurrent.futures` module. Your function will simulate a real-world scenario where each task involves fetching data, processing the ... | 0.615044 | Docs: Python310_30500 | C | [
"fetch_data",
"process_data",
"save_result",
"process_task",
"process_tasks_concurrently"
] | 5 | [
[
"process_task",
"fetch_data"
],
[
"process_task",
"process_data"
],
[
"process_task",
"save_result"
],
[
"process_tasks_concurrently",
"process_task"
]
] | 4 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 81af95111d5195ceccde9715ccaacff90448d33b | 0c0d736780822e33042fc84ba39580c5b70d05a9 | |||
v1.0 | complete | Docs | Docs: Python310_30585_C | import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch_url(url):
"""
Fetch the content of the URL.
Parameters:
- url (str): The URL to fetch.
Returns:
- str: The content of the web page if successful, None otherwise.
"""
return
def scrape_we... | import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch_url(url):
"""
Fetch the content of the URL.
Parameters:
- url (str): The URL to fetch.
Returns:
- str: The content of the web page if successful, None otherwise.
"""
try:
response... | import pytest
from solution import scrape_web_pages
def test_scrape_web_pages_success():
urls = [
"http://example.com",
"http://example.org"
]
results = scrape_web_pages(urls)
assert "http://example.com" in results and results["http://example.com"] is not None
assert "http://example... | [
{
"docstring": "Fetch the content of the URL.\n\nParameters:\n- url (str): The URL to fetch.\n\nReturns:\n- str: The content of the web page if successful, None otherwise.",
"function_declaration": "def fetch_url(url):",
"function_name": "fetch_url",
"parameter_list": "(url)"
},
{
"docstring... | [
0,
1,
1,
1,
1,
0,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"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\n\ndef fetch_url(url):\n \"\"\"\n Fetches the content of a given URL.\n If the... | trial_gpt4o_1 | {
"original_instruction": "## Question: Using `concurrent.futures` for Web Scraping\n\n### Objective:\nDesign a web scraper that concurrently fetches the content of multiple web pages. You will demonstrate your understanding of the `concurrent.futures` module by writing a Python function that uses `ThreadPoolExecutor... | 0.611601 | Docs: Python310_30585 | C | [
"fetch_url",
"scrape_web_pages"
] | 2 | [
[
"scrape_web_pages",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 092f382a4cd9eea9a899b70ac57ac57f82b2e4b3 | 03789e81c6651dbb85f2a4461858cedd27e71e0f | |||
v1.0 | complete | Docs | Docs: Python310_30518_C | import functools
class TailCall:
def __init__(self, args, kwargs):
self.args = args
self.kwargs = kwargs
def tail_call(args, kwargs):
return TailCall(args, kwargs)
def optimize_tail_call(func: callable) -> callable:
"""
Transforms a given Python function to optimize tail-call recursio... | import dis
import types
import functools
def optimize_tail_call(func: callable) -> callable:
"""
Transforms a given Python function to optimize tail-call recursion.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
stack = [(args, kwargs)]
while stack:
args, kwarg... | from solution import optimize_tail_call, tail_call
def factorial(n, acc=1):
if n == 0:
return acc
return tail_call((n-1, n*acc), {})
def fibonacci(n, a=0, b=1):
if n == 0:
return a
if n == 1:
return b
return tail_call((n-1, b, a+b), {})
optimized_factorial = optimize_tail_... | [] | [
0,
1,
1,
0,
1,
0,
1,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import dis\nimport types\nimport functools\n\ndef optimize_tail_call(func):\n \"\"\"\n Transform the given Python function to optimize tail-call recursion.\n \... | trial_gpt4o_2 | {
"original_instruction": "Write a function `optimize_tail_call` that transforms a given Python function to optimize tail-call recursion. Tail-call recursion occurs when a function calls itself as its final action, allowing for optimizations like reusing stack frames. \n\nPython does not optimize tail calls natively,... | 0.546618 | Docs: Python310_30518 | C | [
"optimize_tail_call",
"tail_call",
"factorial"
] | 3 | [
[
"factorial",
"tail_call"
]
] | 1 | [] | false | [
"TailCall"
] | true | pytest | true | [] | true | f0348632bc2ab150903f81cca6b289072da9a288 | acfa10211f463cdc57afa765c820c0f446863205 | |||
v1.0 | complete | Docs | Docs: Scikit_28972_C | import numpy as np
from sklearn.datasets import load_iris, load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor, plot_tree
from sklearn.metrics import accuracy_score, mean_squared_error
import matplotlib.pyplot as plt
def introduce_mi... | import numpy as np
from sklearn.datasets import load_iris, load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor, plot_tree
from sklearn.metrics import accuracy_score, mean_squared_error
import matplotlib.pyplot as plt
# Function to in... | from solution import (decision_tree_classification, decision_tree_regression,
handle_missing_values, decision_tree_pruning)
def test_decision_tree_classification():
accuracy, _ = decision_tree_classification()
assert isinstance(accuracy, float)
assert accuracy > 0.5
def test_dec... | [
{
"docstring": null,
"function_declaration": "def introduce_missing_values(X, percentage=0.1):",
"function_name": "introduce_missing_values",
"parameter_list": "(X, percentage=0.1)"
},
{
"docstring": null,
"function_declaration": "def decision_tree_classification():",
"function_name"... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | 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.datasets import load_iris, load_diabetes\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeCl... | trial_gpt4o_9 | {
"original_instruction": "### Decision Tree Implementation and Evaluation\n\n#### Objective:\nTo test the understanding and application of decision trees in scikit-learn for classification and regression tasks, including handling missing values, pruning, and visualizing the decision tree.\n\n#### Task:\n1. **Decisio... | 0.664203 | Docs: Scikit_28972 | C | [
"introduce_missing_values",
"decision_tree_classification",
"decision_tree_regression",
"handle_missing_values",
"decision_tree_pruning"
] | 5 | [
[
"handle_missing_values",
"introduce_missing_values"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"sklearn"
] | false | 6e492b225bdb336f7f90f4a73144239b4565058f | 81c33a27e6d53888982b300ff49c0768185857ee | |||
v1.0 | complete | Docs | Docs: Python310_30761_C | import syslog
def configure_logging():
"""
Configure the syslog with identifier 'TaskProcessor', log options to include process ID, and log to the user facility.
"""
def log_message(priority, message):
"""
Log a message with the given priority using the syslog module.
Parameters:
prio... | import syslog
def configure_logging():
"""
Configure the syslog with identifier 'TaskProcessor', log options to include process ID, and log to the user facility.
"""
syslog.openlog(ident='TaskProcessor', logoption=syslog.LOG_PID, facility=syslog.LOG_USER)
def log_message(priority, message):
"""
... | import pytest
from solution import configure_logging, log_message, set_log_mask, simulate_tasks
def test_configure_logging():
"""
Test that the logging configuration doesn't raise any exceptions.
"""
try:
configure_logging()
except Exception as e:
pytest.fail(f"configure_logging rai... | [
{
"docstring": "Configure the syslog with identifier 'TaskProcessor', log options to include process ID, and log to the user facility.",
"function_declaration": "def configure_logging():",
"function_name": "configure_logging",
"parameter_list": "()"
},
{
"docstring": "Log a message with the ... | [
1,
0,
0,
0,
0,
0,
1,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import syslog\n\ndef configure_logging():\n \"\"\"\n Configure the syslog with identifier 'TaskProcessor', log options to include process ID, and log to the user ... | trial_gpt4o_0 | {
"original_instruction": "### Advanced Python Logging with syslog Module\n\nYou are required to create a Python logging utility using the `syslog` module that simulates a system processing multiple tasks. The utility should demonstrate advanced functionalities such as setting log options, sending messages with diffe... | 0.620093 | Docs: Python310_30761 | C | [
"configure_logging",
"log_message",
"set_log_mask",
"simulate_tasks"
] | 4 | [
[
"simulate_tasks",
"log_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0cbaf3ff773b34b68bb52763e48a95af30fd9100 | 001f31ba79aad7317825f6ddf6cb715e49a7c6a1 | |||
v1.0 | complete | Docs | Docs: Python310_30523_C | from threading import Thread, Lock
from typing import List
def is_prime(n):
""" Check if a number is a prime number """
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) =... | from threading import Thread, Lock
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def worker... | from solution import count_primes_in_range
def test_count_primes_small_range():
assert count_primes_in_range(1, 10, 2) == 4 # Primes: 2, 3, 5, 7
def test_count_primes_medium_range():
assert count_primes_in_range(1, 100, 4) == 25
def test_count_primes_large_range():
assert count_primes_in_range(1, 10... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def worker(start, end, result, lock):",
"function_name": "worker",
"parameter_list": "(start, end, result, lock)"... | [
0,
0,
0,
1,
0,
0,
1,
1,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from threading import Thread, Lock\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ... | trial_gpt4o_9 | {
"original_instruction": "### Question: Prime Number Calculation with Threading\n\nYou are required to write a Python function that computes the number of prime numbers within a given range concurrently using threads. The goal of this task is to efficiently use threading to improve the performance of your computatio... | 0.697977 | Docs: Python310_30523 | C | [
"is_prime",
"worker",
"count_primes_in_range"
] | 3 | [
[
"worker",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 61f62b9dada5897274b28afa6e91b230786d57e7 | 4716c302276c596c1a2634759e277d76dbada85e | |||
v1.0 | complete | Docs | Docs: Python310_30868_C | from typing import List
import _thread
import time
def process_chunk(chunk: List[int]) -> int:
""" Process a chunk of integers and return their sum
>>> process_chunk([1, 2, 3])
6
>>> process_chunk([-1, -2, -3])
-6
>>> process_chunk([0, 0, 0])
0
>>> process_chunk([])
0
"""
pa... | from typing import List
import _thread
import time
# Function to process a chunk
def process_chunk(chunk: List[int]) -> int:
return sum(chunk)
# Function to process list in parallel
def parallel_sum(lst: List[int], n_threads: int) -> int:
# Validate number of threads
assert 1 <= n_threads <= len(lst), "Nu... | from solution import process_chunk, parallel_sum
def test_process_chunk():
assert process_chunk([1, 2, 3]) == 6
assert process_chunk([-1, -2, -3]) == -6
assert process_chunk([0, 0, 0]) == 0
assert process_chunk([]) == 0
def test_parallel_sum_single_thread():
assert parallel_sum([1, 2, 3, 4, 5], 1)... | [
{
"docstring": null,
"function_declaration": "def process_chunk(chunk):",
"function_name": "process_chunk",
"parameter_list": "(chunk)"
},
{
"docstring": null,
"function_declaration": "def parallel_sum(lst, n_threads):",
"function_name": "parallel_sum",
"parameter_list": "(lst, n... | [
1,
1,
0,
0,
0,
0,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport _thread\nimport time\n\n# Function to process a chunk\ndef process_chunk(chunk: List[int]) -> int:\n return sum(chunk)\n\n# Function ... | trial_gpt4o_0 | {
"original_instruction": "### Problem: Multi-threaded Data Processing\n\nIn this assessment, you are required to write a Python program that uses the `_thread` module to process a list of integers in parallel. The goal is to split the list into several chunks, process each chunk in a separate thread, and then combin... | 0.646302 | Docs: Python310_30868 | C | [
"process_chunk",
"parallel_sum"
] | 2 | [
[
"parallel_sum",
"process_chunk"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 87b4315f605a304e67166b4bb5565473337a9970 | 62fdd7e794f2949a2156090fa816f2f3486b2e66 | |||
v1.0 | complete | Docs | Docs: Python310_30629_C | import asyncio
async def handle_client(reader, writer):
"""
Handle client connection and echo received data back to the client.
Args:
reader: StreamReader object for reading data.
writer: StreamWriter object for writing data.
"""
address = writer.get_extra_info('peername')
prin... | import asyncio
async def handle_client(reader, writer):
address = writer.get_extra_info('peername')
print(f"Connection from {address}")
try:
while True:
data = await reader.read(100)
if not data:
break
message = data.decode()
print(f"... | import asyncio
import pytest
from async_timeout import timeout
from solution import start_server, handle_client
@pytest.mark.asyncio
async def test_echo_server():
server_task = asyncio.create_task(start_server('127.0.0.1', 8888))
await asyncio.sleep(1) # Give the server time to start
reader, writer = aw... | [] | [
1,
1,
1,
1,
0,
0,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n address = writer.get_extra_info('peername')\n print(f\"Connection from {address}\")\n\n try:\n ... | trial_gpt4o_1 | {
"original_instruction": "### Question\n\nYou have been tasked with implementing a simple echo TCP server using the asyncio module in Python. The server should be able to handle multiple clients simultaneously, echoing back any message it receives from a client. Here are the requirements:\n\n1. Create an event loop ... | 0.638303 | Docs: Python310_30629 | C | [
"handle_client",
"start_server"
] | 2 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [
"async_timeout"
] | false | 29635f82b873003d8d19a163b510d2fa3fd017a1 | 483f67d20cf2bc37874af49c992ceb3e9c3b3b0f | |||
v1.0 | complete | Docs | Docs: Python310_31067_C | import requests
from concurrent.futures import ThreadPoolExecutor
def fetch_all_urls(urls, max_workers):
"""Fetch the content from each URL concurrently.
Args:
urls (list): A list of strings where each string is a URL.
max_workers (int): The maximum number of threads to run concurrently.
... | import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch_content(url):
try:
response = requests.get(url)
response.raise_for_status()
return response.text
except requests.RequestException as e:
return str(e)
def fetch_all_urls(urls, max_workers):... | import pytest
import requests
from unittest.mock import patch, MagicMock
from solution import fetch_all_urls
def test_fetch_all_urls_success():
urls = ["http://example.com"]
mock_response = MagicMock()
mock_response.raise_for_status = MagicMock()
mock_response.text = "Example content"
wi... | [
{
"docstring": null,
"function_declaration": "def fetch_content(url):",
"function_name": "fetch_content",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def fetch_all_urls(urls, max_workers):",
"function_name": "fetch_all_urls",
"parameter_list": "(url... | [
1,
1,
0,
0,
1,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"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\n\ndef fetch_content(url):\n try:\n response = requests.get(url)\n res... | trial_gpt4o_0 | {
"original_instruction": "### Python Coding Assessment Question\n\n#### Objective:\nThis question assesses your ability to use the `concurrent.futures` module to manage parallel task execution efficiently.\n\n#### Problem Statement:\nYou are given a list of URLs and need to fetch the content from each URL concurrent... | 0.563234 | Docs: Python310_31067 | C | [
"fetch_content",
"fetch_all_urls"
] | 2 | [
[
"fetch_all_urls",
"fetch_content"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 79e32104a1c6b374c4656ad8e9bb3880db355564 | 9714e53b94c7105c18d3fa031b9e03023515e18d | |||
v1.0 | complete | Docs | Docs: Seaborn_30301_C | import seaborn as sns
import matplotlib.pyplot as plt
def generate_and_print_palettes():
"""
Generate various HUSL color palettes and print them.
Returns:
tuple: (palette_default, palette_8, palette_custom, colormap_continuous)
>>> generate_and_print_palettes()
(list of 6 colors, list ... | import seaborn as sns
import matplotlib.pyplot as plt
def generate_and_print_palettes():
# a. Create a default HUSL palette with 6 colors and print it
palette_default = sns.husl_palette()
print("Default HUSL palette (6 colors):", palette_default)
# b. Create a HUSL palette with 8 colors and print it
... | from solution import generate_and_print_palettes
def test_generate_and_print_palettes():
palette_default, palette_8, palette_custom, colormap_continuous = generate_and_print_palettes()
assert len(palette_default) == 6 # Default HUSL palette should have 6 colors
assert len(palette_8) == 8 # HUSL palette ... | [
{
"docstring": null,
"function_declaration": "def generate_and_print_palettes():",
"function_name": "generate_and_print_palettes",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def visualize_palettes():",
"function_name": "visualize_palettes",
"parameter... | [
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 seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef generate_palettes_and_visualizations():\n # Part 1: Generate Color Palettes\n # a.\n palette_defa... | trial_gpt4o_9 | {
"original_instruction": "#### Objective\nYour task is to demonstrate your understanding of Seaborn's `husl_palette` function by creating various color palettes, modifying their parameters, and applying them to different visualizations.\n\n#### Question\n\n1. **Generate Color Palettes**:\n - a. Create a default HU... | 0.666607 | Docs: Seaborn_30301 | C | [
"generate_and_print_palettes",
"visualize_palettes"
] | 2 | [
[
"visualize_palettes",
"generate_and_print_palettes"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"seaborn"
] | false | 740483e183556c8013a84edc6302064b5a338c74 | 0dece89c88a9c1d11863098f197b60622f8b8560 | |||
v1.0 | complete | Docs | Docs: Python310_30550_C | import sys
import traceback
class CustomError(Exception):
""" Custom error class for general errors """
pass
class CustomRecursionError(CustomError):
""" Custom error class for recursion errors """
pass
def raise_custom_error(condition):
""" Raise a CustomError based on condition
>>> raise_cu... | import sys
import traceback
class CustomError(Exception):
pass
class CustomRecursionError(CustomError):
pass
def raise_custom_error(condition):
if condition == "error":
raise CustomError("A custom error occurred")
def raise_custom_recursion_error():
raise CustomRecursionError("Recursion dept... | from solution import CustomError, CustomRecursionError, raise_custom_error, recursive_function, handle_errors
import pytest
def test_raise_custom_error():
with pytest.raises(CustomError, match="A custom error occurred"):
raise_custom_error("error")
def test_raise_custom_recursion_error():
with pytest.... | [] | [
1,
1,
0,
1,
0,
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": "class CustomError(Exception):\n \"\"\"\n A custom general exception for demonstration purposes.\n \"\"\"\n pass\n\nclass CustomRecursionError(CustomError):\... | trial_gpt4o_1 | {
"original_instruction": "**Question: Custom Exception Handling with Recursive Calls**\n\nYou are tasked with implementing a custom exception handling system in Python, using advanced exception handling techniques. Your goal is to create specific exception classes, manage error indicators properly, and handle recurs... | 0.44247 | Docs: Python310_30550 | C | [
"raise_custom_error",
"raise_custom_recursion_error",
"handle_errors",
"recursive_function"
] | 4 | [
[
"recursive_function",
"raise_custom_recursion_error"
]
] | 1 | [] | false | [
"CustomError",
"CustomRecursionError"
] | true | pytest | true | [] | true | 72ead018301c7a65e65afffacaf3a0b3a79dac10 | 131cc3a97212186265c84e04b3dea81d49046957 | |||
v1.0 | complete | Docs | Docs: Python310_30350_C | import contextvars
from typing import Any, Optional
def create_context() -> contextvars.Context:
"""
Creates and returns a new context.
"""
pass
def create_context_var(name: str, default_value: Optional[Any] = None) -> contextvars.ContextVar:
"""
Creates and returns a new context variable wit... | import contextvars
# Function to create and return a new context
def create_context():
"""
Creates and returns a new context.
"""
return contextvars.copy_context()
# Function to create a context variable with a default value
def create_context_var(name, default_value=None):
"""
Creates and ret... | import pytest
from solution import create_context, create_context_var, set_context_var, get_context_var, context_simulation
def test_create_context():
ctx = create_context()
assert isinstance(ctx, contextvars.Context)
def test_create_context_var():
ctx_var = create_context_var('test_var', 'default_value')... | [
{
"docstring": "Creates and returns a new context.",
"function_declaration": "def create_context():",
"function_name": "create_context",
"parameter_list": "()"
},
{
"docstring": "Creates and returns a new context variable with the given name and default value.",
"function_declaration": "... | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import contextvars\n\ndef create_context() -> contextvars.Context:\n \"\"\"\n Create a new context and return it.\n \"\"\"\n return contextvars.Context()\n\... | trial_gpt4o_1 | {
"original_instruction": "**Objective:** \nWrite a Python program using the `contextvars` module to manage and manipulate context-specific variables.\n\n**Problem Statement:** \n\nYou are required to implement a set of functions to demonstrate your understanding of `contextvars` module in Python. Specifically, you s... | 0.428839 | Docs: Python310_30350 | C | [
"create_context",
"create_context_var",
"set_context_var",
"get_context_var",
"context_simulation"
] | 5 | [
[
"context_simulation",
"create_context"
],
[
"context_simulation",
"create_context_var"
],
[
"context_simulation",
"get_context_var"
],
[
"context_simulation",
"set_context_var"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 4b5bf71b593cefdc55431a8e325ebeb2f99ba19f | 475a628e2106956f9dd5d5cf225c3f1e08a93f16 | |||
v1.0 | complete | Docs | Docs: Python310_30487_C | import asyncio
from typing import List, Tuple
import aiohttp
async def fetch(url: str) -> Tuple[str, int]:
""" Fetches the content of the provided URL asynchronously and returns
a tuple containing the URL and the length of the content.
"""
pass
async def async_scrape(urls: List[str]) -> List[Tuple[str... | import asyncio
from typing import List, Tuple
import aiohttp
async def fetch(url: str) -> Tuple[str, int]:
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
content = await response.text()
return url, len(content)
ex... | import asyncio
from solution import async_scrape
def test_async_scrape_valid_urls():
urls = ["http://example.com"]
result = asyncio.run(async_scrape(urls))
assert isinstance(result, list)
assert len(result) == 1
assert result[0][0] == "http://example.com"
assert isinstance(result[0][1], int)
d... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple\nimport aiohttp\n\nasync def fetch(url: str) -> Tuple[str, int]:\n try:\n async with aiohttp.ClientSession() as... | trial_gpt4o_2 | {
"original_instruction": "### Asynchronous Web Scraper\n\nYou are tasked to implement an asynchronous web scraper using the `asyncio` and `aiohttp` libraries. The scraper will concurrently fetch data from multiple URLs and process the content.\n\n#### Requirements\n\n1. **Function Name**: `async_scrape(urls: List[st... | 0.603353 | Docs: Python310_30487 | C | [
"fetch",
"async_scrape"
] | 2 | [
[
"async_scrape",
"fetch"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 6d7a9e42d0068abcb21930085a7e617a02414ef0 | 48e46c4f40ee9125b92116f7268af89da8dfd205 | |||
v1.0 | complete | Docs | Docs: Python310_30359_C | import hmac
from typing import List
def generate_hmac(key: bytes, msg: bytes, digestmod: str) -> str:
"""
Generate an HMAC digest for the provided message and key using the specified digest mode.
:param key: Secret key as bytes object.
:param msg: Message to be authenticated as bytes object.
:... | import hmac
import hashlib
def generate_hmac(key: bytes, msg: bytes, digestmod: str) -> str:
"""
Generate an HMAC digest for the provided message and key using the specified digest mode.
:param key: Secret key as bytes object.
:param msg: Message to be authenticated as bytes object.
:param dig... | import pytest
from solution import generate_hmac, verify_hmac
def test_generate_hmac_sha256():
key = b'secret_key'
msg = b'This is a secret message'
digestmod = 'sha256'
expected_hmac_hex = hmac.new(key, msg, digestmod).hexdigest()
assert generate_hmac(key, msg, digestmod) == expected_hmac_hex... | [
{
"docstring": "Generate an HMAC digest for the provided message and key using the specified digest mode.\n\n:param key: Secret key as bytes object.\n:param msg: Message to be authenticated as bytes object.\n:param digestmod: Digest mode to use (e.g., 'sha256').\n:return: Hexadecimal HMAC digest as a string.",
... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hmac\nimport hashlib\n\ndef generate_hmac(key: bytes, msg: bytes, digestmod: str) -> str:\n \"\"\"\n Generate an HMAC digest for the provided message and k... | trial_gpt4o_0 | {
"original_instruction": "**Problem Statement:**\n\nYou are tasked with creating a secure data verification system using the `hmac` module. This system should be able to generate HMAC digests for given messages and verify the authenticity of messages using a shared secret key. \n\n**Function 1: generate_hmac**\n\nIm... | 0.807318 | Docs: Python310_30359 | C | [
"generate_hmac",
"verify_hmac"
] | 2 | [
[
"verify_hmac",
"generate_hmac"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4bdfd9414c10037768a036c2e5b30f93d0d4f9bc | 29ae76a6917f55e03c4f9a8dcc3d1d408bfa6ebe | |||
v1.0 | complete | Docs | Docs: Python310_30792_C | import ctypes
from ctypes import pythonapi, py_object
def allocate_raw_memory(size: int) -> int:
"""
Allocates size bytes of raw memory using PyMem_RawMalloc and returns the address as an integer.
In case of a failure to allocate, return -1.
>>> address = allocate_raw_memory(128)
>>> assert ad... | import ctypes
from ctypes import pythonapi, py_object
def allocate_raw_memory(size):
"""
Allocates size bytes of raw memory using PyMem_RawMalloc and returns the address as an integer.
In case of a failure to allocate, return -1.
"""
PyMem_RawMalloc = pythonapi.PyMem_RawMalloc
PyMem_RawMalloc.r... | from solution import allocate_raw_memory, allocate_python_memory, free_raw_memory, free_python_memory, use_custom_allocator
def test_allocate_free_raw_memory():
address = allocate_raw_memory(128)
assert address > 0, "Failed to allocate raw memory"
free_raw_memory(address)
def test_allocate_free_python_mem... | [] | [
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl",
"solution_code": "\"\"\"\nThe Python code below demonstrates how to dynamically load the created C module named 'mymemory'.\nSince actual C extension implementat... | trial_gpt4o_3 | {
"original_instruction": "Python Memory Management\n\n**Objective:**\nDesign a Python extension (in C) that allocates and deallocates memory using Python's memory management functions. Understand and demonstrate the use of memory allocator domains and custom allocator settings.\n\n**Problem Statement:**\n\nYou are r... | 0.460472 | Docs: Python310_30792 | C | [
"allocate_raw_memory",
"allocate_python_memory",
"free_raw_memory",
"free_python_memory",
"use_custom_allocator"
] | 5 | [
[
"use_custom_allocator",
"allocate_python_memory"
],
[
"use_custom_allocator",
"free_python_memory"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 384cf445240ee30dfd688dec68db19d9c1321ab9 | 77f46b8c81f36c26633c47f123105d19d65b4d07 | |||
v1.0 | complete | Docs | Docs: Python310_31179_C | import asyncio
from pathlib import Path
BASE_DIR = Path('./www')
async def handle_client(reader, writer):
"""Handles incoming HTTP requests and serves static files.
- Reads the request line and headers from the client.
- Parses the request line to get the method, path, and version.
- Constructs the f... | import asyncio
from pathlib import Path
BASE_DIR = Path('./www')
# Mime type mapping for basic file types
MIME_TYPES = {
'html': 'text/html',
'txt': 'text/plain',
'css': 'text/css',
'js': 'application/javascript',
'json': 'application/json',
'png': 'image/png',
'jpg': 'image/jpeg',
'jp... | import asyncio
import pytest
import tempfile
import os
from pathlib import Path
from solution import main, BASE_DIR
# Helper function to run the server as a task
@pytest.fixture
async def http_server():
# Create temporary directory structure for serving files
with tempfile.TemporaryDirectory() as tempdir:
... | [
{
"docstring": null,
"function_declaration": "def get_mime_type(file_path):",
"function_name": "get_mime_type",
"parameter_list": "(file_path)"
}
] | [
0,
1,
0,
1,
1,
0,
1,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom pathlib import Path\n\nBASE_DIR = Path('./www')\n\nasync def handle_client(reader, writer):\n try:\n # Read and parse the request\n ... | trial_gpt4o_1 | {
"original_instruction": "**Question: Implement a Concurrent HTTP/1.0 Server Using asyncio Streams**\n\nIn this assessment, you will write a simplified HTTP/1.0 server using the asyncio streams library documented above. The server should handle multiple clients concurrently, serving static files from a directory.\n\... | 0.670546 | Docs: Python310_31179 | C | [
"get_mime_type",
"handle_client",
"main"
] | 3 | [
[
"handle_client",
"get_mime_type"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 19cc1bf9ab9c24002a6f3ca73b0e89e0e79a26a2 | eab188e6641ba55f55a503be86e32645485473fd | |||
v1.0 | complete | Docs | Docs: Pytorch_31554_C | import torch
import time
import random
def async_operation(index):
"""Simulate an asynchronous operation that takes a random time to complete."""
time.sleep(random.random())
return index
def perform_async_operations():
"""
Perform 10 asynchronous operations using torch.futures.Future and aggregate... | import time
import random
import torch
from concurrent.futures import ThreadPoolExecutor
def async_operation(index):
"""Simulate an asynchronous operation that takes a random time to complete."""
time.sleep(random.random())
return index
def perform_async_operations():
"""
Perform 10 asynchronous o... | def test_perform_async_operations():
result = perform_async_operations()
assert result == 45 # Sum of numbers from 0 to 9 is 45
def test_multiple_calls():
results = [perform_async_operations() for _ in range(5)]
for result in results:
assert result == 45 # Each call should produce the sum of ... | [
{
"docstring": "Simulate an asynchronous operation that takes a random time to complete.",
"function_declaration": "def async_operation(index):",
"function_name": "async_operation",
"parameter_list": "(index)"
},
{
"docstring": "Perform 10 asynchronous operations using torch.futures.Future a... | [
1,
0,
1,
0,
0,
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": "import torch\nimport time\nimport random\n\ndef async_operation(index):\n \"\"\"Simulate an asynchronous operation that takes a random time to complete.\"\"\"\n t... | trial_gpt4o_2 | {
"original_instruction": "### Asynchronous Programming in PyTorch using torch.futures\n\nIn this coding assessment, you will demonstrate your understanding of asynchronous programming with PyTorch's `torch.futures` package. You will need to implement a function that performs a series of asynchronous operations and s... | 0.498853 | Docs: Pytorch_31554 | C | [
"async_operation",
"perform_async_operations"
] | 2 | [
[
"perform_async_operations",
"async_operation"
]
] | 1 | [] | false | [] | false | pytest | false | [
"torch"
] | false | e99905f80abdc61ebf53965ffa7b466033a128f7 | f66ef51f27ab7e9d1a84b13a815b912456c0b8ce | |||
v1.0 | complete | Docs | Docs: Python310_30459_C | import contextvars
def create_context_variable(name, default_value):
"""
Create a new context variable.
Parameters:
name (str): The name of the context variable.
default_value: The default value of the context variable.
Returns:
ContextVar: A new context variable instance.
"""
pas... | import contextvars
import asyncio
def create_context_variable(name, default_value):
"""
Create a new context variable.
Parameters:
name (str): The name of the context variable.
default_value: The default value of the context variable.
Returns:
ContextVar: A new context variable instance.
... | import contextvars
import pytest
from solution import create_context_variable, set_context_value, get_context_value, reset_context_value
def test_create_context_variable():
var = create_context_variable("test_var", "default_value")
assert get_context_value(var) == "default_value"
def test_set_context_value():... | [
{
"docstring": "Create a new context variable.\n\nParameters:\nname (str): The name of the context variable.\ndefault_value: The default value of the context variable.\n\nReturns:\nContextVar: A new context variable instance.",
"function_declaration": "def create_context_variable(name, default_value):",
... | [
0,
0,
0,
0,
1,
1,
1,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import contextvars\n\ndef create_context_variable(name, default_value):\n \"\"\"\n Create a new context variable.\n\n Parameters:\n name (str): The name of ... | trial_gpt4o_4 | {
"original_instruction": "### Context Management in Python 3.7+\n\nIn Python, context variables enable the isolation of data between different execution contexts. Using the `contextvars` module in Python, you can create and manipulate context variables to achieve this isolation. This is especially useful in asynchro... | 0.454942 | Docs: Python310_30459 | C | [
"create_context_variable",
"set_context_value",
"get_context_value",
"reset_context_value",
"task",
"main"
] | 6 | [
[
"task",
"get_context_value"
],
[
"task",
"reset_context_value"
],
[
"task",
"set_context_value"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | a54d28c92a8f9d300e741ae427b14a3941a89ab6 | d1dd34c49ca141a61042ba7f96f64df044813793 | |||
v1.0 | complete | Docs | Docs: Pandas_29916_C | import pandas as pd
import numpy as np
data = {
'Product ID': [' P1 ', ' P2 ', ' P3', ' p4 ', ' P-5'],
'Product Name': ['Apple ', 'bAnana', 'Orange ', ' grape', ' Lemon'],
'Product Description': [' Fresh Apple', 'Best bananas*', 'Oranges##', 'Sweet Grapes', '**Fresh Lemon**'],
'Price': ['$1.20', '$... | import pandas as pd
import numpy as np
import re
def clean_product_id(df):
df['Product ID'] = df['Product ID'].str.strip().str.upper()
df['Product ID'] = df['Product ID'].str.replace(r'[^A-Z0-9]', '', regex=True)
return df
def clean_product_name(df):
df['Product Name'] = df['Product Name'].str.strip()... | import pandas as pd
from solution import clean_product_id, clean_product_name, clean_product_description, clean_price, apply_cleaning_functions
def test_clean_product_id():
data = {'Product ID': [' P1 ', ' P2 ', ' P3', ' p4 ', ' P-5']}
df = pd.DataFrame(data)
expected = ['P1', 'P2', 'P3', 'P4', 'P5']
... | [
{
"docstring": null,
"function_declaration": "def clean_product_id(df):",
"function_name": "clean_product_id",
"parameter_list": "(df)"
},
{
"docstring": null,
"function_declaration": "def clean_product_name(df):",
"function_name": "clean_product_name",
"parameter_list": "(df)"
... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport numpy as np\n\ndef clean_product_id(df):\n \"\"\"\n Cleans the 'Product ID' column in the given DataFrame.\n Strip leading/trailing... | trial_gpt4o_7 | {
"original_instruction": "**Pandas String Operations and Data Cleaning**\n\n**Objective:**\nTo assess your understanding of pandas string handling and manipulation techniques by performing a series of transformations on a dataset.\n\n**Background:**\nYou are provided with a DataFrame containing data about various pr... | 0.7957 | Docs: Pandas_29916 | C | [
"clean_product_id",
"clean_product_name",
"clean_product_description",
"clean_price",
"apply_cleaning_functions"
] | 5 | [
[
"apply_cleaning_functions",
"clean_price"
],
[
"apply_cleaning_functions",
"clean_product_description"
],
[
"apply_cleaning_functions",
"clean_product_id"
],
[
"apply_cleaning_functions",
"clean_product_name"
]
] | 4 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas"
] | false | 54296cee823b9f2b4c54a8bb4d38df2a34e2ed28 | 824e7d83eff7c12963fb80e4b0dba21cd3053923 | |||
v1.0 | complete | Docs | Docs: Pytorch_30667_C | import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.distributed.elastic.multiprocessing.errors import record
def setup(rank, world_size):
""" Initialize the process group for distributed training. """
... | import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.distributed.elastic.multiprocessing.errors import record
def setup(rank, world_size):
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_POR... | # Note: Due to the nature of distributed training requiring multiple GPUs
# and the environment setup, it is not feasible to provide unit test code
# for the script in a typical pytest framework. The distributed training
# script inherently requires execution in a distributed compute environment
# which pytest alone ca... | [] | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.multiprocessing as mp\nimport torch.distributed as dist\nfrom torch.nn.parallel import Di... | trial_gpt4o_8 | {
"original_instruction": "### PyTorch Distributed Training with Elasticity\n\nPyTorch's `torch.distributed.elastic` package allows for dynamically resizing distributed training jobs, making it easier to handle worker failures and resource fluctuations. Inside this package, the `control_plane` module provides tools f... | 0.597589 | Docs: Pytorch_30667 | C | [
"setup",
"cleanup",
"train_loop",
"main"
] | 4 | [
[
"train_loop",
"cleanup"
],
[
"train_loop",
"setup"
]
] | 2 | [] | false | [
"SimpleNN"
] | true | pytest | false | [
"torch"
] | false | c7dc7a05574d442984f2255ce1590f46ea20aa41 | 0382a28cdbc4afdca507acd260709bfeaa41ff27 | |||
v1.0 | complete | Docs | Docs: Python310_31556_C | import asyncio
import aiohttp
import os
from aiohttp import ClientSession
from typing import List
async def download_files(url_list: List[str], save_dir: str) -> List[str]:
""" Download multiple files concurrently from a list of URLs and save them to a specified directory.
Args:
url_list (List[str... | import asyncio
import aiohttp
import os
from aiohttp import ClientSession
from typing import List
async def download_file(session: ClientSession, url: str, save_dir: str) -> str:
try:
async with session.get(url) as response:
# Extract file name from URL
filename = os.path.basename(u... | import os
import tempfile
import asyncio
import aiohttp
from solution import download_files
# Sample URLs for testing
URLS = [
"https://example.com/file1.txt", # Replace with real URLs for actual tests
"https://example.com/file2.txt"
]
async def mock_download_file(session, url, save_dir):
"""A mock funct... | [] | [
0,
0,
0,
1,
1,
0,
1,
0,
0
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport aiohttp\nimport os\nfrom typing import List\n\nasync def download_file(session, url, save_path):\n try:\n async with session.get(url) a... | trial_gpt4o_7 | {
"original_instruction": "**Background:** \nYou are tasked with designing a simple file downloader using the `asyncio` library in Python. This should involve fetching multiple files concurrently from a list of URLs and storing them on the disk. You need to ensure that your program handles the concurrency properly an... | 0.602619 | Docs: Python310_31556 | C | [
"download_file",
"download_files"
] | 2 | [
[
"download_files",
"download_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 77444cb75624ef452289c350dba3852d415c6aee | 8a2b1d48b13a9c7ed4217f0a92f444d1501cecb8 | |||
v1.0 | complete | Docs | Docs: Python310_31434_C | import asyncio
from typing import List, Dict, Tuple
async def execute_commands(commands: List[Tuple[str, str]]) -> Dict[str, Tuple[str, str]]:
"""
Takes a list of shell commands, executes them concurrently using asynchronous I/O operations, and collects their output.
:param commands: List of tuples [(comm... | import asyncio
from typing import List, Dict, Tuple
async def run_command(command: str, input_data: str) -> Tuple[str, str]:
"""
Executes a single shell command asynchronously and returns the output and error.
"""
proc = await asyncio.create_subprocess_shell(
command,
stdin=asyncio.subp... | import asyncio
from solution import execute_commands
def test_commands_successful_execution():
commands = [
('echo "Hello, World!"', ''),
('ls /tmp', ''), # Assuming /tmp exists on the system
]
result = asyncio.run(execute_commands(commands))
assert result['echo "Hello, World!"'] == ('... | [] | [
0,
1,
1,
1,
1,
1,
0,
1,
1
] | 7 | easy | 0.778 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Dict, Tuple\n\nasync def run_command(command: str, input: str) -> Tuple[str, str]:\n process = await asyncio.create_subproce... | trial_gpt4o_9 | {
"original_instruction": "**Async Subprocess Management**\n\n### Problem Statement\nYou are required to implement a function that takes a list of shell commands, executes them concurrently using asynchronous I/O operations, and collects their output. Each command may optionally have an input string that should be se... | 0.665629 | Docs: Python310_31434 | C | [
"run_command",
"execute_commands"
] | 2 | [
[
"execute_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fe111104dc8390ebc4aad55005ace2ceadf99e95 | 9a31d4e090067b5eed8e9ff33b92515a8ff43c44 | |||
v1.0 | complete | Docs | Docs: Python310_30415_C | import os
import mailbox
def create_maildir(base_path, folder_name):
folder_path = os.path.join(base_path, folder_name)
maildir = mailbox.Maildir(folder_path, factory=None, create=True)
return maildir
def organize_emails(mbox_path, keywords_to_folders, output_dir):
""" Organize emails from mbox file i... | import os
import mailbox
import email
def create_maildir(base_path, folder_name):
folder_path = os.path.join(base_path, folder_name)
maildir = mailbox.Maildir(folder_path, factory=None, create=True)
return maildir
def organize_emails(mbox_path, keywords_to_folders, output_dir):
# Open the mbox file
... | import os
import shutil
import pytest
import mailbox
from solution import organize_emails
@pytest.fixture(scope="module")
def setup_mbox(tmp_path_factory):
mbox_dir = tmp_path_factory.mktemp("mbox")
mbox_path = os.path.join(mbox_dir, "test.mbox")
mbox = mailbox.mbox(mbox_path)
mbox.lock()
mes... | [
{
"docstring": null,
"function_declaration": "def create_maildir(base_path, folder_name):",
"function_name": "create_maildir",
"parameter_list": "(base_path, folder_name)"
},
{
"docstring": null,
"function_declaration": "def organize_emails(mbox_path, keywords_to_folders, output_dir):",
... | [
1,
0,
1,
0,
0,
1,
1,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport mailbox\nfrom email.utils import getaddresses\n\ndef organize_emails(mbox_path, keywords_to_folders, output_dir):\n \"\"\"\n Organizes emails fr... | trial_gpt4o_9 | {
"original_instruction": "**Question: Email Organizer**\n\nIn this exercise, you will implement a function that organizes emails from an mbox mailbox file into categorized Maildir mailboxes based on their subject lines. Your function should split emails into different folders depending on specific keywords present i... | 0.54795 | Docs: Python310_30415 | C | [
"create_maildir",
"organize_emails"
] | 2 | [
[
"organize_emails",
"create_maildir"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 61339ac62b81b78d3fcedefcdbc70c0fe363ef19 | 3512678365fe0afcc29973889aa01ba7f7e3c3ce | |||
v1.0 | complete | Docs | Docs: Python310_31527_C | import asyncio
import logging
logging.basicConfig(level=logging.INFO)
async def start_server(host: str, port: int):
""" Start an asynchronous echo server.
The server should handle multiple client connections simultaneously and echo back any message
received from a client. It should also log incoming... | import asyncio
import logging
logging.basicConfig(level=logging.INFO)
async def handle_client(reader, writer):
addr = writer.get_extra_info('peername')
logging.info(f"Connection from {addr}")
try:
while True:
data = await reader.read(100)
if not data:
loggi... | import asyncio
from solution import start_server
async def test_server():
server = asyncio.create_task(start_server('127.0.0.1', 8888))
await asyncio.sleep(1) # Allow server to start
reader, writer = await asyncio.open_connection('127.0.0.1', 8888)
message = "Hello, World!"
writer.write(message.e... | [] | [
0,
1,
1,
1,
1,
1,
1,
1,
1
] | 8 | easy | 0.889 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):\n addr = writer.get_extra_info('peername')\n print(f\"Conne... | trial_gpt4o_8 | {
"original_instruction": "### Asynchronous Network Server\n\n**Problem**: \n\nYou are required to implement an asynchronous echo server using the `asyncio` event loop functionalities. The server should be able to handle multiple client connections concurrently and echo back any message received from a client. The se... | 0.603146 | Docs: Python310_31527 | C | [
"handle_client",
"start_server"
] | 2 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8a8a0e8bea475f0fa74ddbc56285a2a67571f80e | 6de3d575319cb182f0aaf0d5e57ca32feaea40a1 | |||
v1.0 | complete | Docs | Docs: Seaborn_31194_C | import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
def create_custom_palettes():
"""
Creates three custom color palettes using seaborn's cubehelix_palette.
Returns a tuple of three palettes.
"""
# Create the palettes as described.
def plot_with_custom_palettes():
"""
... | import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
def create_custom_palettes():
"""
Creates three custom color palettes using seaborn's cubehelix_palette.
Returns a tuple of three palettes.
"""
# Palette 1: 10 colors, starting at 1.5, rotating by -0.8, with gamma 1.2
pale... | def test_custom_palettes_creation():
from solution import create_custom_palettes
# Ensure palettes are created as expected
palette1, palette2, palette3 = create_custom_palettes()
assert len(palette1) == 10, "Palette 1 should have 10 colors."
assert callable(palette2), "Palette 2 should be ... | [
{
"docstring": "Creates three custom color palettes using seaborn's cubehelix_palette.\nReturns a tuple of three palettes.",
"function_declaration": "def create_custom_palettes():",
"function_name": "create_custom_palettes",
"parameter_list": "()"
},
{
"docstring": "Plots a seaborn barplot i... | [
0,
1,
0,
1,
1,
0,
0,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef create_palettes():\n \"\"\"\n Creates three custom color palettes using seaborn'... | trial_gpt4o_9 | {
"original_instruction": "You are asked to demonstrate your understanding of seaborn's `cubehelix_palette` function by creating custom color palettes and using them in a seaborn plot.\n\n### Task\n\n1. **Create three custom color palettes** using the `sns.cubehelix_palette` function:\n - **Palette 1:** Should have... | 0.674125 | Docs: Seaborn_31194 | C | [
"create_custom_palettes",
"plot_with_custom_palettes"
] | 2 | [
[
"plot_with_custom_palettes",
"create_custom_palettes"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"seaborn"
] | false | d72092c22da2c968884c8f87289fec55774eb644 | b430734f250d21530baf77b27371dffe713df1b3 | |||
v1.0 | complete | Docs | Docs: Python310_31011_C | import argparse
import json
import os
DEFAULT_DB_FILE = 'items.json'
def load_items(db_file=DEFAULT_DB_FILE):
"""
Function to load items from the database file
"""
pass
def save_items(items, db_file=DEFAULT_DB_FILE):
"""
Function to save items to the database file
"""
pass
def add_it... | import argparse
import json
import os
# Define default database file path
DEFAULT_DB_FILE = 'items.json'
def load_items(db_file=DEFAULT_DB_FILE):
# Function to load items from the database file
if not os.path.exists(db_file):
return []
with open(db_file, 'r') as f:
return json.load(f)
def... | import pytest
import json
import os
from solution import load_items, save_items, add_item, query_items, delete_item, DEFAULT_DB_FILE
TEST_DB_FILE = 'test_items.json'
@pytest.fixture(autouse=True)
def run_around_tests():
# Code to run before each test
if os.path.exists(TEST_DB_FILE):
os.remove(TEST_DB_... | [
{
"docstring": null,
"function_declaration": "def load_items(db_file=DEFAULT_DB_FILE):",
"function_name": "load_items",
"parameter_list": "(db_file=DEFAULT_DB_FILE)"
},
{
"docstring": null,
"function_declaration": "def save_items(items, db_file=DEFAULT_DB_FILE):",
"function_name": "s... | [
1,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import argparse\nimport json\nimport os\n\n# Define default database file path\nDEFAULT_DB_FILE = 'items.json'\n\ndef load_items(db_file=DEFAULT_DB_FILE):\n # Functi... | trial_gpt4o_0 | {
"original_instruction": "**Python Coding Challenge: Enhanced Command Line Interface**\n\nThe goal of this exercise is to test your ability to create a comprehensive command-line interface using the `argparse` module.\n\n### Problem Statement:\n\nYou are required to create a Python script that processes a series of ... | 0.503794 | Docs: Python310_31011 | C | [
"load_items",
"save_items",
"add_item",
"query_items",
"delete_item",
"main"
] | 6 | [
[
"add_item",
"load_items"
],
[
"add_item",
"save_items"
],
[
"delete_item",
"load_items"
],
[
"delete_item",
"save_items"
],
[
"query_items",
"load_items"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | f34c31240398fc1f88a918f860f026493d81b4c5 | 54d30104b7152d9784ddc2c1e41e8fdc482151ef | |||
v1.0 | complete | Docs | Docs: Scikit_30927_C | import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import r2_score, mean_squar... | import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import r2_score, mean_squar... | import os
import pytest
from solution import preprocess_and_train
# Here we'll create a temporary CSV file for testing
@pytest.fixture
def create_csv_file(tmpdir):
data = {
'feature1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'feature2': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
'target': [3, 6, 9, 12, 15, ... | [
{
"docstring": null,
"function_declaration": "def load_data(file_path):",
"function_name": "load_data",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def preprocess_and_train(data_path):",
"function_name": "preprocess_and_train",
"parameter_list... | [
1,
0,
1,
0,
0,
1,
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 pandas as pd\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.linear_model import LinearRegression, Ridge\nfrom sklearn.metrics ... | trial_gpt4o_5 | {
"original_instruction": "## Coding Assessment Question\n\n### Objective:\nTo assess your understanding of linear models in `scikit-learn`, you are required to implement a machine-learning pipeline to solve a regression problem. Specifically, you will preprocess the data, select a linear model, perform hyperparamete... | 0.782527 | Docs: Scikit_30927 | C | [
"load_data",
"preprocess_and_train"
] | 2 | [
[
"preprocess_and_train",
"load_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas",
"sklearn"
] | false | 85c989e98d86f9f3f4a2baf46f002ce09cbd4944 | bb5e46556ceccfa016facfac523df9924e075cee | |||
v1.0 | complete | Docs | Docs: Python310_31350_C | import hashlib
import os
from typing import Tuple
def compute_hashes(file_path: str, blake2b_digest_size: int, salt: bytes) -> Tuple[str, str, str]:
"""
Computes SHA256, BLAKE2b, and salted BLAKE2b hashes of the file content.
:param file_path: Path to the input file.
:param blake2b_digest_size: D... | import hashlib
import os
def compute_hashes(file_path: str, blake2b_digest_size: int, salt: bytes) -> tuple:
"""
Computes SHA256, BLAKE2b, and salted BLAKE2b hashes of the file content.
:param file_path: Path to the input file.
:param blake2b_digest_size: Digest size for the BLAKE2b hash.
:par... | import pytest
from solution import compute_hashes, secure_password_hash, verify_file_integrity
def create_test_file(content: str) -> str:
file_path = 'testfile.txt'
with open(file_path, 'w') as f:
f.write(content)
return file_path
def test_compute_hashes():
content = "This is a test file."
... | [
{
"docstring": "Computes SHA256, BLAKE2b, and salted BLAKE2b hashes of the file content.\n\n:param file_path: Path to the input file.\n:param blake2b_digest_size: Digest size for the BLAKE2b hash.\n:param salt: The salt to use for the BLAKE2b hash.\n:return: A tuple of hashes in hexadecimal format (SHA256, BLAK... | [
1,
1,
0,
0,
1,
0,
1,
1,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\nfrom typing import Tuple\n\ndef compute_hashes(file_path: str, blake2b_digest_size: int, salt: bytes) -> Tuple[str, str, str]:\n \"\"\"\n Computes... | trial_gpt4o_9 | {
"original_instruction": "**Problem Statement: Implementing a Secure File Integrity Checker**\n\nYou are required to implement a secure file integrity checker using the `hashlib` module. The solution should handle the following requirements:\n\n1. **Compute Hashes:**\n - Compute the SHA256 hash of the file conten... | 0.686273 | Docs: Python310_31350 | C | [
"compute_hashes",
"secure_password_hash",
"verify_file_integrity"
] | 3 | [
[
"verify_file_integrity",
"compute_hashes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d00f37ff7b285cb7e53eb3656dd90d3bd98c4e64 | 6dc71da00057c49d0efaf86b4c35daf61aa36ce7 | |||
v1.0 | complete | Docs | Docs: Python310_31843_C | from contextlib import contextmanager, ExitStack
@contextmanager
def database_connection_manager():
"""Simulate a database connection context manager.
Acquires and releases a mock database connection.
>>> with database_connection_manager() as conn:
>>> print(f"Using {conn}")
Connection Acquired... | from contextlib import contextmanager, ExitStack
@contextmanager
def database_connection_manager():
"""
Simulate a database connection context manager.
Acquires and releases a mock database connection.
"""
print("Connection Acquired")
connection = "connection"
try:
yield connection
... | import pytest
from solution import database_connection_manager, manage_multiple_connections
def test_database_connection_manager(capsys):
try:
with database_connection_manager() as conn:
print(f"Using {conn}")
raise Exception("Test exception")
except Exception as e:
asse... | [
{
"docstring": "Simulate a database connection context manager.\nAcquires and releases a mock database connection.",
"function_declaration": "def database_connection_manager():",
"function_name": "database_connection_manager",
"parameter_list": "()"
},
{
"docstring": "Manages multiple databa... | [
1,
0,
0,
1,
1,
1,
1,
1,
0
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from contextlib import contextmanager, ExitStack\n\n@contextmanager\ndef database_connection_manager():\n try:\n # Simulate acquiring the database connection\... | trial_gpt4o_8 | {
"original_instruction": "### Python Coding Assessment Question\n\n**Objective**: Demonstrate your understanding of Python's `contextlib` module, particularly `contextmanager` decorator and `ExitStack`.\n\n#### Problem Statement\n\nYou are required to implement a custom context manager using the `contextlib.contextm... | 0.32668 | Docs: Python310_31843 | C | [
"database_connection_manager",
"manage_multiple_connections"
] | 2 | [
[
"manage_multiple_connections",
"database_connection_manager"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | de57ba20016e9186ff006d2330e1a1819f05745d | cacb462f73f44217d39c78ad90c5bdb4358ddc60 | |||
v1.0 | complete | Docs | Docs: Python310_30953_C | import aiohttp
import asyncio
from typing import List, Dict, Any
async def scrape_websites(urls: List[str], timeout: float) -> List[Dict[str, Any]]:
""" Asynchronous web scraper that fetches data from multiple websites concurrently.
If a request takes longer than the specified timeout, it is canceled.
The ... | import asyncio
import aiohttp
from typing import List, Dict, Any
async def fetch(session, url, timeout):
try:
async with session.get(url, timeout=timeout) as response:
content = await response.text()
return {
'url': url,
'status': 'success',
... | import asyncio
from solution import scrape_websites
async def test_scrape_websites_success():
urls = ["https://www.example.com", "https://www.python.org"]
timeout = 5.0
result = await scrape_websites(urls, timeout)
assert len(result) == 2
for res in result:
assert res['status'] == 'success'... | [] | [
1,
1,
0,
1,
0,
0,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport aiohttp\nfrom typing import List, Dict, Any\n\nasync def fetch(session, url, timeout):\n try:\n async with session.get(url, timeout=tim... | trial_gpt4o_0 | {
"original_instruction": "### Asynchronous Web Scraper Challenge\n\nYou have been tasked with writing an asynchronous web scraper using the `asyncio` library. This scraper will retrieve data from multiple websites concurrently to demonstrate your understanding of asynchronous programming with Python.\n\n#### Objecti... | 0.658043 | Docs: Python310_30953 | C | [
"fetch",
"scrape_websites"
] | 2 | [
[
"scrape_websites",
"fetch"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 3ef4f17d0c6077282d065234e4ea4c419b4e7646 | 161d4c66d47d000aef6d01761cbe484bb9ed19c2 | |||
v1.0 | complete | Docs | Docs: Python310_31518_C | import asyncio
import contextvars
from typing import List, Tuple
# Initialize context variable
task_counter = contextvars.ContextVar('task_counter', default=0)
async def task_incrementer(task_id: int, increments: int):
"""Increment the task_counter context variable independently for each task.
Args:
... | import asyncio
import contextvars
# Initialize context variable
task_counter = contextvars.ContextVar('task_counter', default=0)
async def task_incrementer(task_id: int, increments: int):
for _ in range(increments):
counter = task_counter.get()
task_counter.set(counter + 1)
print(f"Task {task_... | import pytest
import asyncio
from solution import task_incrementer, run_simulation
@pytest.mark.asyncio
async def test_task_incrementer():
initial_value = task_counter.get()
await task_incrementer(1, 5)
assert task_counter.get() == initial_value + 5
@pytest.mark.parametrize("task_configs,expected_results"... | [
{
"docstring": null,
"function_declaration": "def run_simulation(task_configs):",
"function_name": "run_simulation",
"parameter_list": "(task_configs)"
}
] | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport contextvars\n\n# Initialize context variable\ntask_counter = contextvars.ContextVar('task_counter', default=0)\n\nasync def task_incrementer(task... | trial_gpt4o_2 | {
"original_instruction": "**Managing Context-Sensitive State with Context Variables**\n\n### Objective\nYour task is to implement a state management system that demonstrates the use of the `contextvars` module to manage context-sensitive variables in an asynchronous environment.\n\n### Problem Statement\nCreate an a... | 0.574686 | Docs: Python310_31518 | C | [
"task_incrementer",
"run_simulation"
] | 2 | [
[
"run_simulation",
"task_incrementer"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 545fb7c9ac7763452f2f9a9d3aab02ac7a6f2518 | a5068e2dfc100f146a4f0036e3d47b108b390ddb | |||
v1.0 | complete | Docs | Docs: Python310_30850_C | from email.utils import parseaddr, formataddr, getaddresses
def parse_email(address: str, strict: bool = True) -> tuple:
"""Parse an email address string and return a tuple containing the real name and email address.
If the parsing fails, the function returns an empty tuple ('', '').
>>> parse_email("John ... | from email.utils import parseaddr, formataddr, getaddresses
def parse_email(address: str, strict: bool = True) -> tuple:
real_name, email_address = parseaddr(address)
if strict and '@' not in email_address:
return ('', '')
return (real_name, email_address)
def format_email(address_tuple: tuple, ch... | from solution import parse_email, format_email, extract_addresses
def test_parse_email():
assert parse_email("John Doe <john@example.com>") == ('John Doe', 'john@example.com')
assert parse_email("invalid email") == ('', '')
assert parse_email("No Name <noemail@here>") == ('No Name', 'noemail@here')
ass... | [
{
"docstring": null,
"function_declaration": "def parse_email(address, strict=True):",
"function_name": "parse_email",
"parameter_list": "(address, strict=True)"
},
{
"docstring": null,
"function_declaration": "def format_email(address_tuple, charset='utf-8'):",
"function_name": "for... | [
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": "from email.utils import parseaddr, formataddr, getaddresses\n\ndef parse_email(address: str, strict: bool = True) -> tuple:\n \"\"\"\n Parse the given email addre... | trial_gpt4o_8 | {
"original_instruction": "### Email Address Manipulation and Parsing\n\n**Objective**: Implement a set of functions to manipulate and parse email addresses using the `email.utils` module. This assessment will test your ability to handle common email-related operations in Python.\n\n#### Part 1: Parse Email Address\n... | 0.643354 | Docs: Python310_30850 | C | [
"parse_email",
"format_email",
"extract_addresses"
] | 3 | [
[
"extract_addresses",
"parse_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b98468b64c91901618665183604fb767ae82b05e | e830507fb73a3243d93f081581d62c37e0cbfbab | |||
v1.0 | complete | Docs | Docs: Python310_31497_C | import asyncio
from typing import List, Tuple
async def run_multiple_commands(commands: List[str], timeout: int) -> List[Tuple[str, int, str]]:
""" Execute multiple shell commands concurrently, collects their outputs, and enforces a timeout for each command.
Args:
commands (List[str]): A list of shell... | import asyncio
from typing import List, Tuple
async def run_command(command: str, timeout: int) -> Tuple[str, int, str]:
try:
proc = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
try:
... | import pytest
import asyncio
from solution import run_multiple_commands, run_command
@pytest.mark.asyncio
async def test_run_command_success():
result = await run_command('echo hello', 2)
assert result == ('echo hello', 0, 'hello')
@pytest.mark.asyncio
async def test_run_command_timeout():
result = await ... | [] | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def run_command(command: str, timeout: int) -> Tuple[str, int, str]:\n process = awa... | trial_gpt4o_2 | {
"original_instruction": "### Asynchronous Subprocess Management\n\nIn this task, you are required to write an asynchronous Python function that demonstrates your understanding of creating and managing subprocesses using the `asyncio` library in Python 3.10. \n\n#### Objective:\nWrite a function called `run_multiple... | 0.670377 | Docs: Python310_31497 | C | [
"run_command",
"run_multiple_commands"
] | 2 | [
[
"run_multiple_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 966a6af076869cb294733d2cdce9e99d3ea116b6 | aaf7ed6de40f34a735014acb5e6f4813fd59b8da | |||
v1.0 | complete | Docs | Docs: Python310_31390_C | import asyncio
from typing import List, Tuple
async def run_commands(commands: List[str], timeout: int) -> List[Tuple[str, int, str, str]]:
"""
Execute multiple commands concurrently, handle their outputs, errors, and manage potential timeouts.
Args:
commands (List[str]): List of shell commands to... | import asyncio
from typing import List, Tuple
async def run_command(command: str, timeout: int) -> Tuple[str, int, str, str]:
try:
proc = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
try... | import asyncio
from solution import run_commands
async def test_run_commands_success():
commands = ["echo Hello", "echo World"]
results = await run_commands(commands, timeout=5)
assert len(results) == 2
assert results[0][1] == 0
assert results[0][2].strip() == "Hello"
assert results[1][1] == 0
... | [] | [
1,
1,
1,
1,
0,
0,
1,
0,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def run_commands(commands: List[str], timeout: int) -> List[Tuple[str, int, str, str]]:\n async def run_comma... | trial_gpt4o_6 | {
"original_instruction": "#### **Objective**\nYou are required to implement a function using the `asyncio` subprocess APIs provided. This function should execute multiple commands concurrently, handle their outputs, errors, and manage potential timeouts.\n\n#### **Function Signature**\n\n```python\nimport asyncio\nf... | 0.622552 | Docs: Python310_31390 | C | [
"run_command",
"run_commands"
] | 2 | [
[
"run_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 928d96990b0766e95f9360649cefbdadc55ba720 | 2288b30b8849effe42f11e42ed7a056a471bf6f8 | |||
v1.0 | complete | Docs | Docs: Python310_32159_C | from typing import List
import multiprocessing
def parallel_compute_square_sum(numbers: List[int], num_workers: int) -> int:
"""
Computes the sum of squares of a list of numbers using parallel processing.
Args:
- numbers: List[int]: The list of numbers to process.
- num_workers: int: The numbe... | from typing import List
import multiprocessing
def compute_squares(numbers: List[int]) -> int:
"""
Helper function to compute the sum of squares of a list of numbers.
"""
return sum(number * number for number in numbers)
def parallel_compute_square_sum(numbers: List[int], num_workers: int) -> int:
... | from solution import parallel_compute_square_sum
def test_empty_list():
assert parallel_compute_square_sum([], 4) == 0
def test_single_element_list():
assert parallel_compute_square_sum([2], 2) == 4
def test_small_list():
assert parallel_compute_square_sum([1, 2, 3, 4], 2) == 30 # 1^2 + 2^2 + 3^2 + 4^2
... | [
{
"docstring": "Helper function to compute the sum of squares of a list of numbers.",
"function_declaration": "def compute_squares(numbers):",
"function_name": "compute_squares",
"parameter_list": "(numbers)"
},
{
"docstring": "Computes the sum of squares of a list of numbers using parallel ... | [
1,
1,
1,
0,
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": "from typing import List\nimport multiprocessing\n\ndef compute_square_sum(numbers: List[int]) -> int:\n return sum(x * x for x in numbers)\n\ndef parallel_compute_sq... | trial_gpt4o_5 | {
"original_instruction": "You have been assigned a task to design a multi-process system to perform a computationally intensive operation. You are required to write a Python program using the `multiprocessing` package that performs the following:\n\n**Task**: Implement a function `parallel_compute_square_sum` which ... | 0.741439 | Docs: Python310_32159 | C | [
"compute_squares",
"parallel_compute_square_sum"
] | 2 | [
[
"parallel_compute_square_sum",
"compute_squares"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8e2486644761ed517493341c10ec1db48f421ebb | 627b063050b64f963803b22ab2626107fd81217e | |||
v1.0 | complete | Docs | Docs: Pytorch_31488_C | import torch
import torch.nn as nn
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc1 = nn.Linear(10, 20)
self.fc2 = nn.Linear(20, 30)
self.fc3 = nn.Linear(30, 10)
def forward(self, x):
x = torch.relu(self.fc1(x))
... | import torch
import torch.nn as nn
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc1 = nn.Linear(10, 20)
self.fc2 = nn.Linear(20, 30)
self.fc3 = nn.Linear(30, 10)
def forward(self, x):
x = torch.relu(self.fc1(x))
... | def test_create_pipeline_stages():
stage_obj1, stage_obj2 = create_pipeline_stages()
assert isinstance(stage_obj1.model, nn.Sequential)
assert isinstance(stage_obj2.model, nn.Sequential)
assert stage_obj1.stage_index == 0
assert stage_obj2.stage_index == 1
def test_execute_pipeline_output_shape():
... | [] | [
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 torch\nimport torch.nn as nn\nfrom torch.distributed.pipelining import PipelineStage, ScheduleGPipe\n\nclass SimpleModel(nn.Module):\n def __init__(self):\n ... | trial_gpt4o_9 | {
"original_instruction": "**Pipeline Parallelism with PyTorch**:\n\nYou are tasked with implementing a model training using Pipeline Parallelism in PyTorch to understand its functionality and efficiency. You will demonstrate both creating pipeline stages manually and using them in a pipeline schedule.\n\n### Part 1:... | 0.561741 | Docs: Pytorch_31488 | C | [
"create_pipeline_stages",
"execute_pipeline"
] | 2 | [
[
"execute_pipeline",
"create_pipeline_stages"
]
] | 1 | [] | false | [
"SimpleModel"
] | true | pytest | false | [
"torch"
] | false | 4c96e273f0e23ac0030446d85c0f3b8e057dcb8d | 8a08e5ee94ae506aeff12c91f957394094b50b97 | |||
v1.0 | complete | Docs | Docs: Python310_32146_C | import grp
def get_all_member_names():
"""
Returns a set of unique user names that are members of any group.
"""
pass # Your implementation here
def find_groups_by_member(user_name):
"""
Returns a list of group names that the specified user is a member of.
:param user_name: The user'... | import grp
def get_all_member_names():
"""
Returns a set of unique user names that are members of any group.
"""
all_members = set()
for group in grp.getgrall():
all_members.update(group.gr_mem)
return all_members
def find_groups_by_member(user_name):
"""
Returns a list of grou... | from solution import get_all_member_names, find_groups_by_member, find_common_groups
import grp
import pytest
# Mock data for testing
mock_grp_data = [
grp.struct_group(('group1', 'x', 1001, ['user1', 'user2'])),
grp.struct_group(('group2', 'x', 1002, ['user2', 'user3'])),
grp.struct_group(('group3', 'x', ... | [
{
"docstring": "Returns a set of unique user names that are members of any group.",
"function_declaration": "def get_all_member_names():",
"function_name": "get_all_member_names",
"parameter_list": "()"
},
{
"docstring": "Returns a list of group names that the specified user is a member of.\... | [
1,
1,
0,
1,
1,
1,
1,
1,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import grp\n\ndef get_all_member_names():\n \"\"\"\n Returns a set of unique user names that are members of any group.\n \"\"\"\n all_members = set()\n f... | trial_gpt4o_8 | {
"original_instruction": "**Python Coding Assessment Question: Unix Group Membership Analysis**\n\nYou are given access to the Unix group database through Python's `grp` module. Your task is to implement a set of functions to analyze group memberships based on this data. Your functions should:\n\n1. **Get All Member... | 0.485237 | Docs: Python310_32146 | C | [
"get_all_member_names",
"find_groups_by_member",
"find_common_groups"
] | 3 | [
[
"find_common_groups",
"find_groups_by_member"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ce6b5896cf50a2013f917c40cf2a612ab66ae5e4 | 0e319a7ef121fa5f5e290fef026ced759d90a5f8 | |||
v1.0 | complete | Docs | Docs: Python310_31200_C | import asyncio
import logging
logging.basicConfig(level=logging.DEBUG)
async def io_task(task_data):
"""Simulate I/O-bound task processing."""
await asyncio.sleep(1)
return f"Processed IO task with data: {task_data}"
async def cpu_task(task_data):
"""Simulate CPU-bound task processing."""
import ... | import asyncio
import logging
import concurrent.futures
logging.basicConfig(level=logging.DEBUG)
async def io_task(task_data):
await asyncio.sleep(1) # Simulate I/O work
return f"Processed IO task with data: {task_data}"
async def cpu_task(task_data):
loop = asyncio.get_running_loop()
with concurren... | import pytest
import asyncio
import logging
from solution import io_task, cpu_task, process_task, main
logging.basicConfig(level=logging.DEBUG)
@pytest.mark.asyncio
async def test_io_task():
data = "http://example.com"
result = await io_task(data)
assert result == f"Processed IO task with data: {data}"
@... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\n\nasync def io_task(task_data):\n await asyncio.sleep(1) # Simulate I/O work\n return... | trial_gpt4o_7 | {
"original_instruction": "You are tasked with creating a Python application that simulates a concurrent task processing system using asyncio. The system must read tasks from a queue, process them asynchronously, and handle proper logging and error detection. \n\n### Requirements\n\n1. **Task Queue**: Implement a tas... | 0.509435 | Docs: Python310_31200 | C | [
"io_task",
"cpu_task",
"process_task",
"main",
"worker"
] | 5 | [
[
"process_task",
"cpu_task"
],
[
"process_task",
"io_task"
],
[
"worker",
"process_task"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 87fe1696a22d0907851b77f34fdbfbabc8046b9b | de7a90726e0257b006ff40066f2871a953bbee4a | |||
v1.0 | complete | Docs | Docs: Python310_31580_C | import os
import readline
def initialize_readline_config():
"""Reads and applies configuration from ~/.myreadlineconfig if it exists."""
pass
def load_command_history(file_path: str) -> int:
"""Loads the command history from the specified file and returns the history length before loading."""
pass
de... | import os
import readline
def initialize_readline_config():
"""Reads and applies configuration from ~/.myreadlineconfig if it exists."""
config_file = os.path.expanduser("~/.myreadlineconfig")
if os.path.exists(config_file):
with open(config_file, 'r') as f:
for line in f:
... | import os
import readline
from solution import initialize_readline_config, load_command_history, save_command_history, setup_autocompletion, start_custom_prompt
def test_initialize_readline_config(monkeypatch, tmp_path):
config_path = tmp_path / ".myreadlineconfig"
config_path.write_text("tab: complete\nset ed... | [
{
"docstring": "Reads and applies configuration from ~/.myreadlineconfig if it exists.",
"function_declaration": "def initialize_readline_config():",
"function_name": "initialize_readline_config",
"parameter_list": "()"
},
{
"docstring": "Loads the command history from the specified file and... | [
0,
0,
0,
1,
0,
0,
0,
0,
1
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import readline\nimport os\n\ndef initialize_readline_config():\n \"\"\"Reads and applies configuration from ~/.myreadlineconfig if it exists.\"\"\"\n config_file... | trial_gpt4o_3 | {
"original_instruction": "**Question: Implement a Custom Interactive Python Prompt**\n\nUsing the \"readline\" module in Python, write a custom interactive prompt that includes the following features:\n\n1. **Initialization from a Custom Configuration**: The prompt should read an initialization file (named `.myreadl... | 0.40917 | Docs: Python310_31580 | C | [
"initialize_readline_config",
"load_command_history",
"save_command_history",
"setup_autocompletion",
"start_custom_prompt"
] | 5 | [
[
"start_custom_prompt",
"initialize_readline_config"
],
[
"start_custom_prompt",
"load_command_history"
],
[
"start_custom_prompt",
"save_command_history"
],
[
"start_custom_prompt",
"setup_autocompletion"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 240c4dc64c85d62f112a41d77fecd1ebaf9d2ca3 | 583522ae0f734d89659c8f69aa55604a2fb0a08f | |||
v1.0 | complete | Docs | Docs: Python310_32112_C | import asyncio
async def fetch_data(server_id: int) -> str:
"""
Simulates fetching data from a server. It takes `server_id` as input
and returns a string indicating which server the data came from.
The function uses asyncio.sleep to simulate network delay.
:param server_id: The ID of the server t... | import asyncio
async def fetch_data(server_id: int) -> str:
"""
Simulates fetching data from a server. It takes `server_id` as input
and returns a string indicating which server the data came from.
The function uses asyncio.sleep to simulate network delay.
:param server_id: The ID of the server t... | import asyncio
from solution import fetch_data, manage_tasks
def test_fetch_data():
async def wrapper():
result = await fetch_data(1)
assert result == "Data from server 1"
asyncio.run(wrapper())
def test_manage_tasks_single_server():
async def wrapper():
server_ids = [1]
re... | [] | [
1,
1,
1,
1,
0,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def fetch_data(server_id: int) -> str:\n \"\"\"\n Simulates fetching data from a server. It takes `server_id` as input\n and returns a ... | trial_gpt4o_9 | {
"original_instruction": "#### Objective\nThis question assesses your understanding of Python's `asyncio` library, particularly in writing and managing asynchronous tasks and using synchronization primitives.\n\n#### Problem Statement\nYou are tasked with implementing an asynchronous task manager for a simple distri... | 0.574839 | Docs: Python310_32112 | C | [
"fetch_data",
"manage_tasks"
] | 2 | [
[
"manage_tasks",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | eede294146c11bddffb0e2cc76b56adbe74620b0 | 29b889f5904323f04dd83223da7918a278eeff81 | |||
v1.0 | complete | Docs | Docs: Python310_32086_C | import shelve
import re
def init_storage(filename):
"""
Initializes and returns a shelve storage.
:param filename: The name of the file to store the shelve data.
:return: A shelve storage.
"""
pass
def add_contact(storage, name, email, phone):
"""
Adds a new contact to the storage.
... | import shelve
import re
def init_storage(filename):
"""
Initializes and returns a shelve storage.
:param filename: The name of the file to store the shelve data.
:return: A shelve storage.
"""
return shelve.open(filename)
def is_valid_email(email):
"""
Validates the email format.
... | import pytest
import os
from solution import (
init_storage, add_contact, get_contact,
update_contact, delete_contact, list_contacts
)
import shelve
# Test file name
TEST_DB = 'test_contacts.db'
# Helper function to clean up test database to avoid data persistence across tests
def cleanup_db():
if os.path... | [
{
"docstring": "Initializes and returns a shelve storage.\n\n:param filename: The name of the file to store the shelve data.\n:return: A shelve storage.",
"function_declaration": "def init_storage(filename):",
"function_name": "init_storage",
"parameter_list": "(filename)"
},
{
"docstring": ... | [
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 shelve\nimport re\n\ndef init_storage(filename):\n \"\"\"\n Initializes and returns a shelf using the given filename.\n \"\"\"\n return shelve.open(f... | trial_gpt4o_9 | {
"original_instruction": "### Persistent Storage with Shelve\n\n**Objective:** \nYou are tasked with creating a small application that manages a collection of user contacts using the `shelve` module. Each contact should have the attributes: `name`, `email`, and `phone`. The program should support adding new contact... | 0.348107 | Docs: Python310_32086 | C | [
"init_storage",
"is_valid_email",
"is_valid_phone",
"add_contact",
"get_contact",
"update_contact",
"delete_contact",
"list_contacts"
] | 8 | [
[
"add_contact",
"is_valid_email"
],
[
"add_contact",
"is_valid_phone"
],
[
"update_contact",
"is_valid_email"
],
[
"update_contact",
"is_valid_phone"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 9f48ea662dc551ebad4e84bddbd736b0e926f431 | 9dad5efe669964de72a8c8dc35b47a485c1dd71f | |||
v1.0 | complete | Docs | Docs: Python310_31221_C | import hashlib
def create_hash(filepath: str, algorithm: str = 'sha256') -> str:
"""
Creates a hash digest for a given file using the specified algorithm.
Parameters:
filepath (str): The path to the file to be hashed.
algorithm (str): The hash algorithm to use (default is 'sha256').
R... | import hashlib
def create_hash(filepath: str, algorithm: str = 'sha256') -> str:
"""
Creates a hash digest for a given file using the specified algorithm.
Parameters:
filepath (str): The path to the file to be hashed.
algorithm (str): The hash algorithm to use (default is 'sha256').
Returns:
... | import os
from solution import create_hash, save_hash, load_hash, verify_file
def test_create_hash(tmp_path):
test_file = tmp_path / "test.txt"
test_file.write_text("hello world")
hash_digest = create_hash(test_file, 'sha256')
assert hash_digest == hashlib.sha256(b"hello world").hexdigest()
def t... | [
{
"docstring": "Creates a hash digest for a given file using the specified algorithm.\n\nParameters:\nfilepath (str): The path to the file to be hashed.\nalgorithm (str): The hash algorithm to use (default is 'sha256').\n\nReturns:\nstr: The hex digest of the file content.",
"function_declaration": "def cre... | [
0,
1,
1,
1,
0,
1,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\n\ndef create_hash(filepath: str, algorithm: str = 'sha256') -> str:\n \"\"\"\n Creates a hash digest for a given file using the specified algorith... | trial_gpt4o_8 | {
"original_instruction": "You are tasked with building a secure file integrity verification system using the `hashlib` module in Python. Your system should be able to create hash digests for files using different algorithms, save these digests for later comparison, and verify the integrity of files by checking if th... | 0.706263 | Docs: Python310_31221 | C | [
"create_hash",
"save_hash",
"load_hash",
"verify_file"
] | 4 | [
[
"verify_file",
"create_hash"
],
[
"verify_file",
"load_hash"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3180b074f7d28afa2a808f401d780156d0814d3b | bb36a6c3cee50cda01f50a5ba52152a47f4361cc | |||
v1.0 | complete | Docs | Docs: Pytorch_31864_C | import torch
def create_nested_block_mask(size: int, value: bool = True) -> torch.Tensor:
"""
Creates a nested block mask of given size. For simplicity, let's assume it creates a
block mask with a specified value (True/False).
"""
pass
def and_masks(mask1: torch.Tensor, mask2: torch.Tensor) -> to... | import torch
def create_nested_block_mask(size: int, value: bool = True) -> torch.Tensor:
"""
Creates a nested block mask of given size. For simplicity, let's assume it creates a
block mask with a specified value (True/False).
"""
return torch.full((size, size), value, dtype=torch.bool)
def and_m... | import torch
from solution import create_nested_block_mask, and_masks, or_masks, complex_mask_operations
def test_create_nested_block_mask():
size = 4
mask = create_nested_block_mask(size)
assert mask.shape == (4, 4)
assert torch.all(mask == True)
def test_create_nested_block_mask_false():
size = ... | [
{
"docstring": "Creates a nested block mask of given size. For simplicity, let's assume it creates a \nblock mask with a specified value (True/False).",
"function_declaration": "def create_nested_block_mask(size, value=True):",
"function_name": "create_nested_block_mask",
"parameter_list": "(size, v... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.nn.attention.flex_attention import create_nested_block_mask, and_masks, or_masks\n\ndef complex_mask_operations(size: int) -> torch.Tensor:\n ... | trial_gpt4o_5 | {
"original_instruction": "You are required to implement a function utilizing the block mask operations provided by the `torch.nn.attention.flex_attention` module. Specifically, your task is to create a complex mask using nested block masks and perform logical operations on these masks. \n\n#### Function Signature\n`... | 0.454685 | Docs: Pytorch_31864 | C | [
"create_nested_block_mask",
"and_masks",
"or_masks",
"complex_mask_operations"
] | 4 | [
[
"complex_mask_operations",
"and_masks"
],
[
"complex_mask_operations",
"create_nested_block_mask"
],
[
"complex_mask_operations",
"or_masks"
]
] | 3 | [] | false | [] | false | pytest | true | [
"torch"
] | false | e1bfd7cd91fbfaa2f952524c2bb47fc539735896 | 8c7b68d4c42e40eae506b8f69e639b7d2a8683af |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.