source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
magic_instruct_75k
59,993
Write a Python function to find the largest and smallest numbers among three given integers. The function should return a tuple containing the largest and smallest numbers. The code should start with: ```python def find_largest_smallest(num1: int, num2: int, num3: int) -> (int, int): ```
Here is the Python code to solve the given problem in the markdown block: ```python def find_largest_smallest(num1: int, num2: int, num3: int) -> (int, int): """ Finds the largest and smallest numbers among three given integers. Args: num1 (int): The first integer. num2 (int): The second in...
magic_instruct_75k
60,001
Write a Python function to implement a simplified version of a key-value store. The key-value store should support storing and retrieving values of different types associated with a given key. The function should meet the following requirements: 1. It should support storing and retrieving values of different types (e.g...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Any, Type, Optional def key_value_store(): """ Implements a simplified key-value store. Returns: tuple: A tuple containing two functions: - put: A function to store a value associated...
magic_instruct_75k
60,030
Write a Python function to process a job queue based on provided command-line arguments. The function should filter the job queue based on job names, apply a regular expression filter if provided, and select specific columns to display. Additionally, it should handle a flag to indicate whether to recurse into subfolder...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Optional import re def process_job_queue(job_queue: List[Dict[str, str]], job_name: Optional[List[str]] = None, columns: Optional[List[str]] = None, regex: Optional[str] = None, recurse: bool = False) -> ...
magic_instruct_75k
60,066
Write a Python function to resolve domain dependencies based on a given set of rules. The rules are represented as a dictionary `spf` containing keys 'include' and 'redirect', each associated with a set of domains. The function should start with an empty set `includes` and iteratively update it based on the rules until...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Set def resolve_domain_dependencies(spf: Dict[str, Set[str]]) -> Set[str]: """ Resolve domain dependencies based on the given set of rules. Args: spf (Dict[str, Set[str]]): A dictionary con...
magic_instruct_75k
60,071
Write a Python function to count the occurrences of each unique module name in a list of module names. The module names are structured as strings with the format "pycopia.OS.Linux.proc" or similar. The function should return a dictionary where the keys are the unique module names and the values are the counts of each m...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_module_names(module_list: List[str]) -> Dict[str, int]: """ Counts the occurrences of each unique module name in a list of module names. Args: module_list (List[str]): A list...
magic_instruct_75k
60,074
Write a Python function to generate a square matrix of size `n x n` filled with consecutive numbers in a spiral pattern, starting from the top-left corner and moving in the directions of right, down, left, and up. If the next cell in the current direction is already filled or out of bounds, change the direction to the ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_spiral_matrix(n: int) -> List[List[int]]: """ Generate a square matrix of size `n x n` filled with consecutive numbers in a spiral pattern. Args: n (int): The size of the square...
magic_instruct_75k
60,081
Write a Python function to find the shortest path from a given source node to all other nodes in a weighted directed graph using Dijkstra's algorithm. The graph is represented using an adjacency list where each node is associated with a list of tuples, where each tuple represents an edge to a neighboring node along wit...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import heapq def shortest_path(adj: List[List[Tuple[int, int]]], n: int, src: int) -> List[int]: """ Find the shortest path from a given source node to all other nodes in a weighted directed graph...
magic_instruct_75k
60,096
Write a Python function to process a dictionary `t` containing a key `'is_public'` with a string value representing a boolean. The function should convert the string value to a boolean and update the dictionary accordingly. If the string value is 'True', the corresponding value in the dictionary should be set to `True`...
Here is the Python code to solve the given problem in the markdown block: ```python def process_is_public(t: dict) -> dict: """ Processes a dictionary `t` by converting the string value of the key `'is_public'` to a boolean. Args: t (dict): A dictionary containing a key `'is_public'` with a string ...
magic_instruct_75k
60,099
Write a Python function `concatenate_fastq_qual` that takes two file objects `in_fastq` and `in_qual` as input. The `in_fastq` file contains DNA sequencing data in FASTQ format, and the `in_qual` file contains the corresponding quality scores for the DNA sequencing data. The function should read the first four lines fr...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import TextIO def concatenate_fastq_qual(in_fastq: TextIO, in_qual: TextIO) -> str: """ Concatenates the first four lines from `in_fastq` and the fourth line from `in_qual`. Args: in_fastq (TextIO): A f...
magic_instruct_75k
60,101
Write a Python function to organize and optimize import statements in an Angular application according to the specified rules. The function should take a list of import statements as input, rearrange them according to the rules, and return the organized import statements along with a list of distinct libraries being im...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def organize_imports(imports: List[str]) -> Tuple[List[str], List[str]]: """ Organizes and optimizes import statements in an Angular application according to the specified rules. Args: ...
magic_instruct_75k
60,109
Write a Python function to construct the full command for training a machine learning model using the provided command-line options and their corresponding values. The function should take the values for the variables as input and return the complete command as a string. The command-line options and their correspondin...
Here is the Python code to solve the given problem in the markdown block: ```python def construct_training_command(save_steps: int, warmup_proportion: float, valid_steps: int, epoch: int, lr_rate: str, num_labels: int) -> str: """ Constructs the full command for training a machine learning model using the provi...
magic_instruct_75k
60,118
Write a Python function to traverse a file system represented as a tree structure and return a list of absolute paths of all files reachable from a given entry point. The file system is defined by a dictionary where keys are absolute directory paths and values are lists of files and subdirectories contained in those di...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def traverse_file_system(directory: str, file_map: Dict[str, List[str]], entrypoint: str) -> List[str]: """ Traverse a file system represented as a tree structure and return a list of absolute path...
magic_instruct_75k
60,120
Write a Python function to replace all occurrences of the "&" character with a newline character ("\n") in a given text. The function should take a single string as input and return the modified text with the replacements. The code should start with: ```python def replaceAndWithNewline(text: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def replaceAndWithNewline(text: str) -> str: """ Replaces all occurrences of the "&" character with a newline character ("\n") in the given text. Args: text (str): The input text in which the replacements are to be ...
magic_instruct_75k
60,130
Write a Python function to implement a key binding system for a text editor. The function should take a key combination as input and return the corresponding editing command. If the input key combination does not have a corresponding command, the function should return "No command found". The key combinations are repr...
Here is the Python code to solve the given problem in the markdown block: ```python def get_edit_command(key_combination): """ Returns the corresponding editing command for a given key combination. Args: key_combination (tuple): A tuple representing the key combination. The first elemen...
magic_instruct_75k
60,140
Write a Python function to calculate the final position of a shape after applying a series of animations. Each animation is defined by its type, properties, and duration. The shape starts at the origin (0, 0) and the animations are applied sequentially. The animations can include transformations like scaling and transl...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def calculateFinalPosition(initialPosition: Tuple[int, int], animations: List[Dict]) -> Tuple[int, int]: """ Calculate the final position of a shape after applying a series of animations. ...
magic_instruct_75k
60,144
Write a Python function to process a string with placeholders and replace them with corresponding values from a dictionary. Placeholders are denoted by enclosing the variable name in curly braces (e.g., `{name}`). If a placeholder does not have a corresponding key in the dictionary, it should remain unchanged in the st...
Here is the Python code to solve the given problem in the markdown block: ```python def process_form(tvars: dict, form: str) -> str: """ Replaces placeholders in a form string with corresponding values from a dictionary. Placeholders are denoted by enclosing the variable name in curly braces (e.g., {name})...
magic_instruct_75k
60,154
Write a Python function to convert a given time in seconds to the format "hh:mm:ss" where "hh" represents hours, "mm" represents minutes, and "ss" represents seconds. The function should handle any non-negative integer input for the time in seconds. The code should start with: ```python def convert_seconds_to_hms(time...
Here is the Python code to solve the given problem in the markdown block: ```python def convert_seconds_to_hms(time_in_sec: int) -> str: """ Converts a given time in seconds to the format "hh:mm:ss". Args: time_in_sec (int): The time in seconds to be converted. Returns: str: The time i...
magic_instruct_75k
60,162
Write a Python function to process a dictionary representing font configurations and return a modified dictionary with a new font added to the "font.sans-serif" key. The input dictionary will contain various font configurations, and the output dictionary should maintain all the original configurations while adding "Ari...
Here is the Python code to solve the given problem in the markdown block: ```python def add_font(font_config: dict) -> dict: """ Processes a dictionary representing font configurations and returns a modified dictionary with "Arial" added to the "font.sans-serif" key if it's not already present. Args: ...
magic_instruct_75k
60,163
Write a Python function to manage a custom namespace hierarchy. The function should allow users to create, enter, exit, and delete namespaces. Each namespace is a declarative region that provides a scope to identifiers (names of types, functions, variables, etc.) inside it. The function should also provide a way to get...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional class NamespaceManager: def __init__(self): # Initialize the global namespace self.namespaces = {} self.current_namespace = [] def create_namespace(self, name: str) -> ...
magic_instruct_75k
60,187
Write a Python function to process a list of integers representing shift counts for a series of operations. The shift count is incremented by 1 if the current value of `k` is not divisible by 96; otherwise, the shift count is reset to 0. After processing all the shift counts, the list is converted into a NumPy array. ...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from typing import List def process_shift_counts(shifts: List[int]) -> np.ndarray: """ Process a list of integers representing shift counts and convert them into a NumPy array. The shift count is increme...
magic_instruct_75k
60,228
Write a Python function to manage the registration and invocation of event handlers for different stages of a compilation process. The function should allow registration of actions to be executed at various stages such as the end of the compilation process, after the semantic model is available, for a specific syntax n...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Callable, List, Dict # Dictionary to store registered actions actions: Dict[str, List[Callable[[str, object], None]]] = { "end_of_compilation": [], "semantic_model_available": [], "syntax_node": [], "...
magic_instruct_75k
60,250
Write a Python function `buildWall` that simulates the construction of a wall by stacking bricks. The function should take an array of integers representing the heights of the bricks and simulate the construction process. The function should handle errors that may occur during the construction process and output the pr...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def buildWall(bricks: List[int]) -> None: """ Simulates the construction of a wall by stacking bricks. Args: bricks (List[int]): A list of integers representing the heights of the bricks. ...
magic_instruct_75k
60,252
Write a Python function to identify and categorize errors in a given text document. The errors to be identified include restricted words that are not allowed in the document and instances where data needs to be entered manually. The function should take a list of restricted words and a sample text document as input and...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def find_errors(restricted_words: List[str], sample_document: str) -> Dict[str, List[str]]: """ Identify and categorize errors in a given text document. Args: restricted_words (List[st...
magic_instruct_75k
60,280
Write a Python function `validate_and_write_parametric` that validates the input parametric data and ensures it meets certain criteria before attempting to write it to the database. The function should return a boolean value indicating whether the data was successfully written to the database. The function should perfo...
Here is the Python code to solve the given problem in the markdown block: ```python def validate_and_write_parametric(new_parametric: dict) -> bool: """ Validates the input parametric data and attempts to write it to the database. Args: new_parametric (dict): A dictionary representing the new param...
magic_instruct_75k
60,285
Write a Python function to determine the next stage in a data processing pipeline given the current stage. The pipeline consists of several stages, each with its own set of data. The stages are ordered as follows: 1. `QUERYLOG` 2. `SESSIONS_RAW` 3. `SESSIONS_HOURLY` 4. `SPANS` 5. `TRANSACTIONS` The function should tak...
Here is the Python code to solve the given problem in the markdown block: ```python def get_next_stage(stage: str) -> str: """ Determine the next stage in the data processing pipeline given the current stage. Args: stage (str): The name of the current stage in the pipeline. Returns: st...
magic_instruct_75k
60,352
Write a Python function to retrieve the list of date columns associated with a given table name from a healthcare database. The database contains various tables, each representing different types of healthcare events such as conditions, drug exposures, measurements, observations, and procedures. Each table has columns ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def get_date_columns(table_name: str) -> List[Optional[str]]: """ Retrieves the list of date columns associated with a given table name from a healthcare database. Args: table_name...
magic_instruct_75k
60,353
Write a Python function to remove a specified context processor from a list of Django template context processors. The function should return a new list with the specified processor removed. The function should be named `remove_context_processor` and should take two parameters: - `processors`: A list of strings represe...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_context_processor(processors: List[str], processor_to_remove: str) -> List[str]: """ Removes a specified context processor from a list of Django template context processors. Args: ...
magic_instruct_75k
60,380
Write a Python function to generate the command-line arguments for running the iperf network testing tool based on the given parameters. The iperf tool is used to measure the maximum TCP and UDP bandwidth performance. The function should take in the following parameters: - `l4Type`: A string representing the layer 4 p...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_iperf_args(l4Type: str, udpBw: int) -> str: """ Generates the command-line arguments for running the iperf network testing tool based on the given parameters. Args: l4Type (str): The layer 4 protocol ty...
magic_instruct_75k
60,388
Write a Python function to calculate the counts of renders in each state category from a given list of renders. Each render is represented as a dictionary with a 'state' key containing space-separated state codes. The function should return a dictionary where the keys are the state codes and the values are the counts o...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def calculate_render_state_counts(renderlist: List[Dict[str, str]]) -> Dict[str, int]: """ Calculate the counts of renders in each state category from a given list of renders. Args: re...
magic_instruct_75k
60,392
Write a Python function to simulate the movement of a rectangle on a 2D plane. The function should take in the current position and dimensions of the rectangle, the direction in which it should move, and the distance to move in that direction. The function should then return the new position of the rectangle after the ...
Here is the Python code to solve the given problem in the markdown block: ```python def move_rectangle(rect: dict, direction: str, distance: int) -> dict: """ Simulates the movement of a rectangle on a 2D plane. Args: rect (dict): A dictionary representing the rectangle with keys "left", "top", "wi...
magic_instruct_75k
60,398
Write a Python function `modify_tokens(tokens)` that takes a list of tokens as input and modifies the tokens based on the following rules: 1. If the token is enclosed within square brackets (e.g., `"[abc]"`), it should be appended to a new list of tokens as is. 2. If the token is in the form of `"[digit]"`, where `"dig...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def modify_tokens(tokens: List[str]) -> List[str]: """ Modifies the input list of tokens based on the specified rules. Args: tokens (List[str]): A list of tokens to be modified. Returns...
magic_instruct_75k
60,404
Write a Python function to simulate a simple file system that supports creating, reading, and deleting files, as well as listing all files in the system. The file system should be implemented as a class named `FileSystem`. The class should have the following methods: - `__init__()`: Initializes the file system. - `crea...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List class FileSystem: """ A simple file system class that supports creating, reading, deleting files, and listing all files. Methods: __init__(): Initializes the file system. create_file...
magic_instruct_75k
60,411
Write a Python function `retrieve_installed_tools` that filters a list of tool repository records based on specific conditions and returns a list of installed tools. Each tool repository record is represented as a dictionary with keys: "name", "deleted", "uninstalled", and "status". The function should return only thos...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union def retrieve_installed_tools(tool_repository_records: List[Dict[str, Union[str, bool]]]) -> List[Dict[str, Union[str, bool]]]: """ Filters a list of tool repository records and returns a lis...
magic_instruct_75k
60,416
Write a Python function to determine the type of a file based on its extension. The file types and their corresponding extensions are stored in a dictionary. The function should take a file name as input and return the corresponding file type based on its extension. If the extension is not found in the dictionary, the ...
Here is the Python code to solve the given problem in the markdown block: ```python def get_file_type(file_name: str) -> str: """ Determine the type of a file based on its extension. Args: file_name (str): The name of the file, including its extension. Returns: str: The type of the fil...
magic_instruct_75k
60,418
Write a Python function to calculate the average version number from a list of software licenses. Each license is represented as a string in the format "License, v. x.x", where "x.x" is the version number. The function should extract the version numbers, compute their average, and return the result rounded to two decim...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def averageLicenseVersion(licenses: List[str]) -> float: """ Calculate the average version number from a list of software licenses. Args: licenses (List[str]): A list of strings where each s...
magic_instruct_75k
60,425
Write a Python function to simulate the execution of a set of instructions for a handheld game console. The console has a single accumulator and a small set of instructions: - `acc +/-N`: Increases or decreases the accumulator by the value N. - `jmp +/-N`: Jumps to a new instruction relative to itself. - `nop`: Does no...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_accumulator_value(instructions: List[str]) -> int: """ Simulates the execution of a set of instructions for a handheld game console and returns the value in the accumulator just before any i...
magic_instruct_75k
60,434
Write a Python function to count the number of positive integers in a given list of integers. The function should accurately count the positive integers, ensuring that it handles all edge cases, including an empty list, a list with all negative numbers, and a list with mixed positive and negative numbers. The code sho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_positive_numbers(numbers: List[int]) -> int: """ Counts the number of positive integers in a given list of integers. Args: numbers (List[int]): A list of integers. Returns: ...
magic_instruct_75k
60,435
Write a Python function to calculate the sum of elements in each column of a given matrix. The matrix is represented as a list of lists, where each inner list represents a row in the matrix. The function should return a list containing the sum of elements in each column. The code should start with: ```python from typi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_column_sums(matrix: List[List[int]]) -> List[int]: """ Calculate the sum of elements in each column of a given matrix. Args: matrix (List[List[int]]): A list of lists represent...
magic_instruct_75k
60,499
Write a Python function to check if a given substring is present in any of the strings within a list of strings. The function should return `True` if the substring is found in any of the strings, and `False` otherwise. The code should start with: ```python from typing import List def check_substring_in_list(substring...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def check_substring_in_list(substring: str, string_list: List[str]) -> bool: """ Checks if a given substring is present in any of the strings within a list of strings. Args: substring (str):...
magic_instruct_75k
60,511
Write a Python function to generate a mapping of pin names to their corresponding GPIO numbers for a motor driver module used in a robotics project. The function should take five integer inputs representing the GPIO numbers for the pins `AEnable`, `AIN1`, `AIN2`, `BIN1`, and `BIN2`. The function should return a diction...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_pin_mapping(AEnable: int, AIN1: int, AIN2: int, BIN1: int, BIN2: int) -> dict: """ Generates a mapping of pin names to their corresponding GPIO numbers for a motor driver module. Args: AEnable (int): Th...
magic_instruct_75k
60,512
Write a Python function to find the nth prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The function should take an integer `n` as input and return the nth prime number. The code should start with: ```python def find_nth_prime(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(num: int) -> bool: """ Check if a given number is prime. Args: num (int): The number to check for primality. Returns: bool: True if the number is prime, False otherwise. """ if num ...
magic_instruct_75k
60,517
Write a Python function to encode data using the 'SignedDataPayload' method. The function should take two integers as input: `data` and `ext_data_hash`. The function should return the encoded result as a byte string. The encoding process involves formatting the integers as hexadecimal strings and prefixing them with th...
Here is the Python code to solve the given problem in the markdown block: ```python def encode_data(data: int, ext_data_hash: int) -> bytes: """ Encodes the given data and extended data hash using the 'SignedDataPayload' method. Args: data (int): The data to be encoded. ext_data_hash (int):...
magic_instruct_75k
60,519
Write a Python function to render a template string by replacing placeholders with corresponding values from a dictionary. The placeholders in the template string are in the form `{{ variable_name }}`. If a placeholder does not have a corresponding key in the dictionary, it should remain unchanged in the rendered templ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def render_template(template: str, variables: Dict[str, str]) -> str: """ Renders a template string by replacing placeholders with corresponding values from a dictionary. Args: template (str...
magic_instruct_75k
60,533
Write a Python function to extract the names of datasets that contain a specific data category from a list of datasets. Each dataset is represented as a tuple containing the dataset's name, description, and a list of data categories. The function should return a list of dataset names that match the specified category. ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def get_datasets_by_category(output_list: List[Tuple[str, str, List[str]]], category: str) -> List[str]: """ Extracts the names of datasets that contain a specific data category. Args: ...
magic_instruct_75k
60,539
Write a Python function to calculate the sum of all elements in a given 2D matrix that are greater than a specified threshold value. The matrix is represented as a list of lists, where each inner list represents a row of the matrix. The function should efficiently iterate through the matrix and sum only those elements ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_above_threshold(matrix: List[List[float]], threshold: float) -> float: """ Calculate the sum of all elements in a 2D matrix that are greater than a given threshold. Args: matrix (Lis...
magic_instruct_75k
60,561
Write a Python function to extract unique strings from a given list while preserving their original order. The function should efficiently handle large input lists. The code should start with: ```python from typing import List def get_unique_strings(input_list: List[str]) -> List[str]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def get_unique_strings(input_list: List[str]) -> List[str]: """ Extracts unique strings from a given list while preserving their original order. Args: input_list (List[str]): A list of strin...
magic_instruct_75k
60,562
Write a Python function `process_results` that processes a list of `MathResultModel` objects and performs specific operations based on the values of the `result` attribute. The `MathResultModel` class is defined as follows: ```python from typing import Optional from pydantic import BaseModel class MathResultModel(Bas...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional from pydantic import BaseModel class MathResultModel(BaseModel): result: Optional[float] = None summary: str def process_results(results: List[MathResultModel]) -> List[MathResultModel]: "...
magic_instruct_75k
60,575
Write a Python function to filter a list of branch names in a version control system. The function should return a new list containing only the branch names that meet the following criteria: 1. The branch name must start with "feature/". 2. The branch name must contain at least one alphabet character after "feature/". ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_branch_names(branch_names: List[str]) -> List[str]: """ Filters a list of branch names to include only those that start with "feature/" and contain at least one alphabet character after "featu...
magic_instruct_75k
60,596
Write a Python function to join two parts of a URL together, ensuring that there is exactly one forward slash between them. The function should remove any trailing slashes from the input parts before concatenation. The code should start with: ```python def join_url_parts(part1: str, part2: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def join_url_parts(part1: str, part2: str) -> str: """ Joins two parts of a URL together, ensuring that there is exactly one forward slash between them. Args: part1 (str): The first part of the URL. part2 (s...
magic_instruct_75k
60,639
Write a Python function to parse a given URL string and extract its components: protocol, domain, and any additional parameters. The function should return a dictionary with the extracted components. The URL format is `<protocol>://<domain>/<additional_parameters>`. The dictionary should have the following keys: - "pro...
Here is the Python code to solve the given problem in the markdown block: ```python def parse_url(url: str) -> dict: """ Parses a given URL string and extracts its components: protocol, domain, and any additional parameters. Args: url (str): The URL string to be parsed. Returns: dict: ...
magic_instruct_75k
60,718
Write a Python function to extract email addresses from a list of strings representing contact information from a business card scanner. Each string in the list corresponds to a line of text from the scanned business card. The function should identify lines containing the substring "EMAIL;HOME:" and extract the email a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def extract_emails(card: List[str]) -> List[str]: """ Extracts email addresses from a list of strings representing contact information. Args: card (List[str]): A list of strings where each s...
magic_instruct_75k
60,763
Write a Python function to process a data dictionary and return a response dictionary. The function should extract a specific key from the input data dictionary and construct a response dictionary with the extracted key as a value. The function should handle cases where the specific key is missing from the input data d...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def process_data(data: Dict[str, str], key: str = 'key', default: str = 'default_value') -> Dict[str, str]: """ Processes a data dictionary and returns a response dictionary. Args: data (Dic...
magic_instruct_75k
60,779
Write a Python function `get_nick_value` that retrieves a value associated with a specific key for a given nickname from a chatbot's database. The chatbot has a database interface with a method `get_nick_value(nick, key)` that retrieves the value. If the value does not exist, the method returns `None`. The function sho...
Here is the Python code to solve the given problem in the markdown block: ```python def get_nick_value(bot, nick, key): """ Retrieves the value associated with a specific key for a given nickname from the chatbot's database. Args: bot: An instance of the chatbot with a database interface. n...
magic_instruct_75k
60,791
Write a Python function to filter out signals that do not match a specific pattern from a list of incoming signals. Each signal is represented as a string of characters. The reference signal pattern is also a string. The function should remove leading and trailing whitespace from each incoming signal and compare the fi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_signals(signals: List[str], reference_pattern: str) -> List[str]: """ Filters out signals that do not match a specific pattern from a list of incoming signals. Args: signals (List...
magic_instruct_75k
60,838
Write a Python function to parse a formatted string containing date and time information and extract the individual components of the date and time. The components include the day of the week, month, day, time, timezone, and year. The function should return a dictionary containing these components. The input string is...
Here is the Python code to solve the given problem in the markdown block: ```python import re def parse_schema_output(schema_output: str) -> dict: """ Parses a formatted string containing date and time information and extracts the individual components. Args: schema_output (str): A formatted strin...
magic_instruct_75k
60,848
Implement a function to calculate the reward for each RL (reinforcement learning) vehicle based on whether it has changed lanes at the current time step. If a lane change is detected, the reward should be reduced by a set value. The function should iterate through all RL vehicle IDs, check if a lane change has occurred...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_reward(self) -> float: """ Calculate the reward for each RL vehicle based on whether it has changed lanes at the current time step. If a lane change is detected, the reward is reduced by a set value. Retur...
magic_instruct_75k
60,881
Write a Python function to parse command-line arguments and store them in a dictionary. The function should handle the following command-line argument patterns: - If the argument is `-console`, it should be stored in the `console_params` dictionary. - If the `console_params` dictionary is already populated, the script ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def parse_arguments(args: List[str]) -> Dict[str, str]: """ Parse command-line arguments and store them in a dictionary. Args: args (List[str]): A list of command-line arguments. ...
magic_instruct_75k
60,882
Write a Python function to convert the names of Indian states and union territories to uppercase. The function should take an array of associative arrays as input, where each associative array contains two key-value pairs: 'id' representing the unique identifier of the state or union territory, and 'name' representing ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def convert_to_uppercase(states: List[Dict[str, any]]) -> List[str]: """ Converts the names of Indian states and union territories to uppercase. Args: states (List[Dict[str, any]]): A ...
magic_instruct_75k
60,898
Write a Python function to simulate a simplified version of a command-line interface for a static code analysis tool named "sorbet." The tool is used to analyze and suggest type annotations for Ruby code. The function should take a list of command-line arguments and produce the appropriate output based on the provided ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def simulate_sorbet_cli(args: List[str]) -> str: """ Simulates a simplified command-line interface for a static code analysis tool named "sorbet." Args: args (List[str]): A list of command-l...
magic_instruct_75k
60,913
Write a Python function to implement a simple event handling system. The system should support the following operations: 1. **Registering an event listener**: The `on` function should take an event name and a callback function and register the callback as a listener for the specified event. 2. **Triggering an event**: ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Callable, Any, Dict, List # Event handling system event_listeners: Dict[str, List[Callable[[Any], None]]] = {} def on(event_name: str, callback: Callable[[Any], None]) -> None: """ Register an event listener...
magic_instruct_75k
61,028
Write a Python function to calculate the intensity histogram of a given grayscale image represented as a 2D numpy array and identify the intensity value that corresponds to the peak count in the histogram. The function should start with: ```python import numpy as np def peak_intensity_value(image: np.ndarray) -> int: ...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def peak_intensity_value(image: np.ndarray) -> int: """ Calculate the intensity histogram of a given grayscale image and identify the intensity value that corresponds to the peak count in the histogram. ...
magic_instruct_75k
61,046
Create a Python program that simulates a simple workflow system. The system will have a base class `GenericStep` and a subclass `SpecificStep` for specific steps in the workflow. Each step will have a description and parameters. Your task is to create the `SpecificStep` subclass with the following requirements: - Inhe...
Here is the Python code to solve the given problem in the markdown block: ```python class GenericStep: """ Base class for a generic workflow step. Attributes: description (str): A description of the workflow step. parameters (dict): A dictionary to store parameters for the step. """ ...
magic_instruct_75k
61,058
Write a Python function to convert a given GUID (Globally Unique Identifier) string into its corresponding binary representation. A GUID is a 128-bit value typically represented as a sequence of 32 hexadecimal digits grouped into five parts in the form of 8-4-4-4-12 for a total of 36 characters (32 hexadecimal digits a...
Here is the Python code to solve the given problem in the markdown block: ```python def guid_to_binary(guid_str: str) -> bytes: """ Converts a given GUID string into its corresponding binary representation. Args: guid_str (str): A string representing the GUID in the format "8-4-4-4-12". Return...
magic_instruct_75k
61,068
Write a Python function to find the details of an image based on its name from a given JSON data. The JSON data contains a list of images, each with a name, URL, and type. If the image name is found in the JSON data, return a dictionary containing the image's URL and type. If the image name is not found, return the str...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Union def findImageDetails(jsonData: dict, targetName: str) -> Union[dict, str]: """ Find the details of an image based on its name from a given JSON data. Args: jsonData (dict): A dictionary con...
magic_instruct_75k
61,069
Write a Python function to format a given SQL query string by replacing placeholders with corresponding values from a dictionary of parameters. The function should also handle a boolean flag that determines whether the placeholders should be replaced with dictionary-style placeholders or directly with the parameter val...
Here is the Python code to solve the given problem in the markdown block: ```python def format_sql_query(sql_query: str, parameters: dict, as_dict: bool) -> str: """ Formats an SQL query string by replacing placeholders with corresponding values from a dictionary. Args: sql_query (str): The origina...
magic_instruct_75k
61,075
Write a Python function to calculate the total number of weight updates that will be performed during the training process of a neural network using stochastic gradient descent. The function should take two lists as input: one for learning rates and one for batch sizes. The function should return a dictionary where the...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict import math def calculate_weight_updates(learning_rates: List[float], batch_sizes: List[int]) -> Dict[tuple, int]: """ Calculate the total number of weight updates for each combination of learning ...
magic_instruct_75k
61,079
Write a Python function to calculate the total cost of a meal including tax and tip. The function should take the meal cost, tip percentage, and tax percentage as input and return the total cost of the meal rounded to the nearest integer. The code should start with: ```python def calculate_total_cost(meal_cost: float,...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_total_cost(meal_cost: float, tip_percent: int, tax_percent: int) -> int: """ Calculate the total cost of a meal including tax and tip. Args: meal_cost (float): The cost of the meal before tax and tip. ...
magic_instruct_75k
61,087
Write a Python function to calculate the sum of all unique multiples of 3 and 5 below a given limit efficiently. The function should be optimized to avoid iterating through all numbers below the limit, instead using mathematical formulas to compute the sum of multiples. The code should start with: ```python def sum_of...
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_multiples(limit: int) -> int: """ Calculate the sum of all unique multiples of 3 and 5 below the given limit. Args: limit (int): The upper limit (exclusive) for the multiples. Returns: int: T...
magic_instruct_75k
61,092
Write a Python function to retrieve color information from a configuration dictionary based on a given section and paint type. The configuration dictionary is stored in a module-level variable `config.colors`, where the keys are the color sections and the values are dictionaries containing color information for each se...
Here is the Python code to solve the given problem in the markdown block: ```python COLOR_BRUSH = 0 COLOR_PEN = 1 def getColorFromConfig(section, paint_type): """ Retrieves the color information from the configuration dictionary based on the given section and paint type. Args: section (str): The s...
magic_instruct_75k
61,107
Write a Python function that takes an integer `num1` as input and returns the sum of `num1` and a predefined integer `num2`, which is set to 20. The function should be named `calculate_sum`. The code should start with: ```python def calculate_sum(num1: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_sum(num1: int) -> int: """ Calculate the sum of the input integer `num1` and a predefined integer `num2` which is 20. Args: num1 (int): The input integer to be added to `num2`. Returns: in...
magic_instruct_75k
61,120
Write a Python function to count the occurrences of each color on a game board represented by a 2D list. Each cell in the board is represented by an integer, where each integer corresponds to a different color. The function should return a dictionary where the keys are the colors (integers) and the values are the count...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def get_color_count(board: List[List[int]]) -> Dict[int, int]: """ Counts the occurrences of each color on a game board represented by a 2D list. Args: board (List[List[int]]): A 2D li...
magic_instruct_75k
61,130
Implement a Python function to interpret a simple expression language consisting of two types of expressions: `ValueExpr` and `PowExpr`. A `ValueExpr` represents a single numeric value, while a `PowExpr` represents an exponentiation operation between two sub-expressions. The `interpret` method for `PowExpr` should retu...
Here is the Python code to solve the given problem in the markdown block: ```python import math class ValueExpr: def __init__(self, value: float): """ Initialize a ValueExpr with a given numeric value. Args: value (float): The numeric value to be stored. """ sel...
magic_instruct_75k
61,142
Write a Python function to generate a Django migration script that adds a new field to an existing model. The function should take the necessary parameters and return the migration script as a string. The migration script should include the dependencies and the operation to add the field with the specified attributes. ...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_migration_script(app_name: str, model_name: str, field_name: str, field_type: str, max_length: int, allow_blank: bool) -> str: """ Generates a Django migration script to add a new field to an existing model. Ar...
magic_instruct_75k
61,144
Write a Python function to determine the list of source files that need to be included in a build based on the provided build flags related to the MCP23017 I/O expander interface options. The function should take a dictionary `cppdefines` as input, where the key "CPPDEFINES" maps to a list of build flags. The function ...
Here is the Python code to solve the given problem in the markdown block: ```python def get_source_files(cppdefines: dict) -> list: """ Determine the list of source files to be included in the build based on the provided build flags. Args: cppdefines (dict): A dictionary containing the build flags....
magic_instruct_75k
61,150
Write a Python function to calculate the proportion of positive integers in a given array of integers. The function should return the proportion as a floating-point number rounded to 6 decimal places. The code should start with: ```python from typing import List def calculate_positive_proportion(arr: List[int]) -> fl...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_positive_proportion(arr: List[int]) -> float: """ Calculate the proportion of positive integers in a given array of integers. Args: arr (List[int]): The array of integers from ...
magic_instruct_75k
61,159
Write a Python function to evaluate the clustering results by comparing a set of gold standard documents (`gold_documents`) with a set of automatically generated documents (`auto_documents`). The function should return a confusion matrix that represents the comparison results. Additionally, implement a function to calc...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def evaluate_clusters(gold_documents: List[str], auto_documents: List[str]) -> Dict[str, Dict[str, int]]: """ Evaluate the clustering results by comparing gold standard documents with automatically...
magic_instruct_75k
61,167
Write a Python function to process a given state represented as a list of integers and return a modified version of it. The function should perform the following operations: 1. Remove all occurrences of the number 0 from the state. 2. Sort the remaining numbers in ascending order. 3. If the resulting list is empty, ret...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def process_state(state: List[int]) -> List[int]: """ Processes a given state list and returns a modified version of it. Args: state (List[int]): The state list to be processed. Returns...
magic_instruct_75k
61,175
Write a Python function to automate the process of starting a development environment for a messaging broker plugin. The messaging broker in question is Mosquitto, and the function should handle the setup and initialization of the plugin for development purposes. The function should: 1. Set up the necessary environmen...
Here is the Python code to solve the given problem in the markdown block: ```python import subprocess def start_mosquitto_plugin_dev_env(mosquitto_conf_path: str) -> None: """ Automates the process of starting a development environment for a Mosquitto plugin. Args: mosquitto_conf_path (str): The p...
magic_instruct_75k
61,188
Write a Python function to filter a list of dictionaries containing information about literary prizes based on a given title. Each dictionary represents a prize and contains details about the prize, such as the title of the winning work and the year it was awarded. The function should return a new list containing the d...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def filter_prizes(prizes: List[Dict], title: str) -> List[Dict]: """ Filters a list of dictionaries containing information about literary prizes based on a given title. Args: prizes (L...
magic_instruct_75k
61,190
Write a Python function to count the occurrences of each letter in a given list and store the results in a dictionary. The function should take a list of letters as input and return a dictionary where the keys are the unique letters in the input list and the values are the counts of each letter. The code should start ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_letters(letter_list: List[str]) -> Dict[str, int]: """ Counts the occurrences of each letter in a given list and returns a dictionary with the counts. Args: letter_list (List...
magic_instruct_75k
61,193
Implement a Python class `Repository` that simulates a software repository and its associated operations. The class should support the following operations: 1. **Adding a new software release**: Implement a method `add_release` that takes a `release_name` as an argument and adds it to the list of releases. 2. **Removin...
Here is the Python code to solve the given problem in the markdown block: ```python class Repository: def __init__(self, initial_releases=None): """ Initialize the Repository with an optional list of initial software releases. Args: initial_releases (list, optional): A list of i...
magic_instruct_75k
61,202
Write a Python function to filter out and return a list of prime numbers from a given list of integers. A prime number is defined as a natural number greater than 1 that has no positive divisors other than 1 and itself. The function should be efficient and handle various edge cases, such as an empty list or a list cont...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_primes(numbers: List[int]) -> List[int]: """ Filters and returns a list of prime numbers from the given list of integers. Args: numbers: A list of integers to filter for prime numbe...
magic_instruct_75k
61,206
Write a Python function to generate a Minikube start command based on user input for memory, CPU, Kubernetes version, and cluster signing certificate file paths. The function should validate the user input and construct the command accordingly. The function should accept the following inputs: - `memory`: The amount of ...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_minikube_start_command(memory: int, cpus: int, kubernetes_version: str, cert_file: str, key_file: str) -> str: """ Generates a Minikube start command based on the provided inputs. Args: memory (int): Th...
magic_instruct_75k
61,213
Write a Python function to process a list of orders for different types of containers and return a dictionary containing the total quantity of each type of container ordered. Each order is represented by a dictionary with keys 'tpCacamba' (type of container) and 'quantidade' (quantity ordered). The function should aggr...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def aggregate_container_orders(orders: List[Dict[str, any]]) -> Dict[str, int]: """ Aggregates the quantities of each type of container from a list of orders. Args: orders (List[Dict[s...
magic_instruct_75k
61,214
Create a Python class to manage the player's inventory in a 2D platformer game. The inventory should track the number of coins and keys collected by the player, with a maximum limit of 3 keys. Additionally, the class should manage a sprint bar that represents the player's sprint level. The class should provide methods ...
Here is the Python code to solve the given problem in the markdown block: ```python class GameInventory: def __init__(self): """ Initialize the inventory attributes. """ self.coins = 0 self.keys = 0 self.sprint_level = 0 def add_coin(self): """ Ad...
magic_instruct_75k
61,243
Write a Python function to add a layer of zeros around a given 2D grid. The grid is represented as a list of lists, where each inner list represents a row of the grid. Each cell in the grid contains an integer value. The function should add a layer of zeros to the top, bottom, left, and right sides of the grid. The fu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def add_layer_zero(grid: List[List[int]]) -> List[List[int]]: """ Adds a layer of zeros around the given 2D grid. Args: grid (List[List[int]]): A 2D list of integers representing the origina...
magic_instruct_75k
61,250
Write a Python function to process a series of data points and organize them into a specific data structure. The function should take a list of data points as input and return a dictionary containing the processed data. Each data point is represented as a list of lists, where each inner list contains individual data e...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def process_data_points(data_points: List[List[List[int]]]) -> Dict[int, List[int]]: """ Processes a series of data points and organizes them into a dictionary. Each data point is represented ...
magic_instruct_75k
61,268
Implement a role-based access control system for a project management application. The system should allow users to have different roles within a project, such as owner and delegate. Additionally, the system should handle error messages related to project collections and iRODS backend initialization. 1. Implement a fu...
Here is the Python code to solve the given problem in the markdown block: ```python def get_project_role(user_role: str) -> str: """ Returns the corresponding project role constant for a given user role. Args: user_role (str): The role of the user in the project. Returns: str: The proj...
magic_instruct_75k
61,286
Write a Python function to calculate the properties of a rectangle `r` based on the state of an animation. The rectangle `r` has four properties: `left`, `top`, `right`, and `bottom`. The animation state is represented by the variable `animation_state`. When `animation_state` is 4 or 5, the rectangle's properties are s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple def calculate_rectangle_properties(animation_state: int, f: int) -> Tuple[int, int, int, int]: """ Calculate the properties of a rectangle based on the animation state. Args: animation_stat...
magic_instruct_75k
61,338
Write a Python function to implement the mutation operation for a genetic algorithm. The function should take an individual from the population and a mutation rate as input and return the mutated individual. The mutation operation should randomly alter some genes of the individual based on the given mutation rate. The ...
Here is the Python code to solve the given problem in the markdown block: ```python import random def mutate_individual(individual, mutation_rate): """ Mutates an individual based on the given mutation rate. Args: individual (tuple): A tuple representing the individual's genes. mutation_ra...
magic_instruct_75k
61,342
Write a Python function `handle_path` that manipulates a hierarchical data structure represented by nested dictionaries and lists. The function should ensure that the necessary elements exist to access or modify the specified path within the hierarchical data structure. The path is represented as a list of indices or k...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def handle_path(hmap: Union[dict, list], path: List[Union[int, str]], next_element_type: type) -> Union[dict, list]: """ Ensures that the necessary elements exist in a hierarchical data structure ...
magic_instruct_75k
61,352
Write a Python function to calculate the log probability of a target location in a grid environment given a prior distribution. The prior distribution is represented as a 2D array of floating-point numbers, where each value represents the probability of a cell being occupied. The target location is specified by a tuple...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import math def calculate_log_probability(prior_distribution: List[List[float]], target_location: Tuple[int, int]) -> float: """ Calculate the log probability of a target location in a grid enviro...
magic_instruct_75k
61,373
Write a Python function to increment a given string representing a non-negative integer by 1 without converting the string to an integer. The function should handle strings of length up to 1000. The code should start with: ```python def incrementString(numString: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def incrementString(numString: str) -> str: """ Increment a given string representing a non-negative integer by 1 without converting it to an integer. Args: numString (str): A string representing a non-negative inte...
magic_instruct_75k
61,402
Write a Python function to extract variable assignments from a given string and store them in a dictionary. The input string contains multiple lines, each with a variable assignment in the format "variable_name=value". The variable names consist of alphabetic characters and digits, and the values can be any string. If ...
Here is the Python code to solve the given problem in the markdown block: ```python def extract_variables(input_string: str) -> dict: """ Extracts variable assignments from a given string and stores them in a dictionary. Args: input_string (str): A string containing multiple lines, each with a vari...
magic_instruct_75k
61,405
Write a Python function to process a list of strings and append a new line character (`\n`) to each string. The function should take a list of strings as input and return a new list with each string appended with a new line character. The code should start with: ```python from typing import List def append_new_lines(...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def append_new_lines(strings: List[str]) -> List[str]: """ Appends a new line character (`\n`) to each string in the input list. Args: strings (List[str]): A list of strings to which the new...
magic_instruct_75k
61,411
Write a Python function to remove duplicate vowels from a given string while preserving the order of their first appearance. The input string contains only lowercase vowels (a, e, i, o, u). The function should return a new string with all duplicate vowels removed. The code should start with: ```python def remove_dupli...
Here is the Python code to solve the given problem in the markdown block: ```python def remove_duplicates(vowels: str) -> str: """ Removes duplicate vowels from the given string while preserving the order of their first appearance. Args: vowels (str): A string containing only lowercase vowels (a, e...
magic_instruct_75k
61,415
Write a Python function to calculate the smallest angle in degrees between the hour and minute hands of an analog clock. The function should take two integers, `hour` and `minute`, as input, representing the time on the clock in 24-hour format. The function should return the smallest angle formed between the hour and m...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_clock_angle(hour: int, minute: int) -> float: """ Calculate the smallest angle in degrees between the hour and minute hands of an analog clock. Args: hour (int): The hour in 24-hour format. min...
magic_instruct_75k
61,425
Write a Python function to sort a stack in ascending order using only one additional stack. The input stack will contain integers, and you should return the sorted stack. The function should be named `sortStack` and should take a list of integers as input, representing the stack. The function should return a list of in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sortStack(stack: List[int]) -> List[int]: """ Sorts a stack in ascending order using only one additional stack. Args: stack (List[int]): The input stack represented as a list of integers...
magic_instruct_75k
61,428
Write a Python function to calculate the number of shares to buy or sell in order to adjust the portfolio to a target percentage of the portfolio value for a given asset. The function should take three parameters: the current total value of the portfolio, the target percentage of the portfolio that the asset should rep...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_shares_to_trade(current_portfolio_value: float, target_percentage: float, asset_price: float) -> float: """ Calculate the number of shares to buy or sell to adjust the portfolio to a target percentage of the portfo...
magic_instruct_75k
61,447
Write a Python function to clean a dictionary of data by ensuring that specified keys have valid values. If a key is missing or its corresponding value is invalid (e.g., `None`, empty string, etc.), it should be replaced with a default value provided as an argument. The function should start with: ```python from typin...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Any def clean_data(data: Dict[str, Any], keys: List[str], default: Any) -> Dict[str, Any]: """ Cleans the input data dictionary by ensuring that specified keys have valid values. If a key is m...