source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
magic_instruct_75k
33,807
Write a Python function to repeat each character in a given string `s` once, followed by the original character. For example, if the input string is "hello", the output should be "hheelllloo". The code should start with: ```python def repeat_characters(s: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def repeat_characters(s: str) -> str: """ Returns a new string where each character in the original string is repeated once, followed by the original character. Args: s (str): The input string. Returns: ...
magic_instruct_75k
33,808
Create a Python function to manage and process a set of predefined event types for a game development framework. The framework provides a set of predefined event types, and your goal is to create a data structure and functions to manage these events. You are given the following enumeration of event types: ```python fr...
Here is the Python code to solve the given problem in the markdown block: ```python from enum import Enum from typing import List class EventType(Enum): GAMEPAD_BUTTON_DOWN = 1 GAMEPAD_BUTTON_UP = 2 QUIT = 3 WINDOW_MANAGER = 4 VIDEO_RESIZE = 5 USER = 6 class Event: """ Represents an ev...
magic_instruct_75k
33,816
Implement a Python class `XMLIterPrinter` that constructs XML elements with attributes and values. The class should have methods to add string, integer, and decimal attributes to the XML element. Each method should append the attribute in the format `name="value"`. The class should also manage a boolean member variable...
Here is the Python code to solve the given problem in the markdown block: ```python class XMLIterPrinter: def __init__(self): """ Initialize the XMLIterPrinter class. Attributes: theOpenStart (bool): Indicates whether the XML element is open for adding attributes. xm...
magic_instruct_75k
33,862
Write a Python function to generate a log message pattern based on the given input parameters. The function should construct a log message pattern using the provided variables and format it according to a specific template. The function should take the following parameters: - `level` (str): The log level, e.g., "INFO"...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_log_pattern(level: str, datetime: str, transaction: str, project_name: str, class_name: str, function_name: str, message: str) -> str: """ Generates a log message pattern based on the provided parameters. Args:...
magic_instruct_75k
33,888
Write a Python function `manage_files` that takes in a file system object `ceph`, a base directory `b`, and a list of tuples `files` representing the files to be created. Each tuple in `files` contains a file name and a boolean indicating whether it is a directory or a file. The function should use the provided `get_na...
Here is the Python code to solve the given problem in the markdown block: ```python import os import sys prefix = "data" def get_name(b, i, j): c = '{pre}.{pid}.{i}.{j}'.format(pre=prefix, pid=os.getpid(), i=i, j=j) return c, b + '/' + c def mkdir(ceph, d): print("mkdir {d}".format(d=d), file=sys.stderr)...
magic_instruct_75k
33,906
Write a Python function to calculate the number of possible moves a knight can make from a given cell on a 6x6 chessboard. The knight moves in an L-shape, which means it can move two squares in one direction and one square in a perpendicular direction. The function should be named `knight_moves` and should take two par...
Here is the Python code to solve the given problem in the markdown block: ```python def knight_moves(row: int, col: int) -> int: """ Calculate the number of possible moves a knight can make from a given cell on a 6x6 chessboard. Args: row (int): The row index of the cell (0 <= row <= 5). co...
magic_instruct_75k
33,908
Write a Python function to update metadata for database operations based on the operation type. The function should take a dictionary `metadata` and a string `operation_type` as inputs, and return the modified metadata dictionary. The metadata dictionary has a specific structure, and the function should update it accor...
Here is the Python code to solve the given problem in the markdown block: ```python def update_metadata(metadata: dict, operation_type: str) -> dict: """ Updates the metadata dictionary based on the operation type. Args: metadata (dict): A dictionary containing metadata information. operati...
magic_instruct_75k
33,909
Write a Python function to decode a list of integers into a corresponding message using a given decoding table. The decoding table is a dictionary where keys are integers and values are strings representing characters. The function should take a list of integers and the decoding table as input and return the decoded me...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def decode_message(integers: List[int], decode_table: Dict[int, str]) -> str: """ Decodes a list of integers into a corresponding message using a given decoding table. Args: integers (...
magic_instruct_75k
33,917
Write a Python function to determine if two lists of IDs are exact matches, meaning they contain the same IDs regardless of their order. The function should return `True` if the lists are exact matches, and `False` otherwise. The function should be efficient and handle lists of varying sizes. 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 exact_id_list_match(ids: List[int], matches: List[int]) -> bool: """ Determines if two lists of IDs are exact matches, meaning they contain the same IDs regardless of their order. Args: ...
magic_instruct_75k
33,920
Write a Python function to calculate the total cost of a customer's purchases at a store, including a fixed handling fee. The function should take the number of items purchased and the cost per item as inputs and return the total cost. The handling fee is a fixed amount of $15.00. The code should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_total_cost(num_items: int, cost_per_item: float) -> float: """ Calculate the total cost of a customer's purchases at a store, including a fixed handling fee. Args: num_items (int): The number of items ...
magic_instruct_75k
33,929
Write a Python function to implement a custom sorting algorithm based on the concept of repeatedly swapping adjacent elements if they are in the wrong order. The process should continue until no more swaps are needed, indicating that the list is sorted. The function should return the sorted list. The code should start...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def custom_sort(elements: List[int]) -> List[int]: """ Sorts the given list of integers using a custom sorting algorithm based on the concept of repeatedly swapping adjacent elements if they are in the w...
magic_instruct_75k
33,953
Write a Python function to convert a given number of seconds into a human-readable format. The function should take an integer value representing the number of seconds and return a string with the humanized value. The humanized value should be in the form of weeks, days, hours, minutes, and seconds, as applicable. The ...
Here is the Python code to solve the given problem in the markdown block: ```python def describe_seconds(value: int) -> str: """ Converts a given number of seconds into a human-readable format. Args: value (int): The number of seconds to convert. Returns: str: A string representing the...
magic_instruct_75k
33,961
Write a Python function to generate a list of `stow` commands for managing symbolic links for dotfiles. Each command should be in the format `stow -d $DOTFILES_HOME <package_name>`, where `$DOTFILES_HOME` is a predefined environment variable representing the directory where dotfiles are stored. The function should take...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_stow_commands(package_names: List[str]) -> List[str]: """ Generates a list of `stow` commands to manage symbolic links for dotfiles. Each command is in the format `stow -d $DOTFILES_HOM...
magic_instruct_75k
33,967
Write a Python function to convert a given hex code to its corresponding color name from a predefined color palette. The color palette is represented as a nested dictionary where the outer keys are color names (e.g., "orange", "cyan") and the inner keys are numerical values (e.g., 50, 100, 200) representing shades of t...
Here is the Python code to solve the given problem in the markdown block: ```python def hex_to_color_name(hex_code: str, color_palette: dict) -> str: """ Convert a given hex code to its corresponding color name from a predefined color palette. Args: hex_code (str): The hex code to be converted (e.g...
magic_instruct_75k
33,968
Write a Python function to implement a priority queue data structure that supports the following operations: 1. `del_pdq`: Delete the highest priority element from the priority queue. 2. `snd_pdq`: Insert an element into the priority queue with a specified priority. 3. `psnd_pdq`: Insert an element into the priority q...
Here is the Python code to solve the given problem in the markdown block: ```python import heapq from typing import Callable, Any class PriorityQueue: def __init__(self, capacity: int, priority_func: Callable[[Any], float]): """ Initialize the priority queue with a specified capacity and priority f...
magic_instruct_75k
33,990
Write a Python function to calculate the proportional font size for labels based on the figure size. The font size should be determined by multiplying the first element of the figure size by a given scaling factor. The function should handle cases where the figure size is provided as a tuple of integers and return the ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple def calculate_font_size(figsize: Tuple[int, int], scaling_factor: int = 5) -> int: """ Calculate the proportional font size for labels based on the figure size. The font size is determined by multi...
magic_instruct_75k
33,992
Write a Python function to validate a dictionary of specimen definitions based on a predefined set of fields and their corresponding data types. The function should ensure that the dictionary contains all the required fields and that their values match the expected data types. If any discrepancies are found, the functi...
Here is the Python code to solve the given problem in the markdown block: ```python def validate_specimen_definition(specimen_definition: dict) -> dict: """ Validates a dictionary of specimen definitions based on predefined fields and their corresponding data types. Args: specimen_definition (dict)...
magic_instruct_75k
33,997
Write a Python script to automate the process of uploading files to Dropbox using a custom uploader script. The script should achieve the following: 1. Download the `dropbox_uploader.sh` script from a specified URL. 2. Set the executable permission for the downloaded script. 3. Create two subfolders in Dropbox, named a...
Here is the Python code to solve the given problem in the markdown block: ```python import os import subprocess def upload_to_dropbox(subfolder_name: str, files: list) -> None: """ Automates the process of uploading files to Dropbox using a custom uploader script. Args: subfolder_name (str): The n...
magic_instruct_75k
33,999
Write a Python function `process_style_checks` that takes a dictionary of style check configurations as input and applies specific rules to determine the final set of configurations. The input dictionary contains boolean values indicating whether specific style checks should be applied. The function should apply the fo...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def process_style_checks(configurations: Dict[str, bool]) -> Dict[str, bool]: """ Processes a set of style check configurations and returns the final set of configurations based on certain rules. Ar...
magic_instruct_75k
34,002
Write a Python function to validate the correctness of a given arithmetic expression. The function should take an arithmetic expression in the format "operand1 operator operand2" (where `operand1` and `operand2` are integers, and `operator` is either '+' or '-') and an `expected_result` (integer). The function should r...
Here is the Python code to solve the given problem in the markdown block: ```python def validate_arithmetic_expression(expression: str, expected_result: int) -> bool: """ Validates whether the given arithmetic expression evaluates to the expected result. Args: expression (str): A string representin...
magic_instruct_75k
34,019
Write a Python function to simulate a simple game of dice where two dice are rolled, and the sum of the values obtained from each die is calculated. The function should return the sum of the dice values and print the type of the variable storing the sum. Additionally, the function should print a statement indicating th...
Here is the Python code to solve the given problem in the markdown block: ```python import random def roll_dice_and_sum(): """ Simulates rolling two six-sided dice, calculates the sum of the values obtained, prints the type of the variable storing the sum, and prints the name of the programmer. Return...
magic_instruct_75k
34,053
Write a Python function to update the rating of a branch in a tree structure based on the ratings of its nodes and a given factor. The function should take in a dictionary of nodes, the current branch rating, and a node factor. Each node in the dictionary has a `rating` attribute. The function should iterate through th...
Here is the Python code to solve the given problem in the markdown block: ```python def update_branch_rating(node_list: dict, branch_rating: float, node_factor: float) -> float: """ Update the branch rating based on the ratings of its nodes and a given factor. Args: node_list (dict): A dictionary c...
magic_instruct_75k
34,100
Write a Python function to process a list of URLs and extract specific information from them. The function should take a list of URLs as input and return a dictionary containing the extracted information. Each URL follows a specific pattern, and the function should extract the following information from each URL: 1. Th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union import re def extract_info(urls: List[str]) -> Dict[str, Union[str, int]]: """ Extracts process IDs and activity types from a list of URLs and returns them in a dictionary. Args: ...
magic_instruct_75k
34,101
Write a Python function to create a deep copy of a nested list without using the built-in `deepcopy` function from the `copy` module. The function should handle lists that contain other lists or non-list values. The deep copy should ensure that modifying the copied list does not affect the original list, and vice versa...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def custom_deep_copy(original: List[Any]) -> List[Any]: """ Creates a deep copy of a nested list. Args: original (List[Any]): The original nested list to be copied. Returns: ...
magic_instruct_75k
34,103
Write a Python function to surround existing jobs with new ones. The function should take in a list of existing jobs and a list of new jobs, and return a new list where each existing job is surrounded by the corresponding new jobs. The function should ensure that the length of the existing jobs list is always one less ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def surround_jobs(existing_jobs: List[str], new_jobs: List[str]) -> List[str]: """ Surround each existing job with corresponding new jobs and return the new list. Args: existing_jobs (List[s...
magic_instruct_75k
34,110
Write a Python function to automate the setup and configuration of a Linux server. The function should perform the following tasks: 1. Compile and install any necessary software using the `make` command. 2. Update the PHP configuration file to set the timezone to "Europe/Berlin" by appending a line to `/etc/php/7.3/apa...
Here is the Python code to solve the given problem in the markdown block: ```python import subprocess def setup_and_configure_server(): """ Automates the setup and configuration of a Linux server. This function performs the following tasks: 1. Compiles and installs necessary software using the `make` ...
magic_instruct_75k
34,115
Write a Python function `my_function` that takes a single number as input and returns the square of that number. Additionally, write another function `add_function` that takes two numbers as input and returns their sum. Ensure that the code runs successfully with the provided function calls and variable assignments. T...
Here is the Python code to solve the given problem in the markdown block: ```python def my_function(number: int) -> int: """ Calculate the square of the input number. Args: number (int): The number to be squared. Returns: int: The square of the input number. """ return number *...
magic_instruct_75k
34,145
Write a Python function to process a list of migration operations and return a dictionary containing the names of the models that are being created and deleted. Each migration operation is represented as a tuple containing the operation type and the model name. The function should start with: ```python from typing imp...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def process_migrations(migrations: List[Tuple[str, str]]) -> Dict[str, List[str]]: """ Processes a list of migration operations and returns a dictionary containing the names of the models ...
magic_instruct_75k
34,179
Write a Python function to remove trailing whitespace from each string in a given list of strings and another function to compare the original list of strings with the processed list, identifying any differences. The `trim_trailing_whitespace` function should take a list of strings as input and return a new list with t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def trim_trailing_whitespace(strings: List[str]) -> List[str]: """ Removes trailing whitespace from each string in the input list. Args: strings: A list of strings to be processed...
magic_instruct_75k
34,200
Write a Python function to generate a dependency graph from a list of package names and their dependencies. The function should take a list of tuples as input, where each tuple contains a package name as the first element and a list of its dependencies as the second element. The function should return a dictionary repr...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def generate_dependency_graph(packages: List[Tuple[str, List[str]]]) -> Dict[str, List[str]]: """ Generates a dependency graph from a list of package names and their dependencies. Args:...
magic_instruct_75k
34,218
Write a Python function to extract the IDs belonging to proteins from a given list of strings. Each string in the list represents a protein, and the ID is a substring within the string enclosed in square brackets. The function should return a list of all the IDs belonging to proteins. The code should start with: ```py...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import re def extract_protein_ids(proteins: List[str]) -> List[str]: """ Extracts the IDs belonging to proteins from a given list of strings. Each string in the list represents a protein, and the ID...
magic_instruct_75k
34,222
Write a Python function to parse and return the corresponding storage class specifier from a given string. The function should be case-insensitive and handle the following storage class specifiers: "auto", "register", "static", "extern", "mutable", and "thread_local". The function should return the corresponding enum v...
Here is the Python code to solve the given problem in the markdown block: ```python from enum import Enum class StorageClassSpecifier(Enum): Auto = 1 Register = 2 Static = 3 Extern = 4 Mutable = 5 ThreadLocal = 6 def parse_storage_class_specifier(specifier: str) -> StorageClassSpecifier: "...
magic_instruct_75k
34,246
Write a Python function to return a new array of the squares of each number in a given array, sorted in non-decreasing order. The function should be efficient and handle both positive and negative integers. The code should start with: ```python from typing import List def sortedSquares(A: List[int]) -> List[int]: ```...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sortedSquares(A: List[int]) -> List[int]: """ Returns a new array of the squares of each number in the input array, sorted in non-decreasing order. Args: A (List[int]): The input array o...
magic_instruct_75k
34,265
Implement a market tagging system for a trading platform. The system should allow users to tag various market events with specific tags for easy categorization and filtering. Your task is to create a class `MarketTagManager` that manages these market tags and provides methods for adding, removing, and querying tags. T...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List class MarketTagManager: def __init__(self): """ Initializes the MarketTagManager with an empty dictionary to store tags and their associated events. """ self.tags_to_events = ...
magic_instruct_75k
34,302
Create a Python function to determine the type of intercooler based on the given serial number of a car component. The function should return the type of intercooler as a string. The serial number ranges are as follows: - Serial numbers between 1000 and 1999 (inclusive) correspond to "AirToAir" intercoolers. - Serial n...
Here is the Python code to solve the given problem in the markdown block: ```python def determine_intercooler_type(serial_number: int) -> str: """ Determine the type of intercooler based on the given serial number. Args: serial_number (int): The serial number of the car component. Returns: ...
magic_instruct_75k
34,308
Write a Python script to automate the build process for a set of plugins in a game development environment. The script should iterate through a list of plugin libraries, create release directories, move compiled framework files, and copy configuration files to the release directories. The script should be written in Py...
Here is the Python code to solve the given problem in the markdown block: ```python import os import shutil from typing import List def build_plugins(plugin_list: List[str], debug_dir: str, release_dir: str, config_file: str) -> None: """ Automates the build process for a set of plugins by creating release dir...
magic_instruct_75k
34,326
Write a Python function `find_next_line(buffer: bytes, start: int) -> int` that takes in a binary buffer `buffer` and a start position `start`, and returns the end position of the next line in the buffer after the start position. If no newline character is found after the start position, the function should return -1. ...
Here is the Python code to solve the given problem in the markdown block: ```python def find_next_line(buffer: bytes, start: int) -> int: """ Finds the end position of the next line in the given binary buffer starting from the specified start position. Args: buffer (bytes): The binary buffer contai...
magic_instruct_75k
34,364
Write a Python function to handle the callback from an OAuth 2.0 authorization flow. The function should extract specific parameters from the callback and use them to construct a POST request to exchange an authorization code for an access token. The function should return a dictionary containing the necessary paramete...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def handle_callback(callback_params: Dict[str, str]) -> Dict[str, str]: """ Handles the callback from an OAuth 2.0 authorization flow and constructs the POST data to exchange an authorization code fo...
magic_instruct_75k
34,368
Create a Python function to manage a poll system. The function should allow users to vote for options and retrieve the results of the poll. The function should be implemented with the following specifications: - The function should take a `poll_id` as a parameter and initialize an empty dictionary to store the poll op...
Here is the Python code to solve the given problem in the markdown block: ```python def create_poll(poll_id: str): """ Create a poll system that allows users to vote for options and retrieve the results. Args: poll_id (str): The unique identifier for the poll. Returns: tuple: A tuple c...
magic_instruct_75k
34,369
Write a Python function to categorize a list of cell types based on specific substring criteria. The function should return a dictionary where the keys are the categories and the values are lists of cell types belonging to each category. The categorization rules are as follows: 1. If a cell type contains the substring ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def categorize_cells(cell_types: List[str]) -> Dict[str, List[str]]: """ Categorizes a list of cell types based on specific substring criteria. Args: cell_types (List[str]): A list of ...
magic_instruct_75k
34,378
Extend the provided configuration system to support multiple types of configuration options (e.g., bool, int, string) and provide a mechanism to retrieve and update these options in a thread-safe manner. Implement a function to set the default value for a configuration option. Ensure that each thread can have its own s...
Here is the Python code to solve the given problem in the markdown block: ```python import threading from typing import Any, Dict, Optional class EnvOption: def __init__(self, name: str, default_value: Any, option_type: type): """ Initialize an EnvOption with a name, default value, and type. ...
magic_instruct_75k
34,420
Create a Python function decorator that logs the name of the function being called along with its arguments and return value. The decorator should print the function name, its arguments, and its return value in a formatted string. The code should start with: ```python def log_function_call(func): ```
Here is the Python code to solve the given problem in the markdown block: ```python def log_function_call(func): """ A decorator that logs the name of the function being called, its arguments, and its return value. Args: func: The function to be decorated. Returns: wrapper: The wrapper...
magic_instruct_75k
34,471
Create a Python class `CreateRequest` that represents a request to create a node in a ZooKeeper system. The class should inherit from an abstract base class `ZooKeeperRequest`. The `CreateRequest` class should have a constructor that takes two parameters: a non-null string representing the full path to the node being c...
Here is the Python code to solve the given problem in the markdown block: ```python from abc import ABC, abstractmethod from enum import Enum class ZooKeeperRequest(ABC): def __init__(self, path: str): """ Initialize the ZooKeeperRequest with the given path. Args: path (str): T...
magic_instruct_75k
34,479
Write a Python function to convert RGB color values to their corresponding hexadecimal representation. The function should take a tuple of three integers representing the red, green, and blue components of the color and return a string representing the hexadecimal color code. The function should ensure that each RGB co...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple def colour_to_hex(rgb: Tuple[int, int, int]) -> str: """ Convert RGB color values to their corresponding hexadecimal representation. Args: rgb (Tuple[int, int, int]): A tuple of three integ...
magic_instruct_75k
34,480
Write a Python function to manipulate a given string according to specific rules. The function should perform the following operations: 1. Convert the string to lowercase. 2. Replace all underscores ('_') with spaces (' '). 3. Capitalize the first letter of each word. The function should start with: ```python def mani...
Here is the Python code to solve the given problem in the markdown block: ```python def manipulate_string(name: str) -> str: """ Manipulates the given string according to the following rules: 1. Converts the string to lowercase. 2. Replaces all underscores ('_') with spaces (' '). 3. Capitalizes the...
magic_instruct_75k
34,483
Write a Python function that processes a given set of rules and attributes to generate a specific output. The function should take in a dictionary of attributes and a list of rules, and then produce a list of tuples containing the rule name and its corresponding attribute value. If a rule does not have a corresponding ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Any, Tuple def process_rules_and_attrs(rules: List[str], attributes: Dict[str, Any]) -> List[Tuple[str, Any]]: """ Processes a given set of rules and attributes to generate a list of tuples contai...
magic_instruct_75k
34,507
Write a Python function to validate the presence of certain Python packages on virtual machine images used in different cloud environments. The function should check whether the required packages (`python-backports` and `python-backports-ssl_match_hostname`) are present in a given list of installed packages. If any of ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Set def validate_packages(installed_packages: List[str]) -> Set[str]: """ Validates the presence of required Python packages on virtual machine images. Args: installed_packages (List[str]):...
magic_instruct_75k
34,539
Write a Python function to calculate the fold-change uncertainty associated with the estimate of the total number of phages based on the given confidence interval. The function should take the lower and upper bounds of the confidence interval as inputs and return the fold-change uncertainty as a string in the format "x...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_fold_change(lower_bound: float, upper_bound: float) -> str: """ Calculate the fold-change uncertainty associated with the estimate of the total number of phages. Args: lower_bound (float): The lower bo...
magic_instruct_75k
34,574
Write a Python function to validate the correctness of parentheses in a given string. The function should return `True` if the parentheses are balanced and properly nested, and `False` otherwise. The function should handle three types of parentheses: `()`, `[]`, and `{}`. The code should start with: ```python def vali...
Here is the Python code to solve the given problem in the markdown block: ```python def validate_parentheses(s: str) -> bool: """ Validates the correctness of parentheses in a given string. Args: s (str): The string to validate. Returns: bool: True if the parentheses are balanced and p...
magic_instruct_75k
34,584
Complete the given code snippet to output the training results after a certain number of training iterations. Specifically, you need to calculate and print the average training loss after every `output_interval` iterations. Additionally, print the final training loss after all iterations. The code should start with: `...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def train_model(sess, train_step, loss, training_data, labels, input_batch, labels_batch, num_iterations, output_interval): """ Trains a model using TensorFlow and outputs the average training loss at specifi...
magic_instruct_75k
34,633
Write a Python function to map measured data to model data based on experiment and model IDs. The function should take two lists of dictionaries as input, where each dictionary contains keys 'experiment_id', 'model_id', and 'sample_name_abbreviation'. The function should return a new list of dictionaries where each dic...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def map_data(measured: List[Dict[str, int]], model: List[Dict[str, int]]) -> List[Dict[str, int]]: """ Maps measured data to model data based on experiment and model IDs. Args: measure...
magic_instruct_75k
34,653
Write a Python function to generate a simple HTML template for a webpage. The function should take the title of the webpage and a list of CSS file names as input. It should then generate the HTML code for the webpage, including the specified title and linking the CSS files. The function should output the complete HTML ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_html_template(title: str, css_files: List[str]) -> str: """ Generates a simple HTML template for a webpage. Args: title (str): The title of the webpage. css_files (List[...
magic_instruct_75k
34,655
Write a Python function to calculate the sum of all positive integers up to and including a given integer `n` that are divisible by either 3 or 5. The function should start with: ```python def sum_divisible_by_3_or_5(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def sum_divisible_by_3_or_5(n: int) -> int: """ Calculate the sum of all positive integers up to and including `n` that are divisible by either 3 or 5. Args: n (int): The upper limit of the range of integers to cons...
magic_instruct_75k
34,707
Write a Python function to check if a given iterative solver is available in a predefined list of solvers. The function should take the name of the solver as input and return a boolean value indicating whether the solver is available or not. The function should be case-insensitive and should handle different variations...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_solver_available(solver_name: str) -> bool: """ Check if the given iterative solver is available in the predefined list of solvers. Args: solver_name (str): The name of the solver to ...
magic_instruct_75k
34,714
Write a Python function to implement a simplified version of a custom event handling system. Your goal is to create a class `EventEmitter` with the following methods: 1. `on(eventName, handler)`: This method should register a handler function for a given event name. If the event name does not exist, it should create a ...
Here is the Python code to solve the given problem in the markdown block: ```python class EventEmitter: def __init__(self): """ Initialize the EventEmitter with an empty dictionary to store event handlers. """ self.handlers = {} def on(self, event_name, handler): """ ...
magic_instruct_75k
34,723
Create a Python function to simulate the behavior of the `Client` class methods `get_user_info` and `create_document` without making actual API calls. The function should take the necessary parameters and return the expected results based on predefined mock data. The code should start with: ```python from typing impor...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Any def mock_client_behavior(api_host: str, user_token: str, action: str, **kwargs) -> Any: """ Simulates the behavior of the Client class methods get_user_info and create_document without making actual...
magic_instruct_75k
34,741
Write a Python function to generate a random alphanumeric string of a specified length. The function should take an integer `length` as input and return a string of random alphanumeric characters of the given length. The alphanumeric string should consist of uppercase letters (A-Z), lowercase letters (a-z), and digits ...
Here is the Python code to solve the given problem in the markdown block: ```python import random import string def generate_random_alphanumeric_string(length: int) -> str: """ Generates a random alphanumeric string of the specified length. Args: length (int): The length of the alphanumeric string...
magic_instruct_75k
34,743
Create a Python class `BankAccount` that simulates a simple banking system. The class should allow users to create accounts, deposit and withdraw funds, and check their balance. The class should also handle multiple accounts and perform basic error checking. The `BankAccount` class should have the following specificat...
Here is the Python code to solve the given problem in the markdown block: ```python class BankAccount: def __init__(self, account_number: int, account_holder_name: str): """ Initialize the BankAccount with the given account number and holder name. Args: account_number (int): The...
magic_instruct_75k
34,764
Write a Python function to find the cheapest price from a source city to a destination city with at most a given number of stops, given a list of flights. Each flight is represented as a tuple containing the source city, destination city, and price. The function should return the cheapest price if a valid route exists,...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import collections import heapq def find_cheapest_price(n: int, flights: List[Tuple[int, int, int]], src: int, dst: int, k: int) -> int: """ Find the cheapest price from the source city to the des...
magic_instruct_75k
34,767
Write a Python function `update_config` that modifies a configuration dictionary based on certain rules. The function should take a `config` dictionary and a `new_bucket_name` as input. The function should update the `BUCKET` value in the `config` dictionary with the `new_bucket_name` and also update the `DRIVER` value...
Here is the Python code to solve the given problem in the markdown block: ```python def update_config(config: dict, new_bucket_name: str) -> dict: """ Updates the configuration dictionary with a new bucket name and modifies the DRIVER value accordingly. Args: config (dict): The configuration dictio...
magic_instruct_75k
34,785
Write a Python function `get_emotion_code(emotion_label)` that takes a string `emotion_label` as input and returns the numerical code associated with the emotion label as per the given `emotion_dict`. If the input `emotion_label` is not found in the dictionary, the function should return -1. The code should start with...
Here is the Python code to solve the given problem in the markdown block: ```python def get_emotion_code(emotion_label: str) -> int: """ Returns the numerical code associated with the given emotion label. Args: emotion_label (str): The emotion label to be mapped to a numerical code. Returns: ...
magic_instruct_75k
34,793
Write a Python function to merge two lists of source strings, one representing file sources and the other representing resource sources, into a single list. The merged list should maintain the order of sources, with file sources appearing before resource sources. The function should handle cases where either list might...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sources(file_sources: List[str], resource_sources: List[str]) -> List[str]: """ Merges file sources and resource sources into a single list, maintaining the order of sources. Args: ...
magic_instruct_75k
34,808
Create a Python function to simulate marking an event as failed within a transactional context. The function should take an event ID and a transaction context as parameters. The function should simulate the process of marking the event as failed and returning a confirmation message. The code should start with: ```pyth...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Any def mark_event_as_failed(event_id: str, transaction: Dict[str, Any]) -> str: """ Simulates marking an event as failed within a transactional context. Args: event_id (str): The unique id...
magic_instruct_75k
34,819
Write a Python function to extract metadata information from a given code snippet. The metadata includes the author's name, version, title, and homepage of the code. The function should parse the given code snippet and extract the metadata information into a dictionary. The code snippet will be in a specific format whe...
Here is the Python code to solve the given problem in the markdown block: ```python import re def extract_metadata(code: str) -> dict: """ Extracts metadata information from a given code snippet. The code snippet is expected to contain metadata fields in the format: __author__ = "author_name" __ve...
magic_instruct_75k
34,822
Write a Python function to find the oldest and newest events based on their start times from a list of event records. Each event record is a dictionary with the following keys: - "type": a string representing the type of the event - "started": a datetime object representing the start time of the event - "result": a str...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Tuple from datetime import datetime def find_oldest_and_newest_events(events: List[Dict[str, object]]) -> Tuple[Dict[str, object], Dict[str, object]]: """ Find the oldest and newest events based o...
magic_instruct_75k
34,847
Write a Python function to perform a level order traversal of a binary tree and return the traversal result as a list of lists, where each inner list contains the values of nodes at a specific level in the tree. The function should handle the case where the tree is empty by returning an empty list. The code should sta...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def levelOrder(root: Optional[TreeNode]) -> List[List[i...
magic_instruct_75k
34,848
Write a Python function `construct_install_command` that takes two parameters: 1. `extras` (string): A string representing the extras to be included in the installation command. 2. `index_url` (string): A string representing the index URL from which the package should be installed. The function should return the const...
Here is the Python code to solve the given problem in the markdown block: ```python def construct_install_command(extras: str, index_url: str) -> str: """ Constructs a pip installation command with specified extras and an index URL. Args: extras (str): A string representing the extras to be include...
magic_instruct_75k
34,868
Write a Python function to format a given string by prepending a prefix and appending a suffix, if provided. If either the prefix or suffix is an empty string, the corresponding formatting should be skipped. The function should start with: ```python def bothfix_formatter(value: str, prefix: str = '', suffix: str = '') ...
Here is the Python code to solve the given problem in the markdown block: ```python def bothfix_formatter(value: str, prefix: str = '', suffix: str = '') -> str: """ Formats the given string by prepending a prefix and appending a suffix, if provided. If either the prefix or suffix is an empty string, the co...
magic_instruct_75k
34,914
Write a Python function to process and organize files based on specific command-line arguments. The function should handle the following functionalities: 1. Change the current working directory to a specified directory. 2. If the first command-line argument is `--all`, gather all files with the extensions `.ml` and `.m...
Here is the Python code to solve the given problem in the markdown block: ```python import os from typing import List, Optional def file_organizer(old_dir: str, run_dir: str, test_dir: str, args: List[str]) -> Optional[List[str]]: """ Organizes and manipulates files based on command-line arguments. Args: ...
magic_instruct_75k
34,917
Write a Python function to count the occurrences of each character in a given string, ignoring spaces and treating uppercase and lowercase letters as the same. The function should return a dictionary where the keys are the characters and the values are their respective counts. The code should start with: ```python fro...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def parseStr(input_str: str) -> Dict[str, int]: """ Counts the occurrences of each character in a given string, ignoring spaces and case sensitivity. Args: input_str (str): The input string ...
magic_instruct_75k
34,918
Write a Python function to unserialize key-value pairs from a given input string into a dictionary. The input string contains a series of key-value pairs separated by a specific delimiter. Each key-value pair is represented as "key:value" and separated by a comma. The function should parse the input string and return a...
Here is the Python code to solve the given problem in the markdown block: ```python def unserialize_pairs(input_string: str) -> dict: """ Unserializes key-value pairs from a given input string into a dictionary. Args: input_string (str): The input string containing key-value pairs separated by comm...
magic_instruct_75k
34,924
Write a Python function to implement a command-line interface (CLI) adapter that allows users to interact with a software system through a command-line interface. The adapter should be able to register different command handlers, parse user input, execute the corresponding command handler, and display help information....
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Callable, List class CLIAdapter: def __init__(self): self.command_handlers = {} self.help_messages = {} def register_command_handler(self, command: str, handler: Callable[[List[str]], None], ...
magic_instruct_75k
34,925
Write a Python function to count the number of unique elements in a given array of integers. The function should efficiently handle the input array and return the count of distinct elements. The code should start with: ```python from typing import List def count_unique_elements(arr: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_unique_elements(arr: List[int]) -> int: """ Counts the number of unique elements in a given array of integers. Args: arr (List[int]): The array of integers from which to count uniq...
magic_instruct_75k
34,932
Write a Python function to calculate the final balance based on the given dictionary `dep_dict`, debit, and credit. The function should retrieve the value of `__fb__` from the dictionary and then compute the final balance using the formula: `final_balance = __fb__ + debit - credit`. If `__fb__`, debit, or credit are no...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_final_balance(dep_dict: dict, debit: float = 0, credit: float = 0) -> float: """ Calculate the final balance based on the given dictionary, debit, and credit. Args: dep_dict (dict): A dictionary contai...
magic_instruct_75k
34,975
Write a Python function to process a list of dependencies and return a dictionary containing the dependency name as the key and the version as the value. Each dependency is represented as a tuple containing the name and version. The function should handle cases where the input list might contain duplicate dependency na...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def process_dependencies(dependencies: List[Tuple[str, str]]) -> Dict[str, str]: """ Processes a list of dependencies and returns a dictionary with the latest version of each dependency. ...
magic_instruct_75k
34,979
Write a Python function to calculate the area of a triangle given its three vertices as `Coordinate` objects. The function should use the determinant method to compute the area. The `Coordinate` class is already provided with the necessary methods to initialize coordinates and calculate distances. The code should star...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple class Coordinate(object): def __init__(self, x, y): self.x = x self.y = y def triangle_area(vertex1: Coordinate, vertex2: Coordinate, vertex3: Coordinate) -> float: """ Calculate th...
magic_instruct_75k
34,985
Write a Python function `processInput(input: str) -> str` that processes user input and returns the appropriate response based on predefined strings. The function should handle various commands related to displaying statistics, managing addresses, and providing user options. If the input does not match any predefined s...
Here is the Python code to solve the given problem in the markdown block: ```python def processInput(input: str) -> str: """ Processes user input and returns the appropriate response based on predefined strings. Args: input (str): The user input string to be processed. Returns: str: Th...
magic_instruct_75k
35,017
Write a Python function `get_mx_records(domain: str) -> List[str]` that retrieves MX (Mail Exchange) records for a given domain using the appropriate class based on the domain provider. The function should handle MX record retrieval for generic domains, Google domains, and Cloudflare domains. The function should determ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List class MXRecords: def get_mx_records(self, domain: str) -> List[str]: # Placeholder implementation for generic domains return ["generic-mx-record1", "generic-mx-record2"] class GoogleMXRecord...
magic_instruct_75k
35,027
Write a Python function to map global coordinates to local coordinates in a parallel computing environment. The function should take the lattice grid size in the x and y directions, the number of processes in the x and y directions, and the global coordinates. It should return the process coordinates along with the loc...
Here is the Python code to solve the given problem in the markdown block: ```python def map_global_to_local(lx: int, ly: int, x_size: int, y_size: int, global_x: int, global_y: int) -> tuple: """ Maps global coordinates to local coordinates in a parallel computing environment. Args: lx (int): latti...
magic_instruct_75k
35,038
Write a Python function to simulate a simple game of dice where two dice are rolled a specified number of times. The function should return a dictionary containing the frequency of each possible sum from 2 to 12. The function should handle edge cases such as zero rolls and ensure that the results are correctly calculat...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict import random def simulate_dice_rolls(num_rolls: int) -> Dict[int, int]: """ Simulate rolling two dice a specified number of times and return the frequency of each possible sum. Args: num_ro...
magic_instruct_75k
35,039
Write a Python function to categorize a list of research topics based on their prefixes and count the occurrences of each prefix. Each research topic is represented as a string, and the prefixes are defined as the first two characters of each topic. The function should return a dictionary where the keys are the prefixe...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def categorize_research_topics(topics: List[str]) -> Dict[str, int]: """ Categorizes a list of research topics based on their prefixes and counts the occurrences of each prefix. Args: ...
magic_instruct_75k
35,040
Write a Python function to find the length of the longest common prefix among a list of strings. The function should return the length of the longest common prefix, or 0 if there is no common prefix. The function should be efficient and handle edge cases such as an empty list or a list with varying string lengths. The...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def longest_common_prefix_length(strs: List[str]) -> int: """ Find the length of the longest common prefix among a list of strings. Args: strs (List[str]): A list of strings to find the long...
magic_instruct_75k
35,043
Write a Python function to determine the relative position of a given point with respect to a set of other points on a 2D plane. The function should take in the coordinates of the reference point and a list of other points, and return a list indicating whether each point is to the left, right, or on the same vertical l...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def relative_position(reference_point: Tuple[int, int], other_points: List[Tuple[int, int]]) -> List[str]: """ Determines the relative position of each point in `other_points` with respect to `ref...
magic_instruct_75k
35,058
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 a dictionary with a key "operation" indicating the type of operation. The function should return a dictionary where the keys are the operation types and the value...
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, str]]) -> Dict[str, int]: """ Counts the occurrences of each type of database migration operation in a given list of operations. Args:...
magic_instruct_75k
35,059
Write a Python function to remove duplicate integers from a given list while preserving the original order of the elements. The function should take a list of integers as input and return a new list with all duplicates removed. The function signature should be: ```python from typing import List def remove_duplicates(a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates(arg_list: List[int]) -> List[int]: """ Removes duplicate integers from the given list while preserving the original order of the elements. Args: arg_list (List[int]): T...
magic_instruct_75k
35,061
Write a Python function to process and analyze the metadata of Python packages. The metadata is provided in the form of a dictionary containing various fields such as "name," "version," "description," "keywords," and "classifiers." The function should extract specific information from the metadata and perform certain o...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Tuple, Optional def process_metadata(metadata: Dict[str, any]) -> Tuple[str, str, Optional[str], List[str], int]: """ Processes and analyzes the metadata of a Python package. Args: me...
magic_instruct_75k
35,071
Write a Python function to determine if a given number is a prime number or not. The function should take a single integer as input and return a boolean value indicating whether the number is prime. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The code should...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(n: int) -> bool: """ Determine if a given number is a prime number. Args: n (int): The number to check for primality. Returns: bool: True if the number is prime, False otherwise. """ ...
magic_instruct_75k
35,089
Write a Python function to remove all occurrences of the letter "c" (both uppercase and lowercase) from a given string and return the modified string. The function should be efficient and handle various edge cases, such as an empty string or a string with no occurrences of "c" or "C". The code should start with: ```py...
Here is the Python code to solve the given problem in the markdown block: ```python def remove_c(my_string: str) -> str: """ Removes all occurrences of the letter "c" (both uppercase and lowercase) from the given string. Args: my_string (str): The input string from which to remove the letter "c" an...
magic_instruct_75k
35,090
Write a Python function to convert a given temperature in Celsius to Fahrenheit. The function should take a single parameter representing the temperature in Celsius and return the equivalent temperature in Fahrenheit, rounded to two decimal places. The conversion formula is: \[ F = \frac{9}{5}C + 32 \] The code shoul...
Here is the Python code to solve the given problem in the markdown block: ```python def celsius_to_fahrenheit(celsius: float) -> float: """ Converts a temperature from Celsius to Fahrenheit. Args: celsius (float): The temperature in Celsius to be converted. Returns: float: The equivale...
magic_instruct_75k
35,091
Write a Python function to validate email server configuration settings. The function should take a dictionary of email server settings as input and check if the settings are valid based on certain criteria. The settings dictionary will contain the following keys and their corresponding values: - "MAIL_PORT": an intege...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def validate_email_server_settings(settings: Dict[str, any]) -> bool: """ Validates the email server configuration settings based on certain criteria. Args: settings (Dict[str, any]): A dict...
magic_instruct_75k
35,095
Write a Python function to determine if two given strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. The function should be case-insensitive and should ignore any non-alphabetic charac...
Here is the Python code to solve the given problem in the markdown block: ```python def are_anagrams(str1: str, str2: str) -> bool: """ Determine if two given strings are anagrams of each other. Args: str1 (str): The first string to compare. str2 (str): The second string to compare. Re...
magic_instruct_75k
35,111
Write a Python function to process a list of integers by removing any duplicate elements and sorting the list in ascending order. The function should return the modified list. The code should start with: ```python from typing import List def process_data(data: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def process_data(data: List[int]) -> List[int]: """ Process the input list of integers by removing duplicates and sorting it in ascending order. Args: data (List[int]): The input list of int...
magic_instruct_75k
35,146
Write a Python function to automate the process of updating configuration files for a web server. The configuration files contain placeholders in the form `{{$key}}` that need to be replaced with corresponding values. Additionally, the function should restart the web server after the configuration files have been updat...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List import subprocess def update_config_and_restart(config_dict: Dict[str, str], config_file_path: str, restart_command: List[str]) -> None: """ Updates the configuration file with the provided key-val...
magic_instruct_75k
35,156
Write a Python function to process a list of integers and return a new list containing the cubes of all the even numbers in the input list. The function should handle both positive and negative integers and return an empty list if the input list is empty or does not contain any even numbers. The code should start with...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def background_cube(input_list: List[int]) -> List[int]: """ Processes a list of integers to return a new list containing the cubes of all even numbers. Args: input_list (List[int]): A list ...
magic_instruct_75k
35,187
Write a Python function to calculate the average of a list of integers. The function should take a list of integers as input and return the average as a floating-point number. If the input list is empty, the function should return 0. The code should start with: ```python from typing import List def calculate_average(...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_average(numbers: List[int]) -> float: """ Calculate the average of a list of integers. Args: numbers (List[int]): A list of integers for which the average is to be calculated. ...
magic_instruct_75k
35,215
Write a Python function to process event data and build a metadata result array based on certain conditions. The function should take two inputs: `event_dict_no_overlap`, a dictionary containing event data, and `params`, a dictionary containing parameters for processing the data. The function should perform the followi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def process_event_data(event_dict_no_overlap: Dict[int, list], params: Dict[str, int]) -> Dict[str, Dict]: """ Process event data and build a metadata result array based on certain conditions. Args:...
magic_instruct_75k
35,263
Write a Python function to count the occurrences of unique file extensions in a given list of file names. The file extension is defined as the part of the file name following the last occurrence of the dot ('.'). If a file name does not have an extension, it should be considered as having an empty string as its extensi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_file_extensions(file_list: List[str]) -> Dict[str, int]: """ Counts the occurrences of unique file extensions in the given list of file names. Args: file_list (List[str]): A ...
magic_instruct_75k
35,266
Write a Python function to count the number of set bits (binary 1s) in the binary representation of a given integer `n`. The function should be efficient and handle both positive and negative integers. The code should start with: ```python def count_bits(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def count_bits(n: int) -> int: """ Counts the number of set bits (binary 1s) in the binary representation of the given integer `n`. Args: n (int): The integer whose set bits are to be counted. Returns: ...
magic_instruct_75k
35,279
Write a Python function to determine whether a given namespace is a recursive subnamespace of another namespace. A namespace is a nested structure that contains attributes and sub-namespaces. The function should return `True` if the given namespace is a recursive subnamespace of the other, and `False` otherwise. A nam...
Here is the Python code to solve the given problem in the markdown block: ```python def is_recursive_subnamespace(namespace: dict, parent_namespace: dict) -> bool: """ Determine whether a given namespace is a recursive subnamespace of another namespace. Args: namespace (dict): The namespace to chec...
magic_instruct_75k
35,291
Write a Python function to apply the Rectified Linear Unit (ReLU) activation function element-wise to a given 1D NumPy array. The ReLU activation function is defined as \( f(x) = \max(0, x) \), where \( x \) is the input to the function. The function should return a new array with the ReLU activation applied to each el...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def apply_relu_activation(input_array: np.ndarray) -> np.ndarray: """ Applies the Rectified Linear Unit (ReLU) activation function element-wise to a given 1D NumPy array. The ReLU activation function is ...