version
stringclasses
1 value
style
stringclasses
2 values
subset
stringclasses
12 values
question_id
stringlengths
9
23
question
stringlengths
27
8.13k
solution
stringlengths
99
5.97k
test
stringlengths
105
4.45k
test_info
listlengths
0
13
gpt_pass_sequence
listlengths
1
10
gpt_pass_trial_num
int64
1
10
gpt_difficulty
stringclasses
3 values
gpt_pass_percentage
float64
0.1
1
trials
dict
chosen_trial
stringclasses
10 values
metadata
dict
benchmark_similarity
float64
0.16
0.93
benchmark_instruction
stringclasses
1 value
benchmark_task_id
stringclasses
1 value
filter_reason
stringclasses
1 value
base_id
stringlengths
7
21
variant
stringclasses
2 values
top_function_names
listlengths
2
13
n_top_functions
int64
2
13
helper_call_edges
listlengths
1
16
n_helper_call_edges
int64
1
16
harness_functions
listlengths
0
3
structural_wrapper
bool
1 class
class_names
listlengths
0
5
has_class
bool
2 classes
test_kind
stringclasses
1 value
test_has_solution_import
bool
2 classes
third_party_imports
listlengths
0
5
stdlib_only
bool
2 classes
question_norm_sha1
stringlengths
40
40
solution_ast_sha1
stringlengths
40
40
v1.0
instruct
Docs
Docs: Python310_3456_I
### Remote Task Execution with XML-RPC **Objective**: Implement an XML-RPC server and a client that can communicate with each other to perform a series of mathematical operations on remote data. **Task**: You need to create an XML-RPC server that offers methods to perform basic mathematical operations (addition, subt...
from xmlrpc.server import SimpleXMLRPCServer def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): if y == 0: raise ZeroDivisionError("Cannot divide by zero.") return x / y def start_server(): server = SimpleXMLRPCServer(("lo...
from solution import add, subtract, multiply, divide import pytest def test_add(): assert add(10, 5) == 15 assert add(-1, 1) == 0 assert add(0, 0) == 0 def test_subtract(): assert subtract(10, 5) == 5 assert subtract(5, 10) == -5 assert subtract(0, 0) == 0 def test_multiply(): assert mult...
[ { "docstring": null, "function_declaration": "def add(x, y):", "function_name": "add", "parameter_list": "(x, y)" }, { "docstring": null, "function_declaration": "def subtract(x, y):", "function_name": "subtract", "parameter_list": "(x, y)" }, { "docstring": null, "fu...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from xmlrpc.server import SimpleXMLRPCServer\n\ndef add(x, y):\n return x + y\n\ndef subtract(x, y):\n return x - y\n\ndef multiply(x, y):\n return x * y\n\nde...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00003456", "row_id": 3456, "seed_ids": "[280]" }
0.428259
Docs: Python310_3456
I
[ "add", "subtract", "multiply", "divide", "start_server" ]
5
[ [ "start_server", "add" ], [ "start_server", "divide" ], [ "start_server", "multiply" ], [ "start_server", "subtract" ] ]
4
[]
false
[]
false
pytest
true
[]
true
ecc4f7b41cb24a73674968f23e109c070b4c861d
ee8400304514be5de2ac7555fa3ede03e44ec90c
v1.0
instruct
Docs
Docs: Python310_3464_I
**Objective:** Demonstrate your understanding and effective use of the `unittest.mock` module in Python to create, configure, and assert interactions with mock objects. This question assesses your ability to use `Mock`, `patch`, and their various features. **Question:** Your task is to write a unit test for a functi...
import requests def fetch_data_and_process(url, db): response = requests.get(url) if response.status_code == 200: data = response.json() processed_data = process_data(data) db.save(processed_data) else: raise ValueError(f"Failed to fetch data: {response.status_code}") def p...
import unittest from unittest.mock import patch, Mock from solution import fetch_data_and_process class TestFetchDataAndProcess(unittest.TestCase): @patch('solution.requests.get') def test_successful_fetch_and_process(self, mock_get): url = "http://example.com/data" db = Mock() mock_ge...
[ { "docstring": null, "function_declaration": "def fetch_data_and_process(url, db):", "function_name": "fetch_data_and_process", "parameter_list": "(url, db)" }, { "docstring": null, "function_declaration": "def process_data(data):", "function_name": "process_data", "parameter_lis...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\n\ndef fetch_data_and_process(url, db):\n response = requests.get(url)\n if response.status_code == 200:\n data = response.json()\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003464", "row_id": 3464, "seed_ids": "[375]" }
0.68183
Docs: Python310_3464
I
[ "fetch_data_and_process", "process_data" ]
2
[ [ "fetch_data_and_process", "process_data" ] ]
1
[ "process_data" ]
false
[]
false
pytest
true
[ "requests" ]
false
253e13db00a227b70c8c69456ecd19a0ec98b05f
8f3e2f57ba8d081438f2d8e5c9139bc63da1a372
v1.0
instruct
Docs
Docs: Pytorch_3466_I
### PyTorch Gradient Check and Validation **Objective:** Implement and validate gradient computation for a custom PyTorch function using `gradcheck` and `gradgradcheck`. **Problem Statement:** You are given a custom function implemented in PyTorch. Your task is to write a function to compute its gradients and valid...
import torch def custom_function(x): """ Computes the custom function f(x) = x^3 - 2x^2 + x. Args: x (torch.Tensor): Input tensor with requires_grad=True. Returns: torch.Tensor: Output of the function. """ return x**3 - 2*x**2 + x def validate_gradient(x): """ Validates the g...
import pytest import torch from solution import custom_function, validate_gradient def test_custom_function_output(): x = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float64, requires_grad=True) expected = x**3 - 2*x**2 + x assert torch.allclose(custom_function(x), expected, atol=1e-6), "custom_function outp...
[ { "docstring": "Computes the custom function f(x) = x^3 - 2x^2 + x.\n\nArgs:\nx (torch.Tensor): Input tensor with requires_grad=True.\n\nReturns:\ntorch.Tensor: Output of the function.", "function_declaration": "def custom_function(x):", "function_name": "custom_function", "parameter_list": "(x)" ...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\n\ndef custom_function(x):\n \"\"\"\n Computes the function f(x) = x^3 - 2x^2 + x.\n Args:\n - x (torch.Tensor): Input tensor.\n \n Retur...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00003466", "row_id": 3466, "seed_ids": "[179]" }
0.456582
Docs: Pytorch_3466
I
[ "custom_function", "validate_gradient" ]
2
[ [ "validate_gradient", "custom_function" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
89aebc8f51af34f194b23d6e83546848c935992e
20f3d49f9c1b4cfc7bfb3570f1663a7427ed833f
v1.0
instruct
Docs
Docs: Python310_3471_I
Custom Exception Handling and Propagation #### Objective: Demonstrate your understanding of Python exception handling by implementing custom exceptions and effectively propagating exceptions through various layers of a program. #### Problem Description: You are tasked with designing a flight booking system that requi...
class BaseBookingError(Exception): pass class InvalidBookingError(BaseBookingError): pass class BookingDatabaseError(BaseBookingError): pass class BookingNetworkError(BaseBookingError): pass def create_booking(booking_details): """ Create a booking with the given details. Args: ...
import pytest from solution import BaseBookingError, InvalidBookingError, BookingDatabaseError, BookingNetworkError, create_booking, save_booking_to_database, send_booking_confirmation, handle_booking def test_create_booking_with_invalid_details(): with pytest.raises(InvalidBookingError): create_booking({"...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class BaseBookingError(Exception):\n pass\n\nclass InvalidBookingError(BaseBookingError):\n pass\n\nclass BookingDatabaseError(BaseBookingError):\n pass\n\ncla...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003471", "row_id": 3471, "seed_ids": "[33]" }
0.440414
Docs: Python310_3471
I
[ "create_booking", "save_booking_to_database", "send_booking_confirmation", "handle_booking" ]
4
[ [ "handle_booking", "create_booking" ], [ "handle_booking", "save_booking_to_database" ], [ "handle_booking", "send_booking_confirmation" ] ]
3
[]
false
[ "BaseBookingError", "InvalidBookingError", "BookingDatabaseError", "BookingNetworkError" ]
true
pytest
true
[]
true
7677cc3a7c27ef5080e6727f8897cc953eafdc5c
72d08a46b2c3bba9f7cd15307652316be6ca6db5
v1.0
instruct
Docs
Docs: Python310_3544_I
### Coding Assessment: Profiling and Analyzing Python Code Execution #### Objective: Your task is to demonstrate your comprehension of Python's `cProfile` and `pstats` modules by profiling a Python function and analyzing the results. #### Problem Statement: You are provided with a Python script that executes a comput...
import cProfile import pstats def heavy_computation(n): import time start = time.time() for i in range(n): for _ in range(10000): sum(range(100)) end = time.time() print(f"Computation finished in {end - start:.2f} seconds") def profile_heavy_computation(): """ Profiles ...
def test_profile_heavy_computation(): profile_heavy_computation() import os assert os.path.exists('profile_results.prof') def test_analyze_profile_results(capsys): analyze_profile_results() captured = capsys.readouterr() assert "ncalls" in captured.out assert "tottime" in captured.out a...
[ { "docstring": null, "function_declaration": "def heavy_computation(n):", "function_name": "heavy_computation", "parameter_list": "(n)" }, { "docstring": "Profiles the heavy_computation function and saves the results to 'profile_results.prof'.", "function_declaration": "def profile_heavy...
[ 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 cProfile\nimport pstats\nimport time\n\ndef heavy_computation(n):\n start = time.time()\n for i in range(n):\n for _ in range(10000):\n s...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003544", "row_id": 3544, "seed_ids": "[142]" }
0.547013
Docs: Python310_3544
I
[ "heavy_computation", "profile_heavy_computation", "analyze_profile_results" ]
3
[ [ "profile_heavy_computation", "heavy_computation" ] ]
1
[]
false
[]
false
pytest
false
[]
true
0d04c09c7886f4da17356babd578bda9ad12c30e
00e797725f383c9da3011c4cc28ca0bb25c98a73
v1.0
instruct
Docs
Docs: Python310_3554_I
### Python Coding Assessment #### Objective Your task is to implement a system that utilizes `contextvars` to manage state during asynchronous operations. You will create context variables, manage their state, and use them in an asynchronous function. #### Problem Statement 1. **Context Variable Initialization and ...
import contextvars import asyncio from typing import List # Step 1: Define the ContextVar for request_id request_id = contextvars.ContextVar('request_id') # Step 2: Implement the initialize_request function def initialize_request(request_id_value: str): request_id.set(request_id_value) # Step 3: Implement the pr...
import asyncio from solution import initialize_request, process_request, handle_requests def test_process_request_single(): async def run_test(): result = await process_request("req_123") assert result == "Processed request ID: req_123" asyncio.run(run_test()) def test_handle_requests...
[ { "docstring": null, "function_declaration": "def initialize_request(request_id_value):", "function_name": "initialize_request", "parameter_list": "(request_id_value)" } ]
[ 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 contextvars\nimport asyncio\nfrom typing import List\n\n# Step 1: Define the ContextVar for request_id\nrequest_id = contextvars.ContextVar('request_id')\n\n# St...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00003554", "row_id": 3554, "seed_ids": "[392]" }
0.504442
Docs: Python310_3554
I
[ "initialize_request", "process_request", "handle_requests" ]
3
[ [ "handle_requests", "process_request" ], [ "process_request", "initialize_request" ] ]
2
[]
false
[]
false
pytest
true
[]
true
6e7db438a645766686339b28463a16622a41c57f
d04c288a1402c5e9d4c2056ed7b71b3e2f1816f2
v1.0
instruct
Docs
Docs: Python310_3570_I
#### Objective Implement a Python function that processes transaction records using functional programming concepts such as iterators, generators, and higher-order functions. #### Problem Statement You are given a list of transaction records, where each record is a tuple containing the following information: - `transa...
from functools import reduce def filter_records(records, category): """ Filters the transaction records by the given category. """ return list(filter(lambda record: record[3] == category, records)) def calculate_total_amount(records, transaction_type): """ Calculates the total amount for the g...
from solution import filter_records, calculate_total_amount, generate_summary def test_filter_records(): transactions = [ ("T1", 100.0, "credit", "food"), ("T2", 50.0, "debit", "food"), ("T3", 200.0, "credit", "utility"), ("T4", 150.0, "debit", "utility"), ("T5", 300.0, "cre...
[ { "docstring": "Filters the transaction records by the given category.", "function_declaration": "def filter_records(records, category):", "function_name": "filter_records", "parameter_list": "(records, category)" }, { "docstring": "Calculates the total amount for the given transaction type....
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from functools import reduce\n\ndef filter_records(records, category):\n \"\"\"\n Filters the transaction records based on the given category.\n\n :param recor...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003570", "row_id": 3570, "seed_ids": "[78]" }
0.531277
Docs: Python310_3570
I
[ "filter_records", "calculate_total_amount", "generate_summary" ]
3
[ [ "generate_summary", "calculate_total_amount" ], [ "generate_summary", "filter_records" ] ]
2
[]
false
[]
false
pytest
true
[]
true
9d41873655f9b4c8c1d4789dddb9171e048c8b3c
e884d811d67775767602be45b8cef0188577dfb8
v1.0
instruct
Docs
Docs: Python310_3633_I
#### Objective: Write a Python function that compares the execution times of different approaches for solving a problem using the `timeit` module. #### Problem Description: You are given a list of integers. Your task is to write three different functions to find the sum of all integers in the list. Use the `timeit` mo...
import timeit def sum_by_for_loop(numbers): total = 0 for num in numbers: total += num return total def sum_by_built_in(numbers): return sum(numbers) def sum_by_list_comprehension(numbers): return sum([num for num in numbers]) def compare_sum_methods(numbers: list[int], repetitions: int)...
from solution import compare_sum_methods def test_compare_sum_methods(): numbers = [i for i in range(1000)] repetitions = 3 result = compare_sum_methods(numbers, repetitions) assert "for_loop" in result assert "built_in_sum" in result assert "list_comprehension_sum" in result assert r...
[ { "docstring": null, "function_declaration": "def sum_by_for_loop(numbers):", "function_name": "sum_by_for_loop", "parameter_list": "(numbers)" }, { "docstring": null, "function_declaration": "def sum_by_built_in(numbers):", "function_name": "sum_by_built_in", "parameter_list": "...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import timeit\n\ndef sum_with_for_loop(numbers):\n total = 0\n for number in numbers:\n total += number\n return total\n\ndef sum_with_builtin_sum(numbe...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003633", "row_id": 3633, "seed_ids": "[328]" }
0.576966
Docs: Python310_3633
I
[ "sum_by_for_loop", "sum_by_built_in", "sum_by_list_comprehension", "compare_sum_methods" ]
4
[ [ "compare_sum_methods", "sum_by_built_in" ], [ "compare_sum_methods", "sum_by_for_loop" ], [ "compare_sum_methods", "sum_by_list_comprehension" ] ]
3
[]
false
[]
false
pytest
true
[]
true
679a9214a5ddd2856efc84ea9dee24afe9b45e0f
c2eb4c7824751749212f08a5edc5227f035262fc
v1.0
instruct
Docs
Docs: Python310_3648_I
### Custom Exception Handling in Python #### Objective: Design and implement a custom exception hierarchy to handle specific error scenarios in a database interaction module. This will evaluate your ability to define custom exceptions, raise them appropriately, and ensure proper exception chaining and context. #### T...
class DatabaseError(Exception): """Base class for other database-related exceptions.""" pass class ConnectionError(DatabaseError): """Raised when there is a connection issue to the database.""" pass class QueryError(DatabaseError): """Raised when a query fails due to invalid syntax or execution is...
import pytest from solution import DatabaseError, ConnectionError, QueryError, DataError, connect_to_database, execute_query, process_data, database_operation def test_valid_connection(): assert connect_to_database("valid_connection_string") is None def test_invalid_connection(): with pytest.raises(Connection...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class DatabaseError(Exception):\n \"\"\"Base class for other database-related exceptions.\"\"\"\n pass\n\nclass ConnectionError(DatabaseError):\n \"\"\"Raised ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003648", "row_id": 3648, "seed_ids": "[256]" }
0.472041
Docs: Python310_3648
I
[ "connect_to_database", "execute_query", "process_data", "database_operation" ]
4
[ [ "database_operation", "connect_to_database" ], [ "database_operation", "execute_query" ], [ "database_operation", "process_data" ] ]
3
[ "process_data" ]
false
[ "DatabaseError", "ConnectionError", "QueryError", "DataError" ]
true
pytest
true
[]
true
c69b6f4de17e8e30fb664df01935b0c7207aeb73
96048517f4015db4d5dca2714d655c4514cdaa98
v1.0
instruct
Docs
Docs: Python310_3691_I
### Problem Description You are required to create a utility that configures and retrieves MIME type handling commands based on a user's custom mailcap file configuration. #### Task 1. **Create a function `parse_mailcap_entry(entry: str) -> Dict[str, Any]`**: - Input: A string entry from a mailcap file. - Ou...
import os from typing import Dict, Any, List, Optional def parse_mailcap_entry(entry: str) -> Dict[str, Any]: fields = entry.split(';') if len(fields) < 2: # Invalid entry, should at least contain mime type and command return {} mime_type = fields[0].strip() entries = { 'view': ...
import pytest from solution import parse_mailcap_entry, load_mailcap, generate_command def test_parse_mailcap_entry(): entry = "video/mpeg; xmpeg %s" expected_output = { "video/mpeg": { "view": "xmpeg %s" } } assert parse_mailcap_entry(entry) == expected_output entry = ...
[ { "docstring": null, "function_declaration": "def parse_mailcap_entry(entry):", "function_name": "parse_mailcap_entry", "parameter_list": "(entry)" }, { "docstring": null, "function_declaration": "def load_mailcap(filepath):", "function_name": "load_mailcap", "parameter_list": "(...
[ 0, 0, 0, 1, 0, 1, 1, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def parse_mailcap_entry(entry):\n \"\"\"\n Parses a single mailcap entry into a dictionary.\n \n Parameters:\n entry (str): A single line from a mailcap ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00003691", "row_id": 3691, "seed_ids": "[399]" }
0.495776
Docs: Python310_3691
I
[ "parse_mailcap_entry", "load_mailcap", "generate_command" ]
3
[ [ "generate_command", "load_mailcap" ], [ "load_mailcap", "parse_mailcap_entry" ] ]
2
[]
false
[]
false
pytest
true
[]
true
817734936c9873e5c4adfba4a2b8b2a3f7d7c712
b017e491ef37e03867d3cec54b2edf5c5540c1fb
v1.0
instruct
Docs
Docs: Python310_3704_I
**Question: File Synchronization Tool** Your task is to implement a function `synchronize_directories(src: str, dest: str) -> None` that synchronizes two directories. The function should ensure that the destination directory is an exact copy of the source directory. This includes creating, updating, and deleting files...
from pathlib import Path import shutil def synchronize_directories(src: str, dest: str) -> None: src_path = Path(src) dest_path = Path(dest) # Ensure destination exists dest_path.mkdir(parents=True, exist_ok=True) for item in src_path.rglob('*'): rel_path = item.relative_to(src_pa...
import os from pathlib import Path import shutil import pytest from solution import synchronize_directories @pytest.fixture(autouse=True) def setup_and_teardown(tmp_path): src = tmp_path / "src" dest = tmp_path / "dest" src.mkdir() dest.mkdir() (src / "file1.txt").write_text("hello") ...
[ { "docstring": null, "function_declaration": "def synchronize_directories(src, dest):", "function_name": "synchronize_directories", "parameter_list": "(src, dest)" }, { "docstring": null, "function_declaration": "def file_contents_are_equal(file1, file2):", "function_name": "file_con...
[ 0, 0, 1, 0, 1, 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": "from pathlib import Path\nimport shutil\n\ndef synchronize_directories(src: str, dest: str) -> None:\n \"\"\"\n Synchronizes the destination directory to make it ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00003704", "row_id": 3704, "seed_ids": "[168]" }
0.709537
Docs: Python310_3704
I
[ "synchronize_directories", "file_contents_are_equal" ]
2
[ [ "synchronize_directories", "file_contents_are_equal" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b0f030a4f1cee3ce4157af22c86052b6f8f8c9a3
42562d8667dbf7b4ad519edc8adefbb8c750a9a0
v1.0
instruct
Docs
Docs: Scikit_3724_I
### Question: Implement and Evaluate a Multioutput Regressor with Scikit-learn In this task, you are required to build, train, and evaluate a multioutput regressor using scikit-learn. You will work with a dataset to predict multiple numerical outputs from given inputs. ### Requirements: 1. **Dataset**: Load the prov...
import numpy as np import pandas as pd from sklearn.multioutput import MultiOutputRegressor from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_squared_error def load_dataset(file_path, n_features): """ Load the dataset from the CSV file. Args: - file_path (str)...
import numpy as np import pandas as pd from solution import load_dataset, train_and_evaluate import os def create_dummy_dataset(file_path): data = { 'feature_1': [1.0, 2.0, 3.0, 4.0, 5.0], 'feature_2': [2.0, 3.0, 4.0, 5.0, 6.0], 'target_1': [1.1, 2.1, 3.1, 4.1, 5.1], 'target_2': [2....
[ { "docstring": "Load the dataset from the CSV file.\n\nArgs:\n- file_path (str): Path to the CSV file.\n- n_features (int): Number of feature columns.\n\nReturns:\n- X (numpy array): Input features.\n- y (numpy array): Target variables.", "function_declaration": "def load_dataset(file_path, n_features):", ...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport pandas as pd\nfrom sklearn.multioutput import MultiOutputRegressor\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.metr...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003724", "row_id": 3724, "seed_ids": "[56]" }
0.654123
Docs: Scikit_3724
I
[ "load_dataset", "train_and_evaluate" ]
2
[ [ "train_and_evaluate", "load_dataset" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "pandas", "sklearn" ]
false
0003122670538e3d0c99b144ba72cce56c8aaa63
4c358a644b6721b92c537a83aa319cb8fd6edc68
v1.0
instruct
Docs
Docs: Python310_3730_I
File Operations and Command-Line Parsing #### Objective: You are tasked with implementing a Python script that performs specific file operations based on command-line arguments provided by the user. This will assess your understanding of the `os` and `argparse` modules. #### Problem Statement: Write a Python function...
import os import argparse def list_files(directory): try: files = os.listdir(directory) files = [f for f in files if os.path.isfile(os.path.join(directory, f))] for file in files: print(file) except FileNotFoundError: print(f"Error: The directory '{directory}' does n...
import os import shutil import pytest from solution import list_files, create_file, delete_file @pytest.fixture def setup_directory(tmp_path): test_dir = tmp_path / "test_dir" test_dir.mkdir() (test_dir / "file1.txt").write_text("Hello world") (test_dir / "file2.txt").write_text("Hello again") ret...
[ { "docstring": null, "function_declaration": "def list_files(directory):", "function_name": "list_files", "parameter_list": "(directory)" }, { "docstring": null, "function_declaration": "def create_file(directory, filename):", "function_name": "create_file", "parameter_list": "(d...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport argparse\n\ndef list_files(directory):\n try:\n files = os.listdir(directory)\n for file in files:\n print(file)\n exce...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00003730", "row_id": 3730, "seed_ids": "[165]" }
0.635508
Docs: Python310_3730
I
[ "list_files", "create_file", "delete_file", "file_manager" ]
4
[ [ "file_manager", "create_file" ], [ "file_manager", "delete_file" ], [ "file_manager", "list_files" ] ]
3
[]
false
[]
false
pytest
true
[]
true
cea61b6300d8cc5bf172ffce3deae45a736f01c6
24cbbe982a6604f725c2d17544b2d8ca03ce1bf4
v1.0
instruct
Docs
Docs: Python310_3746_I
#### Objective: Demonstrate your understanding of the asyncio event loop by implementing a server-client system where the server echoes messages sent by the clients. Additionally, use scheduled callbacks to periodically send a status update to connected clients. #### Question: You need to implement an asynchronous ser...
import asyncio clients = [] async def handle_client(reader, writer): addr = writer.get_extra_info('peername') print(f"Connected to {addr}") clients.append(writer) try: while True: data = await reader.read(100) if not data: break message = da...
import asyncio import pytest from unittest.mock import patch, MagicMock from solution import start_server, start_client @pytest.fixture def event_loop(): loop = asyncio.new_event_loop() yield loop loop.close() @pytest.mark.asyncio async def test_server_start(event_loop): with patch('solution.handle_c...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nclients = []\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n print(f\"Connected to {addr}\")\n\n cli...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00003746", "row_id": 3746, "seed_ids": "[267]" }
0.640983
Docs: Python310_3746
I
[ "handle_client", "status_update", "start_server", "start_client" ]
4
[ [ "start_server", "handle_client" ], [ "start_server", "status_update" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5e10a6d0dcfc7d971129d0f187fbb2939e911be6
94acd8efb503e8506f2ff6129b25d201cec2c034
v1.0
instruct
Docs
Docs: Python310_3753_I
### Asynchronous File Processing with asyncio You are tasked with creating a Python script that reads data from multiple files concurrently, processes the content asynchronously, and writes the processed content to new output files using the asyncio package. The required operations include reading the input files, pro...
import asyncio import os async def read_file(file_path: str) -> str: """ Reads the entire content of the given file asynchronously. Arguments: file_path : str : Path to the input file Returns: str : Content of the file """ try: async with aiofiles.open(file_path, 'r') as file:...
import asyncio import os import pytest from solution import read_file, process_data, write_file, process_files_concurrently # Assuming these are the example files and files exist temporarily for the test cases input_files = ['test_file1.txt', 'test_file2.txt'] output_files = ['test_file1_processed.txt', 'test_file2_pr...
[ { "docstring": "The main function to execute the file processing tasks.", "function_declaration": "def main():", "function_name": "main", "parameter_list": "()" } ]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport os\n\nasync def read_file(file_path: str) -> str:\n \"\"\"\n Reads the entire content of the given file asynchronously.\n\n Arguments:\n...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00003753", "row_id": 3753, "seed_ids": "[360]" }
0.504439
Docs: Python310_3753
I
[ "read_file", "process_data", "write_file", "process_files_concurrently", "main" ]
5
[ [ "process_files_concurrently", "process_data" ], [ "process_files_concurrently", "read_file" ], [ "process_files_concurrently", "write_file" ] ]
3
[ "process_data" ]
false
[]
false
pytest
true
[]
true
229c04f40446567f956d93a4845aeb5d46b4bdc2
3cbd6e57a6a05f6b45b75b2e13271d583aa2054e
v1.0
instruct
Docs
Docs: Pytorch_3812_I
**Question:** You are required to build a custom neural network model using PyTorch's `torch.nn` module. This custom model will be a multilayer perceptron (MLP) designed for the task of classifying handwritten digits from the MNIST dataset. Additionally, you will need to register forward and backward hooks to monitor ...
import torch import torch.nn as nn class CustomMLP(nn.Module): def __init__(self): super(CustomMLP, self).__init__() # Define layers self.fc1 = nn.Linear(784, 128) self.relu1 = nn.ReLU() self.dropout1 = nn.Dropout(p=0.5) self.fc2 = nn.Linear(128, 64) self.rel...
import pytest import torch import torch.nn as nn from solution import CustomMLP def test_custom_mlp_structure(): model = CustomMLP() # Check if the model has the correct layers assert isinstance(model.fc1, nn.Linear) assert model.fc1.in_features == 784 assert model.fc1.out_features == 128 ...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\n\nclass CustomMLP(nn.Module):\n def __init__(self):\n super(CustomMLP, self).__init__()\n # Define layers\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00003812", "row_id": 3812, "seed_ids": "[142]" }
0.594201
Docs: Pytorch_3812
I
[ "print_output_shape", "print_gradients", "train_model" ]
3
[ [ "train_model", "print_gradients" ], [ "train_model", "print_output_shape" ] ]
2
[]
false
[ "CustomMLP" ]
true
pytest
true
[ "torch", "torchvision" ]
false
82fba75934a430ccd0c3db5b7c82e267e98e6192
382aa87691112f1b31c3213c9b66c1118c80bf28
v1.0
instruct
Docs
Docs: Python310_3837_I
**Objective:** Demonstrate competence in utilizing Python's system-level modules to create a complex utility. ### Problem Statement: You are required to create a Python script that performs the following system-level tasks using the `os`, `time`, and `logging` modules: 1. **Create a Log File:** - Initialize a logg...
import os import time import logging from logging.handlers import RotatingFileHandler def configure_logger(): # Configure logger settings logger = logging.getLogger() logger.setLevel(logging.INFO) handler = RotatingFileHandler('activity.log', maxBytes=1*1024*1024, backupCount=3) formatter = lo...
import os import time import logging def setup_function(): """ Setup operations before each test runs. """ # Remove sample_data directory if exists if os.path.exists('sample_data'): for file in os.listdir('sample_data'): os.remove(os.path.join('sample_data', file)) os.rm...
[ { "docstring": null, "function_declaration": "def configure_logger():", "function_name": "configure_logger", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def manage_files():", "function_name": "manage_files", "parameter_list": "()" }, { "docstri...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport time\nimport logging\nfrom logging.handlers import RotatingFileHandler\n\n# Configure logger\ndef setup_logger():\n logger = logging.getLogger()\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00003837", "row_id": 3837, "seed_ids": "[165]" }
0.679864
Docs: Python310_3837
I
[ "configure_logger", "manage_files", "log_timestamps" ]
3
[ [ "manage_files", "configure_logger" ] ]
1
[]
false
[]
false
pytest
false
[]
true
3e4620e7a386dc67cbfd9dc30945797cb7ac4646
3b440b5f75660b71024801d82146c956e1452c75
v1.0
instruct
Docs
Docs: Python310_3849_I
You are required to manage a series of tasks using asynchronous programming concepts and the `asyncio` queue described in the provided documentation. Each task involves a varying amount of work to be done (simulated by sleeping for a random amount of time). Your goal is to ensure that work is distributed equally among ...
import asyncio import random import time async def worker(name, queue): while True: try: sleep_for = await queue.get() await asyncio.sleep(sleep_for) queue.task_done() except asyncio.CancelledError: break async def process_tasks(task_count: int, work...
import asyncio import pytest from solution import process_tasks @pytest.mark.asyncio async def test_process_tasks_with_few_tasks(): time_taken = await process_tasks(5, 2) assert isinstance(time_taken, float) assert time_taken > 0 @pytest.mark.asyncio async def test_process_tasks_with_many_tasks(): ti...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\nimport time\n\nasync def worker(name, queue):\n while True:\n try:\n sleep_for = await queue.get()\n awai...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00003849", "row_id": 3849, "seed_ids": "[111]" }
0.568583
Docs: Python310_3849
I
[ "worker", "process_tasks" ]
2
[ [ "process_tasks", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9eaac45abd8b15beb7fab957429a682369c592bd
c7731ac859c3577889a6365656ddf835c38f1b6b
v1.0
instruct
Docs
Docs: Python310_3858_I
**Question: Analyzing Web Page Load Times with concurrent.futures** You are tasked with analyzing the load times of multiple web pages to identify potential performance issues. You will read a list of URLs from a file and measure how long each one takes to load. You'll use the `concurrent.futures` module to speed up t...
import requests import time from concurrent.futures import ThreadPoolExecutor, as_completed def fetch_url(url): """ Fetches the URL and returns the time taken to load the page in seconds. Parameters: url (str): The URL to be fetched. Returns: float: Time taken to fetch the...
import pytest from solution import fetch_url, fetch_all_urls def test_fetch_url_valid(): url = 'http://example.com' url, load_time = fetch_url(url) assert isinstance(load_time, float) assert load_time > 0 def test_fetch_url_invalid(): url = 'http://thisurldoesnotexist.tld' url, load_time = fet...
[ { "docstring": "Fetches the URL and returns the time taken to load the page in seconds.\n\nParameters:\n url (str): The URL to be fetched.\n \nReturns:\n float: Time taken to fetch the URL in seconds.", "function_declaration": "def fetch_url(url):", "function_name": "fetch_url", "parameter_...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nimport time\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\ndef fetch_url(url):\n \"\"\"\n Fetches the URL and returns the ti...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00003858", "row_id": 3858, "seed_ids": "[224]" }
0.484829
Docs: Python310_3858
I
[ "fetch_url", "fetch_all_urls" ]
2
[ [ "fetch_all_urls", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
6416f6f79d9a25292832c0a63f1e657723b719a8
19f177d4a4330214bf6b3315a867152aa58be12c
v1.0
instruct
Docs
Docs: Scikit_3894_I
In this task, you are required to implement a custom metric function for evaluating a machine learning model using scikit-learn. The custom metric will be an adaptation of the provided mean absolute percentage error (MAPE) but will include a log transformation to handle a wide range of target values more effectively. ...
import numpy as np from sklearn.metrics import make_scorer def mean_log_transformed_absolute_percentage_error(y_true, y_pred): """ Compute the Mean Log-Transformed Absolute Percentage Error (MLAPE). Parameters: y_true (array-like): True values. y_pred (array-like): Predicted values. Returns: ...
import numpy as np from solution import mean_log_transformed_absolute_percentage_error, evaluate_model_with_custom_metric from sklearn.datasets import load_diabetes def test_mean_log_transformed_absolute_percentage_error(): y_true = np.array([1, 2, 3, 4, 5]) y_pred = np.array([1.2, 1.9, 2.8, 4.1, 5.2]) ...
[ { "docstring": "Compute the Mean Log-Transformed Absolute Percentage Error (MLAPE).\n\nParameters:\ny_true (array-like): True values.\ny_pred (array-like): Predicted values.\n\nReturns:\nfloat: MLAPE score.", "function_declaration": "def mean_log_transformed_absolute_percentage_error(y_true, y_pred):", ...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn.metrics import make_scorer\nimport numpy as np\n\ndef mean_log_transformed_absolute_percentage_error(y_true, y_pred):\n \"\"\"\n Compute the Mean Log...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00003894", "row_id": 3894, "seed_ids": "[25]" }
0.556658
Docs: Scikit_3894
I
[ "mean_log_transformed_absolute_percentage_error", "evaluate_model_with_custom_metric" ]
2
[ [ "evaluate_model_with_custom_metric", "mean_log_transformed_absolute_percentage_error" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
6a8ec67d4cfa25f8e0659954c229566792d48f73
87800301afda8cbe1e71590ec4b22f455a48a2d4
v1.0
instruct
Docs
Docs: Pandas_3917_I
<|Analysis Begin|> The documentation provided offers an extensive look into time series and date functionalities within the pandas framework. It details various operations such as parsing, generating sequences, manipulating, resampling, and converting date times with timezone information. It introduces fundamental con...
import pandas as pd import numpy as np from pandas.tseries.holiday import USFederalHolidayCalendar from datetime import datetime, timedelta def process_time_series_events(): # Step 1: Generate Timestamps events = generate_timestamps() # Step 2: Timezone Conversion events = convert_timezone(events)...
import pytest from solution import process_time_series_events, generate_timestamps, convert_timezone, resample_aggregation, handle_ambiguous_nonexistent_times, custom_business_day_resampling def test_generate_timestamps(): events = generate_timestamps() assert not events.empty assert 'timestamp' in events....
[ { "docstring": null, "function_declaration": "def process_time_series_events():", "function_name": "process_time_series_events", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def generate_timestamps():", "function_name": "generate_timestamps", "parameter...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom pandas.tseries.holiday import USFederalHolidayCalendar\nfrom pandas.tseries.offsets import CustomBusinessDay\n\ndef process_time_series_events...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00003917", "row_id": 3917, "seed_ids": "[17]" }
0.641032
Docs: Pandas_3917
I
[ "process_time_series_events", "generate_timestamps", "convert_timezone", "resample_aggregation", "handle_ambiguous_nonexistent_times", "custom_business_day_resampling" ]
6
[ [ "process_time_series_events", "convert_timezone" ], [ "process_time_series_events", "custom_business_day_resampling" ], [ "process_time_series_events", "generate_timestamps" ], [ "process_time_series_events", "handle_ambiguous_nonexistent_times" ], [ "process_ti...
5
[]
false
[]
false
pytest
true
[ "numpy", "pandas" ]
false
05aa25f64ec723e6b955674696e1e0c13b97471e
ac89af061d72245f9893ab8ac9ee81c4cef78411
v1.0
instruct
Docs
Docs: Python310_3942_I
**Command-Line Tool for To-Do List Management** You have been assigned to create a simple command-line interface (CLI) for managing a to-do list. The program will support adding tasks, listing all tasks, deleting tasks, and marking tasks as completed. Your task is to implement the CLI using the `argparse` module. You...
import argparse import os TODO_FILE = 'todo.txt' def read_tasks(): if not os.path.exists(TODO_FILE): return [] with open(TODO_FILE, 'r') as file: lines = file.readlines() tasks = [] for line in lines: parts = line.strip().split(';', 2) task_id, status, description = par...
import os import pytest from solution import add_task, list_tasks, delete_task, complete_task, read_tasks, write_tasks TEST_TODO_FILE = 'test_todo.txt' def setup_module(module): global TODO_FILE TODO_FILE = TEST_TODO_FILE if os.path.exists(TEST_TODO_FILE): os.remove(TEST_TODO_FILE) def teardown_m...
[ { "docstring": null, "function_declaration": "def read_tasks():", "function_name": "read_tasks", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def write_tasks(tasks):", "function_name": "write_tasks", "parameter_list": "(tasks)" }, { "docstring":...
[ 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 argparse\nimport os\n\nTODO_FILE = 'todo.txt'\n\ndef read_tasks():\n if not os.path.exists(TODO_FILE):\n return []\n with open(TODO_FILE, 'r') as fi...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00003942", "row_id": 3942, "seed_ids": "[139]" }
0.478361
Docs: Python310_3942
I
[ "read_tasks", "write_tasks", "add_task", "list_tasks", "delete_task", "complete_task", "main" ]
7
[ [ "add_task", "read_tasks" ], [ "add_task", "write_tasks" ], [ "complete_task", "read_tasks" ], [ "complete_task", "write_tasks" ], [ "delete_task", "read_tasks" ], [ "delete_task", "write_tasks" ], [ "list_tasks", "read_tasks" ] ]
7
[]
false
[]
false
pytest
true
[]
true
e67135e893df84bcd9e15e07e361e78ade2d3ae2
2cd9694c198ce283325f1c9cb01e222a41a4b517
v1.0
instruct
Docs
Docs: Python310_3978_I
#### Objective You are tasked to develop a customizable and efficient logging system for a financial application that handles various transaction records. The system will be required to format and display logs, manage performance through threading, and accurately process financial data. #### Requirements 1. **Logging...
import logging import threading from decimal import Decimal from pprint import pprint # Setting up the logger def initialize_logger(): logger = logging.getLogger('FinancialAppLogger') logger.setLevel(logging.DEBUG) # Console handler console_handler = logging.StreamHandler() console_handler.set...
import os from solution import process_transactions, initialize_logger import logging def test_logger_file_creation(): # Clean up before test if os.path.exists('transactions.log'): os.remove('transactions.log') logger = initialize_logger() logger.info("Testing file creation") ...
[ { "docstring": null, "function_declaration": "def initialize_logger():", "function_name": "initialize_logger", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def log_transactions(transactions, logger):", "function_name": "log_transactions", "parameter_lis...
[ 0, 0, 0, 1, 0, 0, 1, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import logging\nimport threading\nfrom decimal import Decimal\nfrom pprint import pprint\nimport time\n\n# Function to initialize the logging system.\ndef initialize_lo...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00003978", "row_id": 3978, "seed_ids": "[420]" }
0.535405
Docs: Python310_3978
I
[ "initialize_logger", "log_transactions", "process_transactions" ]
3
[ [ "process_transactions", "initialize_logger" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6d801ae092677f40b25eb4b25f51b762d5537b96
6a8122c1683d7bfd3c58749477ce598d0714e2bd
v1.0
instruct
Docs
Docs: Python310_4017_I
**Command Line Task Manager** Create a Python script named `task_manager.py` that uses the `argparse` module to manage a simple task list. The script should support the following sub-commands: 1. `add` - Add a new task to the list. 2. `list` - List all tasks. 3. `remove` - Remove a task by its index. 4. `clear` - Clea...
import argparse import json import os TASKS_FILE = 'tasks.json' def load_tasks(): if os.path.exists(TASKS_FILE): with open(TASKS_FILE, 'r') as file: return json.load(file) else: return [] def save_tasks(tasks): with open(TASKS_FILE, 'w') as file: json.dump(tasks, file)...
import pytest import json import os from solution import add_task, list_tasks, remove_task, clear_tasks, TASKS_FILE @pytest.fixture(autouse=True) def setup_and_teardown(): # Setup: Clear the tasks file before each test clear_tasks() yield # Teardown: Remove the tasks file after each test if os.path...
[ { "docstring": null, "function_declaration": "def load_tasks():", "function_name": "load_tasks", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def save_tasks(tasks):", "function_name": "save_tasks", "parameter_list": "(tasks)" }, { "docstring": n...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import argparse\nimport json\nimport os\n\nTASK_FILE = 'tasks.json'\n\ndef read_tasks():\n if os.path.exists(TASK_FILE):\n with open(TASK_FILE, 'r') as file:\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00004017", "row_id": 4017, "seed_ids": "[139]" }
0.560956
Docs: Python310_4017
I
[ "load_tasks", "save_tasks", "add_task", "list_tasks", "remove_task", "clear_tasks", "main" ]
7
[ [ "add_task", "load_tasks" ], [ "add_task", "save_tasks" ], [ "clear_tasks", "save_tasks" ], [ "list_tasks", "load_tasks" ], [ "remove_task", "load_tasks" ], [ "remove_task", "save_tasks" ] ]
6
[]
false
[]
false
pytest
true
[]
true
afe17491d830be4b54b9ce871ca662e3a3a12545
89e190c415587942915604826941365b9f4637b1
v1.0
instruct
Docs
Docs: Pytorch_4020_I
### Complex Tensor Operations and Autograd in PyTorch #### Problem Statement You are given a dataset that represents signals captured from some sensors. These signals are stored in a tensor `S` of size `(N, 2)`, where `N` is the number of signals. Each row in this tensor represents a complex number in the form of two...
import torch def real_to_complex(S: torch.Tensor) -> torch.Tensor: """ Convert the real tensor S to a complex tensor. """ return torch.view_as_complex(S) def compute_magnitude_phase(C: torch.Tensor): """ Compute the magnitude and phase angle (in radians) of each complex number in the tensor. ...
import torch from solution import real_to_complex, compute_magnitude_phase, apply_linear_transformation, compute_gradient def test_real_to_complex(): S = torch.tensor([[3.0, 4.0], [1.0, 2.0]], dtype=torch.float32) C = real_to_complex(S) assert C.shape == (2,) assert torch.allclose(C, torch.tensor([3 + ...
[ { "docstring": "Convert the real tensor S to a complex tensor.", "function_declaration": "def real_to_complex(S):", "function_name": "real_to_complex", "parameter_list": "(S)" }, { "docstring": "Compute the magnitude and phase angle (in radians) of each complex number in the tensor.", "f...
[ 0, 0, 0, 0, 0, 0, 1, 1, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\n\ndef real_to_complex(S: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert a real tensor of shape (N, 2) to a complex tensor.\n \"\"\"\n retur...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00004020", "row_id": 4020, "seed_ids": "[116]" }
0.546251
Docs: Pytorch_4020
I
[ "real_to_complex", "compute_magnitude_phase", "apply_linear_transformation", "compute_gradient" ]
4
[ [ "compute_gradient", "apply_linear_transformation" ], [ "compute_gradient", "real_to_complex" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
a438e01eb7cf285864c911452f10b91fcb267a88
5fc58ad5899341bebcb4ca9669c47f7c7e3c90bb
v1.0
instruct
Docs
Docs: Python310_4043_I
You are tasked with creating a secure login system. Using the `crypt` module, you need to implement functions for password hashing, user registration, and login verification. Your solution should consider different hashing methods and ensure secure password storage and verification. ### Function Requirements 1. **`ge...
import crypt import hmac def generate_hashed_password(password, method=None, rounds=None): """ Generates a hashed password with the given method and number of rounds. Args: password (str): The plain-text password. method (crypt.METHOD_* object, optional): The hashing method to use. Def...
from solution import generate_hashed_password, register_user, verify_login def test_generate_hashed_password(): plain_password = "securepassword123" hashed_password = generate_hashed_password(plain_password) assert hashed_password.startswith("$"), "Hashed password should start with '$'" assert has...
[ { "docstring": "Generates a hashed password with the given method and number of rounds.\n\nArgs:\n password (str): The plain-text password.\n method (crypt.METHOD_* object, optional): The hashing method to use. Defaults to None.\n rounds (int, optional): The number of rounds if applicable.\n \nRetur...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import crypt\nimport hmac\n\ndef generate_hashed_password(password, method=None, rounds=None):\n \"\"\"\n Generates a hashed password using the specified method a...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004043", "row_id": 4043, "seed_ids": "[185]" }
0.566761
Docs: Python310_4043
I
[ "generate_hashed_password", "register_user", "verify_login" ]
3
[ [ "register_user", "generate_hashed_password" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1e0684d4d23c0666e8875890ae866faf4e3cdf95
4cfdb810df846e989e82d644d3379ec62a7b5df6
v1.0
instruct
Docs
Docs: Python310_4068_I
In this exercise, you are expected to write a Python script using asyncio to simulate a real-world scenario where multiple asynchronous tasks need to be managed and coordinated. ### Task Description You are to implement a simulation of a simple download manager that manages multiple download tasks asynchronously. The ...
import asyncio import logging import threading # Configure logging logging.basicConfig(level=logging.DEBUG) async def simulate_download(file_id: int, download_time: int) -> None: # Log the start of the download logging.debug(f'Starting download: file_id={file_id}, download_time={download_time}s') # Simula...
import asyncio import threading import time import logging from contextlib import redirect_stdout import io import pytest from solution import simulate_download, schedule_download, main @pytest.mark.asyncio async def test_simulate_download(): f = io.StringIO() with redirect_stdout(f): await simulate_d...
[ { "docstring": null, "function_declaration": "def schedule_download(loop, file_id, download_time):", "function_name": "schedule_download", "parameter_list": "(loop, file_id, download_time)" } ]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport logging\nimport threading\n\n# Configure logging\nlogging.basicConfig(level=logging.DEBUG)\n\nasync def simulate_download(file_id: int, download_...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004068", "row_id": 4068, "seed_ids": "[200]" }
0.474799
Docs: Python310_4068
I
[ "simulate_download", "schedule_download", "main" ]
3
[ [ "schedule_download", "simulate_download" ] ]
1
[]
false
[]
false
pytest
true
[]
true
371f6265a71c062401d179bb56f9900067df2e59
21590a80a85a3f7bb66b348862a6e01974ef15cd
v1.0
instruct
Docs
Docs: Python310_4077_I
#### Problem Statement You are required to create a Python script that acts as a converter for different temperature units. The script should take a temperature value and convert it between Celsius, Fahrenheit, and Kelvin based on the specified options using the `argparse` module for command-line argument parsing. ##...
import argparse def celsius_to_fahrenheit(celsius): return (celsius * 9/5) + 32 def fahrenheit_to_celsius(fahrenheit): return (fahrenheit - 32) * 5/9 def celsius_to_kelvin(celsius): return celsius + 273.15 def kelvin_to_celsius(kelvin): return kelvin - 273.15 def fahrenheit_to_kelvin(fahrenheit): ...
def test_convert_temperature(): # Celsius to Fahrenheit assert convert_temperature(0, 'C', 'F') == 32.0 assert convert_temperature(100, 'C', 'F') == 212.0 # Fahrenheit to Celsius assert convert_temperature(32, 'F', 'C') == 0.0 assert convert_temperature(212, 'F', 'C') == 100.0 # Celsius to...
[ { "docstring": null, "function_declaration": "def celsius_to_fahrenheit(celsius):", "function_name": "celsius_to_fahrenheit", "parameter_list": "(celsius)" }, { "docstring": null, "function_declaration": "def fahrenheit_to_celsius(fahrenheit):", "function_name": "fahrenheit_to_celsiu...
[ 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 argparse\n\ndef convert_temperature(value: float, input_unit: str, output_unit: str) -> float:\n \"\"\"\n Converts the temperature from one unit to another...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004077", "row_id": 4077, "seed_ids": "[65]" }
0.483702
Docs: Python310_4077
I
[ "celsius_to_fahrenheit", "fahrenheit_to_celsius", "celsius_to_kelvin", "kelvin_to_celsius", "fahrenheit_to_kelvin", "kelvin_to_fahrenheit", "convert_temperature", "main" ]
8
[ [ "convert_temperature", "celsius_to_fahrenheit" ], [ "convert_temperature", "celsius_to_kelvin" ], [ "convert_temperature", "fahrenheit_to_celsius" ], [ "convert_temperature", "fahrenheit_to_kelvin" ], [ "convert_temperature", "kelvin_to_celsius" ], [ ...
10
[]
false
[]
false
pytest
false
[]
true
e4bf5b5a795a3bf1801608f38d45c082c204546a
11abda5c548450723e13692303869e302d137e46
v1.0
instruct
Docs
Docs: Python310_4079_I
### Asyncio Futures in Python 3.10 **Objective:** Implement a function that schedules multiple asynchronous tasks using `asyncio.Future`. Demonstrate the use of Futures by simulating an example where you wait for different asynchronous tasks to complete and aggregate their results. **Instructions:** 1. Write a funct...
import asyncio from typing import List, Tuple async def set_after(fut: asyncio.Future, delay: int, value: str) -> None: """ Sleeps for the specified delay and sets the future's result. :param fut: The asyncio.Future to set the result on. :param delay: The delay in seconds before setting the result. ...
import asyncio import pytest from solution import schedule_tasks @pytest.mark.asyncio async def test_schedule_tasks_single(): task_delays = [(1, 'task1')] results = await schedule_tasks(task_delays) assert results == ['task1'] @pytest.mark.asyncio async def test_schedule_tasks_multiple(): task_delays...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def set_after(fut: asyncio.Future, delay: int, value: str) -> None:\n \"\"\"\n Sleeps for the specified de...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004079", "row_id": 4079, "seed_ids": "[113]" }
0.657378
Docs: Python310_4079
I
[ "set_after", "schedule_tasks", "main" ]
3
[ [ "schedule_tasks", "set_after" ] ]
1
[]
false
[]
false
pytest
true
[]
true
be2ddabf4ea8b94588d46da9a8b7e15799ac1cd4
632221785df9ada27c9771fd95ba4c620bedb6ae
v1.0
instruct
Docs
Docs: Python310_4083_I
#### Title: Custom Warning Handler and Filter Implementation #### Objective: To assess the understanding of issuing custom warnings, configuring warning filters, and using context managers to handle warnings in Python. #### Problem Statement: A new module `custom_module.py` requires setting up custom warning handle...
import warnings def issue_warnings(): """ Issues three types of warnings: * UserWarning * DeprecationWarning * RuntimeWarning """ warnings.warn("This is a user warning.", UserWarning) warnings.warn("This feature is deprecated.", DeprecationWarning) warnings.warn("This is a runtime w...
from solution import issue_warnings, configure_warning_filters, test_warnings def test_issue_warnings(): with warnings.catch_warnings(record=True) as caught_warnings: issue_warnings() assert len(caught_warnings) == 3 assert any(isinstance(w.message, UserWarning) for w in caught_warnings) ...
[ { "docstring": "Issues three types of warnings:\n* UserWarning\n* DeprecationWarning\n* RuntimeWarning", "function_declaration": "def issue_warnings():", "function_name": "issue_warnings", "parameter_list": "()" }, { "docstring": "Configures the warning filters:\n* Ignores DeprecationWarning...
[ 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 warnings\n\ndef issue_warnings():\n \"\"\"\n Issues three types of warnings:\n * UserWarning\n * DeprecationWarning\n * RuntimeWarning\n \"\"\"...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004083", "row_id": 4083, "seed_ids": "[125]" }
0.449534
Docs: Python310_4083
I
[ "issue_warnings", "configure_warning_filters", "test_warnings" ]
3
[ [ "test_warnings", "configure_warning_filters" ], [ "test_warnings", "issue_warnings" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2b32ca712e5bee8994eb81763d153529d639bae7
f436545422e011eff6bd13901345a9715f5ecfbc
v1.0
instruct
Docs
Docs: Python310_4092_I
<|Analysis Begin|> The `sched` module in Python defines a `scheduler` class that provides a general-purpose event scheduler. This class allows scheduling of events to be executed at a specific time or after a delay. It requires two functions for operation: `timefunc` to get the current time and `delayfunc` to wait for...
import time import sched # Create an instance of the scheduler scheduler = sched.scheduler(time.time, time.sleep) def schedule_event(event_time_or_delay: float, is_absolute: bool, priority: int, action: callable, args: tuple = (), kwargs: dict = {}) -> sched.Event: """ Schedule an event either at an absolute ...
import time from solution import schedule_event, cancel_event, run_scheduler, schedule_recurring_event, scheduler def print_message(message): print(f"{time.time()}: {message}") def test_schedule_event(): # Clear any previous events while not scheduler.empty(): scheduler.run(False) event_time ...
[ { "docstring": "Schedule an event either at an absolute time or after a delay.\n\nParameters:\nevent_time_or_delay (float): The time at which the event should run (absolute if `is_absolute` is true or delay otherwise).\nis_absolute (bool): If true, the event_time_or_delay is treated as absolute time, otherwise ...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sched\nimport time\n\n# Create scheduler instance\nscheduler = sched.scheduler(time.time, time.sleep)\n\ndef schedule_event(event_time_or_delay: float, is_absolu...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00004092", "row_id": 4092, "seed_ids": "[180]" }
0.595479
Docs: Python310_4092
I
[ "schedule_event", "cancel_event", "run_scheduler", "schedule_recurring_event" ]
4
[ [ "schedule_recurring_event", "schedule_event" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8a1dd125c8b4e675b5fabc624cbde9091b296269
4642e4306a98a34019bb66c17718e041c5453889
v1.0
instruct
Docs
Docs: Python310_4280_I
#### Title: File System Explorer Using `stat` Module #### Objective Write a Python function that explores a given directory recursively, gathers certain metadata about each file, and returns a summary. This assessment will test your understanding of the `stat` module and your ability to manipulate and interpret file m...
import os import stat def file_permissions(mode): """ Converts a file's mode to a string representation of its permissions, similar to `ls -l`. """ perms = ['-'] * 10 perm_mapping = { '0': '---', '1': '--x', '2': '-w-', '3': '-wx', '4': 'r--', '5': 'r...
from solution import explore_directory import os import pytest def create_test_files(): test_dir = "test_dir" sub_dirs = ["sub_dir_1", "sub_dir_2"] files = ["file_1.txt", "file_2.txt"] os.makedirs(test_dir, exist_ok=True) for sub_dir in sub_dirs: os.makedirs(os.path.join(test_dir, sub_dir)...
[ { "docstring": "Converts a file's mode to a string representation of its permissions, similar to `ls -l`.", "function_declaration": "def file_permissions(mode):", "function_name": "file_permissions", "parameter_list": "(mode)" }, { "docstring": null, "function_declaration": "def explore_...
[ 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 os\nimport stat\n\ndef explore_directory(directory_path: str) -> dict:\n summary = {\n \"total_files\": 0,\n \"total_directories\": 0,\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004280", "row_id": 4280, "seed_ids": "[373]" }
0.627261
Docs: Python310_4280
I
[ "file_permissions", "explore_directory" ]
2
[ [ "explore_directory", "file_permissions" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ed1d8a6fd9afce85d8c578506b0d6137ed62ed77
fd0755f07ad0e2e5b26b395d9df40ce840f876ee
v1.0
instruct
Docs
Docs: Python310_4381_I
#### Objective You are tasked with writing a Python script that embodies the use of debugging and profiling tools to identify and resolve inefficiencies in a given function. #### Problem Statement You are provided with a function, `complex_computation`, which performs a series of mathematical operations on a list of n...
import time import cProfile import pstats import io import tracemalloc from pdb import set_trace def complex_computation(arr): result = [] for i in arr: time.sleep(0.1) # Simulate a time-consuming operation temp = i**2 for j in range(1000): temp = temp * 2 - temp // 3 ...
from solution import complex_computation, optimized_complex_computation, trace_memory def test_complex_computation(): assert complex_computation([1, 2, 3]) == optimized_complex_computation([1, 2, 3]) def test_empty_list(): assert complex_computation([]) == optimized_complex_computation([]) def test_large_num...
[ { "docstring": null, "function_declaration": "def complex_computation(arr):", "function_name": "complex_computation", "parameter_list": "(arr)" }, { "docstring": null, "function_declaration": "def profile_complex_computation(arr):", "function_name": "profile_complex_computation", ...
[ 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 cProfile\nimport pdb\nimport tracemalloc\nfrom typing import List\n\ndef complex_computation(arr: List[int]) -> List[int]:\n result = []\n for i in arr:\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00004381", "row_id": 4381, "seed_ids": "[364]" }
0.535496
Docs: Python310_4381
I
[ "complex_computation", "profile_complex_computation", "optimized_complex_computation", "profile_optimized_computation", "debug_optimized_computation", "trace_memory" ]
6
[ [ "debug_optimized_computation", "optimized_complex_computation" ], [ "profile_complex_computation", "complex_computation" ], [ "profile_optimized_computation", "optimized_complex_computation" ] ]
3
[]
false
[]
false
pytest
true
[]
true
b92b63492ce38726a53bc829d8029e87828dd9dc
c89cc2e26fa8fc5a340f53a5a2c13e03a9463645
v1.0
instruct
Docs
Docs: Python310_4384_I
## Coding Assessment Question ### Objective: Implement a function that processes a list of URLs concurrently to fetch their HTML content. The function should use `concurrent.futures` to handle multiple URL fetching tasks in parallel, ensuring efficient and robust execution. ### Description: Write a function `fetch_ur...
import concurrent.futures import requests from typing import List, Tuple def fetch_url(url: str) -> Tuple[str, str]: """ Fetches the content of the URL and returns a tuple (URL, content/exception message). """ try: response = requests.get(url) response.raise_for_status() return ...
from solution import fetch_urls_concurrently import requests from requests.exceptions import RequestException from unittest.mock import patch, Mock def mock_requests_get(url): mock_resp = Mock() if 'example' in url: mock_resp.status_code = 200 mock_resp.text = "<html>Example Content</html>" ...
[ { "docstring": "Fetches the content of the URL and returns a tuple (URL, content/exception message).", "function_declaration": "def fetch_url(url):", "function_name": "fetch_url", "parameter_list": "(url)" }, { "docstring": "Fetches contents of the given URLs concurrently and returns a list ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nimport requests\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\ndef fetch_url(url: str) -> Tuple[str, str]:\n try...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004384", "row_id": 4384, "seed_ids": "[224]" }
0.567385
Docs: Python310_4384
I
[ "fetch_url", "fetch_urls_concurrently" ]
2
[ [ "fetch_urls_concurrently", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
4893630fbf9706ae42e38936529fab2234ccb0cc
8fecb459dade2b91cc9599fd54e3dbe92be85c1e
v1.0
instruct
Docs
Docs: Python310_4385_I
### Asynchronous News Fetcher In this task, you will build an asynchronous news fetcher that fetches headlines from multiple mock news APIs concurrently. You'll need to use the `asyncio` module to run coroutines in parallel and efficiently manage network I/O. **Your task is to:** 1. Define an asynchronous function `f...
import asyncio from typing import List import random async def fetch_headline(url: str) -> str: """Simulates fetching a headline from a given URL.""" await asyncio.sleep(random.randint(1, 3)) # Simulate network latency return f'Headline from {url}' async def fetch_all_headlines(urls: List[str]) -> List[s...
import pytest import asyncio from solution import fetch_headline, fetch_all_headlines @pytest.mark.asyncio async def test_fetch_headline(): url = 'https://newsapi.org/article' headline = await fetch_headline(url) assert headline == f'Headline from {url}' @pytest.mark.asyncio async def test_fetch_all_headl...
[]
[ 1, 1 ]
2
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\nimport random\n\nasync def fetch_headline(url: str) -> str:\n \"\"\"Simulates fetching a headline from a given URL.\"\"\"\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004385", "row_id": 4385, "seed_ids": "[270]" }
0.525467
Docs: Python310_4385
I
[ "fetch_headline", "fetch_all_headlines" ]
2
[ [ "fetch_all_headlines", "fetch_headline" ] ]
1
[]
false
[]
false
pytest
true
[]
true
89c8e432867a61665e249cc17ae6db5ccefa7ee6
284ba23831ae37cef8a8e1683858e2c72b3f9d7d
v1.0
instruct
Docs
Docs: Python310_4392_I
#### Concurrent Web Scraping and Data Processing with `asyncio` In this exercise, you are required to develop an asynchronous Python application using the `asyncio` library. The goal is to concurrently scrape data from multiple web pages and then process that data. Your implementation should demonstrate a solid unders...
import asyncio import random async def fetch_data(url: str) -> str: await asyncio.sleep(random.randint(1, 5)) return f"Data from {url}" async def process_data(data: str) -> None: print(f"Length of data is {len(data)}") async def worker(name: str, queue: asyncio.Queue): while True: # Get the n...
import pytest from solution import fetch_data, process_data, main @pytest.mark.asyncio async def test_fetch_data(): url = "http://example.com/page1" data = await fetch_data(url) assert data == f"Data from {url}" @pytest.mark.asyncio async def test_process_data(capfd): data = "Data from http://example....
[]
[ 0, 0, 0, 1, 1, 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 asyncio\nimport random\n\nasync def fetch_data(url: str) -> str:\n \"\"\"\n Simulates a network call by sleeping for a random amount of time \n (between...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00004392", "row_id": 4392, "seed_ids": "[270]" }
0.588709
Docs: Python310_4392
I
[ "fetch_data", "process_data", "worker", "main" ]
4
[ [ "worker", "process_data" ] ]
1
[ "process_data" ]
false
[]
false
pytest
true
[]
true
46126bb914691c281d88e068f999948b8c8d61ef
03a620ed586f7e45e78cefe5bce01c25b2b68849
v1.0
instruct
Docs
Docs: Scikit_4454_I
### Task You are given a dataset containing numerical features, and your goal is to transform these features using kernel approximations and then train a linear classifier on the transformed data. Specifically, you will need to: 1. Use the `RBFSampler` to transform the input features. 2. Train a stochastic gradient de...
from sklearn.kernel_approximation import RBFSampler from sklearn.linear_model import SGDClassifier from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score def kernel_approximation_and_classification(X_train, y_train, X_test, y_tes...
import pytest from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from solution import kernel_approximation_and_classification def test_kernel_approximation_and_classification_with_dummy_data(): X, y = make_classification(n_samples=100, n_features=20, random_state=...
[ { "docstring": "Transforms the input features using RBFSampler and trains a SGDClassifier on the transformed data.\nCalculates and prints the accuracy of the classifier on the testing dataset.\n\nParameters:\n- X_train (2D list of floats): Training dataset features.\n- y_train (list of integers): Training datas...
[ 0, 0, 0, 1, 0, 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": "from sklearn.kernel_approximation import RBFSampler\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\n\ndef kernel_approximat...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00004454", "row_id": 4454, "seed_ids": "[58]" }
0.584642
Docs: Scikit_4454
I
[ "kernel_approximation_and_classification", "example_usage" ]
2
[ [ "example_usage", "kernel_approximation_and_classification" ] ]
1
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
6ff772a56e2b5f08f8809f2ddbdd36ef132f6307
e206be1c9cd5760a44dc858d968fa58be01e01cd
v1.0
instruct
Docs
Docs: Python310_4463_I
### Asynchronous Web Scraping using `concurrent.futures` **Description:** You need to implement a function `async_scrape(urls)` that accepts a list of URLs and asynchronously scrapes data from each URL. Use the `concurrent.futures.ThreadPoolExecutor` for this task. The function should return a dictionary where the key...
from typing import List, Dict import requests from concurrent.futures import ThreadPoolExecutor, as_completed def fetch_url(url: str) -> tuple: """ Fetches content from a URL. Args: url (str): The URL to fetch content from. Returns: tuple: A tuple containing the URL and th...
import pytest from unittest.mock import patch from solution import async_scrape, fetch_url def test_async_scrape_success(): urls = ["http://example.com", "http://example.org"] expected = { "http://example.com": "<html>Example Domain</html>", "http://example.org": "<html>Example Domain</html>" ...
[ { "docstring": "Fetches content from a URL.\n\nArgs:\n url (str): The URL to fetch content from.\n \nReturns:\n tuple: A tuple containing the URL and the response text or error message.", "function_declaration": "def fetch_url(url):", "function_name": "fetch_url", "parameter_list": "(url)" ...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Dict\nimport requests\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\ndef fetch_url(url: str) -> (str, str):\n \"\"\"\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004463", "row_id": 4463, "seed_ids": "[224]" }
0.629554
Docs: Python310_4463
I
[ "fetch_url", "async_scrape" ]
2
[ [ "async_scrape", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
745a58fb6ebda5107992f4e1b9f63dc623c2fdd5
3ecd1038d625f2ccd0ea2b15725c0bc71d4b9fff
v1.0
instruct
Docs
Docs: Python310_4499_I
### Advanced Coding Assessment: Analyzing and Optimizing Pickle Files **Objective**: To assess your understanding of the `pickletools` module and your ability to manipulate and analyze pickled data programmatically. **Problem Statement**: You are given the task of writing a Python script that performs the following o...
import pickletools import pickle from typing import List def disassemble_pickle(pickle_data: bytes, annotate: int = 0) -> str: """ Disassembles the contents of pickle data and returns the symbolic disassembly. Args: pickle_data (bytes): A bytes object representing the pickled data. annotat...
from solution import disassemble_pickle, optimize_pickle, process_pickles import pytest def test_disassemble_pickle(): data = {'key': 'value'} pickle_data = pickle.dumps(data) disassembly = disassemble_pickle(pickle_data) assert "PROTO" in disassembly assert "STOP" in disassembly def test_optimize...
[ { "docstring": "Disassembles the contents of pickle data and returns the symbolic disassembly.\n\nArgs:\n pickle_data (bytes): A bytes object representing the pickled data.\n annotate (int): An optional integer specifying the annotation level (default is 0).\n\nReturns:\n str: A string containing the s...
[ 0, 0, 0, 1, 1, 0, 0, 0, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pickletools\nimport pickle\n\ndef disassemble_pickle(pickle_data: bytes, annotate: int = 0) -> str:\n \"\"\"\n Disassembles the pickle data and returns the...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00004499", "row_id": 4499, "seed_ids": "[171]" }
0.606836
Docs: Python310_4499
I
[ "disassemble_pickle", "optimize_pickle", "process_pickles" ]
3
[ [ "process_pickles", "disassemble_pickle" ], [ "process_pickles", "optimize_pickle" ] ]
2
[]
false
[]
false
pytest
true
[]
true
4832908c82674762575b42b94b29a4848416275b
e1d1f87fb9c351c357bde1de12e56e5b2e969949
v1.0
instruct
Docs
Docs: Python310_4530_I
### AsyncIO Task Management and Debugging **Objective**: Your task is to implement a small program using the `asyncio` framework that demonstrates handling asynchronous tasks, managing concurrency, and enabling debugging to identify common pitfalls. **Problem Statement**: Implement a Python program that handles multi...
import asyncio import logging from concurrent.futures import ThreadPoolExecutor async def fetch_data(delay: int): """ Simulates fetching data by sleeping for the given delay. """ await asyncio.sleep(delay) return delay def process_data(data: int): """ Simulates processing data by squaring ...
import asyncio from solution import fetch_data, process_data, run_async_tasks def test_fetch_data(): loop = asyncio.get_event_loop() result = loop.run_until_complete(fetch_data(3)) assert result == 3 def test_process_data(): assert process_data(3) == 9 assert process_data(4) == 16 def test_run_as...
[ { "docstring": "Simulates processing data by squaring the given data.", "function_declaration": "def process_data(data):", "function_name": "process_data", "parameter_list": "(data)" }, { "docstring": null, "function_declaration": "def main():", "function_name": "main", "paramete...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport logging\nfrom concurrent.futures import ThreadPoolExecutor\n\nasync def fetch_data(delay: int):\n \"\"\"\n Simulates fetching data by sleep...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004530", "row_id": 4530, "seed_ids": "[200]" }
0.591006
Docs: Python310_4530
I
[ "fetch_data", "process_data", "run_async_tasks", "main" ]
4
[ [ "run_async_tasks", "fetch_data" ], [ "run_async_tasks", "process_data" ] ]
2
[ "process_data" ]
false
[]
false
pytest
true
[]
true
6951d2fae8883fe007026fadae0577e09f22354b
b997a7dd39c06a20ddb9d015d22db19c18e125fb
v1.0
instruct
Docs
Docs: Pytorch_4531_I
**Question: Managing CUDA Operations in PyTorch Using Environment Variables** You are provided with a PyTorch script that performs matrix multiplications on a CUDA-enabled device. Your task is to modify the script to: 1. Ensure that no GPU devices are made available to the CUDA runtime. 2. Enable synchronous CUDA cal...
import os import torch def configure_cuda_env(): """ Configures the environment variables for CUDA operations as per the task requirements. """ # Ensuring no GPU devices are available os.environ["CUDA_VISIBLE_DEVICES"] = "" # Enabling synchronous CUDA calls os.environ["CUDA_LAUNCH_BLOCKING"...
import os import torch from solution import configure_cuda_env, perform_matrix_multiplication def test_configure_cuda_env(): configure_cuda_env() assert os.environ["CUDA_VISIBLE_DEVICES"] == "" assert os.environ["CUDA_LAUNCH_BLOCKING"] == "1" assert os.environ["CUBLAS_WORKSPACE_CONFIG"] == ":0:0" a...
[ { "docstring": "Configures the environment variables for CUDA operations as per the task requirements.", "function_declaration": "def configure_cuda_env():", "function_name": "configure_cuda_env", "parameter_list": "()" }, { "docstring": "Performs matrix multiplication using CUDA if availabl...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport torch\n\n# Set environment variables programmatically\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\nos.environ[\"CUDA_LAUNCH_BLOCKING\"] = \"1\"\nos.e...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004531", "row_id": 4531, "seed_ids": "[107]" }
0.369919
Docs: Pytorch_4531
I
[ "configure_cuda_env", "perform_matrix_multiplication" ]
2
[ [ "perform_matrix_multiplication", "configure_cuda_env" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
c8368c156cffb4e5131b8b92030ad47832de5624
6f3670aa85596f59ca39ecd8095710800c4db281
v1.0
instruct
Docs
Docs: Python310_4533_I
### Python Iterator Protocol Assessment You are tasked with implementing functions that utilize the Python iterator protocol to handle both synchronous and asynchronous iterators. The goal is to create reliable tools that interact with iterators effectively, using the functions provided in the Python 3.10 API. #### P...
def is_iterator(obj): """ Check if the obj is a valid iterator. """ return hasattr(obj, '__iter__') and hasattr(obj, '__next__') def iterate_all(obj): """ Returns a list of all elements in the iterator obj. """ if not is_iterator(obj): raise TypeError("Object is not an iterator"...
import pytest from solution import is_iterator, iterate_all, is_async_iterator, async_iterate_all def test_is_iterator(): assert is_iterator(iter([1, 2, 3])) == True assert is_iterator([1, 2, 3]) == False assert is_iterator({'key': 'value'}) == False assert is_iterator(iter('abc')) == True def test_it...
[ { "docstring": "Check if the obj is a valid iterator.", "function_declaration": "def is_iterator(obj):", "function_name": "is_iterator", "parameter_list": "(obj)" }, { "docstring": "Returns a list of all elements in the iterator obj.", "function_declaration": "def iterate_all(obj):", ...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_iterator(obj):\n \"\"\"\n Checks if the object is a valid iterator.\n \"\"\"\n try:\n iter(obj)\n return True\n except TypeError:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004533", "row_id": 4533, "seed_ids": "[58]" }
0.419176
Docs: Python310_4533
I
[ "is_iterator", "iterate_all", "is_async_iterator", "async_iterate_all" ]
4
[ [ "async_iterate_all", "is_async_iterator" ], [ "iterate_all", "is_iterator" ] ]
2
[]
false
[]
false
pytest
true
[]
true
0a7c9470d02860dae1e3cfadd5dbb78e046f31ab
39eba9b15eaa211bd670ff836c5c04f13b110a67
v1.0
instruct
Docs
Docs: Scikit_4560_I
### Gaussian Mixture Model Implementation and Analysis **Objective:** Implement and analyze Gaussian Mixture Models using Scikit-learn’s `sklearn.mixture` package to demonstrate your understanding of the concepts and functionalities discussed in the document. **Tasks:** 1. **Data Generation:** Generate a syntheti...
import numpy as np from sklearn.mixture import GaussianMixture, BayesianGaussianMixture import matplotlib.pyplot as plt from matplotlib.patches import Ellipse # Data Generation def generate_data(seed=42): np.random.seed(seed) means = [[2, 2], [-2, -2], [2, -2]] covariances = [[[1, 0.5], [0.5, 1]], [[1, -0....
import numpy as np from sklearn.mixture import GaussianMixture, BayesianGaussianMixture def test_generate_data(): X = generate_data() assert X.shape == (450, 2) # 3 clusters x 150 points each in 2D def test_fit_gaussian_mixture(): X = generate_data() gmm, optimal_components = fit_gaussian_mixture(X) ...
[ { "docstring": null, "function_declaration": "def generate_data(seed=42):", "function_name": "generate_data", "parameter_list": "(seed=42)" }, { "docstring": null, "function_declaration": "def fit_gaussian_mixture(X, max_components=10, random_state=42):", "function_name": "fit_gaussi...
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.mixture import GaussianMixture, BayesianGaussianMixture\nfrom matplotlib.patches import Ellipse\n\ndef...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00004560", "row_id": 4560, "seed_ids": "[23]" }
0.567128
Docs: Scikit_4560
I
[ "generate_data", "fit_gaussian_mixture", "fit_bayesian_gaussian_mixture", "draw_ellipse", "plot_gmm", "main" ]
6
[ [ "plot_gmm", "draw_ellipse" ] ]
1
[]
false
[]
false
pytest
false
[ "matplotlib", "numpy", "sklearn" ]
false
b71f19f1557e7883027b678c411b5af5c4dc1764
0ce75eacbc657743cef1295fa8d48a8af7f9b6a2
v1.0
instruct
Docs
Docs: Python310_4601_I
**Advanced Fraction Manipulation and Arithmetic** You are given a list of tuples where each tuple contains two integers representing the numerator and denominator of a fraction. Your task is to implement a function `process_fractions(fractions_list)` that takes this list, converts each pair of integers into a `Fracti...
from fractions import Fraction from math import gcd def normalize_fraction(numerator, denominator): # Ensure the denominator is positive if denominator < 0: numerator, denominator = -numerator, -denominator common_divisor = gcd(numerator, denominator) return numerator // common_divisor, de...
from solution import process_fractions from fractions import Fraction def test_process_fractions(): fractions_list = [(1, 2), (3, 4), (-4, 5)] result = process_fractions(fractions_list) expected_normalized_fractions = [(1, 2), (3, 4), (-4, 5)] expected_sum = Fraction(1, 2) + Fraction(3, 4) + Fraction(...
[ { "docstring": null, "function_declaration": "def normalize_fraction(numerator, denominator):", "function_name": "normalize_fraction", "parameter_list": "(numerator, denominator)" }, { "docstring": null, "function_declaration": "def fraction_difference(f1, f2):", "function_name": "fr...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from fractions import Fraction\nimport math\n\ndef gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef normalize_fraction(numerator, denominator):\n ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00004601", "row_id": 4601, "seed_ids": "[334]" }
0.613417
Docs: Python310_4601
I
[ "normalize_fraction", "fraction_difference", "closest_fraction", "process_fractions" ]
4
[ [ "closest_fraction", "fraction_difference" ], [ "process_fractions", "closest_fraction" ], [ "process_fractions", "normalize_fraction" ] ]
3
[]
false
[]
false
pytest
true
[]
true
ecca186eb16295e99b647d9a1b0b7fdd822d093f
0df2f83be407ce8ff957cd4eb956dd7235a43caf
v1.0
instruct
Docs
Docs: Pytorch_4610_I
#### Objective: Create and test a custom operator in PyTorch using the `torch.library` module. The custom operator should perform a tailored mathematical operation and support gradient computations. You will also need to test the custom operator using provided utilities to ensure correctness. #### Task: 1. **Define a ...
import torch from torch.autograd import Function class CustomReLU(Function): @staticmethod def forward(ctx, x, c): ctx.save_for_backward(x) ctx.constant = c return torch.relu(x) + c @staticmethod def backward(ctx, grad_output): x, = ctx.saved_tensors grad_x = gr...
import torch from solution import custom_relu def test_gradcheck_custom_relu(): x = torch.randn((5, 5), dtype=torch.float64, requires_grad=True) c = 0.5 assert torch.autograd.gradcheck(lambda x: custom_relu(x, c), (x,)), "gradcheck failed!" def test_output_custom_relu(): test_tensor = torch.tensor([[-...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.autograd import Function\nfrom torch.library import Library\n\n# Create a custom operator using PyTorch library\ncustom_lib = Library(\"custom_...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004610", "row_id": 4610, "seed_ids": "[51]" }
0.413271
Docs: Pytorch_4610
I
[ "custom_relu", "test_custom_op" ]
2
[ [ "test_custom_op", "custom_relu" ] ]
1
[]
false
[ "CustomReLU" ]
true
pytest
true
[ "torch" ]
false
619dc1bec6dc3042e470a2aef6b5aa693c0b1a31
71ef7d072fede91e21f68a17e3a9a95341b1a750
v1.0
instruct
Docs
Docs: Python310_4638_I
#### Objective: To test your understanding of the `random` module, particularly its ability to generate pseudo-random numbers for various distributions and manage the state of the random number generator. #### Problem Statement: You are tasked with creating a mini-simulation of a card game. The game involves shuffling...
import random def create_deck(): """ Returns a standard 52-card deck. """ ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] suits = ['hearts', 'diamonds', 'clubs', 'spades'] deck = [(rank, suit) for rank in ranks for suit in suits] return deck def shuffle_deck(deck...
import pytest from solution import create_deck, shuffle_deck, deal_cards, score_hand, determine_winner, simulate_game def test_create_deck(): deck = create_deck() assert len(deck) == 52 assert ('2', 'hearts') in deck assert ('A', 'spades') in deck def test_shuffle_deck(): deck = create_deck() ...
[ { "docstring": "Returns a standard 52-card deck.", "function_declaration": "def create_deck():", "function_name": "create_deck", "parameter_list": "()" }, { "docstring": "Shuffles the deck of cards in place.", "function_declaration": "def shuffle_deck(deck):", "function_name": "shuff...
[ 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 random\n\ndef create_deck():\n ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']\n suits = ['hearts', 'diamonds', 'clubs', 'spades...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00004638", "row_id": 4638, "seed_ids": "[119]" }
0.632347
Docs: Python310_4638
I
[ "create_deck", "shuffle_deck", "deal_cards", "score_hand", "determine_winner", "simulate_game" ]
6
[ [ "determine_winner", "score_hand" ], [ "simulate_game", "create_deck" ], [ "simulate_game", "deal_cards" ], [ "simulate_game", "determine_winner" ], [ "simulate_game", "shuffle_deck" ] ]
5
[]
false
[]
false
pytest
true
[]
true
63e610d7680083085f9ab1a78205a1a9ec941ebe
b2517bb221a69f6f85561c087b76f8aa2587060c
v1.0
instruct
Docs
Docs: Python310_4647_I
**Title:** Concurrent Execution with concurrent.futures **Objective:** Implement a Python function that utilizes the concurrent.futures module to perform concurrent execution of tasks. This problem will test your understanding of managing parallel tasks using ThreadPoolExecutor or ProcessPoolExecutor. **Problem Stat...
from concurrent.futures import ThreadPoolExecutor, as_completed from typing import List, Dict import requests def fetch_content(url): try: response = requests.get(url) response.raise_for_status() # Raise an error for bad status codes return response.text except requests.RequestExceptio...
import pytest from unittest.mock import patch from solution import fetch_data_concurrently # Example URLs for mock testing example_urls = [ "http://example.com", "http://example.org", "http://example.net" ] example_content = [ "<html>Example Domain</html>", "<html>Example Organization</html>", ...
[ { "docstring": null, "function_declaration": "def fetch_content(url):", "function_name": "fetch_content", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def fetch_data_concurrently(urls, workers):", "function_name": "fetch_data_concurrently", "paramete...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from concurrent.futures import ThreadPoolExecutor, as_completed\nfrom typing import List, Dict\nimport requests\n\ndef fetch_content(url):\n try:\n response =...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004647", "row_id": 4647, "seed_ids": "[224]" }
0.544731
Docs: Python310_4647
I
[ "fetch_content", "fetch_data_concurrently" ]
2
[ [ "fetch_data_concurrently", "fetch_content" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
a9b5adafb5ba71fe7e62669322bb3106f226df64
60711dbeddc07d9cedd562579927206c027ba5e8
v1.0
instruct
Docs
Docs: Python310_4729_I
#### Objective: To test your understanding of the `asyncio` library for writing concurrent code in Python. #### Task: Implement an asynchronous function `fetch_data_and_process` that simulates network data fetching and processing using `asyncio` library functions. 1. **Function Signature**: ```python async def...
import asyncio from typing import List async def fetch_data(url: str) -> str: await asyncio.sleep(1) return f"Data from {url}" async def process_data(data: str) -> str: await asyncio.sleep(1) return f"Processed {data}" async def fetch_data_and_process(urls: List[str]) -> List[str]: # Fetch data c...
import pytest import asyncio from solution import fetch_data_and_process @pytest.mark.asyncio async def test_fetch_data_and_process_single_url(): urls = ["http://example.com/1"] result = await fetch_data_and_process(urls) assert result == ["Processed Data from http://example.com/1"] @pytest.mark.asyncio a...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List\n\nasync def fetch_data(url: str) -> str:\n await asyncio.sleep(1)\n return f\"Data from {url}\"\n\nasync def process_data...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004729", "row_id": 4729, "seed_ids": "[270]" }
0.518831
Docs: Python310_4729
I
[ "fetch_data", "process_data", "fetch_data_and_process" ]
3
[ [ "fetch_data_and_process", "fetch_data" ], [ "fetch_data_and_process", "process_data" ] ]
2
[ "process_data" ]
false
[]
false
pytest
true
[]
true
0ac561d93b6b062ed372c315d9b428a0f8cece72
85fc0689c1c6db5d7b15f3cc7fd6778b3d4483d6
v1.0
instruct
Docs
Docs: Python310_4736_I
### Cryptographic Hashing and Verification System In this task, you are required to implement a system that uses the `hashlib` library to compute and verify the integrity of messages using cryptographic hash functions. The system should support various hash algorithms, allow for keyed hashing, and ensure messages have...
import hashlib def compute_hash(message: bytes, algorithm: str, **kwargs) -> str: """ Computes and returns the hex digest of the provided message using the specified hash algorithm. """ hash_func = hashlib.new(algorithm, **kwargs) hash_func.update(message) return hash_func.hexdigest() def sign...
import pytest from solution import compute_hash, sign_message, verify_message def test_compute_hash_sha256(): message = b"integrity check" expected_hash = hashlib.sha256(message).hexdigest() assert compute_hash(message, 'sha256') == expected_hash def test_sign_and_verify_valid_signature(): message = b...
[ { "docstring": "Computes and returns the hex digest of the provided message using the specified hash algorithm.", "function_declaration": "def compute_hash(message, algorithm, **kwargs):", "function_name": "compute_hash", "parameter_list": "(message, algorithm, **kwargs)" }, { "docstring": "...
[ 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 hashlib\n\ndef compute_hash(message: bytes, algorithm: str, **kwargs) -> str:\n \"\"\"\n Computes and returns the hex digest of the provided message using ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004736", "row_id": 4736, "seed_ids": "[225]" }
0.741034
Docs: Python310_4736
I
[ "compute_hash", "sign_message", "verify_message" ]
3
[ [ "verify_message", "sign_message" ] ]
1
[]
false
[]
false
pytest
true
[]
true
42e835d396b8f8b319d71fc5b650527ec4edd6ba
d450ddd1e7938d50d0d91aaa7187f1008da78845
v1.0
instruct
Docs
Docs: Python310_4795_I
## Coding Assessment Question ### Objective Implement a simple I/O server using the `selectors` module to handle multiple client connections simultaneously. The server should be able to accept connections, read data from clients, echo the data back to them, and handle client disconnection gracefully. ### Requirements...
import selectors import socket sel = selectors.DefaultSelector() def accept(sock, mask): conn, addr = sock.accept() # Should be ready print('Accepted', conn, 'from', addr) conn.setblocking(False) sel.register(conn, selectors.EVENT_READ, read) def read(conn, mask): data = conn.recv(1000) # Shoul...
import socket import threading import time def run_client(host, port, messages, responses): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.connect((host, port)) for message in messages: sock.sendall(message.encode('utf-8')) response = sock.recv(1024) ...
[ { "docstring": null, "function_declaration": "def accept(sock, mask):", "function_name": "accept", "parameter_list": "(sock, mask)" }, { "docstring": null, "function_declaration": "def read(conn, mask):", "function_name": "read", "parameter_list": "(conn, mask)" }, { "doc...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import selectors\nimport socket\n\ndef accept(sock, mask, sel):\n conn, addr = sock.accept() # Should be ready\n print(f'Accepted connection from {addr}')\n c...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00004795", "row_id": 4795, "seed_ids": "[288]" }
0.682463
Docs: Python310_4795
I
[ "accept", "read", "run_echo_server" ]
3
[ [ "accept", "read" ], [ "run_echo_server", "accept" ] ]
2
[]
false
[]
false
pytest
false
[]
true
41f9eeec08d099a423995e3625b8a5d3d6d5c965
245ed2b036cfbbb6c0266f7a20da3ee99097b7e9
v1.0
instruct
Docs
Docs: Python310_4829_I
### Task You are tasked with creating a simulation of a simplified card game where players draw cards until the deck is empty. Each player draws one card per turn from a shuffled deck and the game keeps track of the number of cards each player has drawn. At the end of the game, the player with the most cards wins. ##...
from typing import List, Tuple import random def shuffle_deck(deck: List[str]) -> List[str]: """ Shuffles the deck of cards. Parameters: deck (List[str]): A list of card names. Returns: List[str]: A shuffled list of card names. """ random.shuffle(deck) return deck def dra...
from solution import shuffle_deck, draw_card, simulate_game def test_shuffle_deck(): deck = ["5H", "2D", "KC", "9S", "AH", "7C"] shuffled_deck = shuffle_deck(deck.copy()) assert set(deck) == set(shuffled_deck) assert deck != shuffled_deck # Highly unlikely that shuffled deck would be the same def tes...
[ { "docstring": "Shuffles the deck of cards.\n\nParameters:\ndeck (List[str]): A list of card names.\n\nReturns:\nList[str]: A shuffled list of card names.", "function_declaration": "def shuffle_deck(deck):", "function_name": "shuffle_deck", "parameter_list": "(deck)" }, { "docstring": "Draws...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nimport random\n\ndef shuffle_deck(deck: List[str]) -> List[str]:\n \"\"\"\n Shuffles the deck of cards and returns it.\n \"\"\"...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00004829", "row_id": 4829, "seed_ids": "[119]" }
0.613353
Docs: Python310_4829
I
[ "shuffle_deck", "draw_card", "simulate_game" ]
3
[ [ "simulate_game", "draw_card" ], [ "simulate_game", "shuffle_deck" ] ]
2
[]
false
[]
false
pytest
true
[]
true
47be24a28e57c16f9dec09021239a462d30aa613
ad6ca80e387ebeefcaa5b0e306ccbbb78a27895d
v1.0
instruct
Docs
Docs: Scikit_4868_I
### Semi-supervised Learning Implementation and Comparison **Objective**: Implement and compare two semi-supervised learning techniques, `SelfTrainingClassifier` and `LabelPropagation`, from the `sklearn.semi_supervised` module using a synthetic dataset. **Background**: You are provided with a synthetic dataset consi...
import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.semi_supervised import SelfTrainingClassifier, LabelPropagation from sklearn.metrics import accuracy_score, precision_score, recall_score from sklearn.model_selection import train_test_split def load_data(file_path: str) -> pd.DataFra...
import pytest import os def create_sample_data(): """ Create sample data for testing. """ data = { 'X1': [1, 2, 3, 4, 5, 6], 'X2': [6, 5, 4, 3, 2, 1], 'Y': [1, -1, -1, 0, 1, 0] } df = pd.DataFrame(data) df.to_csv('points.csv', index=False) def test_load_data(): ...
[ { "docstring": "Load the dataset from a CSV file.\n\n:param file_path: Path to the CSV file.\n:return: DataFrame with columns ['X1', 'X2', 'Y'].", "function_declaration": "def load_data(file_path):", "function_name": "load_data", "parameter_list": "(file_path)" }, { "docstring": "Train a Sel...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.semi_supervised import SelfTrainingClassifier, LabelPropagation\nfrom sklearn.met...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00004868", "row_id": 4868, "seed_ids": "[21]" }
0.579918
Docs: Scikit_4868
I
[ "load_data", "train_self_training_classifier", "train_label_propagation", "evaluate_model", "compare_models" ]
5
[ [ "compare_models", "evaluate_model" ], [ "compare_models", "train_label_propagation" ], [ "compare_models", "train_self_training_classifier" ] ]
3
[]
false
[]
false
pytest
false
[ "pandas", "sklearn" ]
false
c9ddc771d31f714233720acfbf67f90f506d3080
a14503f78b7f536d124cfe4d99f9d78f8435cab4
v1.0
instruct
Docs
Docs: Python310_4921_I
### Asynchronous Programming with Coroutine Objects Python 3.5 introduced coroutine objects as a cornerstone of asynchronous programming. This exercise will guide you through understanding and implementing coroutines in Python by creating a function that utilizes these concepts. #### Problem Statement Implement an *...
import asyncio from typing import List, Coroutine async def async_fetch_data(url: str) -> Coroutine: """ Asynchronously fetch data from the given URL. Simulate network delay using asyncio.sleep. """ print(f"Start fetching data from {url}") await asyncio.sleep(1) print(f"Fetching completed f...
import pytest import asyncio from solution import async_fetch_data, fetch_multiple_data @pytest.mark.asyncio async def test_async_fetch_data(capfd): url = "https://example.com" await async_fetch_data(url) captured = capfd.readouterr() assert "Start fetching data from https://example.com" in captured.ou...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Coroutine\n\nasync def async_fetch_data(url: str) -> Coroutine:\n \"\"\"\n Asynchronously fetch data from the given URL.\...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00004921", "row_id": 4921, "seed_ids": "[8]" }
0.568818
Docs: Python310_4921
I
[ "async_fetch_data", "fetch_multiple_data" ]
2
[ [ "fetch_multiple_data", "async_fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5e7fdfaa5f61749f75c505b0f12e1b9c68cb11f6
6fe6c380d54c4640e96481c161d5ec7e29ca225b
v1.0
instruct
Docs
Docs: Python310_4927_I
### Python Coding Assessment Question **Objective**: This assessment will test your understanding of Python's Development Mode and its debugging features. You will be required to write a program that handles file operations and asynchronous tasks, demonstrating your ability to manage resources properly, identify and f...
import asyncio import sys from typing import List async def process_file_content(content: str) -> str: await asyncio.sleep(1) # Simulating a delay in processing return content[::-1] # Reverse content for demonstration purposes def read_and_process_files(file_paths: List[str]) -> None: async def _interna...
import asyncio import os import pytest from solution import read_and_process_files, process_file_content @pytest.mark.asyncio async def test_process_file_content(): content = "Hello, World!" expected_result = "!dlroW ,olleH" result = await process_file_content(content) assert result == expected_result ...
[ { "docstring": null, "function_declaration": "def read_and_process_files(file_paths):", "function_name": "read_and_process_files", "parameter_list": "(file_paths)" } ]
[ 0, 0, 0, 0, 1, 1, 0, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport sys\nfrom typing import List\n\nasync def process_file_content(content: str) -> str:\n \"\"\"\n Simulates processing on file content by rev...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00004927", "row_id": 4927, "seed_ids": "[249]" }
0.555394
Docs: Python310_4927
I
[ "process_file_content", "read_and_process_files" ]
2
[ [ "read_and_process_files", "process_file_content" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0f3c788644197087c8829fa67c7708c78fde1857
fc6eaf70ce946e74a4e8d46391ff918a83378036
v1.0
instruct
Docs
Docs: Seaborn_5026_I
### Task You are tasked with using seaborn’s `cubehelix_palette` function to generate customized color palettes and apply these palettes to visualizations. This task will test your understanding of the seaborn package, specifically around customized color map creation and applying these palettes to plots. ### Detaile...
import seaborn as sns import matplotlib.pyplot as plt def create_custom_palette(n_colors=6, start=0, rot=0.4, gamma=1.0, hue=0.8, dark=0.2, light=0.8, as_cmap=False): """ Generates a color palette using seaborn's cubehelix_palette function with the given parameters. Parameters: n_colors (int):...
import pytest from solution import create_custom_palette def test_create_custom_palette_default(): palette = create_custom_palette() assert len(palette) == 6, "Default number of colors should be 6" def test_create_custom_palette_n_colors(): palette = create_custom_palette(n_colors=10) assert len(palet...
[ { "docstring": "Generates a color palette using seaborn's cubehelix_palette function with the given parameters.\n\nParameters:\n n_colors (int): Number of colors in the palette.\n start (float): Starting position in the cubehelix space.\n rot (float): Number of rotations around the hue wheel.\n gamm...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef create_custom_palette(n_colors=6, start=0, rot=0.4, gamma=1.0, hue=0.8, dark=0.2, light=0.8, as_cmap=False...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005026", "row_id": 5026, "seed_ids": "[88]" }
0.655105
Docs: Seaborn_5026
I
[ "create_custom_palette", "create_plots" ]
2
[ [ "create_plots", "create_custom_palette" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "seaborn" ]
false
8a1e4cdedd894a755e2922e8a8278d8620f55779
cddae02e95ac10db40901c4b9307a2a8f842b77f
v1.0
instruct
Docs
Docs: Python310_5057_I
**Advanced Python Coding Assessment Question:** ### Problem Statement You are given the task of writing a networked application in Python, leveraging the `asyncio` module. Your application needs to function correctly across both Windows and macOS, taking into account specific limitations and capabilities detailed bel...
import asyncio import os import sys import platform async def handle_client(reader, writer): try: while True: data = await reader.read(100) if not data: break writer.write(data) await writer.drain() except asyncio.CancelledError: p...
import asyncio import os import platform import pytest import subprocess from solution import start_server_and_subprocess @pytest.mark.asyncio async def test_server_and_subprocess_unix(monkeypatch): if platform.system() == 'Windows': pytest.skip("Test is for Unix based systems") # Create a temporary U...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport platform\nimport sys\nfrom asyncio.subprocess import create_subprocess_exec\n\nasync def handle_client(reader, writer):\n data = await reader....
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005057", "row_id": 5057, "seed_ids": "[370]" }
0.590026
Docs: Python310_5057
I
[ "handle_client", "start_server_and_subprocess" ]
2
[ [ "start_server_and_subprocess", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0cecfd2a0e89f247f7cfd5b3b7841cb68b95987f
dc804085e47a13b3dd5df0a5b4c0a94309c3a2c9
v1.0
instruct
Docs
Docs: Python310_5080_I
### Configuration and Initialization in Python **Objective:** Implement and customize Python initialization using the `PyConfig` and `PyWideStringList` structures. This task will assess your ability to manipulate configuration settings, manage wide string lists, and handle initialization statuses with error handling m...
import sys import ctypes class PyConfig(ctypes.Structure): _fields_ = [ ("program_name", ctypes.c_wchar_p), ("home", ctypes.c_wchar_p), ("executable", ctypes.c_wchar_p), ] class PyWideStringList(ctypes.Structure): _fields_ = [ ("length", ctypes.c_int), ("items", cty...
def test_pyconfig_initialization(): config = PyConfig() PyConfig_InitPythonConfig(config) assert config.program_name == "custom_program" assert config.home == "custom_home" assert config.executable == "custom_executable" def test_pywidestringlist_initialization(): wide_string_list = PyWide...
[]
[ 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 sys\nfrom ctypes import c_wchar_p, c_int, POINTER, Structure, byref, windll, wstring_at\n\nclass PyWideStringList(Structure):\n _fields_ = [(\"length\", c_int...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00005080", "row_id": 5080, "seed_ids": "[15]" }
0.504024
Docs: Python310_5080
I
[ "PyConfig_InitPythonConfig", "PyWideStringList_Init", "check_status", "init_python_configuration" ]
4
[ [ "init_python_configuration", "PyConfig_InitPythonConfig" ], [ "init_python_configuration", "PyWideStringList_Init" ], [ "init_python_configuration", "check_status" ] ]
3
[]
false
[ "PyConfig", "PyWideStringList", "PyStatus" ]
true
pytest
false
[]
true
3c47dc8196ca29f46c7e36beff1fc64d314b8b30
7c64241572be0e162c5285d793a5fdc43ca0d2da
v1.0
instruct
Docs
Docs: Pytorch_5096_I
#### Objective The objective of this task is to evaluate your understanding and proficiency with PyTorch, specifically using Intel GPUs. You are required to implement a training routine for a deep learning model and optimize its performance using `torch.compile`. #### Problem Statement 1. **Tensor Operations**: Writ...
import time import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms # Function for basic tensor operations on an Intel GPU def basic_tensor_operations(): if not torch.xpu.is_available(): raise RuntimeError("Intel GPU is not available") ...
import torch import pytest from solution import basic_tensor_operations, train_model, optimize_with_torch_compile, SimpleCNN @pytest.mark.skipif(not torch.xpu.is_available(), reason="Intel GPU is not available") def test_basic_tensor_operations(): result = basic_tensor_operations() assert result.device.type =...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\n\ndef basic_tensor_operations():\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005096", "row_id": 5096, "seed_ids": "[176]" }
0.566423
Docs: Pytorch_5096
I
[ "basic_tensor_operations", "train_model", "optimize_with_torch_compile" ]
3
[ [ "optimize_with_torch_compile", "train_model" ] ]
1
[]
false
[ "SimpleCNN" ]
true
pytest
true
[ "torch", "torchvision" ]
false
ba27fc3cbebf3b347507a0fb85f433c5d493d4ee
ef551b80e981f0a888dbc592b604b840ac407651
v1.0
instruct
Docs
Docs: Python310_5133_I
**Problem:** You are working on a scientific project that involves analyzing temperature data collected from various sources globally. Given the temperature readings for a week from different monitoring stations, you need to preprocess and analyze this data. This problem involves several steps – data cleaning, statis...
import math from typing import List, Tuple def clean_data(data: List[float]) -> List[float]: """ Cleans the input data by removing all non-finite numbers (NaN, inf, -inf). """ return [x for x in data if math.isfinite(x)] def calculate_statistics(data: List[float]) -> Tuple[float, float, float, float...
from solution import clean_data, calculate_statistics, weekly_temperature_analysis def test_clean_data(): assert clean_data([1.0, math.nan, 2.0, math.inf, -math.inf, 3.0]) == [1.0, 2.0, 3.0] assert clean_data([math.nan, math.inf, -math.inf]) == [] assert clean_data([7.7, 8.8, 9.9]) == [7.7, 8.8, 9.9] de...
[ { "docstring": "Cleans the input data by removing all non-finite numbers (NaN, inf, -inf).", "function_declaration": "def clean_data(data):", "function_name": "clean_data", "parameter_list": "(data)" }, { "docstring": "Calculates the following statistics from the given data:\n- Mean\n- Stand...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nfrom typing import List, Tuple\n\ndef clean_data(data: List[float]) -> List[float]:\n \"\"\"\n Removes non-finite numbers (NaN, inf, -inf) from the l...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005133", "row_id": 5133, "seed_ids": "[274]" }
0.68002
Docs: Python310_5133
I
[ "clean_data", "calculate_statistics", "weekly_temperature_analysis" ]
3
[ [ "weekly_temperature_analysis", "calculate_statistics" ], [ "weekly_temperature_analysis", "clean_data" ] ]
2
[]
false
[]
false
pytest
true
[]
true
658133450e3c2c560cb1e85997e2d0692942a8d5
273e91345d6b9cfe753fc5a1ecf1dcce8038a0c0
v1.0
instruct
Docs
Docs: Pytorch_5192_I
**Question: Ensuring Reproducibility in PyTorch** You have been provided with the task of developing a PyTorch script that ensures reproducible results across multiple runs of the script. Your script should utilize various methods to control sources of randomness and enforce deterministic behavior as described in the ...
import torch import torch.nn as nn import torch.optim as optim import numpy as np import random # 1. Set seeds to ensure reproducibility across PyTorch, Python, and NumPy. def set_seeds(seed=42): torch.manual_seed(seed) random.seed(seed) np.random.seed(seed) if torch.cuda.is_available(): torch....
from solution import train def test_reproducibility(): state_dict1, loss1 = train() state_dict2, loss2 = train() # Verify if the state dictionaries and losses are identical identical_parameters = all(torch.equal(state_dict1[key], state_dict2[key]) for key in state_dict1) identical_loss = loss1...
[]
[ 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, TensorDataset\nimport numpy as np\nimport random\n\n# Functio...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00005192", "row_id": 5192, "seed_ids": "[174]" }
0.42676
Docs: Pytorch_5192
I
[ "set_seeds", "configure_cuda", "train" ]
3
[ [ "train", "configure_cuda" ], [ "train", "set_seeds" ] ]
2
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "numpy", "torch" ]
false
cf72a8ae98d89a7e32f4b0202a9855c15a52e2ff
3cd8b59655655c98253bb09bfb2f40f86e5be1d8
v1.0
instruct
Docs
Docs: Python310_5255_I
### Asyncio Task Management & Concurrency Assessment **Objective**: Implement a Python function that demonstrates the use of `asyncio` for running multiple tasks concurrently, handling timeouts, and shielding tasks from cancellation. **Question**: You are asked to develop an `asyncio`-based program to simulate a sim...
import asyncio import random async def simulate_task(task_name, duration): """ Simulates a task by sleeping for the given duration. Args: task_name (str): The name of the task. duration (int): The duration (in seconds) for which the task will run. Returns: str: A message indicatin...
import pytest import asyncio from solution import simulate_task, run_tasks @pytest.mark.asyncio async def test_simulate_task(): result = await simulate_task("TestTask", 2) assert result == "Task TestTask completed in 2 seconds" @pytest.mark.asyncio async def test_run_tasks_all_complete(): task_names = ["T...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\n\nasync def simulate_task(task_name, duration):\n \"\"\"\n Simulates a task by sleeping for the given duration.\n \n Args:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005255", "row_id": 5255, "seed_ids": "[317]" }
0.578127
Docs: Python310_5255
I
[ "simulate_task", "run_tasks", "main" ]
3
[ [ "run_tasks", "simulate_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d4abc356325f376257851d02d8d157f774cdb345
129ad55dd2ee7299689bb918e8f8c0b6e367783d
v1.0
instruct
Docs
Docs: Python310_5367_I
### Advanced Python Tracing with SystemTap **Objective:** Your task is to write a SystemTap script that traces the execution of a Python script's function calls and garbage collection activities. This problem will test your ability to understand and apply the given documentation on tracing tools and markers. **Proble...
def generate_function_signature(filename, function_name, line_number): return f"{filename}:{function_name}:{line_number}" def format_entry_event(time, pid, event_type, filename, function_name, line_number): timestamp = f"[{time}]" event_details = generate_function_signature(filename, function_name, line_nu...
def test_generate_function_signature(): signature = generate_function_signature("test_script.py", "func1", 4) assert signature == "test_script.py:func1:4" def test_format_entry_event(): formatted_event = format_entry_event("151080408", "12345", "function-entry", "test_script.py", "func1", 4) expected_o...
[ { "docstring": null, "function_declaration": "def generate_function_signature(filename, function_name, line_number):", "function_name": "generate_function_signature", "parameter_list": "(filename, function_name, line_number)" }, { "docstring": null, "function_declaration": "def format_en...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "systemtap\n# trace_functions.stp\nprobe process(\"python3.6\").mark(\"function__entry\") {\n printf(\"[%d] [%d] function-entry: %s %s %d\\n\",\n gettimeofday_...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00005367", "row_id": 5367, "seed_ids": "[79]" }
0.5228
Docs: Python310_5367
I
[ "generate_function_signature", "format_entry_event", "format_gc_event" ]
3
[ [ "format_entry_event", "generate_function_signature" ] ]
1
[]
false
[]
false
pytest
false
[]
true
5ef6a1b392d31c968833d15fd1e1392192494ce0
17415850136cacb71a64cfcb7999956dc84c4076
v1.0
instruct
Docs
Docs: Python310_5452_I
You are provided with a list of integers and tasked with performing the following operations using Python's functional programming modules (`itertools` and `functools`): 1. Filter the list to include only prime numbers. 2. Create a new list where each element is the square of the prime numbers from the filtered list. ...
from itertools import filterfalse from functools import reduce def is_prime(n): """ Returns True if n is a prime number, otherwise False. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False p = 3 while p * p <= n: if n % p == 0:...
from solution import process_primes def test_process_primes_with_example_input(): numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = process_primes(numbers) assert result == 87 def test_process_primes_with_no_primes(): numbers = [1, 4, 6, 8, 10] result = process_primes(numbers) assert result =...
[ { "docstring": "Returns True if n is a prime number, otherwise False.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Processes a list of integers to filter out prime numbers, square them,\nand return the sum of the square...
[ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import itertools\nimport functools\nimport math\n\ndef is_prime(n):\n \"\"\"\n Check if a number is a prime.\n \"\"\"\n if n <= 1:\n return False\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00005452", "row_id": 5452, "seed_ids": "[387]" }
0.684482
Docs: Python310_5452
I
[ "is_prime", "process_primes" ]
2
[ [ "process_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0af56d4524fd5acae06c13addf7d32e897583cb8
6379c3578afb08e9e5c536795584622d270b0747
v1.0
instruct
Docs
Docs: Python310_5572_I
### Question: Managing Context Variables in Asynchronous Python Code You are tasked with developing a Python application that handles asynchronous tasks and manages context-local state using the `contextvars` module. Specifically, you need to create a context variable that tracks the current user's session information...
import contextvars import asyncio # Step 1: Create the session_var ContextVar session_var = contextvars.ContextVar('session_var', default=None) # Step 2: Implement session management functions def set_session(session_info): session_var.set(session_info) def get_session(): return session_var.get() # Step 3: ...
from solution import set_session, get_session, handle_session import pytest import asyncio async def mock_task(): session = get_session() return session def test_set_and_get_session(): session_info = {"user_id": 456, "token": "zxyabc"} set_session(session_info) assert get_session() == session_info...
[ { "docstring": null, "function_declaration": "def set_session(session_info):", "function_name": "set_session", "parameter_list": "(session_info)" }, { "docstring": null, "function_declaration": "def get_session():", "function_name": "get_session", "parameter_list": "()" } ]
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import contextvars\nimport asyncio\n\n# Step 1: Create the session_var ContextVar\nsession_var = contextvars.ContextVar('session_var', default=None)\n\n# Step 2: Implem...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005572", "row_id": 5572, "seed_ids": "[392]" }
0.455576
Docs: Python310_5572
I
[ "set_session", "get_session", "handle_session", "example_task", "main" ]
5
[ [ "example_task", "get_session" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eda5369996f6f7f4943e63c7e6d3eb2cfc266f59
70ceb91c82ef52fb6b3cce095458a7dd818b864e
v1.0
instruct
Docs
Docs: Python310_5622_I
#### Objective Write a Python program that manages user data by combining object serialization (`pickle`) and database operations (`sqlite3`). The user data includes basic information such as name, age, and email. You will be required to implement the following: 1. A `User` class with `name`, `age`, and `email` attri...
import pickle import sqlite3 class User: def __init__(self, name: str, age: int, email: str): self.name = name self.age = age self.email = email def serialize_user(user: User) -> bytes: """Serialize User object to bytes using pickle.""" return pickle.dumps(user) def deserialize_us...
import os import pytest from solution import User, serialize_user, deserialize_user, create_user_table, insert_user, get_user, update_user, delete_user def test_serialization(): user = User(name='Alice', age=30, email='alice@example.com') data = serialize_user(user) assert isinstance(data, bytes) ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pickle\nimport sqlite3\n\n\nclass User:\n def __init__(self, name: str, age: int, email: str):\n self.name = name\n self.age = age\n self...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005622", "row_id": 5622, "seed_ids": "[140]" }
0.601744
Docs: Python310_5622
I
[ "serialize_user", "deserialize_user", "create_user_table", "insert_user", "get_user", "update_user", "delete_user" ]
7
[ [ "get_user", "deserialize_user" ], [ "insert_user", "serialize_user" ], [ "update_user", "serialize_user" ] ]
3
[]
false
[ "User" ]
true
pytest
true
[]
true
fd7f334095a93fb04c30474cafeafabeee2fef49
1e5564816c4c65f4cfafe59de5048d00d0e550b8
v1.0
instruct
Docs
Docs: Pytorch_5639_I
**Question:** You are provided with the code for a simple neural network implemented in PyTorch. Your task is to modify this neural network to use FSDP2 (Fully Sharded Data Parallelism 2) for distributed training. Follow these steps: 1. Implement a basic fully connected neural network (`SimpleNN`).Your network should...
import torch import torch.nn as nn import torch.distributed as dist from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.utils.data import DataLoader, DistributedSampler import torchvision.datasets as datasets import torchvision.transforms as transforms # 1. Define the simple neural network ...
def test_network_architecture(): model = SimpleNN() assert isinstance(model.fc1, nn.Linear) assert model.fc1.in_features == 784 assert model.fc1.out_features == 256 assert isinstance(model.fc2, nn.Linear) assert model.fc2.in_features == 256 assert model.fc2.out_features == 128 assert isi...
[]
[ 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\nimport torch.nn as nn\nimport torch.distributed as dist\nfrom torch.distributed.fsdp import fully_shard, FlattenParamsWrapper\nfrom torch.utils.data impor...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00005639", "row_id": 5639, "seed_ids": "[112]" }
0.455662
Docs: Pytorch_5639
I
[ "setup_model", "init_distributed", "train" ]
3
[ [ "train", "init_distributed" ], [ "train", "setup_model" ] ]
2
[]
false
[ "SimpleNN" ]
true
pytest
false
[ "torch", "torchvision" ]
false
139a99c179fcaf1ef058e3661969d03aae32b815
3dde8c38363dd81d4124ef53ea8cbcd6fa134c0e
v1.0
instruct
Docs
Docs: Python310_5806_I
**Problem Statement:** You are tasked with developing a Python program that reads a binary file, processes the data to extract meaningful information, stores the results in a custom data structure, and performs computations on the data. The program must also use multithreading to enhance performance while ensuring thr...
import threading import struct from collections import deque from typing import List, Dict, Tuple, Union class ThreadSafeRecords: def __init__(self): self.records = deque() self.lock = threading.Lock() def add_record(self, record: Dict[str, Union[int, bytes]]): with self.lock: ...
import pytest from solution import ThreadSafeRecords, read_and_process_binary_file, compute_average_data_length, find_latest_record def test_thread_safe_records(): records = ThreadSafeRecords() record1 = {'record_id': 1, 'timestamp': 1234567890, 'data': b'test1'} record2 = {'record_id': 2, 'timestamp': 123...
[]
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import threading\nimport struct\nfrom collections import deque, defaultdict\nfrom typing import Dict, Any\n\n# Thread-safe custom data structure\nclass RecordStore:\n ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00005806", "row_id": 5806, "seed_ids": "[420]" }
0.450671
Docs: Python310_5806
I
[ "parse_record", "process_file_segment", "read_and_process_binary_file", "compute_average_data_length", "find_latest_record" ]
5
[ [ "process_file_segment", "parse_record" ] ]
1
[]
false
[ "ThreadSafeRecords" ]
true
pytest
true
[]
true
083f4231e9d5d9aaaadeaa1d815b71cdb3afab80
b16de0ec045fb029c259865f9eb96ac570fdd2ce
v1.0
instruct
Docs
Docs: Python310_5810_I
**Objective:** This coding challenge aims to assess your ability to work with Python's `warnings` module effectively. You are required to implement a function that manages and handles warnings for a given piece of legacy code. **Task:** You are given a function `legacy_function()` in a module that uses deprecated fea...
import warnings from typing import List, Dict def legacy_function(): # Example implementation generating warnings warnings.warn("This is a deprecation warning", DeprecationWarning) warnings.warn("This is a user warning", UserWarning) def manage_warnings(warning_conditions: List[Dict[str, str]], logging_li...
import warnings from solution import manage_warnings, legacy_function def test_manage_warnings(): warning_conditions = [ {"action": "error", "category": "DeprecationWarning", "message": "deprecation"} ] logging_list = [] try: manage_warnings(warning_conditions, logging_list) excep...
[ { "docstring": null, "function_declaration": "def legacy_function():", "function_name": "legacy_function", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def manage_warnings(warning_conditions, logging_list):", "function_name": "manage_warnings", "paramet...
[ 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 warnings\nfrom typing import List, Dict\n\ndef legacy_function():\n warnings.warn(\"This is a deprecation warning\", DeprecationWarning)\n warnings.warn(\"...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00005810", "row_id": 5810, "seed_ids": "[125]" }
0.514588
Docs: Python310_5810
I
[ "legacy_function", "manage_warnings" ]
2
[ [ "manage_warnings", "legacy_function" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a5c215f145bf0f2f45c5ed6b20ae0d3c6de4cfec
877c6506f6299cbd4ee83e1580e265319bb3dda2
v1.0
instruct
Docs
Docs: Scikit_5822_I
Out-of-Core Text Classification In this exercise, you are required to implement an out-of-core learning system using scikit-learn. The system should train a classifier incrementally on text data that is too large to fit into memory. #### Task: 1. **Data Streaming**: Implement a generator function `stream_data(file_pa...
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def stream_data(file_path: str): """ Generator function to yield instances from the file. Each line in the file represents a single instance in the format ...
import pytest from solution import stream_data, train_and_evaluate def test_stream_data(tmp_path): # Create a temporary file with test data test_data = "0\ttext one\n1\ttext two\n0\ttext three\n" test_file = tmp_path / "test_stream_data.txt" test_file.write_text(test_data) result = list(stream...
[ { "docstring": "Generator function to yield instances from the file.\nEach line in the file represents a single instance in the format <label> <text>.", "function_declaration": "def stream_data(file_path):", "function_name": "stream_data", "parameter_list": "(file_path)" }, { "docstring":...
[ 1, 1 ]
2
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\n\ndef stream_...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005822", "row_id": 5822, "seed_ids": "[63]" }
0.548405
Docs: Scikit_5822
I
[ "stream_data", "train_and_evaluate" ]
2
[ [ "train_and_evaluate", "stream_data" ] ]
1
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
10b8cab899851ccfc0a3c7392aa9f686566bd4ae
1b70ea012072e4c58506cfb5cc44015f6cabe40e
v1.0
instruct
Docs
Docs: Scikit_5850_I
**Objective**: Implement and evaluate an `SGDClassifier` to solve a binary classification problem using a given dataset, focusing on hyperparameter optimization and performance evaluation. #### Question You are provided with a dataset `data.csv` containing features (numerical) and a target variable for a binary classi...
import pandas as pd from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.preprocessing import StandardScaler from sklearn.pipeline import make_pipeline from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score, roc_auc_score def load_data(filepath): """ ...
import pandas as pd import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from solution import sgd_classifier_pipeline, load_data, split_data, create_pipeline, define_param_grid, perform_grid_search, evaluate_model def create_test_data(): """ C...
[ { "docstring": "Load the dataset from the given filepath.", "function_declaration": "def load_data(filepath):", "function_name": "load_data", "parameter_list": "(filepath)" }, { "docstring": "Split the dataset into training and testing sets.", "function_declaration": "def split_data(data...
[ 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 ]
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.preprocessing import StandardScaler\nfrom sklearn.pipeline import ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00005850", "row_id": 5850, "seed_ids": "[44]" }
0.50684
Docs: Scikit_5850
I
[ "load_data", "split_data", "create_pipeline", "define_param_grid", "perform_grid_search", "evaluate_model", "sgd_classifier_pipeline" ]
7
[ [ "sgd_classifier_pipeline", "create_pipeline" ], [ "sgd_classifier_pipeline", "define_param_grid" ], [ "sgd_classifier_pipeline", "evaluate_model" ], [ "sgd_classifier_pipeline", "load_data" ], [ "sgd_classifier_pipeline", "perform_grid_search" ], [ "...
6
[]
false
[]
false
pytest
true
[ "numpy", "pandas", "sklearn" ]
false
a3372fd77d0bcd1190ec595e216666021e8a7907
19c255bb30f1bf9c6e8ec67728cf616eff413ab0
v1.0
instruct
Docs
Docs: Python310_5870_I
**Coding Assessment Question** ### Objective Implement a custom context manager that ensures the proper management of multiple resources, allows for optional resource management, and supports both synchronous and asynchronous operations. ### Problem Statement You are required to implement a function `manage_resources...
import contextlib import aiohttp import asyncio @contextlib.contextmanager def file_manager(file_name): print(f"Opening file {file_name}") try: with open(file_name, 'w') as file: yield file finally: print(f"Closing file {file_name}") @contextlib.asynccontextmanager async def as...
import pytest import asyncio from unittest.mock import patch, mock_open from aiohttp import ClientSession from solution import manage_resources @pytest.mark.asyncio async def test_manage_resources_all_sync(): resources = [ {"type": "sync", "resource": "test_file_1.txt", "optional": False}, {"type":...
[ { "docstring": null, "function_declaration": "def file_manager(file_name):", "function_name": "file_manager", "parameter_list": "(file_name)" } ]
[ 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 contextlib\nimport aiohttp\nimport asyncio\n\n@contextlib.contextmanager\ndef file_manager(file_name):\n print(f\"Opening file {file_name}\")\n try:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005870", "row_id": 5870, "seed_ids": "[177]" }
0.433313
Docs: Python310_5870
I
[ "file_manager", "async_http_session", "manage_resources" ]
3
[ [ "manage_resources", "async_http_session" ], [ "manage_resources", "file_manager" ] ]
2
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
ca348b4f25dea100462689bb24128c027b6e8b5c
e9e99faba2040660077f1575f933a08b2fe6d799
v1.0
instruct
Docs
Docs: Python310_5890_I
## Task You are required to create an application that simulates a simple calculator. The calculator should take two numbers and an operator as input and perform the corresponding mathematical operation. You must handle potential errors such as invalid inputs and division by zero, and ensure resources are cleaned up af...
def perform_calculation(num1, num2, operator): """ This function performs basic arithmetic operations. :param num1: First number (integer) :param num2: Second number (integer) :param operator: A string that can be one of '+', '-', '*', '/' :return: The result of the operation as a float ...
from solution import perform_calculation def test_perform_calculation_addition(): assert perform_calculation(3, 4, '+') == 7.0 def test_perform_calculation_subtraction(): assert perform_calculation(10, 4, '-') == 6.0 def test_perform_calculation_multiplication(): assert perform_calculation(3, 5, '*') == ...
[ { "docstring": "This function performs basic arithmetic operations.\n\n:param num1: First number (integer)\n:param num2: Second number (integer)\n:param operator: A string that can be one of '+', '-', '*', '/'\n:return: The result of the operation as a float\n:raises ValueError: If operator is not one of the sp...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def perform_calculation(num1, num2, operator):\n \"\"\"\n This function performs basic arithmetic operations.\n \n :param num1: First number (integer)\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00005890", "row_id": 5890, "seed_ids": "[424]" }
0.620382
Docs: Python310_5890
I
[ "perform_calculation", "calculator" ]
2
[ [ "calculator", "perform_calculation" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3ba46463e4d5213d92f8f9c572033a90acb6b9cb
45917c43a657a18b95d8b7a43b437ac39ec30b96
v1.0
instruct
Docs
Docs: Python310_5892_I
### Comprehensive List Manipulation and Data Extraction You are asked to write a series of functions to manipulate and extract data from nested lists, combining fundamentals of list operations, comprehensions, and set/dictionary use. #### Function 1: Flatten Nested List Write a function `flatten_nested_list(nested_l...
def flatten_nested_list(nested_list): """ Flattens a nested list into a single-level list. Parameters: nested_list (list): A nested list of arbitrary depth. Returns: list: A flattened single-level list. """ flattened_list = [] def flatten(sublist): for item in ...
import pytest from solution import flatten_nested_list, unique_values, nested_dict_construction def test_flatten_nested_list(): assert flatten_nested_list([1, [2, [3, 4], 5], [6, 7]]) == [1, 2, 3, 4, 5, 6, 7] assert flatten_nested_list([1, [2, 3]]) == [1, 2, 3] assert flatten_nested_list([1]) == [1] as...
[ { "docstring": "Flattens a nested list into a single-level list.\n\nParameters:\nnested_list (list): A nested list of arbitrary depth.\n\nReturns:\nlist: A flattened single-level list.", "function_declaration": "def flatten_nested_list(nested_list):", "function_name": "flatten_nested_list", "paramet...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def flatten_nested_list(nested_list):\n \"\"\"\n Flattens a nested list into a single-level list.\n \n Parameters:\n nested_list (list): A nested list of...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00005892", "row_id": 5892, "seed_ids": "[411]" }
0.614561
Docs: Python310_5892
I
[ "flatten_nested_list", "unique_values", "nested_dict_construction" ]
3
[ [ "unique_values", "flatten_nested_list" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7bed885a9e5d833f05e87687dcb59556e92ed26c
071835117594209f99f0c3652ed5f5182b66e020
v1.0
instruct
Docs
Docs: Python310_6029_I
**Question: Implementing and Testing Custom Charset Handling in Emails** Background: In email communication, different character sets may require different encodings for compatibility and proper handling. In particular, headers and bodies in emails might need specific encodings like quoted-printable or base64. Your ta...
from email.charset import Charset, add_charset, QP, BASE64 def setup_custom_charset(input_charset: str, header_enc: str, body_enc: str, output_charset: str): """ Registers a custom charset and returns a Charset instance. """ header_enc_map = { 'quoted-printable': QP, 'base64': BASE64, ...
import pytest from solution import setup_custom_charset, encode_email_parts, test_custom_charset def test_setup_custom_charset(): charset_instance = setup_custom_charset("iso-8859-1", "quoted-printable", "base64", "utf-8") assert charset_instance.input_charset == "iso-8859-1" assert charset_instance.header...
[ { "docstring": "Registers a custom charset and returns a Charset instance.", "function_declaration": "def setup_custom_charset(input_charset, header_enc, body_enc, output_charset):", "function_name": "setup_custom_charset", "parameter_list": "(input_charset, header_enc, body_enc, output_charset)" ...
[ 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 email.charset\n\ndef setup_custom_charset(input_charset, header_enc, body_enc, output_charset):\n \"\"\"\n Registers a new charset with specified encoding ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00006029", "row_id": 6029, "seed_ids": "[162]" }
0.519969
Docs: Python310_6029
I
[ "setup_custom_charset", "encode_email_parts", "test_custom_charset" ]
3
[ [ "test_custom_charset", "encode_email_parts" ], [ "test_custom_charset", "setup_custom_charset" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5cc720e900ac51a55895335241c71809de65465e
beafc8bd3e5ff4994fc3625f8efdca03f4ba6579
v1.0
instruct
Docs
Docs: Pytorch_6032_I
### Question #### Objective: Implement a custom operation in PyTorch using the `torch.library.custom_op` function and test it using `torch.library.opcheck` and `torch.autograd.gradcheck` to ensure its correctness. #### Description: You will create a custom operation `custom_relu` that replicates the behavior of the s...
import torch from torch import Tensor # Step 1: Define the custom operation def custom_relu(x: Tensor) -> Tensor: return torch.maximum(x, torch.tensor(0., device=x.device)) # Step 2: Register the custom kernel (simplified for educational purposes, no OP Library used) # Normally, you might use torch.library.custom...
import pytest from torch import tensor, autograd from solution import custom_relu, test_custom_relu, test_custom_relu_grad def test_custom_relu_output(): x = tensor([-1.0, 0.0, 1.0, 2.0], requires_grad=True) y = custom_relu(x) expected = tensor([0.0, 0.0, 1.0, 2.0]) assert torch.equal(y, expected)...
[ { "docstring": null, "function_declaration": "def custom_relu(x):", "function_name": "custom_relu", "parameter_list": "(x)" }, { "docstring": null, "function_declaration": "def test_custom_relu():", "function_name": "test_custom_relu", "parameter_list": "()" }, { "docstri...
[ 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.library\nfrom torch.autograd import Function, gradcheck\n\nclass CustomReLU(Function):\n @staticmethod\n def forward(ctx, x):\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00006032", "row_id": 6032, "seed_ids": "[51]" }
0.500438
Docs: Pytorch_6032
I
[ "custom_relu", "test_custom_relu", "test_custom_relu_grad" ]
3
[ [ "test_custom_relu", "custom_relu" ], [ "test_custom_relu_grad", "custom_relu" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
41707a67b15a0f94f751d4ef16f43b1cce946799
71c0b263f1474c0df5b705fa19b97d58de1872ab
v1.0
instruct
Docs
Docs: Python310_6090_I
You are required to implement a function `analyze_numbers(numbers: List[Union[int, float]]) -> Tuple[float, float, Tuple[int, int], float, bool]`. The function should perform various mathematical operations and return a tuple containing the following five elements based on the given list of numbers: 1. **The accurate ...
from typing import List, Union, Tuple import math from functools import reduce import operator def gcd(a, b): while b: a, b = b, a % b return abs(a) def lcm(a, b): return abs(a * b) // gcd(a, b) if a and b else 0 def analyze_numbers(numbers: List[Union[int, float]]) -> Tuple[float, float, Tup...
from solution import analyze_numbers import math def test_single_element(): result = analyze_numbers([5]) expected_sum = 5.0 expected_norm = 5.0 expected_gcd_lcm = (5, 5) expected_rem = math.remainder(5, math.pi) expected_close_to_zero = False assert result == (expected_sum, expected_norm, ...
[ { "docstring": null, "function_declaration": "def gcd(a, b):", "function_name": "gcd", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": null, "function_dec...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Union, Tuple\nimport math\nfrom functools import reduce\nimport operator\n\ndef gcd(a, b):\n while b:\n a, b = b, a % b\n return a...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00006090", "row_id": 6090, "seed_ids": "[274]" }
0.633951
Docs: Python310_6090
I
[ "gcd", "lcm", "analyze_numbers" ]
3
[ [ "analyze_numbers", "gcd" ], [ "analyze_numbers", "lcm" ], [ "lcm", "gcd" ] ]
3
[]
false
[]
false
pytest
true
[]
true
21bb536fe52dcf2995b7ea09850e9bf0b0992fd2
79da433095ae71c46a423445eaa8d22bf94b73c5
v1.0
instruct
Docs
Docs: Pytorch_6109_I
### PyTorch and TorchScript Coding Assessment **Objective**: Write a function using PyTorch, convert it to TorchScript, and verify its correctness. **Problem Statement**: You are given a task to implement a function in PyTorch that performs a specific operation on tensors and then convert this function to TorchScrip...
import torch from typing import Callable def custom_relu(x: torch.Tensor, t: float) -> torch.Tensor: """ Apply a modified ReLU operation on the input tensor `x`. Parameters: x (torch.Tensor): Input tensor on which the operation will be applied. t (float): Threshold value. Values in the tensor less...
from solution import custom_relu, convert_to_torchscript, test_custom_relu import torch def test_custom_relu_values(): x = torch.tensor([0.5, 2.0, -1.0, 3.5, 0.0, -0.5]) t = 1.0 expected = torch.tensor([0.0, 2.0, 0.0, 3.5, 0.0, 0.0]) result = custom_relu(x, t) assert torch.equal(expected, resu...
[ { "docstring": "Apply a modified ReLU operation on the input tensor `x`.\n\nParameters:\nx (torch.Tensor): Input tensor on which the operation will be applied.\nt (float): Threshold value. Values in the tensor less than t will be set to zero.\n\nReturns:\ntorch.Tensor: A tensor with the modified ReLU operation ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.jit\n\ndef custom_relu(x: torch.Tensor, t: float) -> torch.Tensor:\n \"\"\"\n Apply a modified ReLU operation on the input tensor `x`.\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006109", "row_id": 6109, "seed_ids": "[41]" }
0.502802
Docs: Pytorch_6109
I
[ "custom_relu", "convert_to_torchscript", "test_custom_relu" ]
3
[ [ "test_custom_relu", "convert_to_torchscript" ], [ "test_custom_relu", "custom_relu" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
c7f3dfdcbe82c81b38b301bbf00c970e417df1ef
1825a2832942fa7e382d6401525e3e2e0911602a
v1.0
instruct
Docs
Docs: Python310_6136_I
You are required to design an application that simulates a simple banking system providing the following functionalities: 1. Create an account. 2. Deposit money into the account. 3. Withdraw money from the account. 4. Save the account transaction history to a file upon program termination. **Specifications**: 1. Impl...
import atexit class InsufficientFunds(Exception): pass class BankAccount: def __init__(self, account_number): self.account_number = account_number self.balance = 0 self.transaction_history = [] def deposit(self, amount): self.balance += amount self.transaction_hist...
import pytest from solution import BankAccount, InsufficientFunds, create_account def test_create_account(): account = create_account(1) assert account.account_number == 1 assert account.get_balance() == 0 assert account.get_transaction_history() == [] def test_deposit(): account = create_account(...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import atexit\n\nclass InsufficientFunds(Exception):\n pass\n\nclass BankAccount:\n def __init__(self, account_number):\n self.account_number = account_num...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00006136", "row_id": 6136, "seed_ids": "[278]" }
0.49499
Docs: Python310_6136
I
[ "save_transaction_history", "create_account" ]
2
[ [ "create_account", "save_transaction_history" ] ]
1
[]
false
[ "InsufficientFunds", "BankAccount" ]
true
pytest
true
[]
true
6b5179699cb09c8e417a0ee5e14e94820feda963
d329aa8298c4ea9ca886f0c30aad34da84eda17c
v1.0
instruct
Docs
Docs: Python310_6171_I
### Turtle Graphics Art Creation #### Objective Write a Python program using the `turtle` module to create a piece of turtle graphics art. The program should demonstrate your understanding of the following concepts: - Turtle motion and control - Pen settings and drawing - Screen settings and events - Visibility and ap...
import turtle def draw_shape(t, sides, length): """ Draws a polygon with a specific number of sides and side length using the turtle object. """ angle = 360 / sides for _ in range(sides): t.forward(length) t.right(angle) def create_turtle_art(): screen = turtle.Screen() scr...
import pytest import turtle from solution import create_turtle_art def test_create_turtle_art_import(): """ Test if the create_turtle_art function can be imported without issues. """ assert create_turtle_art is not None @pytest.mark.skip(reason="Manual test required for graphical output and event hand...
[ { "docstring": "Draws a polygon with a specific number of sides and side length using the turtle object.", "function_declaration": "def draw_shape(t, sides, length):", "function_name": "draw_shape", "parameter_list": "(t, sides, length)" }, { "docstring": null, "function_declaration": "d...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import turtle\n\ndef create_turtle_art():\n # Set up the screen\n screen = turtle.Screen()\n screen.setup(width=800, height=600)\n screen.bgcolor('lightblue...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00006171", "row_id": 6171, "seed_ids": "[179]" }
0.757594
Docs: Python310_6171
I
[ "draw_shape", "create_turtle_art" ]
2
[ [ "create_turtle_art", "draw_shape" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c4fa659f8dbf2421567074551598ffd5f46ba754
28bcf2a513b936b223420cebbf2fc0dd468812f3
v1.0
instruct
Docs
Docs: Python310_6223_I
### **Problem Statement:** You are tasked with writing a set of functions to handle HTTP requests and appropriately manage errors using the `urllib.error` module in Python. #### **Function 1: make_request** Write a function `make_request(url: str) -> str` that performs an HTTP GET request to the given URL and return...
import urllib.request import urllib.error def make_request(url: str) -> str: try: response = urllib.request.urlopen(url) content = response.read() return content.decode('utf-8') except urllib.error.HTTPError as e: print(f"HTTP Error {e.code}: {e.reason}") raise excep...
import pytest import urllib.error from solution import make_request, download_content def test_make_request_success(monkeypatch): class MockResponse: def read(self): return b"Example content" def decode(self, encoding): return "Example content" def mock_urlopen(url): ...
[ { "docstring": null, "function_declaration": "def make_request(url):", "function_name": "make_request", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def download_content(url, expected_length):", "function_name": "download_content", "parameter_list": ...
[ 0, 0, 0, 1, 0, 0, 1, 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 urllib.request\nimport urllib.error\n\ndef make_request(url: str) -> str:\n try:\n response = urllib.request.urlopen(url)\n content = response.r...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00006223", "row_id": 6223, "seed_ids": "[226]" }
0.772308
Docs: Python310_6223
I
[ "make_request", "download_content" ]
2
[ [ "download_content", "make_request" ] ]
1
[]
false
[]
false
pytest
true
[]
true
12d712a0db7d69661a4e2d150f4031cbe2c915f4
08d2c7d5fafe6e48d7c390b795ce9d09ee4d482b
v1.0
instruct
Docs
Docs: Python310_6295_I
### Question: Parallel File Processing with `concurrent.futures` You are provided with a list of text file paths. Your task is to analyze each file to count the number of words it contains. Given the large number of files and their sizes, you should implement this word count using parallel processing to speed up the t...
from typing import List, Dict import concurrent.futures def count_words_in_file(file_path: str) -> int: """ Helper function to count the number of words in a single file. """ try: with open(file_path, 'r', encoding='utf-8') as file: content = file.read() words = content....
from solution import count_words_parallel def test_count_words_parallel_single_file(): file_paths = ["test1.txt"] with open("test1.txt", "w") as file: file.write("Hello world") assert count_words_parallel(file_paths) == {"test1.txt": 2} def test_count_words_parallel_multiple_files(): file_path...
[ { "docstring": "Helper function to count the number of words in a single file.", "function_declaration": "def count_words_in_file(file_path):", "function_name": "count_words_in_file", "parameter_list": "(file_path)" }, { "docstring": "Count the number of words in each file in parallel.\n\n:p...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from concurrent.futures import ThreadPoolExecutor\nfrom typing import List, Dict\n\ndef count_words_in_file(file_path: str) -> int:\n \"\"\"\n Count the number of...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00006295", "row_id": 6295, "seed_ids": "[224]" }
0.653821
Docs: Python310_6295
I
[ "count_words_in_file", "count_words_parallel" ]
2
[ [ "count_words_parallel", "count_words_in_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9d2061b479d9cfcc0e59ac3258b2923b9ac4cda9
255b8381314a1218e089fa90b1ac8c5a3ed27c1e
v1.0
instruct
Docs
Docs: Python310_6309_I
<|Analysis Begin|> The provided documentation is extensive and detailed, covering the `codecs` module in Python, which handles various encoding and decoding tasks, including text encodings, byte encodings, error handling, and more. Key aspects of the `codecs` module: 1. **Basic Functions**: Includes `codecs.encode()`...
import codecs def encode_to_custom_hex(text: str) -> str: """ Encodes a given text to a custom-hex encoded string. """ return '-'.join(f'{ord(char):02x}' for char in text) def custom_ignore_error(exception: UnicodeError): """ Custom ignore error handler. """ return ('', exception.end) ...
from solution import encode_to_custom_hex, decode_from_custom_hex def test_encode_to_custom_hex(): assert encode_to_custom_hex("Hello") == "48-65-6c-6c-6f" assert encode_to_custom_hex(" ") == "20" assert encode_to_custom_hex("A") == "41" assert encode_to_custom_hex("Aa") == "41-61" def test_decode_fro...
[ { "docstring": "Encodes a given text to a custom-hex encoded string.", "function_declaration": "def encode_to_custom_hex(text):", "function_name": "encode_to_custom_hex", "parameter_list": "(text)" }, { "docstring": "Custom ignore error handler.", "function_declaration": "def custom_igno...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import codecs\n\ndef encode_to_custom_hex(text: str) -> str:\n \"\"\"\n Encodes a given text to a custom-hex encoded string.\n \"\"\"\n return '-'.join(f'{o...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00006309", "row_id": 6309, "seed_ids": "[211]" }
0.641658
Docs: Python310_6309
I
[ "encode_to_custom_hex", "custom_ignore_error", "custom_replace_error", "decode_from_custom_hex" ]
4
[ [ "decode_from_custom_hex", "custom_ignore_error" ], [ "decode_from_custom_hex", "custom_replace_error" ] ]
2
[]
false
[]
false
pytest
true
[]
true
24648215b1cb306a33e558dc7538692d16c03624
509fc68831861ab6edb402b8617bae108f3eeb7a
v1.0
instruct
Docs
Docs: Python310_6312_I
### Hashlib Coding Assessment Question #### Objective: You are tasked with creating a Python utility that uses the `hashlib` module to hash files and verify their integrity. This exercise will assess your ability to work with different hashing algorithms and methods provided by the `hashlib` module. #### Problem Stat...
import hashlib def hash_file(file_path: str, algorithm: str = 'sha256') -> str: """ Hash the contents of a file using the specified hashing algorithm. Parameters: - file_path (str): The path to the file that needs to be hashed. - algorithm (str): The name of the hashing algorithm to use (defau...
from solution import hash_file, verify_hash import hashlib import pytest def test_hash_file_sha256(tmp_path): # Create a temporary file test_file = tmp_path / "test.txt" test_file.write_text("This is a test.") # Expected hash using sha256 expected_hash = hashlib.sha256(b"This is a test.").hexd...
[ { "docstring": "Hash the contents of a file using the specified hashing algorithm.\n\nParameters:\n- file_path (str): The path to the file that needs to be hashed.\n- algorithm (str): The name of the hashing algorithm to use (default is 'sha256').\n\nReturns:\n- str: A hexadecimal string representing the hash o...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\n\ndef hash_file(file_path: str, algorithm: str = 'sha256') -> str:\n \"\"\"\n Returns the hash of the contents of the specified file using the giv...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006312", "row_id": 6312, "seed_ids": "[225]" }
0.765835
Docs: Python310_6312
I
[ "hash_file", "verify_hash" ]
2
[ [ "verify_hash", "hash_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a23f3e025d5b00d6c07430d055970ddd2f27804d
8fc71ea78761719c0eb46937cc763aca7f71c03f
v1.0
instruct
Docs
Docs: Pytorch_6319_I
#### Objective Design a PyTorch module and demonstrate advanced features such as hooks, custom initialization, and training using optimizers. Your task is to create a composite module that first applies a custom linear transformation followed by a non-linear activation function, and train it to fit a simple function. ...
import torch from torch import nn import torch.nn.functional as F from torch import optim # 1. Custom Linear Module class CustomLinear(nn.Module): def __init__(self, in_features, out_features): super(CustomLinear, self).__init__() # Initialize parameters with custom techniques self.weight =...
import torch from torch import nn from solution import CompositeNet def test_model_initialization(): model = CompositeNet() for name, param in model.named_parameters(): if 'weight' in name: assert torch.all(param != 0), f"Weight {name} is not properly initialized" if 'bias' in name:...
[]
[ 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\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch import optim\n\n# 1. Custom Linear Module\nclass CustomLinear(nn.Module):\n def __ini...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00006319", "row_id": 6319, "seed_ids": "[175]" }
0.504554
Docs: Pytorch_6319
I
[ "forward_hook", "backward_hook", "train_model" ]
3
[ [ "train_model", "backward_hook" ], [ "train_model", "forward_hook" ] ]
2
[]
false
[ "CustomLinear", "CompositeNet" ]
true
pytest
true
[ "torch" ]
false
b03be89ba6179ac22367bebbbf915f629d844540
fc61866713670f4d7f357caa8b823f3e1feab273
v1.0
instruct
Docs
Docs: Python310_6348_I
### Cryptographic Services: Secure Message Verification In this coding assessment, you will demonstrate your understanding of the `hashlib` and `hmac` modules by implementing a secure message verification system. ### Problem Statement You need to implement two functions to ensure the integrity and authenticity of me...
import hmac import hashlib def generate_secure_hash(message: str, key: bytes) -> str: """ Generate a secure HMAC hash of the message using the provided key and SHA-256 algorithm. Parameters: message (str): The message to hash. key (bytes): The secret key used for hashing. Returns: str: Th...
from solution import generate_secure_hash, verify_secure_hash def test_generate_secure_hash(): message = "Hello, world!" key = b"this_is_a_secret_key" generated_hash = generate_secure_hash(message, key) assert isinstance(generated_hash, str) assert len(generated_hash) == 64 def test_verify_secure_...
[ { "docstring": "Generate a secure HMAC hash of the message using the provided key and SHA-256 algorithm.\n\nParameters:\nmessage (str): The message to hash.\nkey (bytes): The secret key used for hashing.\n\nReturns:\nstr: The hexadecimal representation of the HMAC hash.", "function_declaration": "def genera...
[ 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 hmac\nimport hashlib\n\ndef generate_secure_hash(message: str, key: bytes) -> str:\n \"\"\"\n Generate a secure HMAC hash of the message using the provided...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006348", "row_id": 6348, "seed_ids": "[394]" }
0.83714
Docs: Python310_6348
I
[ "generate_secure_hash", "verify_secure_hash" ]
2
[ [ "verify_secure_hash", "generate_secure_hash" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b58c335a799649b49d0055e14abab522f90fca6e
a5ce0946a4b021b54f57ea3c35ecde13566abcd1
v1.0
instruct
Docs
Docs: Python310_6357_I
**Question: Custom Calendar Filter** You are required to create a function named `filter_calendar_events` that filters out specific days from a given month based on certain criteria. The function will use the `calendar` module to generate the days of the month and filter out days based on whether they fall on weekdays...
import calendar def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def filter_calendar_events(ye...
from solution import filter_calendar_events def test_filter_calendar_events_weekdays(): assert filter_calendar_events(2023, 10, 'weekdays') == [2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 16, 17, 18, 19, 20, 23, 24, 25, 26, 27, 30, 31] def test_filter_calendar_events_weekends(): assert filter_calendar_events(2023, 10, ...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def filter_calendar_events(year, month, filter_criteria):", "function_name": "filter_calendar_events", "parameter...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import calendar\n\ndef is_prime(n):\n \"\"\"Check if a number is a prime number.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006357", "row_id": 6357, "seed_ids": "[403]" }
0.644758
Docs: Python310_6357
I
[ "is_prime", "filter_calendar_events" ]
2
[ [ "filter_calendar_events", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
779a92fa0119e09125c647edb0df0f09c1917eaf
74f1dbce27860cdc5ba348501c0f24593bd3c0e9
v1.0
instruct
Docs
Docs: Python310_6360_I
You are provided with a series of physics experiments recording different values, and you need to process the data using various mathematical calculations. Implement a function `process_experiment_data(data)` that performs the following steps: 1. **Normalize the Data**: Normalize the recorded values in the `data` list...
import math from math import gcd from functools import reduce def lcm(a, b): return abs(a * b) // gcd(a, b) def process_experiment_data(data): # Convert degrees to radians normalized_data = [(math.radians(x), math.radians(y)) for x, y in data] # Calculate Euclidean distances distances = [] ...
from solution import process_experiment_data import pytest def test_normalized_data(): data = [ (0.0, 0.0), (180.0, 90.0) ] result = process_experiment_data(data) expected_normalized_data = [ (0.0, 0.0), (math.pi, math.pi / 2) ] assert result['normalized_data'] =...
[ { "docstring": null, "function_declaration": "def lcm(a, b):", "function_name": "lcm", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def process_experiment_data(data):", "function_name": "process_experiment_data", "parameter_list": "(data)" } ]
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nfrom functools import reduce\nfrom math import gcd\n\ndef normalize_data(data):\n return [(math.radians(x), math.radians(y)) for x, y in data]\n\ndef eu...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00006360", "row_id": 6360, "seed_ids": "[274]" }
0.564975
Docs: Python310_6360
I
[ "lcm", "process_experiment_data" ]
2
[ [ "process_experiment_data", "lcm" ] ]
1
[]
false
[]
false
pytest
true
[]
true
531b97216fdf8e5a5e3c1abf38123c026174282c
7202d51df252e291b3fbb56010a625e62883a4f8
v1.0
instruct
Docs
Docs: Python310_6420_I
**Question:** ### Implementing a Periodic Async Job Scheduler You are required to create an asynchronous job scheduler in Python using `asyncio`, which will periodically execute a set of tasks and log their completion times. Each task should be executed at a specific interval, and the execution should be managed in ...
import asyncio import time from typing import Callable, List, Tuple async def log_execution(func: Callable): """ Log the execution of the function. """ await func() print(f"Task {func.__name__} executed at {time.time()}") async def periodic_task(func: Callable, interval: float): while True...
import asyncio import pytest from solution import periodic_scheduler log_data = [] async def mock_task1(): log_data.append(f"mock_task1 executed at {time.time()}") async def mock_task2(): log_data.append(f"mock_task2 executed at {time.time()}") @pytest.fixture def reset_log_data(): global log_data l...
[]
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport time\nfrom typing import Callable, List, Tuple\n\nasync def log_execution(func: Callable):\n \"\"\"\n Log the execution of the function.\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00006420", "row_id": 6420, "seed_ids": "[267]" }
0.571254
Docs: Python310_6420
I
[ "log_execution", "periodic_task", "periodic_scheduler" ]
3
[ [ "periodic_scheduler", "periodic_task" ], [ "periodic_task", "log_execution" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c6f6cef68e02b0c50df0512ce2b55f18b61ee9de
2c22c82418cae6ec9f1d6e161beb394b272b5ea4
v1.0
instruct
Docs
Docs: Python310_6474_I
### SQLite Database Tasks with `sqlite3` Module In this assessment, you will showcase your proficiency in using Python's `sqlite3` module to interact with an SQLite database. You will perform a series of operations including creating a database, managing transactions, handling custom data types, and executing queries ...
import sqlite3 from typing import List, Tuple # Step 1: Create a database and table def create_database(): connection = sqlite3.connect('books.db') cursor = connection.cursor() cursor.execute('''CREATE TABLE IF NOT EXISTS book ( title TEXT, author TEXT, published_year INTEGER, ...
from solution import create_database, insert_data, get_books_by_year, update_book_rating, Book, store_book, retrieve_books def test_database_creation(): create_database() connection = sqlite3.connect('books.db') cursor = connection.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE type='tab...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sqlite3\nfrom typing import List, Tuple\n\n# Step 1: Create a database and table\ndef create_database():\n conn = sqlite3.connect(\"books.db\")\n cursor = ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006474", "row_id": 6474, "seed_ids": "[103]" }
0.603078
Docs: Python310_6474
I
[ "create_database", "insert_data", "get_books_by_year", "update_book_rating", "adapt_book", "convert_book", "store_book", "retrieve_books" ]
8
[ [ "retrieve_books", "adapt_book" ], [ "retrieve_books", "convert_book" ], [ "store_book", "adapt_book" ], [ "store_book", "convert_book" ] ]
4
[]
false
[ "Book" ]
true
pytest
true
[]
true
90663d2039b23b805de8747453f12843ecca09e0
c44b2e2579a5a1191dbd5fba2a9723fc02c74ed0
v1.0
instruct
Docs
Docs: Python310_6508_I
**Objective**: Implement a Python function to safely handle an asynchronous event in a multithreaded environment using the `signal` module. #### Task You are required to write a program that: 1. Sets up a signal handler for `SIGALRM` that performs a specific task. 2. Creates and starts a separate thread to perform a...
import signal import threading import time def signal_handler(signum, frame): print(f"Signal handler called with signal {signum}") raise TimeoutError("Computation took too long!") def long_computation(): try: for i in range(1, 100): print(f"Computation step {i}") time.sleep...
import signal import time import threading from solution import run_with_timeout def test_run_with_timeout_completes_within_time(): def mock_long_computation(): print("Mock short computation started") time.sleep(1) print("Mock short computation finished") run_with_timeout(2) # The...
[ { "docstring": null, "function_declaration": "def signal_handler(signum, frame):", "function_name": "signal_handler", "parameter_list": "(signum, frame)" }, { "docstring": null, "function_declaration": "def long_computation():", "function_name": "long_computation", "parameter_lis...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import signal\nimport threading\nimport time\n\ndef signal_handler(signum, frame):\n \"\"\"\n Signal handler for SIGALRM.\n Raises a TimeoutError when invoked....
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00006508", "row_id": 6508, "seed_ids": "[253]" }
0.589777
Docs: Python310_6508
I
[ "signal_handler", "long_computation", "run_with_timeout" ]
3
[ [ "run_with_timeout", "signal_handler" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c4b85ec29fcd0490a02219637a8d661af6b772b9
45e280728bf333109cbfe320d7d18e2db67519e0
v1.0
instruct
Docs
Docs: Python310_6602_I
### Advanced Asynchronous Programming with Asyncio #### Objective: Design and implement a Python function that performs multiple asynchronous tasks efficiently while ensuring proper error handling, logging, and concurrency management. #### Problem Statement: You are tasked with simulating a simplified version of a we...
import asyncio import logging import random from typing import List, Dict # Setup logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) async def fetch_data(url: str) -> int: try: await asyncio.sleep(random.randint(1, 5)) data_length = len(url) logger.debug(...
import pytest from solution import fetch_data, process_data, execute_tasks @pytest.mark.asyncio async def test_fetch_data(): url = "https://example.com" result = await fetch_data(url) assert result == len(url) @pytest.mark.asyncio async def test_process_data(): data = 10 result = await process_dat...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport logging\nimport random\nfrom typing import List, Dict\n\n# Initialize logging for debugging\nlogging.basicConfig(level=logging.DEBUG)\nlogger = l...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006602", "row_id": 6602, "seed_ids": "[200]" }
0.59351
Docs: Python310_6602
I
[ "fetch_data", "process_data", "execute_tasks" ]
3
[ [ "execute_tasks", "fetch_data" ], [ "execute_tasks", "process_data" ] ]
2
[ "process_data" ]
false
[]
false
pytest
true
[]
true
540130ef94f35361c218a536e027b3d75ea18275
8942e689d6c2fa3fe59db6d2f2b24cb1d59dd8be
v1.0
instruct
Docs
Docs: Scikit_6621_I
You are tasked with building an out-of-core learning system using scikit-learn. This system should be able to handle extremely large datasets that cannot fit into the computer's main memory (RAM). The task involves creating a pipeline that: 1. Streams data from a large text file. 2. Extracts features using the `Hashin...
import os import numpy as np from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def stream_data(file_path): """ Generator to stream data from a file, one line at a time. Each line is expected to be in the f...
import pytest from solution import out_of_core_learning # Test the function with a small synthetic dataset def test_out_of_core_learning(): # Create a temporary file with labeled instances test_file_path = 'test_large_text_data.txt' with open(test_file_path, 'w') as f: f.write("0\tThis is the first...
[ { "docstring": "Generator to stream data from a file, one line at a time.\nEach line is expected to be in the format: <label> <text>.", "function_declaration": "def stream_data(file_path):", "function_name": "stream_data", "parameter_list": "(file_path)" }, { "docstring": "Extract features ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics impor...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00006621", "row_id": 6621, "seed_ids": "[63]" }
0.47221
Docs: Scikit_6621
I
[ "stream_data", "extract_features", "incremental_train", "out_of_core_learning" ]
4
[ [ "incremental_train", "extract_features" ], [ "incremental_train", "stream_data" ], [ "out_of_core_learning", "extract_features" ], [ "out_of_core_learning", "incremental_train" ], [ "out_of_core_learning", "stream_data" ] ]
5
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
eec61719878f1ef66c0af6dd7fc5514b83b51760
625004779b1682dfa7ef489e313684b682c26d3c
v1.0
instruct
Docs
Docs: Pandas_6669_I
### Memory Optimization, Handling Missing Values, and UDF in Pandas #### **Objective:** Write a function `optimize_dataframe` that optimizes the memory usage of a given Pandas DataFrame. This function should: 1. Convert any columns with `dtype=object` to `categorical` if the number of unique values is less than 50% ...
import pandas as pd import numpy as np def fill_missing_with_median(series: pd.Series) -> pd.Series: """ Fills missing values in a pandas Series with the median of the Series. """ if pd.api.types.is_integer_dtype(series): median_value = series.median() return series.fillna(median_value)...
import pytest import pandas as pd import numpy as np from solution import optimize_dataframe def test_memory_optimization(): data = { 'int_col': np.random.randint(1, 100, size=1000), 'object_col': np.random.choice(['A','B','C','D'], size=1000), 'mix_col': np.random.choice([1, np.nan], size=...
[ { "docstring": "Fills missing values in a pandas Series with the median of the Series.", "function_declaration": "def fill_missing_with_median(series):", "function_name": "fill_missing_with_median", "parameter_list": "(series)" }, { "docstring": "Optimizes a DataFrame by converting object co...
[ 0, 0, 0, 0, 0, 1, 1, 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 pandas as pd\n\ndef fill_median(col):\n \"\"\"\n Fill NaN values in a column with the median of that column.\n \"\"\"\n if pd.api.types.is_integer_dt...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00006669", "row_id": 6669, "seed_ids": "[11]" }
0.631375
Docs: Pandas_6669
I
[ "fill_missing_with_median", "optimize_dataframe" ]
2
[ [ "optimize_dataframe", "fill_missing_with_median" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "pandas" ]
false
27c413acf893c7ef7c18c4866ffcd4441c73f0f7
9dbaa1e2122d021934f8110cb97340bb36128b4c
v1.0
instruct
Docs
Docs: Scikit_6685_I
#### Objective: To assess the student's understanding of out-of-core learning, feature extraction, and the use of incremental learning algorithms in scikit-learn. #### Background: You are given a large text dataset that cannot fit into the system's main memory. Your task is to build a text classification model that pr...
import numpy as np from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score import itertools def stream_data(file_path, batch_size): with open(file_path, 'r', encoding...
import os import pytest from solution import stream_data, train_and_evaluate def test_stream_data(tmpdir): test_file = tmpdir.join("test_data.txt") with open(test_file, "w") as f: f.write("class1,This is the first document.\n") f.write("class2,This is the second document.\n") f.write("...
[ { "docstring": null, "function_declaration": "def stream_data(file_path, batch_size):", "function_name": "stream_data", "parameter_list": "(file_path, batch_size)" }, { "docstring": null, "function_declaration": "def train_and_evaluate(file_path, batch_size, num_batches):", "function...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import t...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00006685", "row_id": 6685, "seed_ids": "[63]" }
0.529232
Docs: Scikit_6685
I
[ "stream_data", "train_and_evaluate" ]
2
[ [ "train_and_evaluate", "stream_data" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
0b8597130c9a4fdc47b70cc3359e1030dee67f51
e2b7c3abe1ecf095bdedce3a258f2b633c837225
v1.0
instruct
Docs
Docs: Python310_6743_I
#### Objective: To assess your understanding of asynchronous programming and the usage of `asyncio` queues in Python. #### Problem Statement: Implement a system that processes a batch of asynchronous tasks using `asyncio.Queue`. The tasks involve calculating the factorial of multiple numbers concurrently. #### Requ...
import asyncio import time import math from typing import List async def worker(name: str, queue: asyncio.Queue, results: List[float]): start_time = time.monotonic() while True: try: number = await queue.get() except asyncio.QueueEmpty: break # Compute factorial ...
import pytest import asyncio from solution import process_factorials @pytest.mark.asyncio async def test_process_factorials_single_worker(): numbers = [5, 10, 15] num_workers = 1 result = await process_factorials(numbers, num_workers) assert len(result) == 1 assert result[0] >= 0 @pytest.mark.asyn...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport time\nimport math\nfrom typing import List\n\nasync def worker(name: str, queue: asyncio.Queue, results: List[float]):\n worker_id = int(name....
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006743", "row_id": 6743, "seed_ids": "[111]" }
0.665816
Docs: Python310_6743
I
[ "worker", "process_factorials" ]
2
[ [ "process_factorials", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
57e460fab392ea695c1f68a8daa3f0e21888970c
50a5774a9f3ef39f70b5554d4dca418766b6e8bc
v1.0
instruct
Docs
Docs: Python310_6768_I
### Advanced Python Initialization and Configuration #### Background Python can be initialized and configured in a highly customizable manner using structures `PyConfig` and `PyPreConfig`. These structures allow setting numerous parameters that can control Python's behavior on initialization. In particular, `PyConfig...
class PyPreConfig: def __init__(self): self.utf8_mode = 0 self.allocator = 0 self.isolated = False self.configure_locale = True def PyPreConfig_InitIsolatedConfig(self): self.isolated = True self.configure_locale = False class PyConfig: def __init__(self): ...
from solution import initialize_isolated_python, PyConfig, PyStatus def test_initialize_successful(): config = PyConfig() config.SetSysPath(['/custom/path/to/modules']) assert simulate_initialize(config) == PyStatus.Ok() def test_initialize_empty_sys_path(): config = PyConfig() assert PyStatus.I...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class PyPreConfig:\n def __init__(self):\n self.utf8_mode = 0\n self.allocator = 0\n\n def PyPreConfig_InitIsolatedConfig(self):\n self.isola...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00006768", "row_id": 6768, "seed_ids": "[15]" }
0.499575
Docs: Python310_6768
I
[ "initialize_isolated_python", "simulate_initialize", "cleanup" ]
3
[ [ "initialize_isolated_python", "cleanup" ], [ "initialize_isolated_python", "simulate_initialize" ] ]
2
[]
false
[ "PyPreConfig", "PyConfig", "PyStatus" ]
true
pytest
true
[]
true
98fd7cf6e0451cff7d861fd889f757ed94e796c4
3042275da614caa85ba8c8a6a1b7d2cf09ea9bc2
v1.0
instruct
Docs
Docs: Python310_6772_I
### Asynchronous Web Scraping with concurrent.futures You are required to implement a function that scrapes the HTML content from a list of URLs concurrently using the `concurrent.futures` module. The function should use the `ThreadPoolExecutor` for this purpose. #### Function Signature ```python def concurrent_scrap...
import concurrent.futures import urllib.request from typing import List, Dict def fetch_url(url: str) -> str: try: with urllib.request.urlopen(url, timeout=30) as response: return response.read().decode('utf-8') except Exception as e: return "Error" def concurrent_scrape(urls: List...
import pytest from solution import concurrent_scrape # Mocking urllib to avoid actual web requests during tests from unittest.mock import patch sample_html_content = "<html><body><h1>Sample Content</h1></body></html>" def mocked_urlopen_success(url, timeout=30): class MockResponse: def read(self): ...
[ { "docstring": null, "function_declaration": "def fetch_url(url):", "function_name": "fetch_url", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def concurrent_scrape(urls, max_workers=5):", "function_name": "concurrent_scrape", "parameter_list": "(url...
[ 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 concurrent.futures\nimport urllib.request\nfrom typing import List, Dict\n\ndef fetch_url(url: str) -> str:\n try:\n with urllib.request.urlopen(url, t...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00006772", "row_id": 6772, "seed_ids": "[347]" }
0.614702
Docs: Python310_6772
I
[ "fetch_url", "concurrent_scrape" ]
2
[ [ "concurrent_scrape", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f36ad41ae8f24c20a280a212c9c1686c6b2873a9
1a9ab665e23483eded4894a6bd3a15140805dde2
v1.0
instruct
Docs
Docs: Python310_6860_I
## Coding Assessment Question ### Objective Implement a Python function that concurrently processes a list of URLs to fetch their contents and processes the data. This task will demonstrate your understanding of asyncio’s capabilities for handling asynchronous network IO and synchronization. ### Problem Statement You...
import aiohttp import asyncio from typing import List async def fetch_url(session, url): try: async with session.get(url, timeout=5) as response: return await response.text() except: return 'ERROR' async def fetch_and_process(urls: List[str]) -> List[str]: async with aiohttp.Cl...
import pytest import asyncio from unittest.mock import patch, AsyncMock from solution import fetch_and_process @pytest.mark.asyncio async def test_fetch_and_process_success(): urls = ["http://example.com/page1", "http://example.com/page2"] async def mock_fetch_url(session, url): if url == "http://...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import aiohttp\nimport asyncio\nfrom typing import List\n\nasync def fetch_url(session, url):\n try:\n async with session.get(url, timeout=5) as response:\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00006860", "row_id": 6860, "seed_ids": "[270]" }
0.572279
Docs: Python310_6860
I
[ "fetch_url", "fetch_and_process" ]
2
[ [ "fetch_and_process", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
1eee25527f91fecace8b477a3e237f26279883dc
24b7ff1eb88e431ffd6bec4f6368105d9cc9cae2
v1.0
instruct
Docs
Docs: Python310_6876_I
**Problem Statement** You are tasked with creating a Python function to manage a schedule of events that span different time zones. You need to account for the varying offsets from UTC and daylight saving adjustments. Write a function `generate_event_summary(events, timezone_str)` that: 1. Takes a list of events an...
from datetime import datetime, timedelta, timezone def convert_to_timezone(dt_str, tz_str): dt = datetime.fromisoformat(dt_str.replace("Z", "+00:00")) sign = 1 if tz_str[3] == '+' else -1 hours_offset = int(tz_str[4:6]) minutes_offset = int(tz_str[7:9]) offset = timedelta(hours=hours_offset, minute...
def test_generate_event_summary(): events = [ ("Meeting", "2023-03-15T14:00:00Z", "2023-03-15T15:30:00Z"), ("Conference", "2023-04-20T08:00:00Z", "2023-04-20T11:00:00Z"), ("Webinar", "2023-05-01T12:00:00Z", "2023-05-01T13:45:00Z") ] timezone_str = "UTC-04:00" expected = { ...
[ { "docstring": null, "function_declaration": "def convert_to_timezone(dt_str, tz_str):", "function_name": "convert_to_timezone", "parameter_list": "(dt_str, tz_str)" }, { "docstring": null, "function_declaration": "def calculate_duration(start_str, end_str):", "function_name": "calcu...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from datetime import datetime, timedelta, timezone\nimport re\n\ndef generate_event_summary(events, timezone_str):\n \"\"\"\n Generates a summary of events with t...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006876", "row_id": 6876, "seed_ids": "[219]" }
0.729898
Docs: Python310_6876
I
[ "convert_to_timezone", "calculate_duration", "generate_event_summary" ]
3
[ [ "generate_event_summary", "calculate_duration" ], [ "generate_event_summary", "convert_to_timezone" ] ]
2
[]
false
[]
false
pytest
false
[]
true
a53ce2c2653f02e6398326fd1ee79eec1da64cd5
6490ceb35516bd7a4f1c1fd7df894b442fe3c869
v1.0
instruct
Docs
Docs: Python310_6951_I
### Garbage Collection Optimization and Debugging with Python's `gc` Module #### Objective Implement a Python script that performs the following tasks using the `gc` module: 1. **Disable and Enable Garbage Collection:** - Initially, disable automatic garbage collection. - Confirm and print whether garbage colle...
import gc def custom_gc_callback(phase, info): print(f"Custom: GC {phase}") def manage_gc(): # Disable automatic garbage collection gc.disable() print(f"Garbage collection enabled: {gc.isenabled()}") # Create cyclic references deliberately cycle_list = [] cycle_list.append(cycle_list) ...
import gc from solution import manage_gc def test_disable_enable_gc(): # Ensure GC is enabled before disabling gc.enable() assert gc.isenabled() == True manage_gc() # After function execution, GC should be re-enabled assert gc.isenabled() == True def test_manual_gc_collection(): # Create c...
[ { "docstring": null, "function_declaration": "def custom_gc_callback(phase, info):", "function_name": "custom_gc_callback", "parameter_list": "(phase, info)" }, { "docstring": null, "function_declaration": "def manage_gc():", "function_name": "manage_gc", "parameter_list": "()" ...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import gc\n\ndef disable_gc():\n gc.disable()\n return gc.isenabled()\n\ndef create_cyclic_reference():\n lst = []\n lst.append(lst)\n return lst\n\ndef ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00006951", "row_id": 6951, "seed_ids": "[216]" }
0.431409
Docs: Python310_6951
I
[ "custom_gc_callback", "manage_gc" ]
2
[ [ "manage_gc", "custom_gc_callback" ] ]
1
[]
false
[]
false
pytest
true
[]
true
38c06e0cd16f04b4cc4c0c4ac1bdf6af6ef57125
cd26ee264f51e203646790d52420d119dd0616fa