source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
magic_instruct_75k
72,740
Write a Python function to count the number of unique items in a given list of items. Each item in the list is represented as a string. The function should return the count of unique items. The code should start with: ```python from typing import List def count_unique_items(items: List[str]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_unique_items(items: List[str]) -> int: """ Counts the number of unique items in a given list of items. Args: items (List[str]): A list of strings representing the items. Retur...
magic_instruct_75k
72,803
Write a Python function to determine if a given string is a valid parentheses sequence. A valid parentheses sequence is defined as a string consisting of only '(' and ')' characters, where each open parenthesis must have a corresponding closing parenthesis and the pairs must be properly nested. The function should sta...
Here is the Python code to solve the given problem in the markdown block: ```python def valid_parentheses(s: str) -> bool: """ Determines if the given string is a valid parentheses sequence. A valid parentheses sequence is defined as a string consisting of only '(' and ')' characters, where each open p...
magic_instruct_75k
72,804
Write a Python function to validate a given payload dictionary based on certain key-value requirements. The payload dictionary should contain specific keys, and each key should have a non-empty value. The function should return a boolean value indicating whether the payload dictionary meets these requirements. The cod...
Here is the Python code to solve the given problem in the markdown block: ```python def validate_payload(payload: dict) -> bool: """ Validates the given payload dictionary based on certain key-value requirements. The payload dictionary should contain the following keys: - 'labels': a dictionary with at...
magic_instruct_75k
72,823
Write a Python function to automate the installation of IntelliJ IDEA on a Linux system. The function should handle the installation of the required JDK and then proceed to install IntelliJ IDEA. The function should perform the following steps: 1. Check if the user has root privileges. If not, the script should request...
Here is the Python code to solve the given problem in the markdown block: ```python import subprocess import os def install_intellij_idea(): """ Automates the installation of IntelliJ IDEA on a Linux system. This function performs the following steps: 1. Checks if the user has root privileges. If not,...
magic_instruct_75k
72,832
Write a Python function to filter and format a list of device information. The function should perform the following steps: 1. Filter out any devices that are CD/DVD drives (identified by "/dev/cd" in the device path). 2. Filter out any devices that are not ATA devices. 3. Format the remaining devices in the following ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_and_format_devices(device_list: List[str]) -> List[str]: """ Filters and formats a list of device information. Args: device_list (List[str]): A list of strings where each string r...
magic_instruct_75k
72,836
Write a Python function to count the number of even numbers in a given list of integers. The function should be efficient and handle various edge cases, such as an empty list or a list with all odd numbers. The code should start with: ```python from typing import List def count_even_numbers(numbers: List[int]) -> int...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_even_numbers(numbers: List[int]) -> int: """ Counts the number of even numbers in a given list of integers. Args: numbers (List[int]): A list of integers. Returns: int...
magic_instruct_75k
72,841
Create a Python class `BankAccount` that simulates a simple banking system. The class should support basic operations such as account creation, deposit, withdrawal, and balance inquiry. Additionally, the class should handle exceptions for invalid operations and insufficient funds. The class should have the following f...
Here is the Python code to solve the given problem in the markdown block: ```python class InvalidOperationError(Exception): pass class InsufficientFundsError(Exception): pass class BankAccount: account_counter = 0 def __init__(self, initial_balance: float): """ Initialize a new bank a...
magic_instruct_75k
72,856
Write a Python function `extract_view_functions(urls)` that takes a list of URL patterns as input and returns a list of view function names. Each URL pattern is a string that follows the format `url(r'regex_pattern', views.view_function_name)`. The function should extract the view function names from these patterns and...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import re def extract_view_functions(urls: List[str]) -> List[str]: """ Extracts the view function names from a list of URL patterns. Args: urls (List[str]): A list of URL patterns where eac...
magic_instruct_75k
72,872
Write a Python function `extract_metadata_info` that takes a code snippet as input and returns a dictionary containing the extracted metadata information. The metadata includes the copyright, version, author, email, and URL. The code snippet will be a multi-line string containing the metadata information in the format ...
Here is the Python code to solve the given problem in the markdown block: ```python import re def extract_metadata_info(code_snippet: str) -> dict: """ Extracts metadata information from a given code snippet and returns it as a dictionary. The code snippet is expected to contain metadata fields in the for...
magic_instruct_75k
72,877
Write a Python function to map old function names to new function names by removing a specific prefix from the old function names. The function should take a dictionary `function_mapping` where the keys are the old function names and the values are the new function names. The prefix to be removed is "ResNet_". The func...
Here is the Python code to solve the given problem in the markdown block: ```python def perform_function_mapping(function_mapping: dict) -> dict: """ Maps old function names to new function names by removing the prefix "ResNet_" from the old function names. Args: function_mapping (dict): A dictiona...
magic_instruct_75k
72,893
Write a Python function to determine if a given string is a valid Git branch name according to the specified rules. The function should return `True` if the input string is a valid Git branch name and `False` otherwise. The rules for a valid Git branch name are: 1. It cannot contain any whitespace characters. 2. It ca...
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_git_branch(branch_name: str) -> bool: """ Determines if the given string is a valid Git branch name. A valid Git branch name must satisfy the following conditions: 1. It cannot contain any whitespace charac...
magic_instruct_75k
72,913
Write a Python function to generate the first n prime numbers. 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 a list of the first `n` prime numbers. The code should start with: ```python def generate_p...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_primes(n: int) -> list: """ Generate the first n prime numbers. Args: n (int): The number of prime numbers to generate. Returns: list: A list containing the first n prime numbers. """ ...
magic_instruct_75k
72,930
Write a Python function to flatten a multi-dimensional array representing an image into a one-dimensional array. The function should handle any number of dimensions, not just 2D arrays. The code should start with: ```python from typing import List, Any def flatten_image(image: List[Any]) -> List[Any]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def flatten_image(image: List[Any]) -> List[Any]: """ Flattens a multi-dimensional array into a one-dimensional array. Args: image (List[Any]): The multi-dimensional array to be flatten...
magic_instruct_75k
72,989
Create a Python function `social_media_integration` that interacts with different social media platform modules and performs specific tasks based on the input parameters. The function should support three platforms: "Admin", "Discord", and "Twitch", and three tasks: "fetch_data", "post_data", and "update_profile". The ...
Here is the Python code to solve the given problem in the markdown block: ```python def social_media_integration(platform: str, task: str) -> str: """ Interacts with different social media platform modules and performs specific tasks. Args: platform (str): The name of the social media platform. Sup...
magic_instruct_75k
72,999
Write a Python function to reverse the order of words in a given string. The function should take a string as input and return the string with the order of words reversed. A word is defined as a sequence of non-space characters. The code should start with: ```python def reverse_words(s: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_words(s: str) -> str: """ Reverses the order of words in a given string. Args: s (str): The input string containing words to be reversed. Returns: str: The string with the order of words rev...
magic_instruct_75k
73,043
Write a Python function to format a multi-dimensional array and return the formatted string. The function should iterate through each element of the multi-dimensional array and format each element into a string following the pattern: "Element at position [i][j] is: value", where `i` and `j` represent the indices of the...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def format_multi_array(arr: List[List[int]]) -> str: """ Formats a multi-dimensional array into a string. Args: arr (List[List[int]]): A multi-dimensional array of integers. Returns: ...
magic_instruct_75k
73,065
Write a Python function to simulate the behavior of the given bash script. The function should take a string `mailcow_installer_function` as input and perform different actions based on its value. If the value is "4", the function should return "Exit with status code 0". For any other value, the function should return ...
Here is the Python code to solve the given problem in the markdown block: ```python def mailcow_installer(mailcow_installer_function: str) -> str: """ Simulate the behavior of a bash script that processes a configuration file for a mail server installation. Args: mailcow_installer_function (str): T...
magic_instruct_75k
73,074
Write a Python function to search for a specific key in a singly linked list. The linked list is represented using a class `Node` with attributes `data` and `next`. The function should return `True` if the key is found in the linked list, and `False` otherwise. The function should start with: ```python def search_key(h...
Here is the Python code to solve the given problem in the markdown block: ```python class Node: def __init__(self, data): self.data = data self.next = None def search_key(head: Node, key: int) -> bool: """ Searches for a specific key in a singly linked list. Args: head (Node): ...
magic_instruct_75k
73,081
Write a Python function to calculate the lengths of each exon from a given list of exon coordinates. Each exon is represented by a tuple containing its start and end points. The function should return a list containing the lengths of each exon. The code should start with: ```python from typing import List, Tuple def ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def calculate_exon_lengths(exon_coordinates: List[Tuple[int, int]]) -> List[int]: """ Calculate the lengths of each exon from a given list of exon coordinates. Args: exon_coordinates ...
magic_instruct_75k
73,086
Write a Python function to initialize a logging system based on the build configuration of a software library. The library can be built with either shared or static linkage. If the library is built with shared linkage, the logging system needs to be explicitly initialized. If the library is built with static linkage, t...
Here is the Python code to solve the given problem in the markdown block: ```python def initializeLoggingSystem(): """ Initializes the logging system based on the build configuration of the library. If the library is built with shared linkage (BUILD_SHARED_LIBS is defined), the logging system is explic...
magic_instruct_75k
73,087
Write a Python function `extract_migration_info` that processes a list of database migration operations and extracts specific information from each `AlterField` operation. Each migration operation is represented as a dictionary containing details about the operation. The function should extract the model name, field na...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union, Tuple def extract_migration_info(migrations: List[Dict[str, Union[str, Dict[str, str]]]]) -> List[Tuple[str, str, str, str, str]]: """ Extracts specific information from a list of database ...
magic_instruct_75k
73,093
Write a Python function to generate a configuration file content for a version control system based on the provided parameters. The function should take in the name of the version control tool, the working directory, a boolean indicating whether to use cache, and the revision to be used. The function should return the ...
Here is the Python code to solve the given problem in the markdown block: ```python def write_config_file(tool_name: str, working_directory: str, use_cache: bool, revision: str) -> str: """ Generates a configuration file content for a version control system based on the provided parameters. Args: t...
magic_instruct_75k
73,132
Write a Python function to calculate the total amount spent by each customer from a list of transactions. Each transaction is represented as a tuple containing the customer's name, the item purchased, and the purchase amount. The function should return a dictionary where the keys are the customer names and the values a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def calculate_total_spent(transactions: List[Tuple[str, str, float]]) -> Dict[str, float]: """ Calculate the total amount spent by each customer from a list of transactions. Args: ...
magic_instruct_75k
73,255
Write a Python function to determine the optimal locations for placing a given number of power generators in a network to minimize the total cost of power transmission. The network is represented by an adjacency matrix, where `adj_matrix[i][j]` is the cost of transmitting power between nodes `i` and `j`. The function s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import numpy as np from itertools import combinations def optimize_generator_placement(n: int, m: int, k: int, adj_matrix: np.ndarray) -> List[int]: """ Determine the optimal locations for placing k powe...
magic_instruct_75k
73,265
Write a Python function to simulate a beamline using given energy limits and the number of rays. The function should generate a list of simulated energy values within the specified energy limits and return this list. The code should start with: ```python from typing import List import random def simulate_beamline(elim...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def simulate_beamline(elimits: List[float], nrays: float) -> List[float]: """ Simulate a beamline using the given energy limits and the number of rays. Args: elimits (List[floa...
magic_instruct_75k
73,269
Create a Python class method that determines whether a result file is the main file in a distributed result set. The method should return `True` if the global number of nodes does not equal the number of nodes in the file, and `False` otherwise. The method should be named `_is_main` and should be part of a class that h...
Here is the Python code to solve the given problem in the markdown block: ```python class ResultFile: def __init__(self, resultheader): self._resultheader = resultheader def _is_main(self): """Determines if this result file is the main file in a distributed result set Returns -...
magic_instruct_75k
73,270
Write a Python function to perform a depth-first search (DFS) on a given JSON object and return a list of all the keys encountered during the traversal. The function should handle nested objects and arrays within the JSON structure. The code should start with: ```python from typing import List, Union def get_json_keys...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def get_json_keys(json_object: Union[dict, list]) -> List[str]: """ Perform a depth-first search on a given JSON object and return a list of all the keys encountered during the traversal. Arg...
magic_instruct_75k
73,280
Write a Python function to generate a formatted output string from a dictionary of metrics. The function should take in a dictionary where the keys are target names and the values are dictionaries of metric keys and their corresponding values. The output string should be formatted such that each line contains a target ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def generate_output_string(metrics: Dict[str, Dict[str, float]]) -> str: """ Generates a formatted output string from a dictionary of metrics. Args: metrics (Dict[str, Dict[str, float]]): A ...
magic_instruct_75k
73,282
Write a Python function to count the frequency of each unique command-line argument, ignoring the script name (the first argument). The function should take a list of command-line arguments as input and return a dictionary where the keys are the unique arguments and the values are their respective frequencies. The cod...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_cmdline_args(cmdline_args: List[str]) -> Dict[str, int]: """ Counts the frequency of each unique command-line argument, ignoring the script name. Args: cmdline_args (List[str...
magic_instruct_75k
73,311
Write a Python function to select important features based on their importance scores and a given threshold. The function should return a list of feature names whose scores are greater than or equal to the threshold. If no features meet the threshold, the function should return an empty list. The code should start wit...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def select_important_features(features: List[str], scores: List[float], threshold: float) -> List[str]: """ Selects important features based on their importance scores and a given threshold. Args: ...
magic_instruct_75k
73,312
Create a Python function to manage a collection of results from a series of computations. The function should provide methods for running computations, retrieving results, and cleaning up the collection. Specifically, implement a function `sum_result_manager` that calculates the sum of a given list of numbers and store...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, TypeVar F = TypeVar('F', int, float) def sum_result_manager(numbers: List[F]) -> 'SumResultManager': return SumResultManager(numbers) class SumResultManager: def __init__(self, numbers: List[F]): ...
magic_instruct_75k
73,318
Write a Python function to extract the values of a specific column from a given 2D grid (list of lists) based on the coordinates provided in a tuple. The function should return a list containing the values of the entire column where the cell at the specified coordinates is located. The code should start with: ```pytho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def get_column_values(grid: List[List[int]], t: Tuple[int, int]) -> List[int]: """ Extracts the values of a specific column from a given 2D grid based on the coordinates provided in a tuple. ...
magic_instruct_75k
73,320
Write a Python function to calculate the total amount of water required for all the plants in a gardening system to grow. The gardening system is represented by a dictionary where each key is a plant name and the corresponding value is a dictionary containing the type of plant, the water requirement in milliliters, and...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def calculate_total_water_required(garden: Dict[str, Dict[str, float]]) -> float: """ Calculate the total amount of water required for all the plants in the gardening system to grow. Args: g...
magic_instruct_75k
73,326
Write a Python function to process custom HTML templates and override the header section with new content, leaving the main and footer sections unchanged. If a template does not contain a header section, it should be left unchanged. The function should take a list of strings representing the custom HTML templates and a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def overrideHeader(templates: List[str], newHeader: str) -> List[str]: """ Overrides the header section of custom HTML templates with new content, leaving the main and footer sections unchanged. Arg...
magic_instruct_75k
73,333
Write a Python function to generate personalized Ramadan greeting messages for a chatbot. The function should take a user's name as input and return a random greeting message from a predefined set of messages. Each message includes a placeholder "$target" that should be replaced with the user's name. The function shou...
Here is the Python code to solve the given problem in the markdown block: ```python import random from typing import List def generate_ramadan_greeting(name: str) -> str: """ Generates a personalized Ramadan greeting message for a chatbot. Args: name (str): The name of the user to be included in t...
magic_instruct_75k
73,347
Write a Python function to count the number of real numbers in a given list of floating-point numbers that have a non-zero fractional part. The function should be named `count_non_whole_numbers` and should take a list of floating-point numbers as input. The function should return an integer representing the count of nu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_non_whole_numbers(myList: List[float]) -> int: """ Counts the number of real numbers in a list that have a non-zero fractional part. Args: myList (List[float]): A list of floating-...
magic_instruct_75k
73,394
Write a Python function to compute the cumulative sum of elements in a given list of integers. The cumulative sum at each index `i` in the output list should be the sum of all elements from index 0 to index `i` in the input list. The code should start with: ```python from typing import List def cumulative_sum(inp: Li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def cumulative_sum(inp: List[int]) -> List[int]: """ Compute the cumulative sum of elements in the input list. Args: inp (List[int]): The input list of integers. Returns: List[i...
magic_instruct_75k
73,403
Write a Python function to calculate the sum of all even numbers in a given list. The function should take a list of integers as input and return the sum of all the even numbers in the list. The function should be named `sum_even_numbers`. The starter code is as follows: ```python from typing import List def sum_even...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_even_numbers(numbers: List[int]) -> int: """ Calculate the sum of all even numbers in the given list. Args: numbers (List[int]): A list of integers. Returns: int: The su...
magic_instruct_75k
73,416
Write a Python function to track the number of unique pages visited by each host for each application from a list of web traffic records. The function should return a dictionary representing the final state of the tracking system. The keys of the dictionary should be the application names, and the values should be dict...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Any def track_web_traffic(web_traffic_records: List[Dict[str, Any]]) -> Dict[str, Dict[str, List[str]]]: """ Track the number of unique pages visited by each host for each application from a list ...
magic_instruct_75k
73,435
Write a Python function to determine if a game is over based on a list of scores. The game ends if a player's score is less than or equal to the previous player's score. The function should return `True` if the game is over and `False` otherwise. The code should start with: ```python from typing import List def game_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def game_over(scores: List[int]) -> bool: """ Determine if the game is over based on a list of scores. The game ends if a player's score is less than or equal to the previous player's score. Ar...
magic_instruct_75k
73,445
Write a Python function to convert a given size in bytes to gigabytes. The function should take the size in bytes as input and return the size in gigabytes as output. The result should be rounded to two decimal places. The code should start with: ```python def bytes_to_gb(size_in_bytes: int) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python def bytes_to_gb(size_in_bytes: int) -> float: """ Converts a given size in bytes to gigabytes and rounds the result to two decimal places. Args: size_in_bytes (int): The size in bytes to be converted. Returns: ...
magic_instruct_75k
73,460
Write a Python function to calculate the sum of all elements in a given list of integers. The function should handle lists of any length, including empty lists. The code should start with: ```python from typing import List def calculate_sum(nums: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_sum(nums: List[int]) -> int: """ Calculate the sum of all elements in a given list of integers. Args: nums (List[int]): A list of integers whose sum needs to be calculated. ...
magic_instruct_75k
73,462
Implement the `perceptron` and `nand` functions to complete the functionality of the given code snippet. The `perceptron` function should compute the dot product of the input list `x` and the weight list `w`, then add the bias value. The `nand` function should return the result of the NAND operation on the elements of ...
Here is the Python code to solve the given problem in the markdown block: ```python def perceptron(x, w, bias): """ Compute the perceptron operation. Args: x (list): A list of two elements representing the input. w (list): A list of two weights corresponding to the input. bias (floa...
magic_instruct_75k
73,477
Write a Python function to generate `echo` commands that update a language file (`messages.en`) with new message keys and their corresponding values. The function should take a dictionary of message keys and values as input and return a string containing the `echo` commands. Each `echo` command should append a new mess...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_echo_commands(messages: dict) -> str: """ Generates `echo` commands to update a language file (`messages.en`) with new message keys and their corresponding values. Args: messages (dict): A dictionary wh...
magic_instruct_75k
73,478
Write a Python function `sort_project_attributes(attributes)` that takes a list of project attributes as input and returns a new list with the attributes sorted based on a predefined order. If an attribute is missing from the input list, it should be replaced with "UNKNOWN". The predefined order is provided in the `ord...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_project_attributes(attributes: List[str]) -> List[str]: """ Sorts the input list of project attributes based on a predefined order and replaces missing attributes with "UNKNOWN". Args: ...
magic_instruct_75k
73,485
Write a Python function to determine the maximum depth of nested parentheses in a given string. The string consists of only '(' and ')' characters. The function should return an integer representing the maximum depth of nesting. The code should start with: ```python def max_parentheses_depth(s: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def max_parentheses_depth(s: str) -> int: """ Calculate the maximum depth of nested parentheses in a given string. Args: s (str): The string containing only '(' and ')' characters. Returns: int: The max...
magic_instruct_75k
73,515
Write a Python function to find the highest version of each software package from a given list of software packages and their corresponding versions. The input list consists of tuples, where each tuple contains the name of the software package as a string and its version as a float. The version numbers are in the forma...
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(packages: List[Tuple[str, float]]) -> Dict[str, float]: """ Find the highest version of each software package from a given list of packages and their versions. ...
magic_instruct_75k
73,529
Write a Python function to implement a custom summation function that takes a list of integers and a lambda function as input. The function should return the sum of the list elements based on the logic defined within the lambda function. The lambda function should define the logic for modifying each element of the list...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Callable def custom_sum(numbers: List[int], func: Callable[[int], int]) -> int: """ Calculate the sum of the list elements based on the transformation logic defined in the lambda function. Args: ...
magic_instruct_75k
73,533
Write a Python function to concatenate four 2D arrays representing token IDs, masks, segment IDs, and block masks into a single 2D array. The concatenation should be performed in the order: `token_ids`, `mask`, `segment_ids`, and `block_mask`. The function should return the concatenated inputs. The code should start w...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def concatenate_inputs(token_ids: List[List[int]], mask: List[List[int]], segment_ids: List[List[int]], block_mask: List[List[int]]) -> List[List[int]]: """ Concatenates four 2D arrays representing token...
magic_instruct_75k
73,551
Write a Python function to calculate the length of the sequence generated by the given rules for a positive integer `n`. The sequence is generated using the following rules: 1. Start with the number `n`. 2. If the current number is even, divide it by 2. 3. If the current number is odd, multiply it by 3 and add 1. 4. Re...
Here is the Python code to solve the given problem in the markdown block: ```python def sequence_length(n: int) -> int: """ Calculate the length of the sequence generated by the given rules for a positive integer `n`. The sequence is generated using the following rules: 1. Start with the number `n`. ...
magic_instruct_75k
73,553
Write a Python function to generate a random n-dimensional array based on the given parameters. The function should take in the dimensions of the array, the distribution type for generating the array elements, and the periodicity type for handling boundary conditions. The function should return the generated array. Th...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def generate_random_array(shape: tuple, distribution: str, periodicity: str) -> np.ndarray: """ Generates a random n-dimensional array based on the given parameters. Args: shape (tuple): A tuple ...
magic_instruct_75k
73,563
Write a Python function to process a list of integers according to specific rules and return the modified list. The function should read a list of integers, manipulate each number according to the following rules, and then return the modified list: 1. Increment the number by 1. 2. Multiply the number by 2. The functio...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def process_numbers(numbers: List[int]) -> List[int]: """ Process a list of integers by incrementing each number by 1 and then multiplying the result by 2. Args: numbers (List[int]): A list ...
magic_instruct_75k
73,568
Write a Python function to retrieve the balance of a specified account from a cryptocurrency trading platform's API. The function should handle an optional account ID parameter. If the account ID is not provided, the function should default to retrieving the balance for a predefined account ID. The function should use ...
Here is the Python code to solve the given problem in the markdown block: ```python def get_balance(acct_id: str = None) -> dict: """ Retrieve the balance of a specified account from a cryptocurrency trading platform's API. Args: acct_id (str, optional): The account ID for which the balance needs t...
magic_instruct_75k
73,574
Write a Python function to process a configuration dictionary for a neural network model. The dictionary contains specifications for the model's backbone, neck, and head. The function should extract specific information from the dictionary and return it as a tuple. 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 Dict, Tuple def process_model_config(config_dict: Dict) -> Tuple[str, str, str, str, int]: """ Processes a configuration dictionary for a neural network model and extracts specific information. Args: ...
magic_instruct_75k
73,581
Write a Python function to calculate the total reflectance and transmittance of a material based on the given components and properties. The function should take into account the presence of specular and microfacet components for both reflection and transmission. The code should start with: ```python def calculateRT(R:...
Here is the Python code to solve the given problem in the markdown block: ```python def calculateRT(R: float, T: float, isSpecular: bool, distrib: float, fresnel: float, eta: list, mode: int) -> tuple: """ Calculate the total reflectance and transmittance of a material based on the given components and properti...
magic_instruct_75k
73,589
Write a Python function to calculate the degrees of nodes in a graph represented by an adjacency matrix. The adjacency matrix is a 2D list where `graph[i][j]` indicates the presence of an edge between node `i` and node `j`. The degree of a node is the sum of the values in its corresponding row in the adjacency matrix. ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def degrees(graph: List[List[int]]) -> List[int]: """ Calculate the degrees of nodes in a graph represented by an adjacency matrix. Args: graph (List[List[int]]): A 2D list representing the ...
magic_instruct_75k
73,590
Write a Python function to extract and validate the author's name and email from a given setup configuration dictionary. The setup configuration dictionary contains information about a Python package, including the name, version, description, long description, author, and author's email. Your function should extract th...
Here is the Python code to solve the given problem in the markdown block: ```python import re def validate_author_info(setup_config: dict) -> tuple: """ Extracts and validates the author's name and email from a setup configuration dictionary. Args: setup_config (dict): A dictionary containing setu...
magic_instruct_75k
73,594
Write a Python function to simulate a simplified version of the `sys.path.append` functionality. The function should take two parameters: 1. `sys_path` (list of strings): The original list of directories in `sys.path`. 2. `new_directory` (string): The new directory to be appended to `sys_path`. The function should ret...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def custom_path_append(sys_path: List[str], new_directory: str) -> List[str]: """ Simulates the `sys.path.append` functionality by appending a new directory to the given `sys_path` list. Args: ...
magic_instruct_75k
73,596
Write a Python function to generate a list of prime numbers up to a given limit using the Sieve of Eratosthenes algorithm. The function should take a non-negative integer `limit` as input and return a list of all prime numbers less than the given limit. If the limit is 0 or 1, the function should return an empty list. ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_primes(limit: int) -> List[int]: """ Generate a list of prime numbers up to a given limit using the Sieve of Eratosthenes algorithm. Args: limit (int): The upper limit for gener...
magic_instruct_75k
73,614
Create a Python function to determine the number of unique paths in a grid from the top-left corner to the bottom-right corner, where you can only move right or down. The grid may contain obstacles represented by the value 1, and empty spaces represented by the value 0. The code should start with: ```python from typin...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def unique_paths_with_obstacles(obstacle_grid: List[List[int]]) -> int: """ Calculate the number of unique paths from the top-left corner to the bottom-right corner in a grid with obstacles. Args: ...
magic_instruct_75k
73,618
Write a Python function to find the maximum profit that can be obtained by making at most one transaction (i.e., buying one share and selling one share of the stock) from a given list of integers representing the daily stock prices of a company. The transaction can only be made on consecutive days. The function should ...
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 at most one transaction (buying one share and selling one share) from a given list of stock pr...
magic_instruct_75k
73,628
Write a Python function to generate a report based on a list of recordings. Each recording is represented as a dictionary with keys: 'recording_name', 'duration', 'storageSize', and 'created'. The function should categorize each recording based on the following rules: 1. If the recording duration is less than 60 second...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict from datetime import datetime, timedelta def generate_report(recordings: List[Dict[str, any]]) -> List[List[any]]: """ Generates a report based on the given list of recordings. Args: r...
magic_instruct_75k
73,631
Write a Python function to calculate the distance and direction between two points in a grid system. The function should take the zone, easting, and northing of the first point, the grid conversion parameters, and the grid distance as inputs. The function should return the distance and direction between the two points....
Here is the Python code to solve the given problem in the markdown block: ```python import math def calculate_distance_and_direction(zone1: int, east1: float, north1: float, grid1to2: str, grid_dist: float) -> (float, str): """ Calculate the distance and direction between two points in a grid system. Args...
magic_instruct_75k
73,632
Write a Python function to process a given text string according to the following rules: 1. Remove all characters from the input text except for letters (both lowercase and uppercase) and spaces. 2. If the input text contains more than one word, concatenate the words into a single string and separate them with a period...
Here is the Python code to solve the given problem in the markdown block: ```python def process_text(text: str) -> str: """ Processes the input text by removing all characters except for letters (both lowercase and uppercase) and spaces, and concatenates the words with a period if there are multiple words. ...
magic_instruct_75k
73,647
Write a Python function to efficiently find the k-th smallest element in a list of integers using the Quickselect algorithm. The Quickselect algorithm is a selection algorithm to find the k-th smallest element in an unordered list. It is similar to the QuickSort algorithm but only recurses into one half of the data. T...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_kth_smallest(nums: List[int], k: int) -> int: """ Finds the k-th smallest element in the given list of integers using the Quickselect algorithm. Args: nums (List[int]): The list of ...
magic_instruct_75k
73,654
Write a Python function to process the `ERROR_BRANCH` environment variable and perform specific operations based on its value. The `ERROR_BRANCH` variable follows the format `<Project>-<Type>-<Number>`, where: - `<Project>` is the name of the project (alphanumeric, no spaces). - `<Type>` is the type of error (alphanume...
Here is the Python code to solve the given problem in the markdown block: ```python import os def process_error_branch(error_branch: str) -> None: """ Processes the ERROR_BRANCH environment variable and performs specific operations based on its value. Args: error_branch (str): The ERROR_BRANCH env...
magic_instruct_75k
73,677
Write a Python function to find all the paths to boolean values within a given JSON object. The paths should be represented as strings, where each key in the path is separated by a forward slash ("/"). The function should handle nested objects and arrays within the JSON object. The code should start with: ```python fr...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_boolean_paths(json_obj: dict) -> List[str]: """ Find all paths to boolean values within a given JSON object. Args: json_obj (dict): The JSON object to search for boolean values. ...
magic_instruct_75k
73,679
Write a Python function to generate a structured overview of university degree programs from a list of cleaned text snippets. The function should take the list of text snippets as input and return a dictionary where the keys are the degree program names and the values are their corresponding descriptions. The input lis...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def generate_degree_overview(text_snippets: List[str]) -> Dict[str, str]: """ Generates a structured overview of university degree programs from a list of cleaned text snippets. Args: ...
magic_instruct_75k
73,689
Write a Bash script to automate the backup and archiving of MySQL databases. The script should perform the following tasks: 1. **Dump SQL Data**: Use `mysqldump` to dump the SQL data of a specified MySQL database. 2. **Create Archive**: Compress the dumped SQL data using `xz` and save it with a filename format: `mysql....
Here is the Python code to solve the given problem in the markdown block: ```bash #!/bin/bash # Define the directory for storing backups DIR="/path/to/backups" # Define the function to dump SQL data dump_sql() { # Dump the SQL data of the specified MySQL database mysqldump -u username -ppassword database_name } ...
magic_instruct_75k
73,704
Write a Python function to generate a list of date sequences for each month within a given date range. Each sequence should consist of the first and last date of a month within the given range. The function should return the list of date sequences in the format `[(first_date, last_date), ...]`. The code should start w...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import date, timedelta from typing import List, Tuple def generate_monthly_sequences(start_date: date, end_date: date) -> List[Tuple[date, date]]: """ Generate a list of date sequences for each month within a give...
magic_instruct_75k
73,708
Write a Python function to generate a Django migration operation code that renames a field within a model named `Image` in the `award` app. The function should take the existing field name and the new field name as input and return the migration operation code as a string. Ensure that the migration operation is compati...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_rename_field_migration(existing_field_name: str, new_field_name: str) -> str: """ Generates a Django migration operation code to rename a field within the `Image` model in the `award` app. Args: existin...
magic_instruct_75k
73,718
Write a Python function to convert a given string into Morse code. The function should ignore any characters that are not letters (i.e., numbers, punctuation, and whitespace). Each character in the input string will be separated by a single space in the Morse code output. The function should be case-insensitive, meanin...
Here is the Python code to solve the given problem in the markdown block: ```python def morse_code_converter(input_string: str) -> str: """ Converts a given string into Morse code. Args: input_string (str): The input string to be converted into Morse code. Returns: str: The Morse code ...
magic_instruct_75k
73,730
Write a Python function to process a dictionary of astronomical sources, where each source has a unique identifier and an alias. The function should iterate through the dictionary and perform operations based on the presence of specific keys in each source. Specifically, the function should: 1. Check if the source has ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Any def process_astronomical_sources(sources: Dict[str, Dict[str, Any]]) -> int: """ Process a dictionary of astronomical sources and count the number of sources that have an 'alias' key. Args: ...
magic_instruct_75k
73,749
Write a Python function to process a dictionary of cases and their corresponding sections, and construct a response in a specific format. The function should take the `cases_db` dictionary as input and return a response in the specified format. The response should include a `success` flag and a `response` dictionary co...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Any def construct_response(cases_db: Dict[int, List[str]]) -> Dict[str, Any]: """ Constructs a response from a dictionary of cases and their corresponding sections. Args: cases_db (Di...
magic_instruct_75k
73,763
Write a Python function to calculate the Fibonacci sequence up to a given limit. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The function should take an integer `limit` as input and return a list of Fibonacci numbers up to the l...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_fibonacci(limit: int) -> List[int]: """ Calculate the Fibonacci sequence up to a given limit. The Fibonacci sequence is a series of numbers where each number is the sum of the two prec...
magic_instruct_75k
73,788
Write a Python function to count the occurrences of each type of database migration operation in a given list of operations. Each operation is represented as an instance of a migration class, and the types of operations include `AddField`, `RemoveField`, `AlterField`, and `RenameField`. The function should return a dic...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_migration_operations(operations: List) -> Dict[str, int]: """ Counts the occurrences of each type of database migration operation in a given list. Args: operations (List): A ...
magic_instruct_75k
73,815
Write a Python function to validate the setup configuration for a Python package. The setup configuration is provided as a dictionary with specific keys and value types. The function should check if all the required keys are present and if their values are of the correct type. Additionally, it should ensure that the 'i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def validate_setup(setup_config: Dict[str, any]) -> bool: """ Validates the setup configuration for a Python package. Args: setup_config (Dict[str, any]): A dictionary containing the s...
magic_instruct_75k
73,858
Write a Python function to validate the fields of a serializer used in a web application. The serializer is responsible for handling expiring links for images. The function should ensure that the serializer contains the expected fields and their corresponding data types. The serializer should have two fields: 1. `imag...
Here is the Python code to solve the given problem in the markdown block: ```python def validate_expiring_link_serializer(serializer_data: dict) -> bool: """ Validates the fields of a serializer used for handling expiring links for images. The serializer should contain the following fields: - `image_id...
magic_instruct_75k
73,867
Write a Python function to parse a Django migration file and extract the names of the models and fields being modified by `AddField` operations. The function should return a dictionary where the keys are the model names and the values are lists of field names being modified. The function should start with: ```python fr...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List import re def parse_migration_file(migration_file_content: str) -> Dict[str, List[str]]: """ Parses a Django migration file content and extracts the names of the models and fields being modifie...
magic_instruct_75k
73,879
Write a Python function to create a zoom matrix for 3D transformations. The zoom matrix is a 4x4 matrix that represents scaling along the x, y, and z axes. The diagonal elements of the matrix represent the scaling factors for each axis, and the off-diagonal elements are zero. The function should take three scaling fact...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def create_zoom_matrix(zx: float, zy: float, zz: float) -> np.ndarray: """ Create a 4x4 zoom matrix for 3D transformations. The zoom matrix represents scaling along the x, y, and z axes. The diagonal ele...
magic_instruct_75k
73,915
Write a Python function to parse and analyze Fluentd performance test logs. The logs are generated every second and contain specific information about the log entry, such as the timestamp, log message, and log size. The function should be able to: 1. Calculate the average log size over a specific time period. 2. Identi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import re def analyze_fluentd_logs(logs: List[str]) -> Tuple[float, int, str, int]: """ Analyzes Fluentd performance test logs to calculate the average log size, identify the maximum log size ...
magic_instruct_75k
73,917
Write a Python function to calculate the weighted sum of the largest bounding box based on its width from a given list of bounding boxes and their corresponding weights. The function should also take a scaling factor into account. The code should start with: ```python from typing import List, Tuple def calculate_weig...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def calculate_weighted_sum(stars: List[Tuple[int, int, int, int]], levelWeights: List[int], sf: float) -> float: """ Calculate the weighted sum of the largest bounding box based on its width. ...
magic_instruct_75k
73,967
Write a Python function to calculate the scaling factor in micrometers per pixel based on the fraction of the image width occupied by a scale bar. The function should take a single parameter, `bar_frac`, which represents the fraction of the image width occupied by the scale bar. The function should return the scaling f...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_scaling_factor(bar_frac: float) -> float: """ Calculate the scaling factor in micrometers per pixel based on the fraction of the image width occupied by a scale bar. Args: bar_frac (float): The fractio...
magic_instruct_75k
73,970
Write a Python function to transpose a given 2x3 matrix. The transpose of a matrix is obtained by swapping its rows and columns. For a 2x3 matrix, the transpose will be a 3x2 matrix where the elements at the `i`-th row and `j`-th column will be the elements at the `j`-th row and `i`-th column of the original matrix. T...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def transpose_matrix(matrix: List[List[int]]) -> List[List[int]]: """ Transposes a given 2x3 matrix. Args: matrix (List[List[int]]): A 2x3 matrix represented as a list of lists. Returns...
magic_instruct_75k
73,979
Write a Python function to manage a list of students, allowing for the addition, removal, and display of student information. Each student has a name, age, and ID. The function should provide the following operations: 1. Add a student to the list. 2. Remove a student from the list based on their ID. 3. Display the info...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def manage_students(operation: str, students: List[Dict[str, any]], student: Dict[str, any] = None) -> List[Dict[str, any]]: """ Manages a list of students by performing operations such as adding, ...
magic_instruct_75k
73,989
Write a Python function to automate the installation of software dependencies for a project. The function should check if a specific tool, such as "docker-compose," is installed and, if not, download and install it. The function should also add the installed tool to the system's path. The function should be able to han...
Here is the Python code to solve the given problem in the markdown block: ```python import os import platform import subprocess import urllib.request import zipfile def install_docker_compose() -> None: """ Automates the installation of "docker-compose" if it is not already installed. Adds "docker-compose"...
magic_instruct_75k
74,002
Write a Python script to process simulation files based on specific input parameters. The script will take in five command-line arguments and perform different actions based on the input. 1. Check if the first argument is 'analyze' or 'simulate'. If it is 'analyze', set the `MODE` variable to 'analysis', and if it is ...
Here is the Python code to solve the given problem in the markdown block: ```python import sys def process_simulation_files(args: list) -> None: """ Process simulation files based on command-line arguments. Args: args (list): A list of command-line arguments. Returns: None: Prints the...
magic_instruct_75k
74,004
Write a Python function to simulate a simple task scheduler that can add, remove, and list tasks, as well as start the scheduler to execute the tasks. The tasks are represented as simple functions that perform some action when executed. The function should ensure that the tasks are executed in the order they were added...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Callable, Dict # Define the task scheduler tasks: List[Dict[str, str | Callable]] = [] def add_task(name: str, task: Callable) -> None: """ Adds a task to the scheduler. Args: name (str): ...
magic_instruct_75k
74,022
Write a Python function to validate the status codes of a list of dictionaries representing HTTP responses. Each dictionary contains a `status_code` key. The function should return `True` if all responses have a status code of 201, and `False` otherwise. The function should start with: ```python from typing import List...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def validate_status_codes(responses: List[Dict[str, int]]) -> bool: """ Validates if all HTTP responses in the list have a status code of 201. Args: responses (List[Dict[str, int]]): A...
magic_instruct_75k
74,056
Write a Python function to process a list of package dependencies and return a dictionary containing the package names as keys and their respective versions as values. The input list will consist of strings in the format "package_name>=version_number", where "package_name" is the name of the package and "version_number...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def extract_versions(install_requires: List[str]) -> Dict[str, str]: """ Extracts package names and their versions from a list of dependency strings. Args: install_requires (List[str])...
magic_instruct_75k
74,073
Write a Python function to parse a simplified version of a cross-platform data representation (XDR) source and extract relevant information. The XDR source consists of a series of data definitions, each defining a data structure. Each data definition starts with the keyword "struct" followed by the name of the structur...
Here is the Python code to solve the given problem in the markdown block: ```python import re def parseXDR(xdr_source: str) -> dict: """ Parses a simplified XDR source and extracts structure names and their field names. Args: xdr_source (str): The XDR source string to be parsed. Returns: ...
magic_instruct_75k
74,079
Write a Python function to process a call stack and generate a string that represents the sequence of function calls, excluding the class names but including the function names. The call stack information is provided as a list of tuples, where each tuple contains information about a specific function call in the format...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def process_call_stack(call_stack_info: List[Tuple[str, int, str, str]]) -> str: """ Processes the call stack information and generates a string representing the sequence of function calls. A...
magic_instruct_75k
74,096
Write a Python function to extract the URLs of web font files (ending with `.woff2`) from a given CSS file and then download these font files using the `wget` command. The CSS file contains `@font-face` declarations with `url` properties pointing to the font files. The function should perform the following steps: 1. Re...
Here is the Python code to solve the given problem in the markdown block: ```python import re import subprocess from typing import List def download_web_fonts(css_file_path: str, output_dir: str) -> None: """ Extracts URLs of web font files (ending with .woff2) from a given CSS file and downloads them using wg...
magic_instruct_75k
74,108
Write a Python function to calculate the Euclidean distance between two specified atoms in a molecular geometry dataset. The molecular geometry data is represented as a list of tuples, where each tuple contains the atomic symbol and the 3D coordinates (x, y, z) of an atom. The indices of the atoms are 0-based. The fun...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import math def calculate_atom_distance(geometry_data: List[Tuple[str, Tuple[float, float, float]]], atom_index1: int, atom_index2: int) -> float: """ Calculate the Euclidean distance between two ...
magic_instruct_75k
74,114
Write a Python function to generate a specific type of tile based on given input parameters. The function should take in the x and y coordinates of a point on the edge of a tile, along with a parameter specifying how to handle edge cases, and return the corresponding tile. The function signature is as follows: ```pytho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple def generate_tile(p_edge: Tuple[int, int], on_edge_use: str) -> str: """ Generates a specific type of tile based on the given x and y coordinates of a point on the edge of the tile, and a parameter ...
magic_instruct_75k
74,121
Write a Python function to determine the minimum number of additional statues needed to make the given array of distinct integers representing the heights of statues consecutive. The function should take an array of integers `statues` and return the minimum number of additional statues needed. The code should start wi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def makeArrayConsecutive2(statues: List[int]) -> int: """ Calculate the minimum number of additional statues needed to make the given array of distinct integers consecutive. Args: statues (L...
magic_instruct_75k
74,138
Write a Python function `process_dependencies` that takes in two lists of dependencies, `install_requires` and `tests_require`, and returns a dictionary with the categorized dependencies. The keys of the dictionary should be "install_requires" and "tests_require", and the values should be the corresponding lists of dep...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def process_dependencies(install_requires: List[str], tests_require: List[str]) -> Dict[str, List[str]]: """ Processes the given lists of dependencies and returns a dictionary with the dependencies...
magic_instruct_75k
74,162
Write a Python function to simulate a simple spinlock using atomic operations. A spinlock is a synchronization primitive that allows only one thread at a time to acquire the lock, while other threads continuously check until the lock becomes available. The spinlock should have the following properties and functions: 1...
Here is the Python code to solve the given problem in the markdown block: ```python import threading import time class Spinlock: def __init__(self): self.lock = threading.Lock() self.atomic_flag = False def spinlock_init(self): """ Initializes the spinlock by setting the atomic...
magic_instruct_75k
74,170
Write a Python function to generate license files for a given directory. The function should take two arguments: the directory path and an optional license boilerplate. If no boilerplate is provided, it should default to a standard license boilerplate. The function should then create a license file in each subdirectory...
Here is the Python code to solve the given problem in the markdown block: ```python import os def generate_license_files(directory_path: str, license_boilerplate: str = "license-boilerplate") -> None: """ Generates a LICENSE file in each subdirectory of the given directory using the provided or default license...
magic_instruct_75k
74,173
Write a Python function to calculate the total balance for a user's account after processing a list of transactions. Each transaction is represented as a dictionary with the keys "id" (transaction ID), "amount" (transaction amount), and "type" (transaction type, either "credit" or "debit"). The function should return t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union def calculate_balance(transactions: List[Dict[str, Union[int, str]]]) -> float: """ Calculate the total balance for a user's account after processing a list of transactions. Args: ...