source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
magic_instruct_75k | 57,409 | Write a Python function to find the highest version number for each unique file name from a list of tuples representing file names and their corresponding version numbers. The function should return a dictionary where the keys are the unique file names and the values are the highest version numbers.
The code should st... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def find_highest_versions(file_list: List[Tuple[str, int]]) -> Dict[str, int]:
"""
Finds the highest version number for each unique file name from a list of tuples.
Args:
file_l... |
magic_instruct_75k | 57,416 | Write a Python function to serialize a list of product dictionaries into a specific format. Each product dictionary contains the product's `id`, `name`, `price`, and `quantity`. The function should return a list of dictionaries where the `price` is formatted as a string with a dollar sign and two decimal places.
The f... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Union
def serialize_products(products: List[Dict[str, Union[int, str, float]]]) -> List[Dict[str, Union[int, str, float]]]:
"""
Serialize a list of product dictionaries into a specific format.
... |
magic_instruct_75k | 57,417 | Write a Python function to filter labeled data based on a specified label criteria and update the original data dictionary with the filtered results. Additionally, the function should return the number of data points that were filtered out.
The function should start with:
```python
from typing import Dict, List, Tuple... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Tuple
def filter_labeled_data(data: Dict[str, List[any]], label_key: str, label_filter_criteria: str) -> Tuple[Dict[str, List[any]], int]:
"""
Filters labeled data based on a specified label crite... |
magic_instruct_75k | 57,437 | Write a Python function to process benchmark data and return specific information in a specific format. The function should take in a list of benchmark names, corresponding benchmark files, and a list of tasks. The function should then return the first benchmark name, the first benchmark file, and the list of tasks.
T... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Optional
def process_benchmark_data(benchmark_names: List[str], benchmark_files: List[str], tasks: List[str]) -> Tuple[Optional[str], Optional[str], List[str]]:
"""
Processes benchmark data and r... |
magic_instruct_75k | 57,462 | Write a Python function to extract unique elements from a given list of integers while preserving their original order. The function should not use any external libraries and should be implemented using Python's built-in data structures and methods.
The code should start with:
```python
from typing import List
def ru... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def run(input_list: List[int]) -> List[int]:
"""
Extracts unique elements from a given list of integers while preserving their original order.
Args:
input_list (List[int]): The list of integ... |
magic_instruct_75k | 57,474 | Write a Python function to simulate a sequence of operations on a set of integers. The operations are represented by a list of tuples, where each tuple consists of an integer `f` (1, 2, or 3) and an integer `s`. The meaning of each operation is as follows:
- If `f` is 1, insert `s` into the set `s`.
- If `f` is 2, eras... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def simulate_operations(n: int, v: List[Tuple[int, int]]) -> None:
"""
Simulate a sequence of operations on a set of integers and print the result of each query of type 3.
Args:
n (in... |
magic_instruct_75k | 57,483 | Write a Python function to count the number of connected components in a graph represented by an adjacency matrix. The function should use a depth-first search (DFS) algorithm to traverse the graph and identify the connected components. The adjacency matrix `M` is a 2D list where `M[i][j]` is 1 if there is an edge betw... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def count_connected_components(M: List[List[int]]) -> int:
"""
Count the number of connected components in a graph represented by an adjacency matrix.
Args:
M (List[List[int]]): The adjacenc... |
magic_instruct_75k | 57,489 | Write a Python function to calculate the number of unique paths from the top-left corner to the bottom-right corner of an m x n grid, where you can only move right or down.
The code should start with:
```python
from typing import List
def unique_paths(m: int, n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
from typing import List
def unique_paths(m: int, n: int) -> int:
"""
Calculate the number of unique paths from the top-left corner to the bottom-right corner of an m x n grid.
Args:
m (int): The number of row... |
magic_instruct_75k | 57,495 | Write a Python function to automate the setup of Git hooks for a software project. The function should perform the following tasks:
1. Check if the system has the necessary helper function `check_help` available.
2. Prepare and set up the Git hooks for the repository using the `prepare_git_hooks` function.
The `check_... | Here is the Python code to solve the given problem in the markdown block:
```python
def setup_git_hooks():
"""
Automates the setup of Git hooks for a software project.
This function performs the following tasks:
1. Checks if the system has the necessary helper function `check_help` available.
2. Pr... |
magic_instruct_75k | 57,508 | Write a Python function to calculate the output shape of a convolutional neural network (CNN) after applying a MaxPooling layer followed by a convolutional layer. The input shape is given in the form of a tuple `(height, width, channels)`. The MaxPooling layer uses a pool size of `(2, 2)` and default strides, while the... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_output_shape(input_shape: tuple) -> tuple:
"""
Calculate the output shape of a CNN after applying a MaxPooling layer followed by a convolutional layer.
Args:
input_shape (tuple): The input shape of the... |
magic_instruct_75k | 57,511 | Write a Python function `create_setup_script` that generates a setup script for a Python package. The setup script should include specific configuration settings to ensure the package's proper functionality. The function should take two boolean parameters: `include_package_data` and `zip_safe`. The function should retu... | Here is the Python code to solve the given problem in the markdown block:
```python
def create_setup_script(include_package_data: bool, zip_safe: bool) -> str:
"""
Generates a setup script for a Python package with the specified configuration settings.
Args:
include_package_data (bool): A boolean i... |
magic_instruct_75k | 57,526 | Write a Python function to parse a list of dependencies into a dictionary where the keys are the component names and the values are lists of corresponding dependency versions. Each dependency is represented as a tuple containing the name of the component and the specific version of the dependency.
The code should star... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def parse_dependencies(dependencies: List[Tuple[str, str]]) -> Dict[str, List[str]]:
"""
Parses a list of dependencies into a dictionary where the keys are the component names
and the va... |
magic_instruct_75k | 57,532 | Write a Python function to identify and return a list of tuples containing the import statements that violate the `from __future__ import annotations` directive in a given code snippet. Each tuple should include the violating import statement and the line number where it occurs. The function should be named `find_inval... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def find_invalid_imports(code: str) -> List[Tuple[str, int]]:
"""
Identifies and returns a list of tuples containing the import statements that violate
the `from __future__ import annotations`... |
magic_instruct_75k | 57,557 | Write a Python function to implement the insertion sort algorithm. The function should take an unsorted list of integers as input and return a new list containing the elements sorted in non-decreasing order. The insertion sort algorithm works by iteratively building a sorted portion of the list, one element at a time. ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def insertion_sort(lst: List[int]) -> List[int]:
"""
Sorts a list of integers using the insertion sort algorithm.
Args:
lst (List[int]): The unsorted list of integers.
Returns:
... |
magic_instruct_75k | 57,572 | Write a Python function to simulate the allocation of students to tables in a school cafeteria. Each table has a maximum capacity, and students should be distributed evenly across the tables as much as possible. If there are more students than can be accommodated at the tables, the remaining students should be assigned... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def allocate_tables(students: List[int], table_capacity: int) -> List[List[int]]:
"""
Simulate the allocation of students to tables in a school cafeteria.
Args:
students (List[int]): A list ... |
magic_instruct_75k | 57,576 | Write a Python function to extract URL mappings from a list of URL patterns. Each URL pattern is represented as a tuple containing the URL path, the view class, and the name of the URL. The function should return a dictionary where the keys are the URL names and the values are the corresponding view classes.
The code ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict, Any
def extract_url_mappings(url_patterns: List[Tuple[str, Any, str]]) -> Dict[str, Any]:
"""
Extracts URL mappings from a list of URL patterns.
Args:
url_patterns (List[Tuple[... |
magic_instruct_75k | 57,664 | Write a Python function `getOperation` that takes a command code as an integer input and returns the corresponding operation as a string. The function should map specific hexadecimal command codes to their corresponding operation names. If the input command code does not match any of the given codes, the function shoul... | Here is the Python code to solve the given problem in the markdown block:
```python
def getOperation(command_code: int) -> str:
"""
Returns the corresponding operation name for a given command code.
Args:
command_code (int): The hexadecimal command code to look up.
Returns:
str: The co... |
magic_instruct_75k | 57,665 | Write a Python function to validate and set the name of the primary key for a given table in a custom database system. The function should ensure that the table name and primary key name are non-empty strings, and that the primary key name consists only of uppercase letters, underscores, and digits, and does not start ... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def set_primary_key(table_name: str, primary_key_name: str) -> bool:
"""
Validates and sets the name of the primary key for a given table in a custom database system.
Args:
table_name (str): The name of t... |
magic_instruct_75k | 57,666 | Write a Python function to identify contiguous blocks of free time within a given list of busy time slots. The function should take a list of tuples, where each tuple represents a busy time slot with a start and end `datetime` object. The function should return a list of tuples representing the free time blocks.
The c... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
from datetime import datetime
def find_free_blocks(time_slots: List[Tuple[datetime, datetime]]) -> List[Tuple[datetime, datetime]]:
"""
Identify contiguous blocks of free time within a given list ... |
magic_instruct_75k | 57,671 | Write a Python function to find the positions of the maximum and minimum values in a given list of integers. If there are multiple occurrences of the maximum or minimum value, the function should return the position of the first occurrence. The function should start with:
```python
from typing import List, Tuple
def f... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def find_max_min_positions(nums: List[int]) -> Tuple[int, int]:
"""
Find the positions of the maximum and minimum values in a list of integers.
Args:
nums (List[int]): A list of integ... |
magic_instruct_75k | 57,706 | Write a Python function to generate an OpenSSL command for creating a certificate signing request (CSR) based on a given key name. The function should accept a string representing the name of the key file without the file extension and return the corresponding OpenSSL command as a string.
The OpenSSL command should be... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_openssl_command(key_name: str) -> str:
"""
Generate an OpenSSL command for creating a certificate signing request (CSR) based on the given key name.
Args:
key_name (str): The name of the key file withou... |
magic_instruct_75k | 57,716 | Write a Python function to extract the base name of an image file from a given string that follows a specific pattern. The input string represents an image file name in the format "name_x4.extension", where "name" is the base name of the image, "x4" is a fixed pattern, and "extension" is the file extension. The functio... | Here is the Python code to solve the given problem in the markdown block:
```python
def extract_image_name(img_name: str) -> str:
"""
Extracts the base name of an image file from a string that follows the pattern "name_x4.extension".
Args:
img_name (str): A string representing the image file name i... |
magic_instruct_75k | 57,724 | Write a Python function to convert an RGB color value to its corresponding hexadecimal representation. The RGB color model consists of three components: red, green, and blue, each with an integer value between 0 and 255. The hexadecimal representation of a color is a six-digit combination of three two-digit hexadecimal... | Here is the Python code to solve the given problem in the markdown block:
```python
def rgb_to_hex(r: int, g: int, b: int) -> str:
"""
Converts an RGB color value to its corresponding hexadecimal representation.
Args:
r (int): The red component of the color, an integer between 0 and 255.
g ... |
magic_instruct_75k | 57,726 | Write a Python function to calculate the total amount of gold acquired by an ambassador from a list of transactions. Each transaction is represented as a dictionary with keys "type" and "amount". The function should only consider transactions of type "acquisition" and ignore all other types. The function should return ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def calculate_total_gold(transactions: List[Dict[str, int]]) -> int:
"""
Calculate the total amount of gold acquired by an ambassador from a list of transactions.
Args:
transactions (L... |
magic_instruct_75k | 57,737 | Write a Python function to determine whether a given number is an Armstrong number. An Armstrong number (also known as a narcissistic number) is a number that is the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.
The functi... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_armstrong_number(n: int) -> bool:
"""
Determines whether a given number is an Armstrong number.
An Armstrong number (or narcissistic number) is a number that is the sum of its own digits
each raised to the power ... |
magic_instruct_75k | 57,738 | Write a Python function to generate environment variable strings for a machine learning platform called Rafiki. The function should take a configuration dictionary as input and produce a single string that represents the environment variables in the format required for deployment. Each environment variable should be pr... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_env_variables(config: dict) -> str:
"""
Generates a string of environment variables in the format required for deploying the Rafiki platform.
Args:
config (dict): A dictionary containing the configurati... |
magic_instruct_75k | 57,741 | Write a Python function to process the result of a service availability check. The function should take the test name and the return status as input and perform the necessary actions based on the validation outcome. The return status is an integer where 0 indicates success and any other value indicates failure. The fun... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_result(test_name: str, return_status: int) -> bool:
"""
Process the result of a service availability check.
Args:
test_name (str): The name of the test being performed.
return_status (int): The r... |
magic_instruct_75k | 57,742 | Write a Python function to calculate the discounted price of an item after applying a given percentage discount. The function should take two parameters: `price` (an integer representing the original price of the item) and `discount_rate` (a float representing the percentage discount to be applied). The function should... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_discount(price: int, discount_rate: float) -> float:
"""
Calculate the discounted price after applying the given discount rate.
Args:
price (int): The original price of the item.
discount_rate ... |
magic_instruct_75k | 57,748 | Write a Python function to find the k-th largest element in a given array of integers efficiently. The function should use a min-heap to achieve this in O(n log k) time complexity.
The code should start with:
```python
from typing import List
import heapq
def findKthLargest(nums: List[int], k: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import heapq
def findKthLargest(nums: List[int], k: int) -> int:
"""
Find the k-th largest element in the given array of integers using a min-heap.
Args:
nums (List[int]): The array of integ... |
magic_instruct_75k | 57,757 | Write a Python function `simulate_dice_roll(dice_roll)` that simulates the rolling of a custom six-sided dice. The dice has unique symbols on each face, represented by the following strings: `red`, `eye = ['o', ' ', 'o']`. The `dice_roll` variable holds the result of the dice roll, which is an integer between 1 and 6 (... | Here is the Python code to solve the given problem in the markdown block:
```python
def simulate_dice_roll(dice_roll: int) -> str:
"""
Simulates the rolling of a custom six-sided dice and returns the corresponding dice face as a string.
Args:
dice_roll (int): The result of the dice roll, an integer... |
magic_instruct_75k | 57,764 | Write a Python function to calculate the total number of stars for all GitHub repositories that have more than 0 stars. Each repository is represented as a dictionary with the keys "name" (string), "owner" (string), and "stars" (integer). The function should filter out repositories with 0 stars and sum the stars of the... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def total_stars(repositories: List[Dict[str, str]]) -> int:
"""
Calculate the total number of stars for all GitHub repositories that have more than 0 stars.
Args:
repositories (List[Di... |
magic_instruct_75k | 57,767 | Write a Python function to read integers from a file, calculate the sum of all the integers, and find the maximum and minimum values among them. The file contains a series of integers, each on a new line. The function should return a tuple containing the sum, maximum, and minimum values.
The code should start with:
``... | Here is the Python code to solve the given problem in the markdown block:
```python
def read_and_process_file(file_path: str) -> tuple:
"""
Reads integers from a file, calculates their sum, and finds the maximum and minimum values.
Args:
file_path (str): The path to the file containing integers, ea... |
magic_instruct_75k | 57,791 | Write a Python function to generate an Alembic migration script for adding a new column to a specified database table. The function should take the table name, the column name, and the new column type as input and return a string representing the Alembic migration script. The generated script should include both the `u... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_alembic_migration(table_name: str, column_name: str, column_type: str) -> str:
"""
Generates an Alembic migration script to add a new column to a specified database table.
Args:
table_name (str): The na... |
magic_instruct_75k | 57,807 | Write a Python function to automate the compilation process for a software project. The function should perform the following tasks:
1. If the variable `betaMark` is not empty, append "DEMO" to its value and store it back in `betaMark`.
2. Print the compile-time headers in the format "// Compiled: Month Day, Year Hour:... | Here is the Python code to solve the given problem in the markdown block:
```python
from datetime import datetime
def compile_project(betaMark: str) -> None:
"""
Automates the compilation process for a software project.
Args:
betaMark (str): A string that may contain a beta mark.
Returns:
... |
magic_instruct_75k | 57,813 | Write a Python function to generate a bootstrap sample from a given dataset. A bootstrap sample is a random sample with replacement from the original dataset. The function should take the dataset and the desired sample size as input and return the bootstrap sample.
The code should start with:
```python
from typing imp... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def gen_bs_sample(dataset: List[int], sample_size: int) -> List[int]:
"""
Generates a bootstrap sample from the given dataset.
Args:
dataset (List[int]): The dataset from which... |
magic_instruct_75k | 57,814 | Write a Python function to compress a given string by replacing repeated characters with the character followed by the count of the repetition. If the compressed string is not shorter than the original string, the function should return the original string.
The code should start with:
```python
def compress_string(s: ... | Here is the Python code to solve the given problem in the markdown block:
```python
def compress_string(s: str) -> str:
"""
Compresses a given string by replacing repeated characters with the character followed by the count of the repetition.
If the compressed string is not shorter than the original string,... |
magic_instruct_75k | 57,817 | Create a Python class `LabelManager` that manages labels associated with integer keys. The class should provide methods to add, retrieve, and remove labels for specific keys. The class should adhere to the following specifications:
1. Implement a method `add_label(key: int, label: str)` to add a label for a given key.
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
class LabelManager:
def __init__(self):
self.labels: Dict[int, List[str]] = {}
def add_label(self, key: int, label: str) -> None:
"""
Adds the given label for the specified... |
magic_instruct_75k | 57,824 | Write a Python function to determine which modules from a given list are available for import in a predefined module management system. The function should return a dictionary where the keys are the module names and the values are boolean flags indicating whether the module is available (`True`) or not (`False`).
The ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
# Predefined list of available modules
__all__ = ["configure", "core", "draw", "io", "interp", "qc", "retrieve"]
def available_modules(module_list: List[str]) -> Dict[str, bool]:
"""
Determines wh... |
magic_instruct_75k | 57,837 | Write a Python function to insert a string value into a list of strings associated with a key in a dictionary, following a specific lexicographical order rule. The function should insert the value at the first position where it is lexicographically greater than the existing elements in the list. If there are multiple e... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def insert_map_value(uni: Dict[str, List[str]], key: str, value: str) -> None:
"""
Inserts a string value into the list associated with a key in a dictionary,
following a specific lexicographic... |
magic_instruct_75k | 57,840 | Write a Python function to implement a custom `randrange` function that mimics the behavior of Python's `random.randrange` function. The function should take two parameters, `start` and `stop`, and return a randomly selected element from the range created by `start` (inclusive) and `stop` (exclusive). If the `start` pa... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
def custom_randrange(start: int, stop: int = None) -> int:
"""
Generate a random integer between `start` (inclusive) and `stop` (exclusive).
If `stop` is not provided, the function generates a random integer ... |
magic_instruct_75k | 57,872 | Write a Python function to process a list of assets and their resolutions. The function should identify the assets that do not match a specified collateral asset and verify that their resolutions are equivalent to the values in a synthetic asset map. The function should return a list of such assets.
The code should st... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def process_assets(ASSET_RESOLUTION: Dict[str, str], COLLATERAL_ASSET: str, SYNTHETIC_ASSET_MAP: Dict[str, str]) -> List[str]:
"""
Process a list of assets and their resolutions to identify assets ... |
magic_instruct_75k | 57,879 | Write a Python function to implement a secure aggregator for processing sensitive data. The aggregator should handle both weighted and unweighted data and apply zeroing and clipping operations as specified. The function should take in a list of floating-point numbers representing the sensitive data, a boolean indicatin... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def secure_aggregator(data: List[float], is_weighted: bool, zeroing: bool, clipping: bool) -> float:
"""
Securely aggregates sensitive data based on specified operations.
Args:
data (List[fl... |
magic_instruct_75k | 57,906 | Write a Python function `parse_bluegenelog` that takes two parameters:
- `parsed`: a dictionary containing keys 'sock', 'number', 'timestamp', 'core1', 'timestamp_bgl', 'core2', 'source', 'service', 'level', and 'message' with corresponding values.
- `parsed_bluegenelog`: a list containing 10 elements.
The function sh... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def parse_bluegenelog(parsed: Dict[str, any], parsed_bluegenelog: List[any]) -> Dict[str, any]:
"""
Parses the `parsed_bluegenelog` list and constructs a new dictionary with specific key-value pair... |
magic_instruct_75k | 57,909 | Write a Python function to analyze the frequency of words in a given text. The function should take a string of text as input and output a list of unique words along with their frequencies in descending order. The function should ignore punctuation and treat uppercase and lowercase letters as equivalent. Additionally, ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
import re
def word_frequency(text: str) -> List[Tuple[str, int]]:
"""
Analyzes the frequency of words in a given text and returns a list of unique words
along with their frequencies in descend... |
magic_instruct_75k | 57,918 | Write a Python function to calculate the maximum profit that can be obtained by making a single transaction (i.e., buying one share of stock and selling it later) from a given list of daily stock prices. The function should ensure that the stock is sold before it is bought again. The code should start with:
```python
f... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def maxProfit(prices: List[int]) -> int:
"""
Calculate the maximum profit that can be obtained by making a single transaction
(buying one share and selling it later) from a given list of daily stock ... |
magic_instruct_75k | 57,932 | Write a Python function `process_chunks(chunks)` that processes a list of chunks, where each chunk is a list of two elements. The function should iterate through the chunks and perform the following operations:
1. Calculate a value `val` based on the elements of the current chunk and the next chunk.
2. If `val` is `Non... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_chunks(chunks: List[List[int]]) -> List[List]:
"""
Processes a list of chunks and appends certain elements to a sorting list based on specific conditions.
Args:
chunks (List[List... |
magic_instruct_75k | 57,960 | Write a Python function to determine the compatibility of given JDK versions with a specified minimum required version. The function should take a list of dictionaries, where each dictionary represents a JDK with its version and compliance information. The function should return a list of JDK versions that are complian... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def compare_versions(version1: str, version2: str) -> int:
"""
Compare two version strings.
Args:
version1 (str): The first version string.
version2 (str): The second version s... |
magic_instruct_75k | 57,963 | Write a Python function `processLogMessage` that processes a log message and extracts specific information based on predefined rules. The function should take a log message as input and return a dictionary containing the extracted information. The rules for extraction are as follows:
1. If the log message contains the ... | Here is the Python code to solve the given problem in the markdown block:
```python
def processLogMessage(log_message: str) -> dict:
"""
Processes a log message and extracts specific information based on predefined rules.
Args:
log_message (str): The log message to be processed.
Returns:
... |
magic_instruct_75k | 57,981 | Write a Python function to parse job submission information for a high-performance computing (HPC) system. The job submission information is provided in a specific format, where each line starts with `#$`, followed by a space, and then a key-value pair. The keys represent different attributes of the job submission, suc... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
import re
def parse_job_info(info: str) -> Dict[str, str]:
"""
Parses job submission information and extracts key-value pairs.
Args:
info (str): A string representing the job submission info... |
magic_instruct_75k | 57,982 | Write a Python function to update a message dictionary with a new key-value pair for tokens. The function should take in two parameters: `message`, a dictionary representing the message, and `tokens`, a list of tokens. The function should add a new key "token" to the `message` dictionary with the value being the list o... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def update_message_with_token(message: Dict[str, str], tokens: List[str]) -> Dict[str, str]:
"""
Updates the message dictionary with a new key-value pair for tokens if the tokens list is not empty.... |
magic_instruct_75k | 57,996 | Write a Python function to format a dictionary of equation keyword arguments into a specific string format. Each keyword argument in the dictionary represents an equation, with the key being the equation name and the value being the equation itself. The function should return a formatted string that lists the equations... | Here is the Python code to solve the given problem in the markdown block:
```python
def format_equations(equation_kwargs: dict) -> str:
"""
Formats a dictionary of equation keyword arguments into a specific string format.
Args:
equation_kwargs (dict): A dictionary where each key is an equation name... |
magic_instruct_75k | 58,013 | Write a Bash script that automates the process of logging in to Azure, creating a Cosmos DB instance, and retrieving the primary master key. The script should store the retrieved URI and key in separate variables and print them to the standard output.
The script should start with:
```bash
#!/bin/bash
# Azure service ... | Here is the Python code to solve the given problem in the markdown block:
```bash
#!/bin/bash
# Azure service principal credentials
CLIENT_ID="your_client_id"
CLIENT_KEY="your_client_key"
TENANT_ID="your_tenant_id"
# Cosmos DB details
dbname="your_cosmosdb_name"
resourcegroup="your_resource_group"
# Log in to Azure ... |
magic_instruct_75k | 58,040 | Write a Python function to calculate the expected shape of grouped points and query points for a point cloud processing layer. The function should take two inputs: `input_dims`, an integer representing the input dimensions for the points, and `group_size`, an integer representing the size of each group. The function sh... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_expected_shape(input_dims: int, group_size: int) -> dict:
"""
Calculate the expected shape of grouped points and query points for a point cloud processing layer.
Args:
input_dims (int): The input dimen... |
magic_instruct_75k | 58,042 | Create a Python decorator named `assert_stringlist` that validates the input arguments of a function. The decorator should ensure that all input arguments are either a list of strings or can be converted to one. If any argument fails this validation, the decorator should raise a `ValueError` with an appropriate error m... | Here is the Python code to solve the given problem in the markdown block:
```python
def assert_stringlist(func):
"""
A decorator that validates the input arguments of a function.
Ensures that all arguments are either a list of strings or can be converted to one.
Args:
func (function): The funct... |
magic_instruct_75k | 58,049 | Write a Python function to find the difference between the maximum and minimum values in a given list of integers. The function should handle lists of any length, including empty lists, and return `None` for empty lists. The code should start with:
```python
from typing import List, Optional
def find_difference(lista:... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def find_difference(lista: List[int]) -> Optional[int]:
"""
Calculate the difference between the maximum and minimum values in a list of integers.
Args:
lista (List[int]): A list o... |
magic_instruct_75k | 58,057 | Write a Python function to perform integer division without using the division operator (`/` or `//`). The function should take two integer inputs, `h` and `t`, representing the dividend and divisor, respectively. The function should return the result of dividing `h` by `t` without using the division operator.
The cod... | Here is the Python code to solve the given problem in the markdown block:
```python
def integer_division(h: int, t: int) -> int:
"""
Perform integer division without using the division operator (`/` or `//`).
Args:
h (int): The dividend.
t (int): The divisor.
Returns:
int: The ... |
magic_instruct_75k | 58,061 | Write a Python function to check whether a given user belongs to a specific group. The function should take a user object and a group name as input and return a boolean value indicating whether the user belongs to the specified group. The `user` object has a method `groups` which returns a queryset of groups to which t... | Here is the Python code to solve the given problem in the markdown block:
```python
def has_group(user, group_name) -> bool:
"""
Checks whether a given user belongs to a specific group.
Args:
user: An object representing the user, which has a method `groups` that returns a queryset of groups.
... |
magic_instruct_75k | 58,072 | Write a Python function to calculate the Euclidean distance between two points in a 2D plane. The function should take two tuples, each containing the x and y coordinates of the respective points, and return the distance rounded to two decimal places.
The code should start with:
```python
import math
def calculate_di... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def calculate_distance(point1: tuple, point2: tuple) -> float:
"""
Calculate the Euclidean distance between two points in a 2D plane.
Args:
point1 (tuple): A tuple containing the x and y coordinates of ... |
magic_instruct_75k | 58,080 | Write a Python function to count the occurrences of each unique file extension in a list of file paths. The function should return a dictionary where the keys are the file extensions (or an empty string for files with no extension) and the values are the counts of files with those extensions.
The code should start wit... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_file_extensions(file_paths: List[str]) -> Dict[str, int]:
"""
Counts the occurrences of each unique file extension in a list of file paths.
Args:
file_paths (List[str]): A li... |
magic_instruct_75k | 58,083 | Write a Python function to process GPS signal strength and pseudorange observations from different satellites. The function should populate a dictionary `p_range_code` based on the signal strength conditions provided. The function should return the populated `p_range_code` dictionary.
The function should start with:
`... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_signal(signal_strength: int, p_range: dict) -> dict:
"""
Process GPS signal strength and pseudorange observations to populate the p_range_code dictionary.
Args:
signal_strength (int): The signal strength... |
magic_instruct_75k | 58,088 | Write a Python function to calculate the sum of elements in a container. The function should be able to handle various types of containers, such as lists, tuples, and sets. Your task is to implement the function `calculate_sum` that takes a single argument, which is the container of elements. The function should return... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Iterable
def calculate_sum(container: Iterable[int]) -> int:
"""
Calculate the sum of elements in a container.
Args:
container (Iterable[int]): The container of elements to sum.
Returns:
... |
magic_instruct_75k | 58,090 | Write a Python function to determine whether a given target integer is present in a sorted list of integers using a binary search algorithm. The list may contain duplicate elements. The function should return `True` if the target is found, and `False` otherwise.
The code should start with:
```python
from typing import... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def test_function(arr: List[int], target: int) -> bool:
"""
Determines whether a target integer is present in a sorted list of integers using binary search.
Args:
arr (List[int]): A sorted l... |
magic_instruct_75k | 58,117 | Write a Python function to manage a list of events. Each event has a name, date, and location. The function should support adding new events, listing all events, and searching for events by name or date. The function should be implemented as a class `EventManager` with the following methods:
- `add_event(name: str, dat... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
class EventManager:
def __init__(self):
"""
Initialize the EventManager with an empty list of events.
"""
self.events = []
def add_event(self, name: str, date: str, locat... |
magic_instruct_75k | 58,124 | Write a Python function to extract the post ID from a given request URL in a web application. The URL structure follows a pattern where the post ID is embedded within the URL. The function `getPostIDFromRequestURL` takes two parameters: `request`, which represents the HTTP request object, and `post_id_key`, which is a ... | Here is the Python code to solve the given problem in the markdown block:
```python
def getPostIDFromRequestURL(request, post_id_key: str) -> str:
"""
Extracts the post ID from the given request URL.
Args:
request: The HTTP request object containing the URL.
post_id_key (str): The key segme... |
magic_instruct_75k | 58,137 | Write a Python function to flatten a nested list structure. The function should take a list that may contain integers or other lists, and return a single list containing all the integers in a flattened form. The function should handle any level of nested lists.
The code should start with:
```python
from typing import ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def flatten_list(l: List[Union[int, List]]) -> List[int]:
"""
Flattens a nested list structure into a single list containing all integers.
Args:
l (List[Union[int, List]]): The input ... |
magic_instruct_75k | 58,163 | Write a Python function to automate the submission of multiple job scripts to a high-performance computing (HPC) cluster. The function should iterate through a list of climate model run names and submit corresponding job scripts to the HPC cluster using a simulated `qsub` command. The job scripts are located in a speci... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import os
def submit_job_scripts(runnames: List[str], job_script_dir: str) -> None:
"""
Automates the submission of multiple job scripts to a high-performance computing (HPC) cluster.
Args:
... |
magic_instruct_75k | 58,164 | Write a Python function to calculate the total cargo capacity of a military transport vehicle in a human-readable format. The function should take in the vehicle's cargo specifications and return a string that includes the maximum number of magazines, weapons, and backpacks the vehicle can transport. The cargo specific... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculateCargoCapacity(supplyRadius: int, showWeaponCargo: int, transportMaxMagazines: int, transportMaxWeapons: int, displayName: str, destrType: str, transportMaxBackpacks: int) -> str:
"""
Calculate the total cargo capaci... |
magic_instruct_75k | 58,165 | Write a Python function to automate the setup process for a voting application's server. The server is built using Node.js and utilizes npm for package management. The function should navigate to the "votes-server" directory and then run the command "npm ci" to install the necessary dependencies. The function should ha... | Here is the Python code to solve the given problem in the markdown block:
```python
import subprocess
import os
def setup_votes_server() -> None:
"""
Automates the setup process for a voting application's server.
This function navigates to the "votes-server" directory and runs the command "npm ci"
to ... |
magic_instruct_75k | 58,168 | Write a Python function to detect cycles in a directed graph represented by a list of commands. Each command represents a directed edge from one node to another. The function should return the first cycle found in the graph as a list of commands that form the cycle. If no cycle is found, the function should return an e... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def detect_cycle(commands: List[str]) -> List[str]:
"""
Detects the first cycle in a directed graph represented by a list of commands.
Args:
commands (List[str]): A list of commands where ea... |
magic_instruct_75k | 58,186 | Write a Python function to process a list of integers and return a modified list based on specific conditions. The function should take a list of integers as input and perform the following operations:
1. If the integer is divisible by 3, replace it with "Fizz".
2. If the integer is divisible by 5, replace it with "Buz... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def fizz_buzz(nums: List[int]) -> List[str]:
"""
Process a list of integers and return a modified list based on specific conditions.
Args:
nums (List[int]): A list of integers to be processe... |
magic_instruct_75k | 58,192 | Write a Python function to find the longest common subsequence (LCS) of two given strings. The function should return the length of the LCS.
The code should start with:
```python
from typing import List
def longest_common_subsequence(str1: str, str2: str) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def longest_common_subsequence(str1: str, str2: str) -> int:
"""
Calculate the length of the longest common subsequence (LCS) of two strings.
Args:
str1 (str): The first string.
str2... |
magic_instruct_75k | 58,240 | Write a Python function to calculate the final price of a product after applying a discount. The function should take the original price of the product and the discount percentage as input and return the final price after applying the discount. Additionally, the function should print the final price in a specific forma... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_final_price(original_price: float, discount_percentage: float) -> float:
"""
Calculate the final price of a product after applying a discount.
Args:
original_price (float): The original price of the pr... |
magic_instruct_75k | 58,274 | Write a Python function to find the maximum power of any substring in a given string `s`. The power of a substring is defined as the maximum number of consecutive repeating characters in that substring. The function should start with:
```python
def max_power(s: str) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def max_power(s: str) -> int:
"""
Calculate the maximum power of any substring in the given string `s`.
The power of a substring is defined as the maximum number of consecutive repeating characters in that substring.
A... |
magic_instruct_75k | 58,285 | Write a Python function to evaluate the fire risk type for a given property based on the history of accidental fires and the frequency of campfires. The fire risk type is categorized as low, moderate, or high based on the following criteria:
- If the history of accidental fires is minimal and campfires are occasional,... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Literal
def evaluate_fire_risk_type(history_of_accidental_fires: Literal["Minimal", "Moderate", "Significant"],
campfires_occasionally: Literal["Minimal", "Moderate", "Significant"]) -> L... |
magic_instruct_75k | 58,303 | Write a Python function to update the file paths in a dictionary of terms related to clustering. The function should take a root path and a dictionary as input, where the dictionary contains term names as keys and their corresponding file paths as values. The function should return a modified dictionary with updated pa... | Here is the Python code to solve the given problem in the markdown block:
```python
def update_paths(root_path: str, term_dict: dict) -> dict:
"""
Updates the file paths in a dictionary of terms by prepending a root path to each file name.
Args:
root_path (str): The root path to prepend to each fil... |
magic_instruct_75k | 58,323 | Write a Python function to extract the username and repository name from a list of GitHub repository URLs. The function should return a list of tuples, where each tuple contains the extracted username and repository name. The function should handle URLs with or without the "https://" prefix and should ignore any URLs t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
import re
def extract_repo_info(urls: List[str]) -> List[Tuple[str, str]]:
"""
Extracts the username and repository name from a list of GitHub repository URLs.
Args:
urls (List[str]):... |
magic_instruct_75k | 58,329 | Write a Python function to retrieve a broadcast handler from a dictionary of broadcast IDs. The function should handle the case where the broadcast ID does not exist in the dictionary. The code should start with:
```python
def get_broadcast_handler(c, broadcast_id):
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def get_broadcast_handler(c, broadcast_id):
"""
Retrieve the broadcast handler corresponding to the given broadcast ID from the dictionary.
Args:
c (object): An object containing the dictionary of broadcast IDs.
... |
magic_instruct_75k | 58,359 | Write a Python function to delete the nth node from the end of a singly linked list and return the head of the updated list. The function should be efficient and handle edge cases such as deleting the first or last node.
The code should start with:
```python
class ListNode:
def __init__(self, value=0, next=None):
... | Here is the Python code to solve the given problem in the markdown block:
```python
class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def delete_nth_from_end(head: ListNode, n: int) -> ListNode:
"""
Deletes the nth node from the end of a singly link... |
magic_instruct_75k | 58,361 | Write a Python function to extract all unique words from a given disclaimer text and return them in a sorted list. The function should be case-insensitive, meaning that "Word" and "word" should be considered the same. A word is defined as a sequence of characters separated by spaces, punctuation marks, or line breaks.
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def extract_unique_words(disclaimer_text: str) -> List[str]:
"""
Extracts all unique words from a given disclaimer text and returns them in a sorted list.
Args:
disclaimer_text (st... |
magic_instruct_75k | 58,370 | Write a Python function to process feedback data for various projects and return a structured dictionary containing the project names, questions, and responses. The feedback data is provided as a list of dictionaries, where each dictionary represents a row of feedback data. Each row contains keys such as "Project Name"... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any
def process_feedback(feedback_data: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
"""
Process feedback data for various projects and return a structured dictionary.
Args:
fe... |
magic_instruct_75k | 58,371 | Write a Python function to process and analyze a series of text inputs. The function should take a list of strings as input and perform the following operations:
1. Concatenate all the strings together into a single text block.
2. Split the text block into individual words.
3. Count the occurrences of each word and sto... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def process_text(text_list: List[str]) -> Dict[str, int]:
"""
Process a list of strings to concatenate them into a single text block, split the text into words,
and count the occurrences of eac... |
magic_instruct_75k | 58,375 | Write a Python function to cluster junctions based on given keys and return the labels for each cluster. Each key in the input list is a tuple of two elements representing a donor and an acceptor. The function should group identical keys into the same cluster and assign a unique label to each cluster. The labels should... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def cluster_junctions(v_keys: List[Tuple[int, int]]) -> List[str]:
"""
Clusters junctions based on given keys and returns the labels for each cluster.
Args:
v_keys (List[Tuple[int, in... |
magic_instruct_75k | 58,377 | Write a Python function to format a search query for news articles by replacing spaces with the plus symbol (`+`). The function should take a single parameter, `news_query`, which is a string representing the search query for news articles. The function should return a formatted version of the search query where spaces... | Here is the Python code to solve the given problem in the markdown block:
```python
def format_news_search_query(news_query: str) -> str:
"""
Formats the search query for news articles by replacing spaces with the plus symbol (+).
Args:
news_query (str): A string representing the search query for n... |
magic_instruct_75k | 58,407 | Write a Python function to convert a time value in milliseconds into a string representation of hours, minutes, seconds, and milliseconds in the format "hh:mm:ss.fff". The function should handle the conversion of milliseconds to hours, minutes, seconds, and milliseconds, and format the output accordingly.
The code sho... | Here is the Python code to solve the given problem in the markdown block:
```python
def format_time(time_ms: int) -> str:
"""
Converts a time value in milliseconds into a string representation of hours, minutes, seconds, and milliseconds in the format "hh:mm:ss.fff".
Args:
time_ms (int): The time v... |
magic_instruct_75k | 58,409 | Write a Python function to parse a list of strings and create a dictionary where the keys are item names and the values are their corresponding prices. The input list follows a specific pattern: each item name is followed by its price on the next line. The item names are strings without any leading or trailing whitespa... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def parse_items(items_list: List[str]) -> Dict[str, float]:
"""
Parses a list of strings to create a dictionary where the keys are item names and the values are their corresponding prices.
Arg... |
magic_instruct_75k | 58,415 | Write a Python function to update the processed data cache for a job configuration. The job configuration is represented by a `MorfJobConfig` object, which contains information about the data buckets to be processed. The function should update the processed data cache using the parameters in the job configuration. It i... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
class MorfJobConfig:
"""
Represents a job configuration object containing information about the processed data buckets.
"""
def __init__(self, proc_data_buckets: List[dict]):
se... |
magic_instruct_75k | 58,422 | Write a Python function to find all species under a given genus from a list of species and their corresponding genus identifiers. The function should take in a genus identifier and a list of tuples, where each tuple contains a species name and its corresponding genus identifier. The function should return a list of spe... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_species_under_genus(genus: str, species_data: List[tuple]) -> List[str]:
"""
Find all species under a given genus from a list of species and their corresponding genus identifiers.
Args:
... |
magic_instruct_75k | 58,448 | Write a Python function to convert a synchronous iterator into an asynchronous iterator using the `async` and `await` keywords. The function should take a synchronous iterator as input and return an asynchronous iterator. The resulting asynchronous iterator should be usable with `async for` loops and `await` expression... | Here is the Python code to solve the given problem in the markdown block:
```python
async def iter_to_aiter(iter):
"""
Converts a synchronous iterator into an asynchronous iterator.
This function takes a synchronous iterator and returns an asynchronous generator
that yields each item from the synchrono... |
magic_instruct_75k | 58,497 | Write a Python function to construct grammatically correct sentences from a list of tuples, where each tuple contains a country name and its corresponding adjective. The function should print a sentence for each country using the provided adjective. The sentence format should be: "I have heard that [Country] is a [Adje... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def construct_sentences(countries: List[Tuple[str, str]]) -> None:
"""
Constructs and prints grammatically correct sentences for each country and its corresponding adjective.
Args:
co... |
magic_instruct_75k | 58,511 | Write two Python functions to solve the following tasks:
1. **`rearrange_name(full_name: str) -> str`**: This function takes a string `full_name` in the format "last_name, first_name" and returns the rearranged full name in the format "first_name last_name". If the input format is incorrect, the function should return ... | Here is the Python code to solve the given problem in the markdown block:
```python
def rearrange_name(full_name: str) -> str:
"""
Rearranges a full name from the format "last_name, first_name" to "first_name last_name".
Args:
full_name (str): The full name in the format "last_name, first_name".
... |
magic_instruct_75k | 58,513 | Write a Python function to filter out even numbers from a given list of integers. The function should return a new list containing only the even numbers from the input list. The function should be efficient and handle various edge cases, such as an empty list or a list with no even numbers.
The code should start with:... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def filter_even_numbers(nums: List[int]) -> List[int]:
"""
Filters out even numbers from a given list of integers.
Args:
nums (List[int]): A list of integers from which to filter even number... |
magic_instruct_75k | 58,515 | Write a Python function to count the occurrences of each resource type in a list of drawing resources. Each resource in the list is represented as a string in the format "resource_type:resource_name". The function should return a dictionary where the keys are the resource types and the values are the counts of each res... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_drawing_resources(drawing_resources: List[str]) -> Dict[str, int]:
"""
Counts the occurrences of each resource type in a list of drawing resources.
Args:
drawing_resources (L... |
magic_instruct_75k | 58,545 | Write a Python function to simulate a simple version control system. The function should take a list of commands and output the final state of the files based on the commands executed. Each command can either be a "commit" or a "checkout" command.
- **Commit Command**: A string in the format "commit <file_name>", wher... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def version_control(commands: List[str]) -> Dict[str, List[str]]:
"""
Simulates a simple version control system based on a list of commands.
Args:
commands (List[str]): A list of comma... |
magic_instruct_75k | 58,566 | Create a Python class `BankAccount` that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the current balance. Additionally, the class should keep track of the transaction history, including the type of transaction (deposit or withdrawal) and the amo... | Here is the Python code to solve the given problem in the markdown block:
```python
class BankAccount:
def __init__(self):
"""
Initialize the BankAccount with a balance of 0 and an empty transaction history.
"""
self.balance = 0
self.transaction_history = []
def deposit(... |
magic_instruct_75k | 58,574 | Implement an `EventDispatcher` class in Python that allows registration of event listeners and dispatching events to all registered listeners. Each listener should be able to subscribe to multiple event types and should be notified when any of those event types are dispatched. The class should include the following met... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Callable, Any, Dict, Set
class EventDispatcher:
def __init__(self):
"""
Initializes the EventDispatcher with an empty dictionary to store event listeners.
"""
self.listeners: Dict[... |
magic_instruct_75k | 58,586 | Write a Python function to normalize a given answer text by converting it to lowercase, removing punctuation, articles (such as "a", "an", "the"), and extra whitespace. The function should utilize two helper functions: `remove_articles(text)` and `white_space_fix(text)`. The `remove_articles` function removes articles ... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def normalize_answer(s: str) -> str:
"""
Normalize the given answer text by converting it to lowercase, removing punctuation,
articles (such as "a", "an", "the"), and extra whitespace.
Args:
s (str): ... |
magic_instruct_75k | 58,598 | Write a Python program to implement a card game scoring system. The program should read input for the number of players and their names, then for each player, read input for the number of cards they have and the details of each card (number of points and suit). The program should calculate the total points for each pla... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Tuple
def add_player_card(players: Dict[str, List[Tuple[int, str]]], player_name: str, points: int, suit: str) -> None:
"""
Adds a card to a player's set of cards.
Args:
players: A di... |
magic_instruct_75k | 58,631 | Write a Python function to map a coefficient register constant to its corresponding hexadecimal value. The function should return `-1` if the input constant is not valid. The coefficient register constants are named `COEFF_REG_5`, `COEFF_REG_6`, `COEFF_REG_7`, and so on, with their corresponding hexadecimal values star... | Here is the Python code to solve the given problem in the markdown block:
```python
def get_coefficient_value(register_constant: str) -> int:
"""
Returns the hexadecimal value corresponding to the given coefficient register constant.
Args:
register_constant (str): The coefficient register constant ... |
magic_instruct_75k | 58,655 | Write a Python function to manipulate a given string based on specific rules. The function should replace occurrences of the substring "abc" with "def" and occurrences of the substring "xyz" with "123". The function should return the modified string.
The code should start with:
```python
def manipulateString(s: str) -... | Here is the Python code to solve the given problem in the markdown block:
```python
def manipulateString(s: str) -> str:
"""
Manipulates the input string by replacing occurrences of "abc" with "def" and "xyz" with "123".
Args:
s (str): The input string to be manipulated.
Returns:
str: ... |
magic_instruct_75k | 58,657 | Write a Python function to process a list of dictionaries, where each dictionary contains a key "result" with a string value. The function should return a new list of dictionaries with the "result" values modified by appending " - Processed" to the original string.
The function should start with:
```python
from typing... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def process_results(input_list: List[Dict[str, str]]) -> List[Dict[str, str]]:
"""
Processes a list of dictionaries by appending " - Processed" to the value of the "result" key in each dictionary.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.