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 | Filter | Filter_42278_I | Create a Python function that encodes a given string using a Base64 algorithm and then reverses the resulting encoded string. Decode the reversed string back to its original form and return both the reversed encoded string and the decoded original string. Additionally, implement the function to accept an optional param... | import base64
def caesar_cipher(text, shift):
result = []
for char in text:
if char.isalpha():
shift_amount = 65 if char.isupper() else 97
result.append(chr((ord(char) + shift - shift_amount) % 26 + shift_amount))
else:
result.append(char)
return ''.join(... | from solution import encode_and_reverse
def test_encode_and_reverse_no_shift():
reversed_encoded, decoded = encode_and_reverse("Hello, World!")
assert decoded == "Hello, World!"
def test_encode_and_reverse_with_shift():
base_string = "Hello, World!"
reversed_encoded, decoded = encode_and_reverse(base_... | [
{
"docstring": null,
"function_declaration": "def caesar_cipher(text, shift):",
"function_name": "caesar_cipher",
"parameter_list": "(text, shift)"
},
{
"docstring": null,
"function_declaration": "def encode_and_reverse(base_string, shift=None):",
"function_name": "encode_and_reverse... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import base64\n\ndef caesar_cipher(text, shift):\n \"\"\"\n Encode text using Caesar cipher with a given shift.\n \"\"\"\n encrypted_text = []\n for char in text:\n if ch... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00042278",
"row_id": 42278,
"seed_ids": "['Qwen2-72B-Instruct_91770']"
} | 0.690466 | Filter_42278 | I | [
"caesar_cipher",
"encode_and_reverse"
] | 2 | [
[
"encode_and_reverse",
"caesar_cipher"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4139714e67758fbd596ea7c7c4e0eaf9bad7639b | 3e599d60cbb1a7bed9c1711c8fc2ebd31b562a2c | |||
v1.0 | instruct | Filter | Filter_42303_I | Design a script for performing text-based enary (base 9) arithmetic operations which supports addition, subtraction, multiplication and division. The script should have function to convert base 9 number to base 10 number and vice-versa. Implement error checking for input correctness. | def base9_to_base10(number: str) -> int:
"""
Convert a base 9 number (as a string) to base 10 integer.
"""
try:
return int(number, 9)
except ValueError:
raise ValueError("Invalid base 9 number")
def base10_to_base9(number: int) -> str:
"""
Convert a base 10 number (as an int... | import pytest
from solution import base9_to_base10, base10_to_base9, add_base9, subtract_base9, multiply_base9, divide_base9
def test_base9_to_base10():
assert base9_to_base10('10') == 9
assert base9_to_base10('8') == 8
assert base9_to_base10('100') == 81
assert base9_to_base10('0') == 0
# Test inv... | [
{
"docstring": "Convert a base 9 number (as a string) to base 10 integer.",
"function_declaration": "def base9_to_base10(number):",
"function_name": "base9_to_base10",
"parameter_list": "(number)"
},
{
"docstring": "Convert a base 10 number (as an integer) to a base 9 string.",
"function... | [
0,
0,
0,
0,
1,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def enary_to_decimal(enary_str):\n \"\"\"\n Converts a base 9 (enary) number to a base 10 (decimal) number.\n \"\"\"\n try:\n return int(enary_str, 9)\n except ValueError... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00042303",
"row_id": 42303,
"seed_ids": "['Qwen2-72B-Instruct_91828']"
} | 0.532592 | Filter_42303 | I | [
"base9_to_base10",
"base10_to_base9",
"add_base9",
"subtract_base9",
"multiply_base9",
"divide_base9"
] | 6 | [
[
"add_base9",
"base10_to_base9"
],
[
"add_base9",
"base9_to_base10"
],
[
"divide_base9",
"base10_to_base9"
],
[
"divide_base9",
"base9_to_base10"
],
[
"multiply_base9",
"base10_to_base9"
],
[
"multiply_base9",
"base9_to_base10"
],
[
"subtr... | 8 | [] | false | [] | false | pytest | true | [] | true | d654cbd431a2f41b1326919d4a894a3715814316 | aca9f0f74c85a1a6c2bd7b8cc97098660b6772ff | |||
v1.0 | instruct | Filter | Filter_42311_I | I want you to create a Python function that modifies complete passages of text. This function should focus on replacing a specified character within a string, but instead of a simple replacement, it should replace the target character with a predefined sequence of characters based on its binary representation. Addition... | def binary_representation(char):
return format(ord(char), '08b')
def encrypt(sequence):
encrypted_sequence = ""
for char in sequence:
if char.isalpha():
encrypted_sequence += chr((ord(char) + 3 - 97) % 26 + 97) if char.islower() else chr((ord(char) + 3 - 65) % 26 + 65)
elif char... | from solution import replace_and_encrypt
def test_replace_and_encrypt_simple():
text = "hello world"
target_char = "o"
replacement_sequence = "ab"
result = replace_and_encrypt(text, target_char, replacement_sequence)
expected = "hell" + encrypt('0110000101100010') + " w" + encrypt('0110000101100010... | [
{
"docstring": null,
"function_declaration": "def binary_representation(char):",
"function_name": "binary_representation",
"parameter_list": "(char)"
},
{
"docstring": null,
"function_declaration": "def encrypt(sequence):",
"function_name": "encrypt",
"parameter_list": "(sequence... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def char_to_binary(char):\n \"\"\"\n Converts a character to its binary representation.\n \"\"\"\n return format(ord(char), '08b')\n\ndef caesar_cipher(text, shift):\n \"\"\"\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00042311",
"row_id": 42311,
"seed_ids": "['Qwen2-72B-Instruct_91847']"
} | 0.6709 | Filter_42311 | I | [
"binary_representation",
"encrypt",
"replace_and_encrypt"
] | 3 | [
[
"replace_and_encrypt",
"binary_representation"
],
[
"replace_and_encrypt",
"encrypt"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8695c3a6ee79165fa86992fc15c8d7df464673ce | eec728d69f11a3417fcae4be60918fc14afdc98a | |||
v1.0 | instruct | Filter | Filter_42374_I | Develop a Python script that can perform the task of converting temperatures from Celsius to Fahrenheit and vice versa. Moreover, the program should include the functionality of converting temperature in Kelvin to Celsius and Fahrenheit. Additionally, the program should incorporate a feature that allows the user to inp... | def celsius_to_fahrenheit(c):
"""
Convert Celsius to Fahrenheit.
"""
return (c * 9/5) + 32
def fahrenheit_to_celsius(f):
"""
Convert Fahrenheit to Celsius.
"""
return (f - 32) * 5/9
def kelvin_to_celsius(k):
"""
Convert Kelvin to Celsius.
"""
return k - 273.15
def cels... | from solution import celsius_to_fahrenheit, fahrenheit_to_celsius, kelvin_to_celsius, celsius_to_kelvin, kelvin_to_fahrenheit, fahrenheit_to_kelvin, convert_temperature
def test_celsius_to_fahrenheit():
assert celsius_to_fahrenheit(0) == 32
assert celsius_to_fahrenheit(100) == 212
assert celsius_to_fahrenh... | [
{
"docstring": "Convert Celsius to Fahrenheit.",
"function_declaration": "def celsius_to_fahrenheit(c):",
"function_name": "celsius_to_fahrenheit",
"parameter_list": "(c)"
},
{
"docstring": "Convert Fahrenheit to Celsius.",
"function_declaration": "def fahrenheit_to_celsius(f):",
"fu... | [
0,
0,
0,
1,
0,
0,
1,
1,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def celsius_to_fahrenheit(celsius):\n \"\"\"\n Convert Celsius to Fahrenheit.\n \"\"\"\n return (celsius * 9/5) + 32\n\ndef fahrenheit_to_celsius(fahrenheit):\n \"\"\"\n Conv... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00042374",
"row_id": 42374,
"seed_ids": "['Qwen2-72B-Instruct_91972']"
} | 0.454059 | Filter_42374 | I | [
"celsius_to_fahrenheit",
"fahrenheit_to_celsius",
"kelvin_to_celsius",
"celsius_to_kelvin",
"kelvin_to_fahrenheit",
"fahrenheit_to_kelvin",
"convert_temperature"
] | 7 | [
[
"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 | true | [] | true | 9ee53fda3cb3cf4aace856f220a264811aa65cf9 | 703958a526121ac509b34aa7d3fde3fa1c78e43d | |||
v1.0 | instruct | Filter | Filter_42379_I | Create a decorator in Python that allows me to specify a default value for a function argument. | def default_value_decorator(arg_name, default_value):
"""
A decorator that allows specifying a default value for a
function argument if it is not provided.
:param arg_name: The name of the argument.
:param default_value: The default value to be used if the argument is not provided.
"""
... | from solution import default_value_decorator, example_function
def test_example_function_with_value():
assert example_function(x=5) == 5
def test_example_function_without_value():
assert example_function() == 10
def test_custom_function_with_decorator():
@default_value_decorator('y', 20)
def custom_f... | [
{
"docstring": "A decorator that allows specifying a default value for a \nfunction argument if it is not provided.\n\n:param arg_name: The name of the argument.\n:param default_value: The default value to be used if the argument is not provided.",
"function_declaration": "def default_value_decorator(arg_na... | [
0,
0,
0,
0,
1,
1,
1,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import wraps\n\ndef default_arg_value(arg_name, default_value):\n def decorator(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n if arg_name n... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00042379",
"row_id": 42379,
"seed_ids": "['Qwen2-72B-Instruct_91983']"
} | 0.470071 | Filter_42379 | I | [
"default_value_decorator",
"example_function"
] | 2 | [
[
"example_function",
"default_value_decorator"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ab7da549dce0c043af1b2c032acb6430da5cf619 | db506086707f65abd550b3dfe4d325e284be85f8 | |||
v1.0 | instruct | Filter | Filter_42439_I | Receive a port number and check if a server is running on that port using Python. If a server is running, terminate it and display an error message. Additionally, implement a feature that allows the user to specify a range of ports to check, and display the total number of servers found and terminated within that range... | import socket
import os
def is_port_in_use(port):
"""
Checks if the port is currently in use.
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(('localhost', port)) == 0
def terminate_process_on_port(port):
"""
Terminates the process running on the gi... | from solution import is_port_in_use, terminate_process_on_port, check_port_range_and_terminate
def test_is_port_in_use():
assert not is_port_in_use(1) # Assuming port 1 is not in use
def test_terminate_process_on_port():
# Mocking scenario where a port is in use
class MockSocket:
@staticmethod
... | [
{
"docstring": "Checks if the port is currently in use.",
"function_declaration": "def is_port_in_use(port):",
"function_name": "is_port_in_use",
"parameter_list": "(port)"
},
{
"docstring": "Terminates the process running on the given port and returns an error message.",
"function_decla... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import socket\nimport os\n\ndef check_and_terminate_port(port):\n \"\"\"\n Check if a server is running on the given port.\n If running, terminate it and display an error message.\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00042439",
"row_id": 42439,
"seed_ids": "['Qwen2-72B-Instruct_92088']"
} | 0.640203 | Filter_42439 | I | [
"is_port_in_use",
"terminate_process_on_port",
"check_port_range_and_terminate"
] | 3 | [
[
"check_port_range_and_terminate",
"is_port_in_use"
],
[
"check_port_range_and_terminate",
"terminate_process_on_port"
],
[
"terminate_process_on_port",
"is_port_in_use"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 440b64cc271f276c373c2f5c8e2953c337f7ee37 | a1964753d8bce73bb0d5e1b2281c4e07517d6650 | |||
v1.0 | instruct | Filter | Filter_42460_I | Here's another challenge for Tic-Tac- Toe. This time, write the program in a functional programming style, using recursive functions to determine the possible next moves and outcomes of the game. The game board will be represented using the same 3x3 matrix as before, with 1s for the player's moves, -1s for the computer... | from typing import List, Tuple
def get_winner(board: List[List[int]]) -> int:
lines = board + list(map(list, zip(*board))) + \
[[board[i][i] for i in range(3)]] + \
[[board[i][2-i] for i in range(3)]]
if [1, 1, 1] in lines:
return 1
elif [-1, -1, -1] in lines:
return... | from solution import get_winner, is_full, possible_moves, make_move, best_move
def test_get_winner():
assert get_winner([[1, 1, 1], [0, -1, 0], [-1, 0, 0]]) == 1
assert get_winner([[1, 0, -1], [1, -1, 0], [1, 0, 0]]) == 1
assert get_winner([[-1, 1, 0], [1, -1, 0], [0, 1, -1]]) == -1
assert get_winner([... | [
{
"docstring": null,
"function_declaration": "def get_winner(board):",
"function_name": "get_winner",
"parameter_list": "(board)"
},
{
"docstring": null,
"function_declaration": "def is_full(board):",
"function_name": "is_full",
"parameter_list": "(board)"
},
{
"docstring... | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import partial\n\ndef has_won(board, player):\n \"\"\"\n Check if the given player has won the game on the current board.\n \"\"\"\n win_conditions = [\n [boa... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00042460",
"row_id": 42460,
"seed_ids": "['Qwen2-72B-Instruct_92126']"
} | 0.543216 | Filter_42460 | I | [
"get_winner",
"is_full",
"possible_moves",
"make_move",
"evaluate",
"minimax",
"best_move"
] | 7 | [
[
"best_move",
"make_move"
],
[
"best_move",
"minimax"
],
[
"best_move",
"possible_moves"
],
[
"evaluate",
"get_winner"
],
[
"evaluate",
"is_full"
],
[
"minimax",
"evaluate"
],
[
"minimax",
"make_move"
],
[
"minimax",
"possi... | 8 | [] | false | [] | false | pytest | true | [] | true | 6400570d2513fb2a3e7ba183fd51d34270865ac9 | 7be45204db8e3779131773b1cc1a0b600562d83b | |||
v1.0 | instruct | Filter | Filter_42468_I | Create a program that generates an array of prime numbers from 0 to 100 in descending order. Implement the solution using a recursive function and ensure that the prime numbers are sorted within the array. Additionally, optimize the program to have a time complexity of O(n√m), where n is the size of the array and m is ... | def sieve_of_eratosthenes(max_num):
"""
Generates an array of prime numbers up to max_num using the Sieve of Eratosthenes.
"""
is_prime = [True] * (max_num + 1)
p = 2
while p * p <= max_num:
if is_prime[p]:
for i in range(p * p, max_num + 1, p):
is_prime[i] = ... | from solution import prime_numbers_descending
def test_primes_up_to_10():
assert prime_numbers_descending(10) == [7, 5, 3, 2]
def test_primes_up_to_50():
assert prime_numbers_descending(50) == [47, 43, 41, 37, 31, 29, 23, 19, 17, 13, 11, 7, 5, 3, 2]
def test_primes_up_to_100():
assert prime_numbers_desce... | [
{
"docstring": "Generates an array of prime numbers up to max_num using the Sieve of Eratosthenes.",
"function_declaration": "def sieve_of_eratosthenes(max_num):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(max_num)"
},
{
"docstring": "Generates an array of prime numbers u... | [
0,
0,
0,
1,
1,
1,
0,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n, i=2):\n \"\"\"\n Recursively checks if a number n is a prime.\n \"\"\"\n if n <= 2:\n return n == 2\n if n % i == 0:\n return False\n if i * i >... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00042468",
"row_id": 42468,
"seed_ids": "['Qwen2-72B-Instruct_92137']"
} | 0.620396 | Filter_42468 | I | [
"sieve_of_eratosthenes",
"prime_numbers_descending"
] | 2 | [
[
"prime_numbers_descending",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 10912bd331dfe7a23bf749af12592962c8153336 | 1f68e5539fc0193b9ba379eb4a031774416cbf59 | |||
v1.0 | instruct | Filter | Filter_42618_I | In addition to stacking the papers in a single, implement efficient functions to compute Fibonacci-like sequences, factorial, calculate large number multiplication, and find the larger number in a prime list (bigger than 1000), all using recursion. Also implement "Tail recursion" for efficient memory usage. | # Fibonacci-like sequence
def fibonacci_like(a, b, n):
"""
Returns the n-th number in a Fibonacci-like sequence where the first
two numbers are a and b.
"""
if n == 0:
return a
elif n == 1:
return b
else:
return fibonacci_like(a, b, n-1) + fibonacci_like(a, b, n-2)
#... | import pytest
from solution import fibonacci_like, factorial, large_multiply, largest_prime_bigger_than_1000
def test_fibonacci_like():
assert fibonacci_like(1, 1, 0) == 1
assert fibonacci_like(1, 1, 1) == 1
assert fibonacci_like(1, 1, 2) == 2
assert fibonacci_like(1, 1, 3) == 3
assert fibonacci_li... | [
{
"docstring": "Returns the n-th number in a Fibonacci-like sequence where the first\ntwo numbers are a and b.",
"function_declaration": "def fibonacci_like(a, b, n):",
"function_name": "fibonacci_like",
"parameter_list": "(a, b, n)"
},
{
"docstring": "Returns the factorial of n using tail r... | [
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Function to compute the n-th term in a Fibonacci-like sequence with given starting numbers a and b\ndef fibonacci_like(n, a=0, b=1):\n if n == 0:\n return a\n elif n == 1:\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00042618",
"row_id": 42618,
"seed_ids": "['Qwen2-72B-Instruct_92397']"
} | 0.369209 | Filter_42618 | I | [
"fibonacci_like",
"factorial",
"large_multiply",
"is_prime",
"largest_prime_bigger_than_1000"
] | 5 | [
[
"largest_prime_bigger_than_1000",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e380681ac6342becdd3ae6f787583d9bbeb5be96 | 7e113000f72553e2e7ed6f8db6a5b9cf620d5579 | |||
v1.0 | instruct | Filter | Filter_42648_I | Write a Python function that takes in two arguments 'arr1' and 'arr2', which are lists of positive integers. The function should calculate the sum of elements in 'arr1' that have the same index as elements in 'arr2' that are prime numbers. The length of 'arr1' and 'arr2' will be between 1 and 1000, inclusive. The eleme... | def is_prime(n):
"""
Helper function to determine if a number is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while (i * i) <= n:
if n % i == 0 or n % (i + 2) == 0:
return Fa... | from solution import sum_prime_indexed_elements
def test_example_case():
arr1 = [10, 20, 30, 40, 50]
arr2 = [2, 4, 5, 6, 7]
assert sum_prime_indexed_elements(arr1, arr2) == 90
def test_all_primes():
arr1 = [1, 2, 3, 4, 5]
arr2 = [2, 3, 5, 7, 11]
assert sum_prime_indexed_elements(arr1, arr2) ==... | [
{
"docstring": "Helper function to determine if a number is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns the sum of elements in 'arr1' that have the same index as elements in 'arr2' that are prim... | [
0,
0,
0,
1,
1,
1,
1,
1,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Utility function to check if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 =... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00042648",
"row_id": 42648,
"seed_ids": "['Qwen2-72B-Instruct_92453']"
} | 0.602363 | Filter_42648 | I | [
"is_prime",
"sum_prime_indexed_elements"
] | 2 | [
[
"sum_prime_indexed_elements",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 09d070a7c2dfd2f7a39bedf22c64ef0b9d22aab7 | 08acad0b17fa4c2e57c118d7c18c9feabaea748e | |||
v1.0 | instruct | Filter | Filter_42745_I | Given the string "abc123", create a Python function that finds the number of unique permutations of the string where no two adjacent characters are consecutive digits or letters in the alphabet. For example, "abc" is not a valid permutation because "b" and "c" are consecutive letters in the alphabet. However, "acb" is ... | from itertools import permutations
def is_valid_permutation(s):
"""
Check if the permutation is valid.
No two adjacent characters should be consecutive digits or consecutive letters.
"""
for i in range(len(s) - 1):
if (s[i].isdigit() and s[i + 1].isdigit() and abs(int(s[i]) - int(s[i + 1]))... | from solution import count_valid_permutations
def test_count_valid_permutations_abc123():
assert count_valid_permutations("abc123") > 0 # Just a general check to ensure there are some valid permutations
def test_count_valid_permutations_ab():
assert count_valid_permutations("ab") == 0 # 'ab' and 'ba' are not ... | [
{
"docstring": "Check if the permutation is valid.\nNo two adjacent characters should be consecutive digits or consecutive letters.",
"function_declaration": "def is_valid_permutation(s):",
"function_name": "is_valid_permutation",
"parameter_list": "(s)"
},
{
"docstring": "Returns the number... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import permutations\n\ndef is_valid_permutation(p):\n \"\"\"\n Checks if the permutation is valid where no two adjacent characters are consecutive\n digits or letters i... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00042745",
"row_id": 42745,
"seed_ids": "['Qwen2-72B-Instruct_92626']"
} | 0.707417 | Filter_42745 | I | [
"is_valid_permutation",
"count_valid_permutations"
] | 2 | [
[
"count_valid_permutations",
"is_valid_permutation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 48272acc507dc963c9a6a241d3d01ff845bc4087 | c0510d74fadc3bf0e3933f6fb7e17a40d73097af | |||
v1.0 | instruct | Filter | Filter_42777_I | Using PyTorch, write a function that takes a list of image file paths, and returns predictions for each image. | import torch
import torchvision.transforms as transforms
from PIL import Image
def load_model():
"""
Loads a pre-trained model (here we use ResNet18) for image classification.
"""
model = torch.hub.load('pytorch/vision:v0.9.0', 'resnet18', pretrained=True)
model.eval()
return model
def preproc... | from solution import predict_images, load_model, preprocess_image, predict_image
import pytest
import os
# Mocking the image paths for testing since we don't have actual image files
def test_preprocess_image():
# Note: Replace 'path/to/image.jpg' with an actual image path during real-world testing
try:
... | [] | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torchvision import transforms, models\nfrom PIL import Image\n\ndef get_image_predictions(image_paths):\n \"\"\"\n Takes a list of image file paths, and returns predic... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00042777",
"row_id": 42777,
"seed_ids": "['Qwen2-72B-Instruct_92680']"
} | 0.487916 | Filter_42777 | I | [
"load_model",
"preprocess_image",
"predict_image",
"predict_images"
] | 4 | [
[
"predict_image",
"preprocess_image"
],
[
"predict_images",
"load_model"
],
[
"predict_images",
"predict_image"
]
] | 3 | [] | false | [] | false | pytest | true | [
"PIL",
"torch",
"torchvision"
] | false | 346bc2b64a6b77817dc0c762c7a098926af19b65 | 37bb1ccf7b56da3a38a5d97f746b93ed28db808b | |||
v1.0 | instruct | Filter | Filter_42860_I | I want to create a simple web application using Flask that allows users to upload images and then displays the images they've uploaded. How can I achieve this? | from flask import Flask, request, redirect, url_for, render_template, send_from_directory
import os
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'}
if not os.path.exists(app.config['UPLOAD_FOLDER']):
os.makedirs(app.config['UPLOAD_FOL... | import os
import tempfile
import pytest
from solution import app
@pytest.fixture
def client():
db_fd, app.config['DATABASE'] = tempfile.mkstemp()
app.config['TESTING'] = True
client = app.test_client()
yield client
os.close(db_fd)
os.unlink(app.config['DATABASE'])
def test_upload_file(client):... | [
{
"docstring": null,
"function_declaration": "def allowed_file(filename):",
"function_name": "allowed_file",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def upload_file():",
"function_name": "upload_file",
"parameter_list": "()"
},
{
"d... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, redirect, url_for, render_template, send_from_directory\nimport os\n\napp = Flask(__name__)\nUPLOAD_FOLDER = 'uploads'\napp.config['UPLOAD_FOLDER'] = UPLOAD_F... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00042860",
"row_id": 42860,
"seed_ids": "['Qwen2.5-72B-Instruct_92803']"
} | 0.426787 | Filter_42860 | I | [
"allowed_file",
"upload_file",
"display_uploaded_images",
"uploaded_file"
] | 4 | [
[
"upload_file",
"allowed_file"
],
[
"upload_file",
"display_uploaded_images"
]
] | 2 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 72a9703725d00bccb2b9f980041a41f776c6ce0f | 3a7ebc55601c92426349cde6c32135f6252fd859 | |||
v1.0 | instruct | Filter | Filter_42938_I | Is it possible to send an email with a scheduled delivery time using Python? If yes, how can I do it? | import smtplib
import time
import threading
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(subject, body, to_email, from_email, from_email_password, smtp_server, smtp_port):
"""
Sends an email.
"""
msg = MIMEMultipart()
msg['From'] = from_email
... | import pytest
from solution import send_email, schedule_email
def mock_send_email(subject, body, to_email, from_email, from_email_password, smtp_server, smtp_port):
"""
Mock function to replace the actual send_email function for testing.
"""
return {
"subject": subject,
"body": body,
... | [
{
"docstring": "Sends an email.",
"function_declaration": "def send_email(subject, body, to_email, from_email, from_email_password, smtp_server, smtp_port):",
"function_name": "send_email",
"parameter_list": "(subject, body, to_email, from_email, from_email_password, smtp_server, smtp_port)"
},
... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import smtplib\nimport time\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\ndef send_scheduled_email(smtp_server, port, login, password, from_addr, to_... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00042938",
"row_id": 42938,
"seed_ids": "['Qwen2.5-72B-Instruct_92927']"
} | 0.493325 | Filter_42938 | I | [
"send_email",
"schedule_email"
] | 2 | [
[
"schedule_email",
"send_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d08281874ce308a7993485df41d44b3d66806823 | 4ae988724ba5d7dd3c92675cee99aa450abe76ae | |||
v1.0 | instruct | Filter | Filter_42987_I | I am working on a project that involves processing a large dataset in Python. I need to implement a pipeline that can handle data streaming and batch processing efficiently. What are some best practices for designing such a system in Python, and can you recommend any specific libraries or tools that might help? | def data_pipeline(data_stream, batch_size=1000):
"""
Process a data stream in batches efficiently.
Parameters:
data_stream (iterable): The input data stream that yields data records.
batch_size (int): The size of batch to process at each iteration.
Returns:
List of batches processe... | from solution import data_pipeline, process_batch, process_data
def test_process_data():
assert process_data(1) == 1
assert process_data("test") == "test"
def test_process_batch():
assert process_batch([1, 2, 3]) == [1, 2, 3]
assert process_batch(["a", "b", "c"]) == ["a", "b", "c"]
def test_data_pipe... | [
{
"docstring": "Process a data stream in batches efficiently.\n\nParameters:\ndata_stream (iterable): The input data stream that yields data records.\nbatch_size (int): The size of batch to process at each iteration.\n\nReturns:\nList of batches processed",
"function_declaration": "def data_pipeline(data_st... | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def streaming_pipeline(data_stream, process_batch_function, batch_size=1000):\n \"\"\"\n Processes data from a stream in batches.\n\n :param data_stream: A generator that yields data ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00042987",
"row_id": 42987,
"seed_ids": "['Qwen2.5-72B-Instruct_92998']"
} | 0.381717 | Filter_42987 | I | [
"data_pipeline",
"process_batch",
"process_data"
] | 3 | [
[
"data_pipeline",
"process_batch"
],
[
"process_batch",
"process_data"
]
] | 2 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | c18897006b421ab78c8f513e0f3466be5f644ee1 | 5e08ef6ed860a81e56b2a9b7141b40f7affc88f1 | |||
v1.0 | instruct | Filter | Filter_42994_I | I need to create a simple web application that allows users to upload an image and then displays the image on the page. I want to use Python and Flask for the backend. How can I achieve this? Can you provide a basic example? | from flask import Flask, request, redirect, url_for, send_from_directory, render_template_string
import os
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'}
if not os.path.exists('uploads'):
os.makedirs('uploads')
def allowed_file(filen... | import os
import pytest
from io import BytesIO
from solution import app
@pytest.fixture
def client():
app.config['TESTING'] = True
with app.test_client() as client:
yield client
def test_upload_form(client):
rv = client.get('/')
assert b'Upload an Image' in rv.data
def test_upload_file_no_fil... | [
{
"docstring": null,
"function_declaration": "def allowed_file(filename):",
"function_name": "allowed_file",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def upload_form():",
"function_name": "upload_form",
"parameter_list": "()"
},
{
"d... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, redirect, url_for, send_from_directory, render_template_string\nimport os\n\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = 'uploads'\napp.config['MAX_C... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00042994",
"row_id": 42994,
"seed_ids": "['Qwen2.5-72B-Instruct_93008']"
} | 0.4017 | Filter_42994 | I | [
"allowed_file",
"upload_form",
"upload_file",
"uploaded_file"
] | 4 | [
[
"upload_file",
"allowed_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | af2fa9c390559b42f5c23965489e7d1e9af30671 | dfcf41ae37234a0aeaabad32f222ef0be46e94e0 | |||
v1.0 | instruct | Filter | Filter_43073_I | I want to create a small web application that allows users to submit text and get a summary of the text in return. How can I achieve this using Python and Flask? Can you provide a basic example? | from flask import Flask, request, render_template_string
app = Flask(__name__)
def summarize_text(text):
"""
A simple summarization function that returns the first and last sentence of the text.
"""
sentences = text.split('. ')
if len(sentences) < 2:
return text # Return as is if there is... | import pytest
from solution import summarize_text
def test_summarize_text_with_multiple_sentences():
text = "This is the first sentence. Here is the second sentence. Finally, here is the last sentence."
expected_summary = "This is the first sentence. Finally, here is the last sentence."
assert summarize_te... | [
{
"docstring": "A simple summarization function that returns the first and last sentence of the text.",
"function_declaration": "def summarize_text(text):",
"function_name": "summarize_text",
"parameter_list": "(text)"
},
{
"docstring": null,
"function_declaration": "def home():",
"f... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, jsonify\nfrom gensim.summarization import summarize\n\napp = Flask(__name__)\n\n@app.route('/summarize', methods=['POST'])\ndef summarize_text():\n data = ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00043073",
"row_id": 43073,
"seed_ids": "['Qwen2.5-72B-Instruct_93145']"
} | 0.493579 | Filter_43073 | I | [
"summarize_text",
"home"
] | 2 | [
[
"home",
"summarize_text"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | a9c088a4fbfcf9507577ab3ff479c86e2e5904ad | 3e22615cad0e5f04ac0e93a523255f32434b605f | |||
v1.0 | instruct | Filter | Filter_43085_I | How can I implement a simple linear regression model using PyTorch? I have a basic understanding of Python and some familiarity with machine learning concepts but am new to PyTorch. Could you guide me through the process step-by-step, including setting up the environment and training the model? | import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
class LinearRegressionModel(nn.Module):
def __init__(self, input_dim, output_dim):
super(LinearRegressionModel, self).__init__()
self.linear = nn.Linear(input_dim, output_dim)
def forward(sel... | import numpy as np
from solution import LinearRegressionModel, train_model, simple_linear_regression, predict
def test_linear_regression_training():
# Define simple linear relationship (y = 2x + 1)
x_train = np.array([[1], [2], [3], [4]], dtype=np.float32)
y_train = np.array([[3], [5], [7], [9]], dtype=np.... | [] | [
0,
0,
0,
1,
1,
0,
0,
1,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\n# Step 1: Create synthetic data\ndef create_synthetic_data(num_samples=100):\n # y = 2x + 3 with some noise\n X = torc... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00043085",
"row_id": 43085,
"seed_ids": "['Qwen2.5-72B-Instruct_93163']"
} | 0.510708 | Filter_43085 | I | [
"train_model",
"simple_linear_regression",
"predict"
] | 3 | [
[
"simple_linear_regression",
"train_model"
]
] | 1 | [] | false | [
"LinearRegressionModel"
] | true | pytest | true | [
"numpy",
"torch"
] | false | fe718a0a7093a08668ffdf995ca0f7930fd32300 | f03e8ccc6095dfb4b804c5353516967168c4a6f6 | |||
v1.0 | instruct | Filter | Filter_43163_I | How can I create a Python script that monitors a directory for changes and logs these changes into a file? I want to track any new files added, files deleted, or files modified within the directory. | import os
import time
import logging
import hashlib
# Configuring logging
logging.basicConfig(filename='file_changes.log', level=logging.INFO,
format='%(asctime)s - %(message)s')
def calculate_file_hash(filepath):
"""
Calculates the SHA1 hash of the file content.
"""
sha1 = hashli... | import os
import time
import logging
from pathlib import Path
from solution import monitor_directory
def test_monitor_directory(tmp_path, caplog):
"""
This test monitors a temporary directory for changes and verifies the logs.
"""
test_dir = tmp_path / "test_dir"
test_dir.mkdir()
# Set the log... | [
{
"docstring": "Calculates the SHA1 hash of the file content.",
"function_declaration": "def calculate_file_hash(filepath):",
"function_name": "calculate_file_hash",
"parameter_list": "(filepath)"
},
{
"docstring": "Monitors the specified directory for changes and logs any new files added,\n... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import time\nimport os\nimport logging\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\n\n# Setup logging configuration\nlogging.basicConfig(filena... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00043163",
"row_id": 43163,
"seed_ids": "['Qwen2.5-72B-Instruct_93279']"
} | 0.591292 | Filter_43163 | I | [
"calculate_file_hash",
"monitor_directory"
] | 2 | [
[
"monitor_directory",
"calculate_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 63b15878e885e92673822218feee27bfdc20a156 | bb120c00ed7277d1b5e20d60e47eaf51940eefe8 | |||
v1.0 | instruct | Filter | Filter_43180_I | How can I create a Python script that automatically sends an email when a specific condition is met, such as a stock price reaching a certain threshold? | import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email(subject, body, to_email, from_email, from_password):
"""
Sends an email with the given subject and body to the specified recipient.
"""
# Set up the MIME
message = MIMEMultipart()
m... | from solution import check_stock_and_notify
import smtplib
from unittest.mock import patch, MagicMock
def test_check_stock_and_notify_below_threshold():
result = check_stock_and_notify(150, 200, "to@example.com", "from@example.com", "password")
assert result == False
def test_check_stock_and_notify_above_thre... | [
{
"docstring": "Sends an email with the given subject and body to the specified recipient.",
"function_declaration": "def send_email(subject, body, to_email, from_email, from_password):",
"function_name": "send_email",
"parameter_list": "(subject, body, to_email, from_email, from_password)"
},
{... | [
0,
0,
0,
1,
0,
0,
0,
1,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import yfinance as yf\nimport smtplib\nfrom email.mime.text import MIMEText\n\ndef get_stock_price(ticker):\n \"\"\"\n Fetches the latest stock price for the given ticker.\n \"\"\"\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00043180",
"row_id": 43180,
"seed_ids": "['Qwen2.5-72B-Instruct_93308']"
} | 0.442703 | Filter_43180 | I | [
"send_email",
"check_stock_and_notify"
] | 2 | [
[
"check_stock_and_notify",
"send_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7a8eb8d785d5c6038f28d77e99a3689f9d009cad | ca3e3d3e14ef8dab0fb1dbb3cc10906b595029b9 | |||
v1.0 | instruct | Filter | Filter_43205_I | Can you help me with a Python script to generate a report of the most frequently used words in a text file? I want to exclude common English stop words and only consider words longer than three characters. The report should list the top 10 words with their frequencies. | from collections import Counter
import re
def load_stopwords(file_path):
with open(file_path, 'r') as f:
return set(f.read().split())
def most_frequent_words(file_path, stopwords_path, top_n=10):
with open(file_path, 'r') as f:
text = f.read()
stopwords = load_stopwords(stopwords_path... | from solution import most_frequent_words, load_stopwords
def test_load_stopwords(tmp_path):
stopwords_file = tmp_path / "stopwords.txt"
stopwords_file.write_text("a\nan\nthe\nand")
stopwords = load_stopwords(stopwords_file)
assert stopwords == {"a", "an", "the", "and"}
def test_most_frequent_words(tmp... | [
{
"docstring": null,
"function_declaration": "def load_stopwords(file_path):",
"function_name": "load_stopwords",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def most_frequent_words(file_path, stopwords_path, top_n=10):",
"function_name": "most_fr... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import Counter\nimport re\n\ndef read_file(file_path):\n \"\"\"\n Reads the entire content of the given text file.\n \"\"\"\n with open(file_path, 'r', encoding='u... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00043205",
"row_id": 43205,
"seed_ids": "['Qwen2.5-72B-Instruct_93347']"
} | 0.695781 | Filter_43205 | I | [
"load_stopwords",
"most_frequent_words"
] | 2 | [
[
"most_frequent_words",
"load_stopwords"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 033c934dc05f1c751c8bca206edb61ac6a607025 | b98bdbda0f0a432729b23f13beee7dc3f7a0529c | |||
v1.0 | instruct | Filter | Filter_43306_I | I need to create a simple web application that allows users to upload images and then apply various filters to them, such as grayscale, sepia, and blur. I want to use Python for the backend and Flask for the web framework. Can you guide me through the process of setting up the application, including how to handle image... | from flask import Flask, request, redirect, url_for, send_from_directory, render_template
from werkzeug.utils import secure_filename
from PIL import Image, ImageFilter
import os
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
if not os.path.exists(app.... | import os
import pytest
from io import BytesIO
from PIL import Image
from solution import app, allowed_file, apply_filter
@pytest.fixture
def client():
app.config['TESTING'] = True
with app.test_client() as client:
yield client
def test_allowed_file():
assert allowed_file("test.jpg") == True
a... | [
{
"docstring": null,
"function_declaration": "def allowed_file(filename):",
"function_name": "allowed_file",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def apply_filter(image_path, filter_name):",
"function_name": "apply_filter",
"parameter_li... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, redirect, url_for, send_from_directory, render_template\nimport os\nfrom PIL import Image, ImageFilter, ImageOps\n\napp = Flask(__name__)\napp.config['UPLOAD_... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00043306",
"row_id": 43306,
"seed_ids": "['Qwen2.5-72B-Instruct_93516']"
} | 0.351676 | Filter_43306 | I | [
"allowed_file",
"apply_filter",
"index",
"upload_file"
] | 4 | [
[
"upload_file",
"allowed_file"
],
[
"upload_file",
"apply_filter"
]
] | 2 | [] | false | [] | false | pytest | true | [
"PIL",
"flask",
"werkzeug"
] | false | 343d864243e1bd14f2f6f71fa1d903dd1ebe9862 | a587dc8c11f5a70a46bc7e5f195498fe574d5596 | |||
v1.0 | instruct | Filter | Filter_43318_I | I want to create a small web application that allows users to upload images and then apply various filters to them using Python. How can I get started with this project? What are the key components I need to consider? | from flask import Flask, request, jsonify, send_file
from PIL import Image, ImageFilter
import io
app = Flask(__name__)
def apply_filter(image, filter_type):
"""
This function applies a specified filter to the input image.
"""
if filter_type == 'BLUR':
return image.filter(ImageFilter.BLUR)
... | import pytest
from PIL import Image
import io
import os
from solution import app, apply_filter
@pytest.fixture
def client():
app.config['TESTING'] = True
with app.test_client() as client:
yield client
def test_apply_filter():
image = Image.new('RGB', (10, 10), color = 'white')
filtered_image =... | [
{
"docstring": "This function applies a specified filter to the input image.",
"function_declaration": "def apply_filter(image, filter_type):",
"function_name": "apply_filter",
"parameter_list": "(image, filter_type)"
},
{
"docstring": "Endpoint to upload an image and apply a filter.",
"... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, redirect, url_for, render_template, send_from_directory\nfrom PIL import Image, ImageFilter\nimport os\n\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] =... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00043318",
"row_id": 43318,
"seed_ids": "['Qwen2.5-72B-Instruct_93533']"
} | 0.384524 | Filter_43318 | I | [
"apply_filter",
"upload"
] | 2 | [
[
"upload",
"apply_filter"
]
] | 1 | [] | false | [] | false | pytest | true | [
"PIL",
"flask"
] | false | 75fab2ea85e9c247b203c71dd116a55038ef3378 | 0144ca592c181b827f52a222f8e4a2aa083c9134 | |||
v1.0 | instruct | Filter | Filter_43573_I | How can I create a simple chatbot using Python and Dialogflow? | from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
req = request.get_json(silent=True, force=True)
intent = req.get('queryResult').get('intent').get('displayName')
if intent == 'Default Welcome Intent':
return welcome_respon... | import pytest
from flask import json
from solution import app
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_welcome_response(client):
response = client.post('/webhook', data=json.dumps({
"queryResult": {
"intent": {
"displayNa... | [
{
"docstring": null,
"function_declaration": "def webhook():",
"function_name": "webhook",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def welcome_response():",
"function_name": "welcome_response",
"parameter_list": "()"
},
{
"docstring": null,... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import dialogflow_v2 as dialogflow\n\ndef create_intent(project_id, display_name, training_phrases_parts, message_texts):\n \"\"\"\n Create an intent in Dialogflow.\n \n :param pro... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00043573",
"row_id": 43573,
"seed_ids": "['Qwen2.5-72B-Instruct_93939']"
} | 0.308509 | Filter_43573 | I | [
"webhook",
"welcome_response",
"fallback_response",
"other_responses"
] | 4 | [
[
"webhook",
"fallback_response"
],
[
"webhook",
"other_responses"
],
[
"webhook",
"welcome_response"
]
] | 3 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 7add48a366f6b5de1b784e3b248ae3daa5af6654 | 29c86277bed3ed2bbb9a4614bcb71558dc4eb391 | |||
v1.0 | instruct | Filter | Filter_43640_I | How can I create a Python script to automate the process of checking a website's SSL certificate expiration date and notify me via email if it's close to expiring? | import ssl
import socket
import datetime
import smtplib
from email.mime.text import MIMEText
def get_ssl_expiry_date(hostname):
context = ssl.create_default_context()
conn = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=hostname)
conn.settimeout(3.0)
conn.connect((hostname, 443))
... | import pytest
import datetime
from unittest.mock import patch
@patch('solution.get_ssl_expiry_date')
@patch('solution.send_email_notification')
def test_check_ssl_expiry(mock_send_email, mock_get_ssl_date):
mock_get_ssl_date.return_value = datetime.datetime.now() + datetime.timedelta(days=10)
from solutio... | [
{
"docstring": null,
"function_declaration": "def get_ssl_expiry_date(hostname):",
"function_name": "get_ssl_expiry_date",
"parameter_list": "(hostname)"
},
{
"docstring": null,
"function_declaration": "def send_email_notification(expiry_date, email_recipient):",
"function_name": "se... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import ssl\nimport socket\nimport smtplib\nfrom datetime import datetime\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom typing import Tuple\n\ndef ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00043640",
"row_id": 43640,
"seed_ids": "['Qwen2.5-72B-Instruct_94045']"
} | 0.615068 | Filter_43640 | I | [
"get_ssl_expiry_date",
"send_email_notification",
"check_ssl_expiry"
] | 3 | [
[
"check_ssl_expiry",
"get_ssl_expiry_date"
],
[
"check_ssl_expiry",
"send_email_notification"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0a1e24d680f89de5fb0a4d1d3ccce7c9ca23d164 | cb7497ebfb734d437d574a69600b984632c92b96 | |||
v1.0 | instruct | Filter | Filter_43696_I | I need to create a simple web application that allows users to upload images and then apply various filters to those images. I want to use Python for the backend and React for the frontend. Can you guide me through the basic steps to set this up? | from flask import Flask, request, jsonify
from PIL import Image, ImageFilter
import os
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
def apply_filter(image_path, filter_type):
image = Image.open(ima... | import os
import pytest
from io import BytesIO
from PIL import Image
from solution import app, apply_filter
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_upload_file(client):
data = {
'file': (BytesIO(b'my file contents'), 'test.jpg')
}
response ... | [
{
"docstring": null,
"function_declaration": "def apply_filter(image_path, filter_type):",
"function_name": "apply_filter",
"parameter_list": "(image_path, filter_type)"
},
{
"docstring": null,
"function_declaration": "def upload_file():",
"function_name": "upload_file",
"paramet... | [
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def test_upload_image_no_filters(client):\n data = {\n 'file': (io.BytesIO(b\"fake_image_data\"), 'test.png'),\n 'filters': ''\n }\n response = client.post('/upload', co... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00043696",
"row_id": 43696,
"seed_ids": "['Qwen2.5-72B-Instruct_94129']"
} | 0.293645 | Filter_43696 | I | [
"apply_filter",
"upload_file",
"filter_image"
] | 3 | [
[
"filter_image",
"apply_filter"
]
] | 1 | [] | false | [] | false | pytest | true | [
"PIL",
"flask"
] | false | f6aeda8867503c236d68c7a85951201e97382f98 | 4183d89da066231773deb693f370379a4a98568f | |||
v1.0 | instruct | Filter | Filter_43845_I | Is there a way to turn an image into ASCII art using Python? If so, how can I do it? | from PIL import Image
# Define the ASCII characters to be used in the output ASCII art
ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]
def resize_image(image, new_width=100):
"""
Resize the image to a new width while maintaining the aspect ratio.
"""
(original_width, original_hei... | import pytest
from solution import image_to_ascii
from PIL import Image
import os
def create_test_image(path):
"""Helper function to create a test image."""
image = Image.new('RGB', (10, 10), color = 'white')
image.save(path)
def test_image_to_ascii_output():
test_image_path = 'test_image.jpg'
cre... | [
{
"docstring": "Resize the image to a new width while maintaining the aspect ratio.",
"function_declaration": "def resize_image(image, new_width=100):",
"function_name": "resize_image",
"parameter_list": "(image, new_width=100)"
},
{
"docstring": "Convert the image to grayscale.",
"funct... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from PIL import Image\nimport numpy as np\n\ndef image_to_ascii(image_path, output_width=100):\n # ASCII characters used for mapping from grayscale\n ascii_chars = \"@%#*+=-:. \"\n \n... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00043845",
"row_id": 43845,
"seed_ids": "['Qwen2.5-72B-Instruct_94381']"
} | 0.481796 | Filter_43845 | I | [
"resize_image",
"grayify",
"pixels_to_ascii",
"image_to_ascii"
] | 4 | [
[
"image_to_ascii",
"grayify"
],
[
"image_to_ascii",
"pixels_to_ascii"
],
[
"image_to_ascii",
"resize_image"
]
] | 3 | [] | false | [] | false | pytest | true | [
"PIL"
] | false | 85f6cccb580003ae2f3de7f4fcc53f74b062a27d | b5d7e8e6de34152ac1906e4090c435391427ae89 | |||
v1.0 | instruct | Filter | Filter_43903_I | How can I create a Python script to monitor the CPU usage of my computer and alert me if it exceeds a certain threshold? | import psutil
import time
import smtplib
from email.mime.text import MIMEText
def send_alert_email(cpu_usage, threshold, email_settings):
"""
Send an alert email if the CPU usage exceeds the threshold.
:param cpu_usage: Current CPU usage
:param threshold: CPU usage threshold
:param email_setti... | from unittest.mock import patch, MagicMock
from solution import send_alert_email, monitor_cpu_usage
def test_send_alert_email():
email_settings = {
'smtp_server': 'smtp.example.com',
'smtp_port': 587,
'from_email': 'your_email@example.com',
'email_password': 'your_password',
... | [
{
"docstring": "Send an alert email if the CPU usage exceeds the threshold.\n\n:param cpu_usage: Current CPU usage\n:param threshold: CPU usage threshold\n:param email_settings: Dictionary containing email settings (SMTP server, port, login details, etc.)",
"function_declaration": "def send_alert_email(cpu_... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import psutil\nimport time\n\ndef monitor_cpu(threshold, check_interval):\n \"\"\"\n Monitors the CPU usage and prints an alert message if it exceeds a given threshold.\n \n Params... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00043903",
"row_id": 43903,
"seed_ids": "['Qwen2.5-72B-Instruct_94467']"
} | 0.657352 | Filter_43903 | I | [
"send_alert_email",
"monitor_cpu_usage"
] | 2 | [
[
"monitor_cpu_usage",
"send_alert_email"
]
] | 1 | [] | false | [] | false | pytest | true | [
"psutil"
] | false | 314f4e11cc12e9a28c32c19a34758c7c10fff3b5 | 1e0e9d5e661bfc972d9fbdcb8eca3dd9ae1ef8e5 | |||
v1.0 | instruct | Filter | Filter_44022_I | I need to create a simple web application that allows users to upload images, and then the application should automatically resize the images to a fixed size (e.g., 800x600 pixels). Can you guide me on how to implement this using Python and Flask? | from flask import Flask, request, jsonify
from PIL import Image
import os
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
RESIZED_FOLDER = 'resized'
# Make directories if they do not exist
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(RESIZED_FOLDER, exist_ok=True)
@app.route('/upload', methods=['POST'])
de... | import os
import pytest
from PIL import Image
from io import BytesIO
from solution import app, UPLOAD_FOLDER, RESIZED_FOLDER
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_upload_no_file(client):
response = client.post('/upload')
assert response.status_code =... | [
{
"docstring": null,
"function_declaration": "def upload_image():",
"function_name": "upload_image",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def resize_image(filepath, filename):",
"function_name": "resize_image",
"parameter_list": "(filepath, file... | [
0,
0,
0,
1,
0,
0,
0,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nfrom flask import Flask, request, redirect, url_for, render_template, send_from_directory\nfrom werkzeug.utils import secure_filename\nfrom PIL import Image\n\nUPLOAD_FOLDER = 'uplo... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00044022",
"row_id": 44022,
"seed_ids": "['Qwen2.5-72B-Instruct_94657']"
} | 0.418001 | Filter_44022 | I | [
"upload_image",
"resize_image"
] | 2 | [
[
"upload_image",
"resize_image"
]
] | 1 | [] | false | [] | false | pytest | true | [
"PIL",
"flask"
] | false | 33982ba5962da1798b5088f20e1cbff4fd9e8d20 | 1aa107a5b4dc675a04812bb505e414275c1c166e | |||
v1.0 | instruct | Filter | Filter_44203_I | How can I design a Python script to monitor a specific website for changes in its content and notify me via email when changes are detected? I want to make sure that the script is efficient and does not consume too much bandwidth or processing power. | import hashlib
import time
import smtplib
from email.mime.text import MIMEText
from urllib.request import urlopen
def send_email_notification(subject, body, to_email):
"""
Sends an email notification.
Parameters:
- subject: Subject of the email.
- body: Body of the email.
- to_email: Recipient ... | import tempfile
import os
from solution import get_website_content, compute_md5_hash, send_email_notification
def test_get_website_content():
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(b"Test content")
temp_file.flush()
url = f"file://{temp_file.name}"
... | [
{
"docstring": "Sends an email notification.\nParameters:\n- subject: Subject of the email.\n- body: Body of the email.\n- to_email: Recipient email address.",
"function_declaration": "def send_email_notification(subject, body, to_email):",
"function_name": "send_email_notification",
"parameter_list... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nimport hashlib\nimport smtplib\nfrom email.mime.text import MIMEText\nimport time\n\ndef hash_content(content):\n \"\"\"Returns the MD5 hash of the content.\"\"\"\n retu... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00044203",
"row_id": 44203,
"seed_ids": "['Qwen2.5-72B-Instruct_94944']"
} | 0.397333 | Filter_44203 | I | [
"send_email_notification",
"get_website_content",
"compute_md5_hash",
"monitor_website"
] | 4 | [
[
"monitor_website",
"compute_md5_hash"
],
[
"monitor_website",
"get_website_content"
],
[
"monitor_website",
"send_email_notification"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 17831a5591ca09c93e6dc5513d7299b1894778d9 | c246fb3b3839dbe8f7c74e6aa2db2d4e80384506 | |||
v1.0 | instruct | Filter | Filter_44207_I | I am looking to create a web application that allows users to upload images and then apply various filters to them, similar to Instagram. I want to use Python and Flask for the backend. Can you guide me on how to get started with this project? | from flask import Flask, request, redirect, url_for, render_template
import os
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filena... | import os
import io
import pytest
from solution import app, allowed_file
@pytest.fixture
def client():
app.config['TESTING'] = True
app.config['UPLOAD_FOLDER'] = 'test_uploads'
client = app.test_client()
# Ensure the test upload folder exists
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=... | [
{
"docstring": null,
"function_declaration": "def allowed_file(filename):",
"function_name": "allowed_file",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def index():",
"function_name": "index",
"parameter_list": "()"
},
{
"docstring": n... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, render_template, send_from_directory\nfrom PIL import Image, ImageFilter\nimport os\n\napp = Flask(__name__)\nUPLOAD_FOLDER = 'uploads'\nPROCESSED_FOLDER = 'p... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00044207",
"row_id": 44207,
"seed_ids": "['Qwen2.5-72B-Instruct_94954']"
} | 0.383249 | Filter_44207 | I | [
"allowed_file",
"index",
"upload_file",
"uploaded_file"
] | 4 | [
[
"upload_file",
"allowed_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask",
"werkzeug"
] | false | 5396f0c56419913be5290eaeb01bf9f886904564 | a8d613f7085462dc40774e236976e27a74f2d96c | |||
v1.0 | instruct | Filter | Filter_44244_I | Write a Python function to calculate the greatest common divisor (GCD) of two numbers. The function should take two integers as input and return their GCD. Additionally, implement a simple user interface that asks the user to input two numbers and displays the GCD of these numbers. Ensure your code is well-commented an... | def gcd(a, b):
"""
Returns the greatest common divisor (GCD) of two integers a and b.
Uses the Euclidean algorithm.
"""
while b != 0:
a, b = b, a % b
return abs(a)
def user_interface():
"""
A simple user interface to input two numbers and display their GCD.
"""
try:
... | from solution import gcd
def test_gcd_positive_numbers():
assert gcd(54, 24) == 6
def test_gcd_with_one_number_zero():
assert gcd(0, 5) == 5
assert gcd(7, 0) == 7
def test_gcd_negative_numbers():
assert gcd(-48, -18) == 6
def test_gcd_mixed_sign_numbers():
assert gcd(-48, 18) == 6
assert gcd... | [
{
"docstring": "Returns the greatest common divisor (GCD) of two integers a and b.\nUses the Euclidean algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "A simple user interface to input two numbers and display their G... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n \"\"\"\n Returns the greatest common divisor (GCD) of two integers a and b.\n Uses the Euclidean algorithm.\n \"\"\"\n while b != 0:\n a, b = b, a % b\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00044244",
"row_id": 44244,
"seed_ids": "['Qwen2.5-72B-Instruct_95009']"
} | 0.715867 | Filter_44244 | I | [
"gcd",
"user_interface"
] | 2 | [
[
"user_interface",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b53b4e368ddaba9873aeee3acc394e78706448fe | 1d54eded5c0c49968e31ec56cb98ea284049b021 | |||
v1.0 | instruct | Filter | Filter_44284_I | I want to create a Python program that can automatically generate and send personalized emails to a list of recipients. How can I achieve this? | import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(sender_email, sender_password, recipient_email, subject, message_body):
"""
Sends an email using SMTP.
Args:
sender_email (str): The sender's email address.
sender_password (str): The ... | from solution import send_email, send_personalized_emails
from unittest.mock import patch
def test_send_email():
with patch('smtplib.SMTP') as mock_smtp:
mock_server = mock_smtp.return_value
send_email('sender@example.com', 'password', 'recipient@example.com', 'Test Subject', 'Test Body')
... | [
{
"docstring": "Sends an email using SMTP.\n\nArgs:\nsender_email (str): The sender's email address.\nsender_password (str): The password for the sender's email account.\nrecipient_email (str): The recipient's email address.\nsubject (str): The subject of the email.\nmessage_body (str): The body of the email.",... | [
0,
0,
0,
1,
0,
0,
1,
1,
0
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import smtplib\nfrom email.message import EmailMessage\n\ndef send_personalized_emails(smtp_server, port, sender_email, sender_password, recipient_list, subject_templa... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00044284",
"row_id": 44284,
"seed_ids": "['Qwen2.5-72B-Instruct_95070']"
} | 0.489903 | Filter_44284 | I | [
"send_email",
"send_personalized_emails"
] | 2 | [
[
"send_personalized_emails",
"send_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d8fa39feb57b3e80ee2ed775692bcfec8117517b | c3f831bc49a29b3b62c0165237e664534df8f310 | |||
v1.0 | instruct | Filter | Filter_44325_I | I need to create a simple web application using Flask that allows users to upload images and then displays them. Can you guide me through the process step-by-step? I'm new to Flask and web development in general. | from flask import Flask, request, redirect, url_for, render_template, send_from_directory
import os
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'}
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
def allowed_file(filename):
ret... | from solution import app, allowed_file
import pytest
import os
import io
@pytest.fixture
def client():
app.config['TESTING'] = True
client = app.test_client()
yield client
def test_allowed_file():
assert allowed_file('test.png') == True
assert allowed_file('test.jpg') == True
assert allowed_fi... | [
{
"docstring": null,
"function_declaration": "def allowed_file(filename):",
"function_name": "allowed_file",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def upload_file():",
"function_name": "upload_file",
"parameter_list": "()"
},
{
"d... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, render_template, request, redirect, url_for\nimport os\n\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = 'uploads/'\napp.config['ALLOWED_EXTENSIONS'] = {'png', '... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00044325",
"row_id": 44325,
"seed_ids": "['Qwen2.5-72B-Instruct_95132']"
} | 0.439849 | Filter_44325 | I | [
"allowed_file",
"upload_file",
"uploaded_file"
] | 3 | [
[
"upload_file",
"allowed_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 2d16b63b9d66b44f3fdb30dfde5c9576f52f0924 | 730f0dbab0086e69881fd73ef85b747245e653c1 | |||
v1.0 | instruct | Filter | Filter_44344_I | How can I implement a simple recommendation system using collaborative filtering in Python? | import numpy as np
def cosine_similarity(matrix):
"""
Compute the cosine similarity between rows of the given matrix.
"""
norm = np.linalg.norm(matrix, axis=1)
similarity = np.dot(matrix, matrix.T) / (norm[:, None] * norm[None, :])
return similarity
def predict_ratings(ratings, similarity, use... | from solution import cosine_similarity, predict_ratings, recommend
import numpy as np
import pytest
def test_cosine_similarity():
ratings = np.array([
[5, 0, 0, 1, 1],
[4, 0, 0, 1, 1],
[1, 1, 1, 0, 0],
[0, 1, 1, 0, 0],
])
similarity = cosine_similarity(ratings)
assert si... | [
{
"docstring": "Compute the cosine similarity between rows of the given matrix.",
"function_declaration": "def cosine_similarity(matrix):",
"function_name": "cosine_similarity",
"parameter_list": "(matrix)"
},
{
"docstring": "Predict ratings for a user given similarity matrix.",
"functio... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport pandas as pd\nfrom sklearn.metrics.pairwise import cosine_similarity\n\ndef collaborative_filtering(user_item_matrix, user_index, top_n=5):\n \"\"\"\n Simple c... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00044344",
"row_id": 44344,
"seed_ids": "['Qwen2.5-72B-Instruct_95168']"
} | 0.47916 | Filter_44344 | I | [
"cosine_similarity",
"predict_ratings",
"recommend"
] | 3 | [
[
"recommend",
"cosine_similarity"
],
[
"recommend",
"predict_ratings"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 844146f7e488b60cc8f511d985f202596e88bd11 | 984dcd51fe70d231848ab4fcea009c25c4588ebd | |||
v1.0 | instruct | Filter | Filter_44603_I | Write a Python script to find the largest file in a directory and its subdirectories. The script should output the file's path and its size in human-readable format (e.g., 1.5 MB, 2.3 GB). Ensure the script is efficient and handles large directories gracefully. | import os
def convert_size(size):
"""
Convert a file size to human-readable form.
"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024:
return f"{size:.2f} {unit}"
size /= 1024
def find_largest_file(directory):
"""
Find the largest file in a directory and i... | import os
import tempfile
from solution import find_largest_file, convert_size
def test_convert_size():
assert convert_size(1023) == "1023.00 B"
assert convert_size(1024) == "1.00 KB"
assert convert_size(1048576) == "1.00 MB"
assert convert_size(1073741824) == "1.00 GB"
def test_find_largest_file():
... | [
{
"docstring": "Convert a file size to human-readable form.",
"function_declaration": "def convert_size(size):",
"function_name": "convert_size",
"parameter_list": "(size)"
},
{
"docstring": "Find the largest file in a directory and its subdirectories.\n\nArgs:\ndirectory (str): The root dir... | [
0,
0,
0,
1,
0,
0,
0,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef get_human_readable_size(size_bytes):\n \"\"\"\n Convert a size in bytes to a human-readable format.\n \"\"\"\n if size_bytes == 0:\n return \"0B\"\n size... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00044603",
"row_id": 44603,
"seed_ids": "['Qwen2.5-72B-Instruct_95594']"
} | 0.588738 | Filter_44603 | I | [
"convert_size",
"find_largest_file"
] | 2 | [
[
"find_largest_file",
"convert_size"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f069b7b5dbf22c004364349713c9c36eda220ef9 | e31061641e9d906e6ee363488bb8b6e488357096 | |||
v1.0 | instruct | Filter | Filter_44618_I | I'm trying to implement a basic version of a genetic algorithm to solve the traveling salesman problem (TSP) in Python. Can you provide a simple example to get me started? | import random
def create_route(city_list):
"""
Returns a random route (a chromosome) which is a permutation of the city_list.
"""
return random.sample(city_list, len(city_list))
def initial_population(pop_size, city_list):
"""
Returns the initial population of routes (chromosomes).
"""
... | import pytest
from solution import (
create_route,
initial_population,
route_distance,
rank_routes,
selection,
mating_pool,
breed,
breed_population,
mutate,
mutate_population,
next_generation,
genetic_algorithm
)
class City:
def __init__(self, x, y):
... | [
{
"docstring": "Returns a random route (a chromosome) which is a permutation of the city_list.",
"function_declaration": "def create_route(city_list):",
"function_name": "create_route",
"parameter_list": "(city_list)"
},
{
"docstring": "Returns the initial population of routes (chromosomes).... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport numpy as np\n\ndef create_route(city_list):\n \"\"\"\n Creates a random route from the list of cities.\n \"\"\"\n route = random.sample(city_list, len(city_li... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00044618",
"row_id": 44618,
"seed_ids": "['Qwen2.5-72B-Instruct_95616']"
} | 0.288286 | Filter_44618 | I | [
"create_route",
"initial_population",
"route_distance",
"rank_routes",
"selection",
"mating_pool",
"breed",
"breed_population",
"mutate",
"mutate_population",
"next_generation",
"genetic_algorithm"
] | 12 | [
[
"breed_population",
"breed"
],
[
"genetic_algorithm",
"initial_population"
],
[
"genetic_algorithm",
"next_generation"
],
[
"genetic_algorithm",
"rank_routes"
],
[
"initial_population",
"create_route"
],
[
"mutate_population",
"mutate"
],
[
... | 12 | [] | false | [] | false | pytest | true | [] | true | e3e46d2791739b0d9f6ec42ab69658e6a96473fe | 6581511de493093d3678755e10c723607fa7e7a7 | |||
v1.0 | instruct | Filter | Filter_44708_I | I'm trying to create a Python script that can take a list of URLs as input and download the content of each URL to a local file. How can I achieve this? I want to make sure that the filenames are unique and based on the URL's domain name and path. Can you provide a script that does this? | import os
import requests
from urllib.parse import urlparse
def download_content(urls, output_dir='downloads'):
"""
Download the content from each URL in the list and save it to a local file.
Parameters:
urls (list of str): List of URLs to download content from.
output_dir (str): Direc... | import os
import tempfile
from solution import download_content, create_unique_filename
from urllib.parse import urlparse
def test_create_unique_filename():
url = "http://example.com/path/to/resource"
parsed_url = urlparse(url)
file_name = create_unique_filename(parsed_url)
assert file_name == 'example... | [
{
"docstring": "Download the content from each URL in the list and save it to a local file.\n\nParameters:\n urls (list of str): List of URLs to download content from.\n output_dir (str): Directory to save downloaded files. Default is 'downloads'.",
"function_declaration": "def download_content(urls, ... | [
0,
0,
0,
1,
0,
1,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport requests\nfrom urllib.parse import urlparse\n\ndef download_urls(url_list, download_folder='downloads'):\n \"\"\"\n Downloads the content of each URL in the provided li... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00044708",
"row_id": 44708,
"seed_ids": "['Qwen2.5-72B-Instruct_95766']"
} | 0.594323 | Filter_44708 | I | [
"download_content",
"create_unique_filename"
] | 2 | [
[
"download_content",
"create_unique_filename"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 18a00d9740b315a74210a424c695f432086148a6 | 70f0f2c03998374f71e17aae2d64c8a8ad8bef2b | |||
v1.0 | instruct | Filter | Filter_45102_I | I need help with a Python script to automate the process of downloading files from a list of URLs. Can you provide a script that can read URLs from a text file, download each file, and save them to a specified directory? It would be great if the script could also handle basic error checking, such as checking if the URL... | import os
import requests
from urllib.parse import urlparse
def download_file(url, dest_folder):
"""
Downloads a file from a URL and saves it to a specified destination folder.
:param url: URL of the file to download
:param dest_folder: Destination folder where the file should be saved
:return: No... | import os
import tempfile
from unittest.mock import patch, mock_open
import pytest
from solution import download_file, download_files_from_list
def test_download_file_success():
with tempfile.TemporaryDirectory() as tmpdirname:
url = "https://www.example.com/sample.txt"
file_contents = b"Sample fil... | [
{
"docstring": "Downloads a file from a URL and saves it to a specified destination folder.\n\n:param url: URL of the file to download\n:param dest_folder: Destination folder where the file should be saved\n:return: None",
"function_declaration": "def download_file(url, dest_folder):",
"function_name": ... | [
0,
0,
0,
0,
0,
1,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport requests\n\ndef download_files(url_file, destination_folder):\n \"\"\"\n Downloads files from the list of URLs in the specified text file \n and saves them to the sp... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00045102",
"row_id": 45102,
"seed_ids": "['Qwen2.5-72B-Instruct_96423']"
} | 0.597497 | Filter_45102 | I | [
"download_file",
"download_files_from_list"
] | 2 | [
[
"download_files_from_list",
"download_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | a3b4ab8e9cf147d979deb76d52bbf7c6072ce686 | 4e12c88dcaae2ad91e56f29f4b8d880843d6e129 | |||
v1.0 | instruct | Filter | Filter_45279_I | Write a script that converts a given number to its binary representation using Python. The script should take an integer input from the user and print the binary equivalent. Make sure to handle cases where the input is not a valid integer. | def integer_to_binary(n):
"""
Converts an integer to its binary representation.
Returns a string representing the binary equivalent of the provided integer.
"""
return bin(n)[2:]
def get_binary_representation(input_str):
"""
Converts the input string to an integer and returns its binary rep... | from solution import integer_to_binary, get_binary_representation
def test_integer_to_binary():
assert integer_to_binary(5) == "101"
assert integer_to_binary(0) == "0"
assert integer_to_binary(10) == "1010"
assert integer_to_binary(-8) == "b1000" # Python's bin function returns '-0b1000' for negatives... | [
{
"docstring": "Converts an integer to its binary representation.\nReturns a string representing the binary equivalent of the provided integer.",
"function_declaration": "def integer_to_binary(n):",
"function_name": "integer_to_binary",
"parameter_list": "(n)"
},
{
"docstring": "Converts the... | [
0,
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def convert_to_binary():\n \"\"\"\n Prompts the user for an integer and prints its binary representation.\n Handles invalid integer inputs.\n \"\"\"\n try:\n user_input =... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00045279",
"row_id": 45279,
"seed_ids": "['Qwen2.5-72B-Instruct_96722']"
} | 0.751937 | Filter_45279 | I | [
"integer_to_binary",
"get_binary_representation"
] | 2 | [
[
"get_binary_representation",
"integer_to_binary"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b2e20a7d0c67e83cbb177f2d92f8e26ab4e26a42 | fb2d7b60bdaa588115e5742d37525042facd7cad | |||
v1.0 | instruct | Filter | Filter_45357_I | Write a Python script that takes a directory path as input and recursively calculates the total size of all files in that directory and its subdirectories. The script should handle exceptions gracefully and provide a user-friendly message in case of errors. Additionally, it should display the total size in a human-read... | import os
def get_size_format(size_in_bytes):
"""
Returns size in a human-readable format (e.g., KB, MB, GB).
"""
for unit in ['Bytes', 'KB', 'MB', 'GB', 'TB']:
if size_in_bytes < 1024.0:
return f"{size_in_bytes:.2f} {unit}"
size_in_bytes /= 1024.0
def calculate_total_size(... | import os
import tempfile
from solution import calculate_total_size, get_size_format
def test_get_size_format():
assert get_size_format(0) == "0.00 Bytes"
assert get_size_format(1023) == "1023.00 Bytes"
assert get_size_format(1024) == "1.00 KB"
assert get_size_format(1048576) == "1.00 MB"
assert ge... | [
{
"docstring": "Returns size in a human-readable format (e.g., KB, MB, GB).",
"function_declaration": "def get_size_format(size_in_bytes):",
"function_name": "get_size_format",
"parameter_list": "(size_in_bytes)"
},
{
"docstring": "Takes a directory path as input and recursively calculates t... | [
0,
0,
0,
0,
0,
1,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef get_human_readable_size(size):\n \"\"\"\n Convert a size in bytes to a human-readable format (e.g., KB, MB, GB).\n \"\"\"\n for unit in ['B', 'KB', 'MB', 'GB', 'TB... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00045357",
"row_id": 45357,
"seed_ids": "['Qwen2.5-72B-Instruct_96843']"
} | 0.641968 | Filter_45357 | I | [
"get_size_format",
"calculate_total_size"
] | 2 | [
[
"calculate_total_size",
"get_size_format"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3706c56e80c907cb58797b8c8985aa73cb9eaae8 | 9f30bab5f208ed47b719fbc256cf8527b9fdea7c | |||
v1.0 | instruct | Filter | Filter_45410_I | I am working on a project that involves creating a simple web application using Flask. I want to include a feature where users can upload images, and the application will display a thumbnail of the uploaded image. How can I implement this functionality in Flask? Could you provide a simple example? | from flask import Flask, request, redirect, url_for, send_from_directory, render_template
from werkzeug.utils import secure_filename
from PIL import Image
import os
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
THUMBNAIL_FOLDER = 'thumbnails'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
app.config['UPLOAD_FO... | import os
import pytest
from io import BytesIO
from PIL import Image
from flask import url_for
from solution import app
@pytest.fixture
def client():
app.config['TESTING'] = True
with app.test_client() as client:
yield client
def create_test_image():
img = Image.new('RGB', (100, 100), color = 'red... | [
{
"docstring": null,
"function_declaration": "def allowed_file(filename):",
"function_name": "allowed_file",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def create_thumbnail(image_path, thumbnail_path):",
"function_name": "create_thumbnail",
"p... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, render_template, redirect, url_for\nfrom werkzeug.utils import secure_filename\nimport os\nfrom PIL import Image\n\napp = Flask(__name__)\n\n# Configuration\n... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00045410",
"row_id": 45410,
"seed_ids": "['Qwen2.5-72B-Instruct_96939']"
} | 0.453484 | Filter_45410 | I | [
"allowed_file",
"create_thumbnail",
"upload_file",
"uploaded_file"
] | 4 | [
[
"upload_file",
"allowed_file"
],
[
"upload_file",
"create_thumbnail"
]
] | 2 | [] | false | [] | false | pytest | true | [
"PIL",
"flask",
"werkzeug"
] | false | e6506b2a3db2d72c8e8f8cfa218858f09b4b3ad3 | a6514943e3dda76a71777380381819b98c12ed3c | |||
v1.0 | instruct | Filter | Filter_45536_I | How can I create a Python script that monitors a folder for changes and logs these changes to a file? I want to track any new files, deleted files, and modifications to existing files. | import os
import time
import hashlib
def get_file_hash(file_path):
"""Get MD5 hash of a file."""
hash_md5 = hashlib.md5()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def monitor_folder(folder_path... | import os
import time
from solution import monitor_folder
def setup_temp_folder(folder_path):
if not os.path.exists(folder_path):
os.makedirs(folder_path)
with open(os.path.join(folder_path, "file1.txt"), "w") as f:
f.write("Hello World")
with open(os.path.join(folder_path, "file2.txt"), "w... | [
{
"docstring": "Get MD5 hash of a file.",
"function_declaration": "def get_file_hash(file_path):",
"function_name": "get_file_hash",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def monitor_folder(folder_path, log_file):",
"function_name": "monitor... | [
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import time\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\nimport logging\n\nclass Watcher:\n def __init__(self, fold... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00045536",
"row_id": 45536,
"seed_ids": "['Qwen2.5-72B-Instruct_97151']"
} | 0.552496 | Filter_45536 | I | [
"get_file_hash",
"monitor_folder"
] | 2 | [
[
"monitor_folder",
"get_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cac7bdc112e7dd901f92cc3c398bef401a0094af | 709143ba0bebe639d4d22e5935055ec945f9044c | |||
v1.0 | instruct | Filter | Filter_45565_I | How can I create a Python script that will automatically check for updates on a website and notify me via email when the content changes? | import requests
import hashlib
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def fetch_website_content(url):
response = requests.get(url)
response.raise_for_status()
return response.text
def compute_hash(content):
return hashlib.md5(content.encode()... | import pytest
from unittest.mock import patch, MagicMock
from solution import fetch_website_content, compute_hash, send_email_notification, check_for_update
def test_fetch_website_content():
with patch('requests.get') as mock_get:
mock_get.return_value.text = "Website content"
expected_content = "... | [
{
"docstring": null,
"function_declaration": "def fetch_website_content(url):",
"function_name": "fetch_website_content",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def compute_hash(content):",
"function_name": "compute_hash",
"parameter_list": "(c... | [
0,
0,
0,
1,
0,
1,
1,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\n# Define the website URL and email details\nWEBSITE_URL = 'https://exam... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00045565",
"row_id": 45565,
"seed_ids": "['Qwen2.5-72B-Instruct_97198']"
} | 0.415219 | Filter_45565 | I | [
"fetch_website_content",
"compute_hash",
"send_email_notification",
"check_for_update"
] | 4 | [
[
"check_for_update",
"compute_hash"
],
[
"check_for_update",
"fetch_website_content"
],
[
"check_for_update",
"send_email_notification"
]
] | 3 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 0e5243c55a562f713dc9a977428b71bcb3f0afb9 | c4ff947c42800e91b0f4e49852cd9a98f9f8157f | |||
v1.0 | instruct | Filter | Filter_45679_I | How can I create a Python script that automatically generates a report of the latest stock prices for a given list of companies and sends it via email? | import smtplib
import requests
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def fetch_stock_price(company_symbol):
"""
Fetches the latest stock price for the given company symbol.
"""
# Using a mock response as an example since there would be an actual API call in... | from solution import fetch_stock_price, generate_report, send_email
def test_fetch_stock_price_valid():
assert fetch_stock_price("AAPL") == 150.00
assert fetch_stock_price("GOOGL") == 2800.00
assert fetch_stock_price("MSFT") == 300.00
def test_fetch_stock_price_invalid():
assert fetch_stock_price("INV... | [
{
"docstring": "Fetches the latest stock price for the given company symbol.",
"function_declaration": "def fetch_stock_price(company_symbol):",
"function_name": "fetch_stock_price",
"parameter_list": "(company_symbol)"
},
{
"docstring": "Generates a report of the latest stock prices for a g... | [
0,
0,
0,
0,
1,
0,
1,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import yfinance as yf\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\ndef get_stock_data(tickers):\n \"\"\"\n Retrieves the lates... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00045679",
"row_id": 45679,
"seed_ids": "['Qwen2.5-72B-Instruct_97399']"
} | 0.447489 | Filter_45679 | I | [
"fetch_stock_price",
"generate_report",
"send_email"
] | 3 | [
[
"generate_report",
"fetch_stock_price"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 5daa4d1de96ee1ba978021457c59d52322419f72 | 3e06fcf7ebfc1285895c176a805230c945355fae | |||
v1.0 | instruct | Filter | Filter_45853_I | I am in need of a function that can calculate the distance between two points on the Earth's surface given their latitude and longitude. The function should be able to handle input data as a pandas DataFrame with columns for the origin and destination points' latitudes and longitudes. The output should be the distances... | import pandas as pd
import numpy as np
def haversine_distance(lat1, lon1, lat2, lon2):
"""
Calculate the Haversine distance between two points on the Earth's surface specified in decimal degrees.
"""
# Convert decimal degrees to radians
lat1, lon1, lat2, lon2 = map(np.radians, [lat1, lon1, lat2, lo... | import pytest
from solution import haversine_distance, calculate_distances
import pandas as pd
def test_haversine_distance():
assert np.isclose(haversine_distance(36.12, -86.67, 33.94, -118.40), 2887.26, rtol=1e-2)
def test_calculate_distances():
df = pd.DataFrame({
'origin_lat': [36.12, 40.7128],
... | [
{
"docstring": "Calculate the Haversine distance between two points on the Earth's surface specified in decimal degrees.",
"function_declaration": "def haversine_distance(lat1, lon1, lat2, lon2):",
"function_name": "haversine_distance",
"parameter_list": "(lat1, lon1, lat2, lon2)"
},
{
"docs... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport numpy as np\n\ndef haversine(lat1, lon1, lat2, lon2):\n \"\"\"\n Calculate the great circle distance in kilometers between two points \n on the Earth speci... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00045853",
"row_id": 45853,
"seed_ids": "['Qwen2.5-72B-Instruct_97691']"
} | 0.703465 | Filter_45853 | I | [
"haversine_distance",
"calculate_distances"
] | 2 | [
[
"calculate_distances",
"haversine_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas"
] | false | 86e6bd806a1e361971d26ec596511803f0b75809 | c13c57d4563c3e22be5a329d10b3d6bfa081ed25 | |||
v1.0 | instruct | Filter | Filter_45868_I | Is it possible to create a Python script that can monitor the disk usage of a specific directory and send an email alert if the usage exceeds a certain threshold? | import os
import smtplib
import shutil
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def get_disk_usage(directory):
"""
Returns the disk usage of the specified directory as a percentage.
"""
total, used, free = shutil.disk_usage(directory)
return (used / total)... | from unittest.mock import patch, call
from solution import get_disk_usage, send_email, monitor_disk_usage
def test_get_disk_usage():
with patch('shutil.disk_usage') as mock_disk_usage:
mock_disk_usage.return_value = (100, 50, 50)
assert get_disk_usage('/') == 50.0
mock_disk_usage.return_val... | [
{
"docstring": "Returns the disk usage of the specified directory as a percentage.",
"function_declaration": "def get_disk_usage(directory):",
"function_name": "get_disk_usage",
"parameter_list": "(directory)"
},
{
"docstring": "Sends an email with the specified subject and body to the to_em... | [
0,
0,
0,
1,
0,
1,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport smtplib\nfrom email.message import EmailMessage\n\ndef get_disk_usage(directory):\n \"\"\"\n Returns the current disk usage of the given directory as a percentage.\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00045868",
"row_id": 45868,
"seed_ids": "['Qwen2.5-72B-Instruct_97710']"
} | 0.507415 | Filter_45868 | I | [
"get_disk_usage",
"send_email",
"monitor_disk_usage"
] | 3 | [
[
"monitor_disk_usage",
"get_disk_usage"
],
[
"monitor_disk_usage",
"send_email"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e50a17b680de9a2d2432fe6d78943f672887b2e1 | 1bbad65aa4992d9ba707a807f98b42872e4ccb85 | |||
v1.0 | instruct | Filter | Filter_45991_I | I'm looking to automate a simple task using Python. I have a directory full of text files, and I need a script that will read each file, count the number of words in each, and then output the total word count for all files together. How can I do this? | import os
def count_words_in_file(file_path):
"""
Returns the number of words in the specified file.
"""
with open(file_path, 'r') as file:
contents = file.read()
return len(contents.split())
def total_word_count(directory):
"""
Returns the total word count for all text files in th... | import os
import tempfile
from solution import count_words_in_file, total_word_count
def test_count_words_in_file():
with tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as temp_file:
temp_file.write("Hello world")
temp_file_path = temp_file.name
assert count_words_in_file(te... | [
{
"docstring": "Returns the number of words in the specified file.",
"function_declaration": "def count_words_in_file(file_path):",
"function_name": "count_words_in_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Returns the total word count for all text files in the specified dire... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef count_words_in_file(file_path):\n \"\"\"\n Counts the number of words in the given file.\n \n Parameters:\n - file_path (str): The path to the file.\n \n ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00045991",
"row_id": 45991,
"seed_ids": "['Qwen2.5-72B-Instruct_97928']"
} | 0.757555 | Filter_45991 | I | [
"count_words_in_file",
"total_word_count"
] | 2 | [
[
"total_word_count",
"count_words_in_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 033c61f798c593a113c89027af95b616b8b7f720 | f135cf259170319c5a2bbebc0a7d8d687ad0b2de | |||
v1.0 | instruct | Filter | Filter_46000_I | I need help with a Python script that can monitor a specific directory for changes. I want it to log any new files, modified files, or deleted files. How can I achieve this? | import os
import time
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', handlers=[logging.FileHandler("directory_changes.log"), logging.StreamHandler()])
FILE_SNAPSHOT = {}
def get_files_snapshot(directory):
snapshot = {}
with os.scandir(directory) as entries:
... | import os
import pytest
import shutil
import tempfile
from solution import monitor_directory, get_files_snapshot, detect_changes
@pytest.fixture(scope="module")
def test_directory():
tempdir = tempfile.mkdtemp()
yield tempdir
shutil.rmtree(tempdir)
def create_file(directory, filename, content=""):
wit... | [
{
"docstring": null,
"function_declaration": "def get_files_snapshot(directory):",
"function_name": "get_files_snapshot",
"parameter_list": "(directory)"
},
{
"docstring": null,
"function_declaration": "def monitor_directory(directory):",
"function_name": "monitor_directory",
"pa... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport time\nfrom datetime import datetime\n\ndef monitor_directory(directory_path):\n \"\"\"\n Monitor a specific directory for new, modified, or deleted files.\n \"\"\"\n... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00046000",
"row_id": 46000,
"seed_ids": "['Qwen2.5-72B-Instruct_97940']"
} | 0.620314 | Filter_46000 | I | [
"get_files_snapshot",
"monitor_directory",
"detect_changes"
] | 3 | [
[
"monitor_directory",
"detect_changes"
],
[
"monitor_directory",
"get_files_snapshot"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cbe8d5a21bd3d4b12637855c268901bde19acd4a | 4a08518d00c9360a2c4247e3e4d80cbefdc5c04a | |||
v1.0 | instruct | Filter | Filter_46024_I | I have a piece of code that is supposed to implement a simple calculator using a stack. However, it doesn't handle parentheses and operator precedence correctly. How can I modify it to support these features? | def precedence(op):
if op in ('+', '-'):
return 1
if op in ('*', '/'):
return 2
return 0
def apply_op(a, b, op):
if op == '+':
return a + b
if op == '-':
return a - b
if op == '*':
return a * b
if op == '/':
return a / b
def evaluate(expressi... | from solution import evaluate
def test_simple_addition():
assert evaluate("1 + 2") == 3
def test_simple_subtraction():
assert evaluate("5 - 2") == 3
def test_simple_multiplication():
assert evaluate("3 * 4") == 12
def test_simple_division():
assert evaluate("12 / 4") == 3
def test_combined_operatio... | [
{
"docstring": null,
"function_declaration": "def precedence(op):",
"function_name": "precedence",
"parameter_list": "(op)"
},
{
"docstring": null,
"function_declaration": "def apply_op(a, b, op):",
"function_name": "apply_op",
"parameter_list": "(a, b, op)"
},
{
"docstri... | [
0,
0,
0,
1,
0,
1,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate(s: str) -> int:\n \"\"\"\n Calculate the value of a mathematical expression in string format\n considering parentheses and operator precedence.\n \"\"\"\n def prec... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00046024",
"row_id": 46024,
"seed_ids": "['Qwen2.5-72B-Instruct_97981']"
} | 0.496304 | Filter_46024 | I | [
"precedence",
"apply_op",
"evaluate"
] | 3 | [
[
"evaluate",
"apply_op"
],
[
"evaluate",
"precedence"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6b8784562a96f5a99b01267f91763ee3fdc9998c | ecc95f541ed6c889c8d129004ff18b4713032b4b | |||
v1.0 | instruct | Filter | Filter_46093_I | Write a Python script to check the disk usage of the system and send an email alert if the usage exceeds 80%. Use the `shutil` module to get the disk usage and the `smtplib` module to send the email. The email should include the current disk usage percentage and a warning message. Assume the system is running a Linux d... | import shutil
import smtplib
from email.mime.text import MIMEText
def check_disk_usage():
"""
Checks the current disk usage and returns the percentage used.
"""
total, used, free = shutil.disk_usage("/")
return (used / total) * 100
def send_email_alert(disk_usage):
"""
Sends an email alert... | import pytest
from unittest.mock import patch, MagicMock
from solution import check_disk_usage, send_email_alert, monitor_disk_usage
def test_check_disk_usage():
with patch("shutil.disk_usage") as mock_disk_usage:
mock_disk_usage.return_value = (100, 90, 10)
assert check_disk_usage() == 90.0
def t... | [
{
"docstring": "Checks the current disk usage and returns the percentage used.",
"function_declaration": "def check_disk_usage():",
"function_name": "check_disk_usage",
"parameter_list": "()"
},
{
"docstring": "Sends an email alert if disk usage exceeds 80%.",
"function_declaration": "de... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import shutil\nimport smtplib\nfrom email.mime.text import MIMEText\n\ndef check_disk_usage_and_send_alert(threshold=80, recipient_email=''):\n \"\"\"\n Checks the disk usage of the syst... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00046093",
"row_id": 46093,
"seed_ids": "['Qwen2.5-72B-Instruct_98092']"
} | 0.443119 | Filter_46093 | I | [
"check_disk_usage",
"send_email_alert",
"monitor_disk_usage"
] | 3 | [
[
"monitor_disk_usage",
"check_disk_usage"
],
[
"monitor_disk_usage",
"send_email_alert"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 82ed484f1d6a1ebb0aaa8a1688272cbd18c7ee17 | 9b9bd2bf5ada907dca487fa1d1f9cc5fb03e5b37 | |||
v1.0 | instruct | Filter | Filter_46225_I | How can I implement a distributed machine learning model using PyTorch and Alibaba Cloud's infrastructure? | # To implement a distributed machine learning model using PyTorch and Alibaba Cloud's infrastructure, follow these steps:
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
import os
# Step 1: Initialize the process group
def i... | # Since the solution code is distributed and uses multiprocessing,
# unit tests for such a setup would involve integration tests rather than basic unit tests.
# However, I'll provide examples of testing the model and the training function in isolation.
from solution import SimpleModel, train, init_process
import torch... | [] | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import DataLoa... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00046225",
"row_id": 46225,
"seed_ids": "['Qwen2.5-72B-Instruct_98305']"
} | 0.264232 | Filter_46225 | I | [
"init_process",
"train",
"main"
] | 3 | [
[
"train",
"init_process"
]
] | 1 | [] | false | [
"SimpleModel"
] | true | pytest | true | [
"torch"
] | false | 77efebccf79eb44d57c1c7b5ed4d8286f5186cc4 | 0c1f45426ec43785e640fad8169e55b88b3cc8e6 | |||
v1.0 | instruct | Filter | Filter_46264_I | Write a Python script that takes a directory as input and prints a list of all files in that directory and its subdirectories, along with their sizes in human-readable format (e.g., KB, MB, GB). The output should be sorted by file size, from largest to smallest. | import os
def human_readable_size(size, decimal_places=2):
"""
Converts a size in bytes to a human-readable format.
"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024:
return f"{size:.{decimal_places}f} {unit}"
size /= 1024
def list_files_with_sizes(directory):
... | import os
import pytest
from solution import list_files_with_sizes, human_readable_size
def test_list_files_with_sizes(tmpdir):
# Create a temporary directory with files
file1 = tmpdir.mkdir("subdir1").join("file1.txt")
file1.write("a" * 1024) # 1 KB
file2 = tmpdir.mkdir("subdir2").join("file2.tx... | [
{
"docstring": "Converts a size in bytes to a human-readable format.",
"function_declaration": "def human_readable_size(size, decimal_places=2):",
"function_name": "human_readable_size",
"parameter_list": "(size, decimal_places=2)"
},
{
"docstring": "Returns a list of files in the given dire... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef get_files_in_directory(directory):\n \"\"\"\n Takes a directory as input and returns a list of tuples containing filenames\n with their sizes in a human-readable form... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00046264",
"row_id": 46264,
"seed_ids": "['Qwen2.5-72B-Instruct_98354']"
} | 0.610315 | Filter_46264 | I | [
"human_readable_size",
"list_files_with_sizes"
] | 2 | [
[
"list_files_with_sizes",
"human_readable_size"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7072fa281f474d221a048c5994824367a8a9f860 | 74e894bf3d60cf591156d8fef1ed6857e103bf53 | |||
v1.0 | instruct | Filter | Filter_46411_I | Design a Python function that calculates the maximum product of any two numbers from a given list of integers. The function should be named `max_product_pair` and it should return the two integers that produce this maximum product. Ensure the function is self-contained, with all necessary imports included at the beginn... | def max_product_pair(numbers):
"""
Returns the pair of numbers from the list 'numbers' that produces the maximum product.
"""
if len(numbers) < 2:
raise ValueError("The list must contain at least two numbers.")
max1 = max2 = float('-inf')
min1 = min2 = float('inf')
for numb... | from solution import max_product_pair
def test_positive_numbers():
assert max_product_pair([1, 2, 3, 4]) in [(3, 4), (4, 3)]
def test_negative_numbers():
assert max_product_pair([0, -1, -2, -3]) in [(-2, -3), (-3, -2)]
def test_mixed_numbers():
assert max_product_pair([-10, -20, 5, 1]) in [(-10, -20), (-... | [
{
"docstring": "Returns the pair of numbers from the list 'numbers' that produces the maximum product.",
"function_declaration": "def max_product_pair(numbers):",
"function_name": "max_product_pair",
"parameter_list": "(numbers)"
},
{
"docstring": null,
"function_declaration": "def verif... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_product_pair(nums):\n \"\"\"\n Returns the pair of integers from the list that produces the maximum product.\n \"\"\"\n if len(nums) < 2:\n return None\n \n nu... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00046411",
"row_id": 46411,
"seed_ids": "['Qwen2.5-72B-Instruct_98579']"
} | 0.773683 | Filter_46411 | I | [
"max_product_pair",
"verify_solution"
] | 2 | [
[
"verify_solution",
"max_product_pair"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aa82d3887e6af7b27db4b64722570e06b918451d | 2e7bb7cb9e30fbf9de9687420b2cf820b03aa70d | |||
v1.0 | instruct | Filter | Filter_46570_I | Design a Python function that simulates a simplified version of the game "Guess the Number." In this game, the computer will think of a number within a given range, and the player has to guess the number. The function should take the lower and upper bounds of the range as inputs and should output the number of attempts... | import random
def guess_the_number(lower_bound, upper_bound):
"""
Simulates the 'Guess the Number' game.
Parameters:
lower_bound (int): The lower bound of the number range.
upper_bound (int): The upper bound of the number range.
Returns:
int: The number of attempts it took the pla... | import random
from unittest.mock import patch
from solution import guess_the_number, play_guessing_game
# Helper function to simulate user input in unit tests
def simulate_guess_sequence(mock_input, sequence):
def side_effect(*args, **kwargs):
return sequence.pop(0)
mock_input.side_effect = side_effect... | [
{
"docstring": "Simulates the 'Guess the Number' game.\n\nParameters:\nlower_bound (int): The lower bound of the number range.\nupper_bound (int): The upper bound of the number range.\n\nReturns:\nint: The number of attempts it took the player to guess the number.",
"function_declaration": "def guess_the_nu... | [
0,
0,
0,
1,
0,
1,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef guess_the_number(lower, upper):\n \"\"\"\n Simulates the game \"Guess the Number\".\n Args:\n - lower (int): the lower bound of the range.\n - upper (int): ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00046570",
"row_id": 46570,
"seed_ids": "['Qwen2.5-72B-Instruct_98837']"
} | 0.587596 | Filter_46570 | I | [
"guess_the_number",
"play_guessing_game"
] | 2 | [
[
"play_guessing_game",
"guess_the_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 97df093149da801b3ddc5ad76fe1620bb5642f7b | 9cbf94f621e6d287d9ba3a00467c07c4a64e175d | |||
v1.0 | instruct | Filter | Filter_46580_I | Write a Python program that converts a given temperature from Celsius to Fahrenheit. The user should be able to input the temperature in Celsius, and the program should output the temperature in Fahrenheit. Make sure to include error handling for non-numeric inputs. | def celsius_to_fahrenheit(celsius):
"""
Converts a temperature from Celsius to Fahrenheit.
Parameters:
celsius (float): Temperature in Celsius.
Returns:
float: Temperature in Fahrenheit.
"""
return (celsius * 9/5) + 32
def safe_convert(celsius):
"""
Safely converts a t... | from solution import celsius_to_fahrenheit, safe_convert
def test_celsius_to_fahrenheit():
assert celsius_to_fahrenheit(0) == 32
assert celsius_to_fahrenheit(100) == 212
assert celsius_to_fahrenheit(-40) == -40
assert celsius_to_fahrenheit(37) == 98.6
def test_safe_convert_valid_input():
assert sa... | [
{
"docstring": "Converts a temperature from Celsius to Fahrenheit.\n\nParameters:\ncelsius (float): Temperature in Celsius.\n\nReturns:\nfloat: Temperature in Fahrenheit.",
"function_declaration": "def celsius_to_fahrenheit(celsius):",
"function_name": "celsius_to_fahrenheit",
"parameter_list": "(ce... | [
0,
0,
0,
1,
0,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def celsius_to_fahrenheit(celsius):\n \"\"\"\n Converts a temperature from Celsius to Fahrenheit.\n \"\"\"\n try:\n celsius = float(celsius)\n except ValueError:\n ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00046580",
"row_id": 46580,
"seed_ids": "['Qwen2.5-72B-Instruct_98856']"
} | 0.441948 | Filter_46580 | I | [
"celsius_to_fahrenheit",
"safe_convert"
] | 2 | [
[
"safe_convert",
"celsius_to_fahrenheit"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c3383df16efb7aaf8d77132a467209e04cb1ea47 | eda18fac20bb2ed2a43a394bc1ce8a600d0e1dd0 | |||
v1.0 | instruct | Filter | Filter_46644_I | Write a Python function that takes a list of tuples as an input, where each tuple represents a simple polygon in a 2D plane (the first element is a list of x-coordinates, and the second element is a list of y-coordinates). The function should return a list of tuples, each containing the area and the perimeter of the co... | import math
def polygon_area_and_perimeter(polygon):
"""
Calculate the area and perimeter of a polygon defined by a list of x-coordinates and y-coordinates.
Parameters:
polygon (tuple of lists): A tuple where the first element is a list of x-coordinates and the second
el... | from solution import list_of_polygon_metrics
def test_single_square():
squares = [([0, 0, 1, 1], [0, 1, 1, 0])]
result = list_of_polygon_metrics(squares)
assert result == [(1.0, 4.0)], f"Unexpected result {result}"
def test_multiple_polygons():
polygons = [
([0, 0, 1, 1], [0, 1, 1, 0]), # squ... | [
{
"docstring": "Calculate the area and perimeter of a polygon defined by a list of x-coordinates and y-coordinates.\n\nParameters:\npolygon (tuple of lists): A tuple where the first element is a list of x-coordinates and the second \n element is a list of y-coordinates of the polygon ve... | [
0,
0,
0,
0,
0,
1,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef polygon_area_and_perimeter(polygons):\n \"\"\"\n Takes a list of tuples representing polygons and returns a list of tuples\n containing the area and perimeter of ea... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00046644",
"row_id": 46644,
"seed_ids": "['Qwen2.5-72B-Instruct_98948']"
} | 0.572815 | Filter_46644 | I | [
"polygon_area_and_perimeter",
"list_of_polygon_metrics"
] | 2 | [
[
"list_of_polygon_metrics",
"polygon_area_and_perimeter"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3c24ba861436160fd0f87e74085cdb667f90a4af | 0f198e99152a03d4b5770c48358d1c30c8a20772 | |||
v1.0 | instruct | Filter | Filter_46862_I | How can I implement a distributed machine learning model training using PyTorch on multiple GPUs? I have a basic understanding of PyTorch and GPU usage but need guidance on setting up a distributed training environment. | import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, Dataset
# Initialize Process Group for Distributed Training
def setup_process_group(backend='nccl', init_method='env://')... | import pytest
import torch
from solution import SampleModel, SampleDataset
def test_sample_dataset():
data = torch.randn(100, 10)
labels = torch.randn(100, 1)
dataset = SampleDataset(data, labels)
assert len(dataset) == 100
for i in range(len(dataset)):
sample, label = dataset[i]
... | [] | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom torch.nn.parallel import DistributedDataParallel as DDP\n\ndef setup(rank, world_size):\n \"\"\"\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00046862",
"row_id": 46862,
"seed_ids": "['Qwen2.5-72B-Instruct_99283']"
} | 0.217591 | Filter_46862 | I | [
"setup_process_group",
"train",
"main"
] | 3 | [
[
"train",
"setup_process_group"
]
] | 1 | [] | false | [
"SampleDataset",
"SampleModel"
] | true | pytest | true | [
"torch"
] | false | 8ab8c97cc71fe3404ac25d2011d5554f8a746c39 | 279782e562c9da04bd7c780d0d3c0d480db37eb7 | |||
v1.0 | instruct | Filter | Filter_46942_I | I need to implement a feature in my web application that allows users to upload images and display them on their profile page. Can you provide guidance on how to do this using Python and Flask? | from flask import Flask, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
# Configure the upload folder and allowed extensions
UPLOAD_FOLDER = 'uploads/'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER... | import pytest
from solution import allowed_file
def test_allowed_file_with_allowed_extension():
assert allowed_file('image.png') == True
assert allowed_file('image.jpg') == True
assert allowed_file('image.jpeg') == True
assert allowed_file('image.gif') == True
def test_allowed_file_with_disallowed_ext... | [
{
"docstring": "Check if the file has one of the allowed extensions.",
"function_declaration": "def allowed_file(filename):",
"function_name": "allowed_file",
"parameter_list": "(filename)"
},
{
"docstring": "Render the home page with the upload form.",
"function_declaration": "def index... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, redirect, url_for, render_template, send_from_directory\nimport os\n\napp = Flask(__name__)\nUPLOAD_FOLDER = 'uploads'\nALLOWED_EXTENSIONS = {'png', 'jpg', 'j... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00046942",
"row_id": 46942,
"seed_ids": "['Qwen2.5-72B-Instruct_99410']"
} | 0.387117 | Filter_46942 | I | [
"allowed_file",
"index",
"upload_file",
"uploaded_file"
] | 4 | [
[
"upload_file",
"allowed_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask",
"werkzeug"
] | false | 43b962498672fbb6be5ec737ff2505157fed5c90 | 44a87d43d072f9a34939331f3ec7072758595776 | |||
v1.0 | instruct | Filter | Filter_46956_I | I'm planning to create a Python function that will calculate the harmonic mean of a set of numbers, based on a given DataFrame. The harmonic mean is defined as the reciprocal of the average of the reciprocals of the numbers. I want to apply this calculation to a DataFrame column and group the results by another column.... | import pandas as pd
def harmonic_mean(series):
"""
Calculate the harmonic mean of a pandas Series.
The harmonic mean is defined as the reciprocal of the average of the reciprocals of the data points.
Parameters:
series (pd.Series): A pandas Series of numerical data.
Returns:
... | from solution import harmonic_mean, harmonic_mean_by_group
import pandas as pd
def test_harmonic_mean():
# Test with a series of positive numbers
series = pd.Series([1, 2, 4])
assert harmonic_mean(series) == 1.7142857142857142
# Test with a series containing zeros (should return inf)
series_wi... | [
{
"docstring": "Calculate the harmonic mean of a pandas Series.\n\nThe harmonic mean is defined as the reciprocal of the average of the reciprocals of the data points.\n\nParameters:\nseries (pd.Series): A pandas Series of numerical data.\n\nReturns:\nfloat: The harmonic mean of the input data.",
"function_... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\n\ndef harmonic_mean(series):\n \"\"\"\n Calculate the harmonic mean of a pandas Series.\n The harmonic mean is the reciprocal of the arithmetic mean of the recipr... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00046956",
"row_id": 46956,
"seed_ids": "['Qwen2.5-72B-Instruct_99428']"
} | 0.546036 | Filter_46956 | I | [
"harmonic_mean",
"harmonic_mean_by_group"
] | 2 | [
[
"harmonic_mean_by_group",
"harmonic_mean"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | 734f9459a0f9e5e1eadd6e15f0d5d87bef8757b8 | 7c6237b4d9e712ea37123607785402d38c12f412 | |||
v1.0 | instruct | Filter | Filter_47035_I | Design a Python function that checks if a given number is a prime number. The function should take an integer as input and return `True` if the number is a prime number, otherwise `False`. Additionally, write a function to test the prime number checker with a list of numbers and print out the results. Ensure the soluti... | def is_prime(n):
"""
Checks if a given number n is a prime number.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i +=... | from solution import is_prime, check_prime_numbers
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(29) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(-5) ==... | [
{
"docstring": "Checks if a given number n is a prime number.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Checks a list of numbers and prints for each number whether it is prime.",
"function_declaration": "def chec... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef is_prime(n):\n \"\"\"\n Check if the given integer n is a prime number.\n \n Parameters:\n n : int : Input integer to check for primality\n \n Returns:\... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00047035",
"row_id": 47035,
"seed_ids": "['Qwen2.5-72B-Instruct_99556']"
} | 0.824319 | Filter_47035 | I | [
"is_prime",
"check_prime_numbers"
] | 2 | [
[
"check_prime_numbers",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 31755e50526e8ccaae099b6f1ce209ccc4c645c6 | 364c932b5cde802f5f80fffefcdf930683252f87 | |||
v1.0 | instruct | Filter | Filter_47204_I | Can you provide an example of how to use a genetic algorithm to solve the traveling salesman problem in Python? | import random
import numpy as np
# Function to create the initial population
def initial_population(cities, population_size):
population = []
for _ in range(population_size):
individual = random.sample(cities, len(cities))
population.append(individual)
return population
# Function to calcu... | from solution import initial_population, fitness, selection, crossover, mutate, genetic_algorithm
def test_initial_population():
cities = list(range(5))
population = initial_population(cities, 10)
assert len(population) == 10
for individual in population:
assert set(individual) == set(cities)
... | [
{
"docstring": null,
"function_declaration": "def initial_population(cities, population_size):",
"function_name": "initial_population",
"parameter_list": "(cities, population_size)"
},
{
"docstring": null,
"function_declaration": "def fitness(individual, distance_matrix):",
"function... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport numpy as np\n\ndef create_individual(city_list):\n \"\"\"\n Creates an individual (a tour) which is a permutation of the city list.\n \"\"\"\n individual = ci... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00047204",
"row_id": 47204,
"seed_ids": "['Qwen2.5-72B-Instruct_99826']"
} | 0.326208 | Filter_47204 | I | [
"initial_population",
"fitness",
"selection",
"crossover",
"mutate",
"genetic_algorithm"
] | 6 | [
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"fitness"
],
[
"genetic_algorithm",
"initial_population"
],
[
"genetic_algorithm",
"mutate"
],
[
"genetic_algorithm",
"selection"
]
] | 5 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 3c9b8ebcb7861b8b116874536a4cac27cb004c9f | 98199dba59fb285c3a94a84bab9495c1fbcdf991 | |||
v1.0 | instruct | Filter | Filter_47307_I | How can I create a web application that allows users to submit text for analysis, and then displays the results of the analysis, using Python and Flask? | from flask import Flask, request, render_template
app = Flask(__name__)
def analyze_text(text):
"""
Analyzes the submitted text and returns the results.
Here the analysis is a placeholder that counts characters and words.
"""
num_characters = len(text)
num_words = len(text.split())
return ... | import pytest
from flask import url_for
from solution import app, analyze_text
# Unit tests for the `analyze_text` function
def test_analyze_text_empty():
result = analyze_text("")
assert result == {'num_characters': 0, 'num_words': 0}
def test_analyze_text_single_word():
result = analyze_text("hello")
... | [
{
"docstring": "Analyzes the submitted text and returns the results.\nHere the analysis is a placeholder that counts characters and words.",
"function_declaration": "def analyze_text(text):",
"function_name": "analyze_text",
"parameter_list": "(text)"
},
{
"docstring": null,
"function_de... | [
0,
0,
0,
0,
1,
1,
1,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, render_template\n\napp = Flask(__name__)\n\ndef analyze_text(text):\n \"\"\"\n Analyze the input text and return the analysis result.\n Here, the ana... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00047307",
"row_id": 47307,
"seed_ids": "['Qwen2.5-72B-Instruct_99997']"
} | 0.466372 | Filter_47307 | I | [
"analyze_text",
"index",
"analyze"
] | 3 | [
[
"analyze",
"analyze_text"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 2eddca2b88265a8780f002181f89399eafb60d3d | b85b7f6a5c30c75d20e7450aa6be21d735f9c130 | |||
v1.0 | instruct | Filter | Filter_47541_I | How can I create a Python program to generate a report of the top 5 most frequently used words in a text file? The program should also exclude common English stop words. | from collections import Counter
import re
def load_stop_words(filepath):
"""
Load a list of common English stop words from the given file.
:param filepath: Path to the stop words file
:return: A set of stop words
"""
with open(filepath, 'r') as file:
stop_words = set(file.read().sp... | import pytest
from solution import load_stop_words, get_top_words
def test_load_stop_words(tmp_path):
stop_words_file = tmp_path / "stop_words.txt"
stop_words_file.write_text("the and is")
stop_words = load_stop_words(stop_words_file)
assert "the" in stop_words
assert "and" in stop_words
... | [
{
"docstring": "Load a list of common English stop words from the given file.\n\n:param filepath: Path to the stop words file\n:return: A set of stop words",
"function_declaration": "def load_stop_words(filepath):",
"function_name": "load_stop_words",
"parameter_list": "(filepath)"
},
{
"doc... | [
0,
0,
0,
0,
0,
1,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import Counter\nimport string\n\ndef load_stop_words(file_path='stop_words.txt'):\n \"\"\"\n Loads stop words from a file. Each stop word is expected to be on a new line... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00047541",
"row_id": 47541,
"seed_ids": "['Qwen2.5-72B-Instruct_100375']"
} | 0.656708 | Filter_47541 | I | [
"load_stop_words",
"get_top_words",
"generate_report"
] | 3 | [
[
"generate_report",
"get_top_words"
],
[
"generate_report",
"load_stop_words"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d854a9d457a1217c9434abf5d589e9f5c7403b76 | bc4577b3839e3c4f5310c5261e6909c80b7f7107 | |||
v1.0 | instruct | Filter | Filter_47651_I | You are given a dataset that includes the positions of thousands of stars in a 3D coordinate system. Your task is to implement a Python function that calculates the nearest neighbor for each star, excluding itself. The dataset is structured as a list of tuples, where each tuple represents the (x, y, z) coordinates of a... | import math
def euclidean_distance(p1, p2):
"""
Compute the Euclidean distance between two points in 3D space.
Parameters:
p1, p2 (tuple): Tuples representing the (x, y, z) coordinates of two points.
Returns:
float: Euclidean distance between p1 and p2.
"""
return math.sqrt((p... | import pytest
from solution import find_nearest_neighbors
def test_nearest_neighbors_basic():
stars = [(0, 0, 0), (1, 1, 1), (2, 2, 2)]
expected = [1, 0, 1]
assert find_nearest_neighbors(stars) == expected
def test_nearest_neighbors_single_star():
stars = [(0, 0, 0)]
expected = [None]
assert f... | [
{
"docstring": "Compute the Euclidean distance between two points in 3D space.\n\nParameters:\np1, p2 (tuple): Tuples representing the (x, y, z) coordinates of two points.\n\nReturns:\nfloat: Euclidean distance between p1 and p2.",
"function_declaration": "def euclidean_distance(p1, p2):",
"function_nam... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_nearest_neighbors(stars):\n \"\"\"\n Calculate the nearest neighbor for each star in a 3D coordinate space.\n \n Parameters:\n stars (list of tuple): A list where ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00047651",
"row_id": 47651,
"seed_ids": "['Qwen2.5-72B-Instruct_100560']"
} | 0.664022 | Filter_47651 | I | [
"euclidean_distance",
"find_nearest_neighbors"
] | 2 | [
[
"find_nearest_neighbors",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0550c4e9e335c22620b4e4a459a5ad6f9a3cbc7a | 4447b34dd81aa9e534d7e7c48fa066f923dc9d72 | |||
v1.0 | instruct | Filter | Filter_47697_I | Is there a way to use Python to create a simple script that can periodically check a website for updates and notify me via email if there are any changes? | import hashlib
import smtplib
import time
import requests
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def get_website_content(url):
"""
Fetches the content of the website at the specified URL.
"""
response = requests.get(url)
response.raise_for_status()
r... | import pytest
from unittest.mock import patch, MagicMock
from solution import get_website_content, compute_md5_hash, send_email_notification, monitor_website
def test_compute_md5_hash():
content = "Hello World"
expected_hash = "b10a8db164e0754105b7a99be72e3fe5"
assert compute_md5_hash(content) == expected_... | [
{
"docstring": "Fetches the content of the website at the specified URL.",
"function_declaration": "def get_website_content(url):",
"function_name": "get_website_content",
"parameter_list": "(url)"
},
{
"docstring": "Computes the MD5 hash of the given content.",
"function_declaration": "... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nimport hashlib\nimport smtplib\nimport time\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\ndef get_website_content(url):\n \"\"\"\... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00047697",
"row_id": 47697,
"seed_ids": "['Qwen2.5-72B-Instruct_100621']"
} | 0.414112 | Filter_47697 | I | [
"get_website_content",
"compute_md5_hash",
"send_email_notification",
"monitor_website"
] | 4 | [
[
"monitor_website",
"compute_md5_hash"
],
[
"monitor_website",
"get_website_content"
],
[
"monitor_website",
"send_email_notification"
]
] | 3 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 14c8a610a381fdfeef0075fadf68404b93b89370 | 2659a14598ac56c9f416aa322123831906ce3e8d | |||
v1.0 | instruct | Filter | Filter_47754_I | I have a list of email addresses and I need to check which ones are valid and which ones are not. How can I do this programmatically in Python? | import re
def validate_email(email):
"""
Validates if the given email address is in the correct format.
"""
# Regular expression for validating an email
email_regex = re.compile(
r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")
return bool(email_regex.match(email))
def validate_e... | from solution import validate_email, validate_emails
def test_validate_email_valid():
assert validate_email("test@example.com")
assert validate_email("user.name+tag+sorting@example.com")
assert validate_email("x@example.com")
assert validate_email("example-indeed@strange-example.com")
def test_validat... | [
{
"docstring": "Validates if the given email address is in the correct format.",
"function_declaration": "def validate_email(email):",
"function_name": "validate_email",
"parameter_list": "(email)"
},
{
"docstring": "Given a list of email addresses, returns a dictionary with the email addres... | [
0,
0,
0,
1,
1,
0,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef is_valid_email(email):\n \"\"\"\n This function takes an email string and returns True if the email is valid, else returns False.\n \"\"\"\n email_regex = re.compi... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00047754",
"row_id": 47754,
"seed_ids": "['Qwen2.5-72B-Instruct_100714']"
} | 0.459162 | Filter_47754 | I | [
"validate_email",
"validate_emails"
] | 2 | [
[
"validate_emails",
"validate_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cc07dc12aa507f172428847710ff79fee9bf05c2 | b8bfd45e2dabe0ecdea03c7b3c9f044a3048676d | |||
v1.0 | instruct | Filter | Filter_47978_I | Write a Python program that reads a CSV file containing names and email addresses, and then sends a personalized greeting email to each person using their email. Assume the CSV file has columns 'Name' and 'Email'. Use the smtplib for sending emails and pandas for reading the CSV file. Ensure to handle exceptions for em... | import pandas as pd
import smtplib
from email.mime.text import MIMEText
def send_email(name, email):
"""
Sends a personalized greeting email.
"""
sender_email = "youremail@example.com"
sender_password = "yourpassword"
subject = "Personalized Greeting"
body = f"Hello {name},\n\nThis is a per... | import pytest
from unittest.mock import patch
from solution import send_email, send_emails_from_csv
# Mocking smtplib.SMTP_SSL for testing purposes
@pytest.fixture
def mock_smtp_ssl():
with patch('smtplib.SMTP_SSL') as mock:
yield mock
def test_send_email_success(mock_smtp_ssl):
mock_smtp_ssl.return_v... | [
{
"docstring": "Sends a personalized greeting email.",
"function_declaration": "def send_email(name, email):",
"function_name": "send_email",
"parameter_list": "(name, email)"
},
{
"docstring": "Reads a CSV file and sends personalized emails to each person.\nReturns a summary of emails sent ... | [
0,
0,
0,
1,
0,
0,
1,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\ndef send_emails(file_path, smtp_server, smtp_port, smtp_user, smtp_... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00047978",
"row_id": 47978,
"seed_ids": "['Qwen2.5-72B-Instruct_101046']"
} | 0.52291 | Filter_47978 | I | [
"send_email",
"send_emails_from_csv"
] | 2 | [
[
"send_emails_from_csv",
"send_email"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | d2e5e1fde0a472a869086551ed79fe4fb9024c39 | 840e024332d2b0a8127a9400743084c0cbe60925 | |||
v1.0 | instruct | Filter | Filter_48045_I | How can I create a Python script that generates a random quote from a list of quotes and sends it to a specific email address daily at a set time? | import smtplib
from datetime import datetime, timedelta
import time
import random
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# List of quotes
quotes = [
"The best way to predict the future is to invent it. - Alan Kay",
"Life is 10% what happens to us and 90% how we reac... | from solution import get_random_quote, quotes
def test_get_random_quote():
quote = get_random_quote(quotes)
assert quote in quotes | [
{
"docstring": null,
"function_declaration": "def send_email(subject, body, sender, receiver, password):",
"function_name": "send_email",
"parameter_list": "(subject, body, sender, receiver, password)"
},
{
"docstring": null,
"function_declaration": "def get_random_quote(quotes):",
"... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import smtplib\nimport random\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nimport schedule\nimport time\n\n# List of quotes\nquotes = [\n \"Quote 1... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00048045",
"row_id": 48045,
"seed_ids": "['Qwen2.5-72B-Instruct_101157']"
} | 0.507498 | Filter_48045 | I | [
"send_email",
"get_random_quote",
"schedule_daily_email"
] | 3 | [
[
"schedule_daily_email",
"get_random_quote"
],
[
"schedule_daily_email",
"send_email"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c6f401362c83870b9524e94a759508cf0ec42c31 | 2f4407f7af0fe9e3bff3032638b269ebba01cfd4 | |||
v1.0 | instruct | Filter | Filter_48159_I | Can you help me find a way to automate my daily email responses using Python? I get a lot of similar emails and it would be great if I could have a script that can automatically send out pre-defined responses. | import imaplib
import email
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
def check_emails(email_user, email_password):
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(email_user, email_password)
mail.select('inbox')
result, data = mail.se... | import pytest
from solution import check_emails, send_email, respond_to_emails
def test_check_emails(monkeypatch):
class MockIMAP:
def login(self, user, password): pass
def select(self, folder): pass
def search(self, charset, search_criteria): return 'OK', [b'1 2']
def fetch(self, n... | [
{
"docstring": null,
"function_declaration": "def check_emails(email_user, email_password):",
"function_name": "check_emails",
"parameter_list": "(email_user, email_password)"
},
{
"docstring": null,
"function_declaration": "def send_email(smtp_server, smtp_port, email_user, email_passwo... | [
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.125 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "Magpie-Filter-89K_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\ndef send_email(sender_email, sender_password, recipient_email, ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00048159",
"row_id": 48159,
"seed_ids": "['Qwen2.5-72B-Instruct_101348']"
} | 0.508249 | Filter_48159 | I | [
"check_emails",
"send_email",
"respond_to_emails"
] | 3 | [
[
"respond_to_emails",
"check_emails"
],
[
"respond_to_emails",
"send_email"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f5685a501c682448c2596c5171a0493cb5dd77bd | d697838e7e957e20e0bdc45141ac9d4cc9731439 | |||
v1.0 | instruct | Filter | Filter_48256_I | Write a Python program that will download an image from a given URL and save it to a local file. Additionally, the program should verify the integrity of the downloaded file by comparing its MD5 hash with a provided hash value. If the hashes match, the program should print "File integrity verified." If they don't match... | import hashlib
import requests
def download_image(url, local_filename):
# Send GET request to the URL to download the image
response = requests.get(url)
# Write the image to a local file
with open(local_filename, 'wb') as f:
f.write(response.content)
return local_filename
def md5(file... | from solution import verify_download
import pytest
def test_verify_download(monkeypatch):
class MockResponse:
@staticmethod
def get(url):
class Content:
@property
def content(self):
return b"test image content"
return Conte... | [
{
"docstring": null,
"function_declaration": "def download_image(url, local_filename):",
"function_name": "download_image",
"parameter_list": "(url, local_filename)"
},
{
"docstring": null,
"function_declaration": "def md5(file_path):",
"function_name": "md5",
"parameter_list": "... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nimport hashlib\n\ndef download_image(url, local_filename):\n \"\"\"\n Downloads an image from the specified URL and saves it to the local file system.\n \n Paramet... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00048256",
"row_id": 48256,
"seed_ids": "['Qwen2.5-72B-Instruct_101516']"
} | 0.641473 | Filter_48256 | I | [
"download_image",
"md5",
"verify_download"
] | 3 | [
[
"verify_download",
"download_image"
],
[
"verify_download",
"md5"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 24ec73f0864a6e2d64e783d1b7d40fd657d6a0b2 | bdcff443ff782dd0e130a25845d2388d62165bef | |||
v1.0 | instruct | Filter | Filter_48275_I | How can I create a Python script to automate the process of checking if a website is up and running? I want to monitor multiple websites and get notified via email if any of them are down. | import smtplib
import requests
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(subject, body, to_email, from_email, from_password, smtp_server='smtp.gmail.com', smtp_port=587):
"""
Sends an email with the specified subject and body.
"""
msg = MIMEMulti... | import pytest
from unittest.mock import patch
from solution import check_website, send_email
@patch('solution.requests.get')
def test_check_website(mock_get):
# Mock a successful response
mock_get.return_value.status_code = 200
assert check_website("http://example.com") == True
# Mock a failed respons... | [
{
"docstring": "Sends an email with the specified subject and body.",
"function_declaration": "def send_email(subject, body, to_email, from_email, from_password, smtp_server='smtp.gmail.com', smtp_port=587):",
"function_name": "send_email",
"parameter_list": "(subject, body, to_email, from_email, fr... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nfrom smtplib import SMTP\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\ndef check_website_status(url):\n \"\"\"\n Check if a we... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00048275",
"row_id": 48275,
"seed_ids": "['Qwen2.5-72B-Instruct_101546']"
} | 0.543128 | Filter_48275 | I | [
"send_email",
"check_website",
"monitor_websites"
] | 3 | [
[
"monitor_websites",
"check_website"
],
[
"monitor_websites",
"send_email"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 6d6976542e33adb9b779f333a28d49b08c7f2588 | de2fa108d255898b5c7999127bf9b7061a5f8a55 | |||
v1.0 | instruct | Filter | Filter_48349_I | I need to create a simple web application that allows users to upload images and then applies a basic image processing filter (like grayscale or sepia) to the uploaded image. The application should then display the original and the processed image side by side. Can you guide me through the process of creating this appl... | from flask import Flask, request, render_template, redirect, url_for
from PIL import Image, ImageOps
import os
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['PROCESSED_FOLDER'] = 'processed'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
if not os.path.exists(app.config['UPLOAD_FOLDER']... | from solution import allowed_file, apply_grayscale
import os
from flask import Flask
def test_allowed_file():
assert allowed_file('test.jpg') == True
assert allowed_file('test.png') == True
assert allowed_file('test.gif') == True
assert allowed_file('test.jpeg') == True
assert allowed_file('test.pd... | [
{
"docstring": null,
"function_declaration": "def allowed_file(filename):",
"function_name": "allowed_file",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def apply_grayscale(image_path):",
"function_name": "apply_grayscale",
"parameter_list": "(... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, render_template, send_file\nimport os\nfrom PIL import Image, ImageOps\nfrom io import BytesIO\n\napp = Flask(__name__)\nUPLOAD_FOLDER = 'uploads'\nPROCESSED_... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00048349",
"row_id": 48349,
"seed_ids": "['Qwen2.5-72B-Instruct_101665']"
} | 0.460127 | Filter_48349 | I | [
"allowed_file",
"apply_grayscale",
"upload_file",
"uploaded_file",
"processed_file"
] | 5 | [
[
"upload_file",
"allowed_file"
],
[
"upload_file",
"apply_grayscale"
]
] | 2 | [] | false | [] | false | pytest | true | [
"PIL",
"flask"
] | false | 30b068325f0af837a95465ab00713be3a328d156 | 980dbe31d1a9a594c4edd242fc7bf4311f2e79e3 | |||
v1.0 | instruct | Filter | Filter_48423_I | I need to create a simple web application that allows users to input text and displays the sentiment of the text (positive, negative, or neutral). I want to use Python and Flask for the backend. Can you guide me through the process? | from flask import Flask, request, render_template_string
app = Flask(__name__)
def analyze_sentiment(text):
"""
Analyzes the sentiment of the input text.
Returns 'positive', 'negative', or 'neutral'.
"""
positive_words = ['good', 'happy', 'joyful', 'awesome', 'excellent']
negative_words = ['ba... | from solution import analyze_sentiment
def test_analyze_sentiment_positive():
assert analyze_sentiment("I am feeling so happy and joyful") == 'positive'
assert analyze_sentiment("This is awesome and excellent work") == 'positive'
def test_analyze_sentiment_negative():
assert analyze_sentiment("I am feelin... | [
{
"docstring": "Analyzes the sentiment of the input text.\nReturns 'positive', 'negative', or 'neutral'.",
"function_declaration": "def analyze_sentiment(text):",
"function_name": "analyze_sentiment",
"parameter_list": "(text)"
},
{
"docstring": null,
"function_declaration": "def index()... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, render_template, request\nfrom textblob import TextBlob\n\napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n@app.rout... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00048423",
"row_id": 48423,
"seed_ids": "['Qwen2.5-72B-Instruct_101784']"
} | 0.451504 | Filter_48423 | I | [
"analyze_sentiment",
"index"
] | 2 | [
[
"index",
"analyze_sentiment"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | a3ed61ddca3ebfadc88245c0ded7d5d3701c8675 | ca7b6cce9007bf5c04fd37f54ac33cd6a19793b0 | |||
v1.0 | instruct | Filter | Filter_48437_I | I want to write a simple Python script that can monitor the disk usage of my Ubuntu server and alert me via email if the usage exceeds 80%. Can you help me with the script? | import psutil
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def get_disk_usage():
"""
Returns the disk usage percentage.
"""
disk_usage = psutil.disk_usage('/')
return disk_usage.percent
def send_email_alert(subject, body, to_email, from_email, ... | import pytest
from unittest.mock import patch
from solution import get_disk_usage, send_email_alert, monitor_disk_usage
def test_get_disk_usage():
with patch('psutil.disk_usage') as mock_disk_usage:
mock_disk_usage.return_value.percent = 75
assert get_disk_usage() == 75
def test_send_email_alert()... | [
{
"docstring": "Returns the disk usage percentage.",
"function_declaration": "def get_disk_usage():",
"function_name": "get_disk_usage",
"parameter_list": "()"
},
{
"docstring": "Sends an email alert with the given subject and body to the specified to_email.",
"function_declaration": "de... | [
0,
0,
0,
0,
1,
1,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import shutil\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\ndef check_disk_usage(path, threshold):\n \"\"\"\n Checks the disk u... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00048437",
"row_id": 48437,
"seed_ids": "['Qwen2.5-72B-Instruct_101805']"
} | 0.462942 | Filter_48437 | I | [
"get_disk_usage",
"send_email_alert",
"monitor_disk_usage"
] | 3 | [
[
"monitor_disk_usage",
"get_disk_usage"
],
[
"monitor_disk_usage",
"send_email_alert"
]
] | 2 | [] | false | [] | false | pytest | true | [
"psutil"
] | false | 58626ca8f5efcc368f89a0801325202ba060e010 | ccdf9cec598b5d65ce022672f13c70650120df3a | |||
v1.0 | instruct | Filter | Filter_48524_I | How can I implement a chatbot using Python and Rasa? I want to create a chatbot that can answer questions about weather and news. | def ask_weather(location):
"""
This function would connect to a weather API to get the weather info.
Currently returns a hardcoded response.
"""
return f"The weather today in {location} is sunny with a high of 75°F."
def ask_news(news_source=None):
"""
This function would connect to a news ... | def test_ask_weather():
assert ask_weather("New York") == "The weather today in New York is sunny with a high of 75°F."
def test_ask_news():
assert ask_news("CNN") == "Here's the latest news: ..."
def test_handle_intent_ask_weather():
response = handle_intent("ask_weather", {"location": "New York"})
a... | [
{
"docstring": "This function would connect to a weather API to get the weather info.\nCurrently returns a hardcoded response.",
"function_declaration": "def ask_weather(location):",
"function_name": "ask_weather",
"parameter_list": "(location)"
},
{
"docstring": "This function would connect... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def create_chatbot():\n \"\"\"\n This function outlines the steps required to create a chatbot using Python and Rasa to answer questions about weather and news.\n \"\"\"\n import o... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00048524",
"row_id": 48524,
"seed_ids": "['Qwen2.5-72B-Instruct_101961']"
} | 0.392333 | Filter_48524 | I | [
"ask_weather",
"ask_news",
"handle_intent",
"get_response"
] | 4 | [
[
"get_response",
"handle_intent"
],
[
"handle_intent",
"ask_news"
],
[
"handle_intent",
"ask_weather"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 2988a74dec7cdb848cd62c58803bfa3ac708064c | 908652667fbdf9255e61c4bbd5cd0dd2d9aa0666 | |||
v1.0 | instruct | Filter | Filter_48531_I | I want to create a simple web application that allows users to upload images and apply filters to them, such as grayscale, sepia, and blur. How can I achieve this using Python and a web framework like Flask? | from flask import Flask, request, render_template, send_file
from PIL import Image, ImageFilter, ImageOps
import io
app = Flask(__name__)
def apply_filter(image, filter_type):
if filter_type == 'grayscale':
return ImageOps.grayscale(image)
elif filter_type == 'sepia':
sepia_image = ImageOps.co... | import pytest
from solution import apply_filter
from PIL import Image, ImageOps
def test_apply_grayscale_filter():
img = Image.new('RGB', (10, 10), color = 'red')
grayscale_img = apply_filter(img, 'grayscale')
expected_img = ImageOps.grayscale(img)
assert list(grayscale_img.getdata()) == list(expected_... | [
{
"docstring": null,
"function_declaration": "def apply_filter(image, filter_type):",
"function_name": "apply_filter",
"parameter_list": "(image, filter_type)"
},
{
"docstring": null,
"function_declaration": "def index():",
"function_name": "index",
"parameter_list": "()"
},
... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, render_template, send_file\nfrom PIL import Image, ImageFilter, ImageOps\nimport io\n\napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n return rende... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00048531",
"row_id": 48531,
"seed_ids": "['Qwen2.5-72B-Instruct_101969']"
} | 0.43171 | Filter_48531 | I | [
"apply_filter",
"index",
"upload"
] | 3 | [
[
"upload",
"apply_filter"
]
] | 1 | [] | false | [] | false | pytest | true | [
"PIL",
"flask"
] | false | 3d93f63c82a36b376dd57aee04da28020feb4123 | 2db45504d3daec88c0146d3935029db5286c2ceb | |||
v1.0 | instruct | Filter | Filter_48599_I | How can I create a Python script to monitor a folder and automatically compress files into a zip archive when they are added or modified? | import os
import time
import zipfile
def monitor_and_compress(folder_path, archive_name):
"""
Monitors a folder and compresses new or modified files into a zip archive.
Parameters:
folder_path (str): Path of the folder to monitor.
archive_name (str): Name of the zip archive to create or append... | import os
import zipfile
import time
from solution import monitor_and_compress, compress_file
def test_compress_file(tmpdir):
# Create a test file
test_file = os.path.join(tmpdir, "test_file.txt")
with open(test_file, "w") as f:
f.write("Hello, World!")
# Compress the file
test_archiv... | [
{
"docstring": "Monitors a folder and compresses new or modified files into a zip archive.\n\nParameters:\nfolder_path (str): Path of the folder to monitor.\narchive_name (str): Name of the zip archive to create or append to.",
"function_declaration": "def monitor_and_compress(folder_path, archive_name):",
... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport time\nimport zipfile\n\ndef compress_file(file_path):\n zip_path = file_path + '.zip'\n with zipfile.ZipFile(zip_path, 'w') as zipf:\n zipf.write(file_path, os.p... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00048599",
"row_id": 48599,
"seed_ids": "['Qwen2.5-72B-Instruct_102063']"
} | 0.648279 | Filter_48599 | I | [
"monitor_and_compress",
"compress_file"
] | 2 | [
[
"monitor_and_compress",
"compress_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f2ebd4dac7a27adf603527d4e874b693a0f38db4 | ec8922a4f5a6106fd3425e37e672dc004fdfc329 | |||
v1.0 | instruct | Filter | Filter_48796_I | I'm working on a project that involves analyzing the color composition of images. I need to create a program that can extract the 5 most dominant colors from an image and display them in a histogram. Can you guide me on how to achieve this using Python and any necessary libraries? | from sklearn.cluster import KMeans
import numpy as np
import cv2
from collections import Counter
import matplotlib.pyplot as plt
def rgb_to_hex(rgb):
"""
Converts an RGB color to HEX.
"""
return '#{:02x}{:02x}{:02x}'.format(int(rgb[0]), int(rgb[1]), int(rgb[2]))
def get_dominant_colors(image_path, num... | from solution import get_dominant_colors, plot_histogram
import cv2
import numpy as np
def test_get_dominant_colors():
# Create a dummy image with 5 different colors
image = np.zeros((100, 100, 3), dtype=np.uint8)
colors = [ (255, 0, 0), (0, 255, 0), (0, 0, 255), (0, 0, 0), (255, 255, 255)]
for i, colo... | [
{
"docstring": "Converts an RGB color to HEX.",
"function_declaration": "def rgb_to_hex(rgb):",
"function_name": "rgb_to_hex",
"parameter_list": "(rgb)"
},
{
"docstring": "Extract the most dominant colors from an image and return them in a histogram.\n\nParameters:\n- image_path: The path to... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from PIL import Image\nimport requests\nfrom io import BytesIO\nfrom sklearn.cluster import KMeans\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef get_image(url):\n \"\"\"\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00048796",
"row_id": 48796,
"seed_ids": "['Qwen2.5-72B-Instruct_102371']"
} | 0.576711 | Filter_48796 | I | [
"rgb_to_hex",
"get_dominant_colors",
"plot_histogram"
] | 3 | [
[
"plot_histogram",
"rgb_to_hex"
]
] | 1 | [] | false | [] | false | pytest | true | [
"cv2",
"matplotlib",
"numpy",
"sklearn"
] | false | 3bf1e16473d9ea4f8e6a72446bbd1f0757fa09da | dfe27d8d98556f1d2f2ec14ed4e91224ba79ef46 | |||
v1.0 | instruct | Filter | Filter_48824_I | Write a Python function to implement a simple version of the K-Nearest Neighbors (KNN) algorithm for a classification problem. The function should take a dataset (a list of tuples where each tuple contains a data point and its label), a new data point to classify, and the number of neighbors \( k \) as inputs. The func... | import math
from collections import Counter
def euclidean_distance(point1, point2):
return math.sqrt(sum((x - y) ** 2 for x, y in zip(point1, point2)))
def knn_classification(dataset, new_point, k):
"""
Implements a simple K-Nearest Neighbors (KNN) algorithm for classification.
:param dataset: Li... | from solution import knn_classification
def test_knn_basic():
dataset = [((1, 2), 'A'), ((2, 3), 'A'), ((3, 4), 'B')]
new_point = (2, 2)
k = 2
assert knn_classification(dataset, new_point, k) == 'A'
def test_knn_ties():
dataset = [((1, 2), 'A'), ((2, 3), 'A'), ((3, 3), 'B'), ((3, 4), 'B')]
new... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Implements a simple K-Nearest Neighbors (KNN) algorithm for classification.\n\n:param dataset: List of tuples... | [
0,
0,
0,
1,
0,
1,
0,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom collections import Counter\n\ndef euclidean_distance(point1, point2):\n \"\"\"\n Calculates the Euclidean distance between two points.\n \"\"\"\n return math.sqrt... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00048824",
"row_id": 48824,
"seed_ids": "['Qwen2.5-72B-Instruct_102416']"
} | 0.672023 | Filter_48824 | I | [
"euclidean_distance",
"knn_classification"
] | 2 | [
[
"knn_classification",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 71e17f68643de9152361ff7f501c1be64c4b7a6e | 4ef95ce3461095d4fd59a83aeb502566bf4df2cd | |||
v1.0 | instruct | Filter | Filter_49007_I | Write a Python program that can automatically detect the language of a given text. The program should be able to identify at least 10 different languages, including English, Spanish, German, French, Italian, Dutch, Russian, Chinese, Japanese, and Korean. The program should output the detected language in ISO 639-1 form... | import re
from collections import defaultdict, Counter
from typing import List
# Example texts in different languages
LANG_TEXTS = {
'en': "This is a sample text in English to build the model.",
'es': "Este es un texto de muestra en español para construir el modelo.",
'de': "Dies ist ein Beispieltext auf D... | from solution import detect_language, language_models
def test_english_text():
assert detect_language("This is a test sentence to detect English.", language_models) == 'en'
def test_spanish_text():
assert detect_language("Esta es una oración de prueba para detectar español.", language_models) == 'es'
def tes... | [
{
"docstring": "Generate trigram frequency count from a text.",
"function_declaration": "def get_trigrams(text):",
"function_name": "get_trigrams",
"parameter_list": "(text)"
},
{
"docstring": "Build language models containing trigram frequencies.",
"function_declaration": "def build_lan... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from langdetect import detect\n\ndef detect_language(text):\n \"\"\"\n Detects the language of the given text.\n Returns the language code in ISO 639-1 format.\n \"\"\"\n langua... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00049007",
"row_id": 49007,
"seed_ids": "['Qwen2.5-72B-Instruct_102726']"
} | 0.441631 | Filter_49007 | I | [
"get_trigrams",
"build_language_model",
"detect_language"
] | 3 | [
[
"build_language_model",
"get_trigrams"
],
[
"detect_language",
"get_trigrams"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9698d468fc1ad09881681a34d0695a043f83037a | 7832384fb3e7dbd2725300c3b1fbc20ef49cb393 | |||
v1.0 | instruct | Filter | Filter_49047_I | Create a Python script to monitor the availability of a website by pinging it at regular intervals and logging the results. The script should also send an email notification if the website is down. Include the ability to specify the interval, the email address to notify, and the website to monitor. | import time
import smtplib
import requests
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email(subject, body, to_email, from_email, smtp_server, smtp_port, smtp_login, smtp_password):
"""
Sends an email.
"""
msg = MIMEMultipart()
msg['From'] = from_ema... | from unittest.mock import patch, Mock
import pytest
from solution import check_website, send_email
def test_check_website_success(monkeypatch):
class MockResponse:
status_code = 200
monkeypatch.setattr('requests.get', lambda url: MockResponse())
assert check_website('http://example.com') == Tr... | [
{
"docstring": "Sends an email.",
"function_declaration": "def send_email(subject, body, to_email, from_email, smtp_server, smtp_port, smtp_login, smtp_password):",
"function_name": "send_email",
"parameter_list": "(subject, body, to_email, from_email, smtp_server, smtp_port, smtp_login, smtp_passwo... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nimport smtplib\nfrom email.mime.text import MIMEText\nimport time\n\ndef check_website(url):\n \"\"\"\n Checks the availability of the given website.\n Returns True i... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00049047",
"row_id": 49047,
"seed_ids": "['Qwen2.5-72B-Instruct_102790']"
} | 0.596068 | Filter_49047 | I | [
"send_email",
"check_website",
"monitor_website"
] | 3 | [
[
"monitor_website",
"check_website"
],
[
"monitor_website",
"send_email"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | a2a430efd7a19ff06a04ef1b14915562caa0dae1 | b79d634d3bcfb21f2ba1a1de547949ba675a5e27 | |||
v1.0 | instruct | Filter | Filter_49088_I | I want to create a simple web application that allows users to upload a text file, and then displays the most frequently occurring words in the file. What are the basic steps I should follow to build this application using Python and Flask? | from flask import Flask, request, render_template_string
from collections import Counter
import os
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def process_file(file_path):
with open(file_path, 'r') as file:
words =... | import os
import tempfile
import pytest
from solution import app, process_file
# Flask provides a way to test your application by exposing the test_client method.
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_process_file():
# Create a temporary file with some t... | [
{
"docstring": null,
"function_declaration": "def process_file(file_path):",
"function_name": "process_file",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def upload_file():",
"function_name": "upload_file",
"parameter_list": "()"
}
] | [
0,
0,
0,
0,
1,
0,
1,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, render_template_string\nfrom collections import Counter\nfrom werkzeug.utils import secure_filename\nimport os\n\napp = Flask(__name__)\nUPLOAD_FOLDER = './up... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00049088",
"row_id": 49088,
"seed_ids": "['Qwen2.5-72B-Instruct_102849']"
} | 0.577142 | Filter_49088 | I | [
"process_file",
"upload_file"
] | 2 | [
[
"upload_file",
"process_file"
]
] | 1 | [] | false | [] | false | pytest | true | [
"flask"
] | false | 807bfd7183f18b8877ae370650717e6c4d0c971a | 43d33cbeffee0326fed0563064b05ff0fc385346 | |||
v1.0 | instruct | Filter | Filter_49408_I | I want to create a simple Python script to monitor my home server. It should check if the server is up by pinging it, and if it's down, send an email notification. Can you help me with that? | import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def ping_server(ip):
"""
Pings the server with the given IP address.
Returns True if the server is up, False if it's down.
"""
response = os.system(f"ping -c 1 {ip}")
return respons... | from unittest.mock import patch
import pytest
from solution import ping_server, send_email_notification, monitor_server
def test_ping_server():
assert ping_server("127.0.0.1") == True # Assuming 127.0.0.1 (localhost) is up
with patch('os.system', return_value=1): # Mocking os.system to simulate server d... | [
{
"docstring": "Pings the server with the given IP address.\n\nReturns True if the server is up, False if it's down.",
"function_declaration": "def ping_server(ip):",
"function_name": "ping_server",
"parameter_list": "(ip)"
},
{
"docstring": "Sends an email notification to the specified rece... | [
0,
0,
0,
0,
0,
1,
1,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport smtplib\nfrom email.mime.text import MIMEText\n\ndef ping_server(server_ip):\n \"\"\"\n Pings the server IP to check if it's online.\n Returns True if server is up, ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00049408",
"row_id": 49408,
"seed_ids": "['Qwen2.5-72B-Instruct_103364']"
} | 0.529208 | Filter_49408 | I | [
"ping_server",
"send_email_notification",
"monitor_server"
] | 3 | [
[
"monitor_server",
"ping_server"
],
[
"monitor_server",
"send_email_notification"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 741dae0fa999acf87fbcc7150e905919994e937a | 00babb92f7449970aba7b90b06831d0f4c31f852 | |||
v1.0 | instruct | Filter | Filter_49509_I | Is there a way to create a Python script that monitors the CPU and memory usage of a system and sends an alert if the usage exceeds a certain threshold? | import psutil
import smtplib
from email.mime.text import MIMEText
def send_alert(subject, body):
"""
Sends an email alert with the specified subject and body.
"""
from_email = "your_email@example.com"
to_email = "recipient_email@example.com"
password = "your_password"
msg = MIMEText(body)
... | def test_send_alert(monkeypatch):
"""
Mocks the `smtplib.SMTP_SSL` instance to avoid sending real emails during the test.
Verifies that the email sending function works correctly.
"""
class MockSMTP:
def __init__(self, *args, **kwargs):
pass
def login(self, user,... | [
{
"docstring": "Sends an email alert with the specified subject and body.",
"function_declaration": "def send_alert(subject, body):",
"function_name": "send_alert",
"parameter_list": "(subject, body)"
},
{
"docstring": "Monitors the system's CPU and memory usage.\nSends an alert if usage exc... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import psutil\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\ndef check_system_usage(cpu_threshold, memory_threshold):\n \"\"\"\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00049509",
"row_id": 49509,
"seed_ids": "['Qwen2.5-72B-Instruct_103517']"
} | 0.658188 | Filter_49509 | I | [
"send_alert",
"monitor_system"
] | 2 | [
[
"monitor_system",
"send_alert"
]
] | 1 | [] | false | [] | false | pytest | false | [
"psutil"
] | false | f22f109fd926bdeac29896fcbab2b80760d284de | 7f18767c75b1cfc37926926964ff46b4dbd520ad | |||
v1.0 | instruct | Filter | Filter_49623_I | I want to create a simple web application that allows users to upload images and then applies a basic image processing function, such as converting the image to grayscale. I plan to use Python for the backend and Flask for the web framework. Can you guide me through the steps to set up this application? | from flask import Flask, request, redirect, url_for, send_from_directory, render_template
from werkzeug.utils import secure_filename
from PIL import Image
import os
app = Flask(__name__)
# Configuration
UPLOAD_FOLDER = 'uploads'
PROCESSED_FOLDER = 'processed'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
app.con... | import os
import pytest
from io import BytesIO
from PIL import Image
from solution import app, allowed_file, convert_to_grayscale
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_allowed_file():
assert allowed_file("test.jpg") is True
assert allowed_file("test.... | [
{
"docstring": null,
"function_declaration": "def allowed_file(filename):",
"function_name": "allowed_file",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def upload_file():",
"function_name": "upload_file",
"parameter_list": "()"
},
{
"d... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from flask import Flask, request, redirect, url_for, send_file, render_template\nfrom werkzeug.utils import secure_filename\nfrom PIL import Image\nimport os\n\napp = Flask(__name__)\napp.conf... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00049623",
"row_id": 49623,
"seed_ids": "['Qwen2.5-72B-Instruct_103696']"
} | 0.342905 | Filter_49623 | I | [
"allowed_file",
"upload_file",
"convert_to_grayscale",
"uploaded_file"
] | 4 | [
[
"upload_file",
"allowed_file"
],
[
"upload_file",
"convert_to_grayscale"
]
] | 2 | [] | false | [] | false | pytest | true | [
"PIL",
"flask",
"werkzeug"
] | false | fff22439c12dd663249b7f44d027b601d12e0381 | b4d23c47f687a095b9f744975a027f8332f8b608 | |||
v1.0 | instruct | Filter | Filter_49805_I | How can I create a Python script to monitor the disk usage of a system and send an email alert if the usage exceeds 80%? | import shutil
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def check_disk_usage(threshold=80):
"""
Checks disk usage and returns True if it exceeds the threshold, otherwise False.
"""
total, used, free = shutil.disk_usage('/')
usage_percentage =... | import pytest
from unittest.mock import patch, MagicMock
from solution import check_disk_usage, send_alert_email, monitor_disk_and_alert
def test_check_disk_usage_under_threshold():
with patch('shutil.disk_usage', return_value=(100, 50, 50)):
assert check_disk_usage(80) is False
def test_check_disk_usage_... | [
{
"docstring": "Checks disk usage and returns True if it exceeds the threshold, otherwise False.",
"function_declaration": "def check_disk_usage(threshold=80):",
"function_name": "check_disk_usage",
"parameter_list": "(threshold=80)"
},
{
"docstring": "Sends an email alert to the specified e... | [
0,
0,
0,
0,
1,
0,
1,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import shutil\nimport smtplib\nfrom email.message import EmailMessage\n\ndef check_disk_usage():\n total, used, free = shutil.disk_usage('/')\n usage_percentage = used / total * 100\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00049805",
"row_id": 49805,
"seed_ids": "['Qwen2.5-72B-Instruct_104015']"
} | 0.503991 | Filter_49805 | I | [
"check_disk_usage",
"send_alert_email",
"monitor_disk_and_alert"
] | 3 | [
[
"monitor_disk_and_alert",
"check_disk_usage"
],
[
"monitor_disk_and_alert",
"send_alert_email"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 014294a74616ac2b23b608b73941d505d0ab84b4 | 4be647bd4f3c0df054831630780e6d54d0bc9e25 | |||
v1.0 | instruct | Filter | Filter_49879_I | Is it possible to create a script to simulate the drawing of a simple L-system (Lindenmayer system) fractal using Python? Can you provide an example of how to do this with a common fractal, like the Koch curve? | import turtle
def apply_rules(ch):
rules = {
'F': 'F+F--F+F'
}
return rules.get(ch, ch)
def generate_fractal(axiom, iterations):
result = axiom
for _ in range(iterations):
next_result = "".join(apply_rules(ch) for ch in result)
result = next_result
return result
def dr... | from solution import apply_rules, generate_fractal
def test_apply_rules():
assert apply_rules('F') == 'F+F--F+F'
assert apply_rules('+') == '+'
assert apply_rules('-') == '-'
def test_generate_fractal():
assert generate_fractal('F', 1) == 'F+F--F+F'
assert generate_fractal('F', 2) == 'F+F--F+F+F+F... | [
{
"docstring": null,
"function_declaration": "def apply_rules(ch):",
"function_name": "apply_rules",
"parameter_list": "(ch)"
},
{
"docstring": null,
"function_declaration": "def generate_fractal(axiom, iterations):",
"function_name": "generate_fractal",
"parameter_list": "(axiom... | [
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import turtle\n\ndef koch_curve(turtle, order, size):\n \"\"\"\n Draws a Koch curve using the turtle graphics.\n\n Parameters:\n turtle (Turtle): The turtle instance to draw with.\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00049879",
"row_id": 49879,
"seed_ids": "['Qwen2.5-72B-Instruct_104121']"
} | 0.33609 | Filter_49879 | I | [
"apply_rules",
"generate_fractal",
"draw_koch_curve",
"create_koch_fractal"
] | 4 | [
[
"create_koch_fractal",
"draw_koch_curve"
],
[
"create_koch_fractal",
"generate_fractal"
],
[
"generate_fractal",
"apply_rules"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 76d13531055f3a363fe5f072df022f9a4b708fdd | c5571a3e40a8460b014f6e17c35c5f89b1ac559e | |||
v1.0 | instruct | Filter | Filter_50087_I | Please help me with a Python script that can convert CSV files to JSON format. The script should be able to handle multiple CSV files and output the JSON files with the same name but with a .json extension in the same directory. The CSV files may contain various data types (strings, integers, floats, etc.) and might ha... | import csv
import json
import os
def csv_to_json(csv_file_path):
"""
Convert a CSV file to a JSON file with the same name in the same directory.
The JSON file will be properly indented for readability.
:param csv_file_path: The file path of the CSV file to be converted
"""
json_file_path =... | import os
import json
import pytest
from solution import csv_to_json, convert_multiple_csv_to_json
def setup_module(module):
"""
Setup module for testing - create temporary CSV files for testing.
"""
with open('test1.csv', mode='w', encoding='utf-8', newline='') as file:
writer = csv.writer(fi... | [
{
"docstring": "Convert a CSV file to a JSON file with the same name in the same directory.\nThe JSON file will be properly indented for readability.\n\n:param csv_file_path: The file path of the CSV file to be converted",
"function_declaration": "def csv_to_json(csv_file_path):",
"function_name": "csv_... | [
0,
0,
0,
1,
1,
1,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import csv\nimport json\nimport os\n\ndef csv_to_json(csv_file_path):\n # Extract the base name of the file without extension\n base_name = os.path.splitext(csv_file_path)[0]\n json_f... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00050087",
"row_id": 50087,
"seed_ids": "['Qwen2.5-72B-Instruct_104465']"
} | 0.727481 | Filter_50087 | I | [
"csv_to_json",
"convert_multiple_csv_to_json"
] | 2 | [
[
"convert_multiple_csv_to_json",
"csv_to_json"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e4943ed6d1f16cc48d2f0a156fb261318b7239f8 | 9e16c80322dabdf26ca380da4ce8283053cb9a6c | |||
v1.0 | instruct | Filter | Filter_50243_I | Design a method to filter a list in Python, removing elements that are not palindromes or whose lengths are not palindromic numbers. For example, if the input list is ["racecar", "level", "world", "madam", "123"], the output should be ["racecar", "level", "madam"] because "world" is not a palindrome and "123" has a len... | def is_palindrome(s):
return s == s[::-1]
def is_length_palindromic_number(s):
length = str(len(s))
return length == length[::-1]
def filter_palindromes_and_lengths(lst):
"""
Filters the input list to remove elements that are not palindromes
or whose lengths are not palindromic numbers.
""... | from solution import filter_palindromes_and_lengths
def test_filter_palindromes_and_lengths_all_valid():
assert filter_palindromes_and_lengths(["racecar", "level", "madam"]) == ["racecar", "level", "madam"]
def test_filter_palindromes_and_lengths_mixed():
assert filter_palindromes_and_lengths(["racecar", "wor... | [
{
"docstring": null,
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def is_length_palindromic_number(s):",
"function_name": "is_length_palindromic_number",
"parameter_list... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(s):\n \"\"\"\n Check if a given string s is a palindrome.\n \"\"\"\n return s == s[::-1]\n\ndef is_palindromic_number(n):\n \"\"\"\n Check if an integer n i... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00050243",
"row_id": 50243,
"seed_ids": "['Qwen2.5-72B-Instruct_104712']"
} | 0.684834 | Filter_50243 | I | [
"is_palindrome",
"is_length_palindromic_number",
"filter_palindromes_and_lengths"
] | 3 | [
[
"filter_palindromes_and_lengths",
"is_length_palindromic_number"
],
[
"filter_palindromes_and_lengths",
"is_palindrome"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3eed39884b409da06f356050f3ed8f472b33daca | 10c3e0e4dae17d690938c600e9437575667e5e05 | |||
v1.0 | instruct | Filter | Filter_50246_I | How can I efficiently find the nearest location from a list of geographical coordinates to a specific point? For example, I have a list of coordinates and I want to find which one is the closest to a given coordinate. What's the best way to do this in Python? | import math
def haversine_distance(coord1, coord2):
"""
Calculate the Haversine distance between two geographical coordinates.
Args:
coord1, coord2: Tuples representing the latitude and longitude of the two coordinates.
Returns:
The Haversine distance in kilometers between the two coordinates... | from solution import haversine_distance, find_nearest_location
def test_haversine_distance():
coord1 = (50.066389, -5.714722)
coord2 = (58.643889, -3.070000)
assert math.isclose(haversine_distance(coord1, coord2), 968.9, rel_tol=1e-3)
def test_find_nearest_location():
target = (34.052235, -118.243683)... | [
{
"docstring": "Calculate the Haversine distance between two geographical coordinates.\n\nArgs:\ncoord1, coord2: Tuples representing the latitude and longitude of the two coordinates.\n\nReturns:\nThe Haversine distance in kilometers between the two coordinates.",
"function_declaration": "def haversine_dist... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from geopy.distance import geodesic\n\ndef find_nearest_location(point, locations):\n \"\"\"\n Returns the nearest location from a list of geographical coordinates to a specific point.\n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00050246",
"row_id": 50246,
"seed_ids": "['Qwen2.5-72B-Instruct_104718']"
} | 0.590931 | Filter_50246 | I | [
"haversine_distance",
"find_nearest_location"
] | 2 | [
[
"find_nearest_location",
"haversine_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 169f19b64ea970169c1779e7bbeb20910515772b | db1938b67605035be5946cead7e47fef998fe07c | |||
v1.0 | instruct | Filter | Filter_50393_I | How can I design a simple text-based game using Python that involves the player making decisions at different stages, leading to different outcomes? | def display_intro():
"""
Display the introduction to the game.
"""
print("Welcome to the Adventure Game!")
print("You find yourself at the entrance of a dark cave.")
print("Your mission is to explore the cave and find the hidden treasure.")
print("Beware of the dangers that may lurk in the s... | import pytest
from io import StringIO
import sys
from solution import (
display_intro,
make_decision,
explore_cave,
investigate_noise,
keep_walking,
sneak_past_dragon,
fight_dragon,
find_treasure,
play_game
)
def test_make_decision(monkeypatch):
monkeypatch.setattr('sys.stdin', ... | [
{
"docstring": "Display the introduction to the game.",
"function_declaration": "def display_intro():",
"function_name": "display_intro",
"parameter_list": "()"
},
{
"docstring": "Prompt the player to make a decision.\n\nParameters:\n- prompt (str): The prompt to display to the player.\n- ch... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def start_game():\n \"\"\"\n This is the starting point of the game.\n \"\"\"\n print(\"You are at home. You have two choices:\")\n print(\"1. Go to the forest.\")\n print(\"... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00050393",
"row_id": 50393,
"seed_ids": "['Qwen2.5-72B-Instruct_104950']"
} | 0.432922 | Filter_50393 | I | [
"display_intro",
"make_decision",
"explore_cave",
"investigate_noise",
"keep_walking",
"sneak_past_dragon",
"fight_dragon",
"find_treasure",
"play_game"
] | 9 | [
[
"explore_cave",
"investigate_noise"
],
[
"explore_cave",
"keep_walking"
],
[
"explore_cave",
"make_decision"
],
[
"investigate_noise",
"fight_dragon"
],
[
"investigate_noise",
"make_decision"
],
[
"investigate_noise",
"sneak_past_dragon"
],
[... | 10 | [] | false | [] | false | pytest | true | [] | true | 02156e7e7834cfd550e1d799d85ce9f26f8615ec | d7e1c527fa55066f4c4a515cc8c4a78819e2200a | |||
v1.0 | instruct | Filter | Filter_50411_I | Can you create a simple web crawler using Python that can scrape a website for all URLs, and also download images from those URLs? It should be a script that can be run from the command line. Please include explanations for the code. | import requests
from bs4 import BeautifulSoup
import os
import urllib.parse
def fetch_html(url):
"""
Fetches the HTML content of the given URL.
"""
response = requests.get(url)
if response.status_code == 200:
return response.text
return None
def extract_urls(html, base_url):
"""
... | from unittest.mock import patch, MagicMock
from solution import fetch_html, extract_urls, extract_image_urls, download_image, crawl_and_download_images
import os
def test_fetch_html():
url = "http://example.com"
with patch("requests.get") as mocked_get:
mocked_get.return_value.status_code = 200
... | [
{
"docstring": "Fetches the HTML content of the given URL.",
"function_declaration": "def fetch_html(url):",
"function_name": "fetch_html",
"parameter_list": "(url)"
},
{
"docstring": "Extracts all the URLs found in the HTML content.",
"function_declaration": "def extract_urls(html, base... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nfrom bs4 import BeautifulSoup\nimport os\nimport urllib.parse\n\ndef get_all_urls(base_url):\n \"\"\"\n Scrape the given base_url for all URLs.\n \"\"\"\n try:\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00050411",
"row_id": 50411,
"seed_ids": "['Qwen2.5-72B-Instruct_104982']"
} | 0.565426 | Filter_50411 | I | [
"fetch_html",
"extract_urls",
"extract_image_urls",
"download_image",
"crawl_and_download_images"
] | 5 | [
[
"crawl_and_download_images",
"download_image"
],
[
"crawl_and_download_images",
"extract_image_urls"
],
[
"crawl_and_download_images",
"extract_urls"
],
[
"crawl_and_download_images",
"fetch_html"
]
] | 4 | [] | false | [] | false | pytest | true | [
"bs4",
"requests"
] | false | 70f6bb147e87c72fc3d01ea80f411677cf7a4b5d | c73bc30705df3183857f0f5ee12a22b25a4c9312 | |||
v1.0 | instruct | Filter | Filter_50498_I | Write a Python script to automate the process of checking a website's SSL certificate expiration date and send an email notification if the certificate is expiring within 30 days. The script should use the `requests` and `smtplib` libraries for the HTTP request and sending emails, respectively. Assume that the email se... | import requests
import ssl
import socket
import smtplib
from datetime import datetime, timedelta
import logging
def get_ssl_expiry_date(hostname):
context = ssl.create_default_context()
with socket.create_connection((hostname, 443)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as s... | import pytest
import socket
from unittest.mock import patch
from datetime import datetime, timedelta
from solution import get_ssl_expiry_date, send_email_notification, check_ssl_and_notify
# Mock SSL certificate expiry date to control the environment
def mock_get_ssl_expiry_date(hostname):
return datetime.utcnow()... | [
{
"docstring": null,
"function_declaration": "def get_ssl_expiry_date(hostname):",
"function_name": "get_ssl_expiry_date",
"parameter_list": "(hostname)"
},
{
"docstring": null,
"function_declaration": "def send_email_notification(smtp_server, smtp_port, smtp_user, smtp_password, to_emai... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nimport smtplib\nimport ssl\nimport logging\nfrom datetime import datetime, timedelta\nfrom OpenSSL import crypto\nfrom socket import socket\nfrom urllib.parse import urlparse\... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00050498",
"row_id": 50498,
"seed_ids": "['Qwen2.5-72B-Instruct_105115']"
} | 0.643508 | Filter_50498 | I | [
"get_ssl_expiry_date",
"send_email_notification",
"check_ssl_and_notify"
] | 3 | [
[
"check_ssl_and_notify",
"get_ssl_expiry_date"
],
[
"check_ssl_and_notify",
"send_email_notification"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | f52b02fb4d7c9abfbbdfd5a141c4adee1e630b48 | 6df13c3e4efb5d9d686bd4fbe03d3386d16d0868 | |||
v1.0 | instruct | Filter | Filter_50686_I | You are tasked with creating a simple Python script that monitors the availability of a specific product on an e-commerce website. The script should check if the product is in stock every hour and send an email notification when the product becomes available. The product's availability can be determined by checking if ... | import requests
from bs4 import BeautifulSoup
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import time
def check_product_availability(url, sold_out_message):
"""
Checks if the product is available on the e-commerce website.
Parameters:
url (str... | import requests
import smtplib
from bs4 import BeautifulSoup
from unittest.mock import patch, MagicMock
import time
from solution import check_product_availability, send_email_notification, monitor_product
# Mock email configuration for testing
email_config = {
'smtp_server': 'smtp.example.com',
'smtp_port': ... | [
{
"docstring": "Checks if the product is available on the e-commerce website.\n\nParameters:\nurl (str): The URL of the product page.\nsold_out_message (str): The message displayed when the product is sold out.\n\nReturns:\nbool: True if the product is available, False otherwise.",
"function_declaration": "... | [
0,
0,
0,
1,
0,
1,
1,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nimport time\nfrom bs4 import BeautifulSoup\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\ndef check_product_availabil... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00050686",
"row_id": 50686,
"seed_ids": "['Qwen2.5-72B-Instruct_105412']"
} | 0.47356 | Filter_50686 | I | [
"check_product_availability",
"send_email_notification",
"monitor_product"
] | 3 | [
[
"monitor_product",
"check_product_availability"
],
[
"monitor_product",
"send_email_notification"
]
] | 2 | [] | false | [] | false | pytest | true | [
"bs4",
"requests"
] | false | a458928977134fcea17c3a913182a40a7da13f55 | 12e5715831fe02cc6433caf09e0e485218d08b30 | |||
v1.0 | instruct | Filter | Filter_50991_I | How can I use Python to automate the process of monitoring the stock market and sending alerts based on specific conditions, such as a stock price increase or decrease? | import requests
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# Stock market API URL template
# You would need an API key to access the stock data from most services
STOCK_API_URL = "https://www.alphavantage.co/query"
API_KEY = "<Your Alpha Vantage API Key>"
def ge... | from solution import get_stock_price, send_email_alert, monitor_stock
def mock_get_stock_price(stock_symbol):
return 150.00
def mock_send_email_alert(subject, body, to_email):
assert subject is not None
assert body is not None
assert to_email is not None
def test_get_stock_price(monkeypatch):
def... | [
{
"docstring": "Fetches the current stock price for a given stock symbol from Alpha Vantage API.",
"function_declaration": "def get_stock_price(stock_symbol):",
"function_name": "get_stock_price",
"parameter_list": "(stock_symbol)"
},
{
"docstring": "Sends an email alert with a given subject... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import yfinance as yf\nimport smtplib\nfrom email.mime.text import MIMEText\n\ndef fetch_stock_price(stock_ticker):\n \"\"\"\n Fetches the current stock price of the given ticker.\n \... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00050991",
"row_id": 50991,
"seed_ids": "['Qwen2.5-72B-Instruct_105897']"
} | 0.420318 | Filter_50991 | I | [
"get_stock_price",
"send_email_alert",
"monitor_stock"
] | 3 | [
[
"monitor_stock",
"get_stock_price"
],
[
"monitor_stock",
"send_email_alert"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 75d4b5d7acb1be9c664991fd217211d9a288a946 | d08c028466331299ad4bffdd32011c58fa9989e4 | |||
v1.0 | instruct | Filter | Filter_51115_I | Design a simple web crawler in Python that can extract all URLs from a given webpage. Please include error handling for common issues, such as handling invalid URLs, network errors, and parsing errors. Additionally, ensure that the crawler follows the robots.txt rules for the site being crawled. | import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
import re
from urllib.robotparser import RobotFileParser
def is_valid_url(url):
parts = urlparse(url)
return parts.scheme in {"http", "https"} and bool(parts.netloc)
def get_robots_parser(base_url):
robots_url = urljo... | import pytest
from unittest.mock import patch, Mock
from solution import extract_urls
def test_extract_urls_valid_url():
url = "http://example.com"
response_content = '''
<html>
<head></head>
<body>
<a href="page1.html">Page 1</a>
<a href="http://example.com/page2.ht... | [
{
"docstring": null,
"function_declaration": "def is_valid_url(url):",
"function_name": "is_valid_url",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def get_robots_parser(base_url):",
"function_name": "get_robots_parser",
"parameter_list": "(base_url... | [
0,
0,
1,
0,
0,
1,
0,
0,
1
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urlparse, urljoin\nimport re\nimport robotexclusionrulesparser\n\ndef get_robots_txt(url):\n \"\"\"\n Retrieves a... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00051115",
"row_id": 51115,
"seed_ids": "['Qwen2.5-72B-Instruct_106109']"
} | 0.686487 | Filter_51115 | I | [
"is_valid_url",
"get_robots_parser",
"can_fetch_url",
"extract_urls"
] | 4 | [
[
"extract_urls",
"can_fetch_url"
],
[
"extract_urls",
"get_robots_parser"
],
[
"extract_urls",
"is_valid_url"
]
] | 3 | [] | false | [] | false | pytest | true | [
"bs4",
"requests"
] | false | c83cad40d9c5200303b4dd9aaaf2ad44fea5e1c1 | 09e911f88789f9e06e9b7c3ad764617ee0407208 | |||
v1.0 | instruct | Filter | Filter_51134_I | I want to simulate a simple double pendulum system using Python. Can you provide a basic code that could help me get started with the simulation, including the visualization of the pendulum's movement? | import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
def double_pendulum_deriv(t, y, m1, m2, L1, L2, g):
θ1, θ2, p1, p2 = y
δ = θ2 - θ1
sinδ = np.sin(δ)
cosδ = np.cos(δ)
denominator1 = (m1 + m2) * L1 - m2 * L1 * cosδ * cosδ
denominator2 = (L2/L1) * denominat... | import numpy as np
from solution import simulate_double_pendulum
def test_simulate_double_pendulum_initial_conditions():
θ1_init, θ2_init = np.pi/2, np.pi/2
p1_init, p2_init = 0, 0
m1, m2 = 1.0, 1.0
L1, L2 = 1.0, 1.0
g = 9.81
T = 1
dt = 0.01
t, x1, y1, x2, y2 = simulate_double_pend... | [
{
"docstring": null,
"function_declaration": "def double_pendulum_deriv(t, y, m1, m2, L1, L2, g):",
"function_name": "double_pendulum_deriv",
"parameter_list": "(t, y, m1, m2, L1, L2, g)"
},
{
"docstring": null,
"function_declaration": "def simulate_double_pendulum(θ1_init, θ2_init, p1_i... | [
0,
0,
0,
1,
0,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n# Constants\ng = 9.81 # Acceleration due to gravity\nL1 = 1.0 # Length of first rod\nL2... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00051134",
"row_id": 51134,
"seed_ids": "['Qwen2.5-72B-Instruct_106139']"
} | 0.306712 | Filter_51134 | I | [
"double_pendulum_deriv",
"simulate_double_pendulum",
"visualize_double_pendulum"
] | 3 | [
[
"simulate_double_pendulum",
"double_pendulum_deriv"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"scipy"
] | false | 4638a08e71da149a30c3aaeac67d911825abdceb | 266dee621d629db0f4126531940222ce07af7c76 | |||
v1.0 | instruct | Filter | Filter_51196_I | How can I develop a skill for my Amazon Echo device using Alexa Skills Kit (ASK) in Python? | def lambda_handler(event, context):
"""
Main entry point for the Alexa skill.
"""
if event['request']['type'] == "LaunchRequest":
return on_launch(event['request'])
elif event['request']['type'] == "IntentRequest":
return on_intent(event['request'])
elif event['request']['type'] ... | from solution import lambda_handler, on_launch, on_intent, on_session_ended, handle_my_intent
def test_lambda_handler_launch_request():
event = {'request': {'type': 'LaunchRequest'}}
context = {}
response = lambda_handler(event, context)
assert response['response']['outputSpeech']['text'] == "Welcome t... | [
{
"docstring": "Main entry point for the Alexa skill.",
"function_declaration": "def lambda_handler(event, context):",
"function_name": "lambda_handler",
"parameter_list": "(event, context)"
},
{
"docstring": null,
"function_declaration": "def on_launch(request):",
"function_name": "... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from ask_sdk_core.skill_builder import SkillBuilder\nfrom ask_sdk_core.dispatch_components import AbstractRequestHandler\nfrom ask_sdk_core.dispatch_components import AbstractExceptionHandler\... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00051196",
"row_id": 51196,
"seed_ids": "['Qwen2.5-72B-Instruct_106239']"
} | 0.31115 | Filter_51196 | I | [
"lambda_handler",
"on_launch",
"on_intent",
"on_session_ended",
"handle_my_intent",
"build_response"
] | 6 | [
[
"handle_my_intent",
"build_response"
],
[
"lambda_handler",
"on_intent"
],
[
"lambda_handler",
"on_launch"
],
[
"lambda_handler",
"on_session_ended"
],
[
"on_intent",
"handle_my_intent"
],
[
"on_launch",
"build_response"
],
[
"on_session_... | 7 | [] | false | [] | false | pytest | true | [] | true | e11ea4347a120d61888e80cf03ab4f025b8fb543 | 08563322f3282db6665e730c6b2bc954de89c3ea | |||
v1.0 | instruct | Filter | Filter_51271_I | Can you create a Python script that would allow a user to input a directory path, and then the script would count and display the number of files and directories within that path? It should also be able to show the total size of all files in the directory in human-readable format (e.g., KB, MB, GB). The script should h... | import os
def human_readable_size(size, decimal_places=2):
"""
Convert size in bytes to a human-readable format.
"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024:
return f"{size:.{decimal_places}f} {unit}"
size /= 1024
def count_files_and_directories(path):
... | from solution import count_files_and_directories
def test_nonexistent_path():
result = count_files_and_directories("/path/does/not/exist")
assert result == "Error: The provided path does not exist."
def test_permission_denied():
result = count_files_and_directories("/root")
assert result == "Error: Pe... | [
{
"docstring": "Convert size in bytes to a human-readable format.",
"function_declaration": "def human_readable_size(size, decimal_places=2):",
"function_name": "human_readable_size",
"parameter_list": "(size, decimal_places=2)"
},
{
"docstring": "Counts the number of files and directories i... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "Magpie-Filter-89K_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef get_human_readable_size(size, decimal_places=2):\n \"\"\"\n Converts a size in bytes to a human-readable format (KB, MB, GB, etc.)\n \"\"\"\n for unit in ['B', 'KB... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00051271",
"row_id": 51271,
"seed_ids": "['Qwen2.5-72B-Instruct_106366']"
} | 0.626398 | Filter_51271 | I | [
"human_readable_size",
"count_files_and_directories"
] | 2 | [
[
"count_files_and_directories",
"human_readable_size"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f17094e87d60e9e81f6ee9b3cce04e846d192e24 | fa174ff556ee09846be39f9036811045a25427ac |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.