source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
magic_instruct_75k
62,821
Write a Python function to calculate the sum of the squares of the elements in a given list. The function should take a list of integers as input and return the sum of the squares of these integers. The code should start with: ```python from typing import List def sum_of_squares(values: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_of_squares(values: List[int]) -> int: """ Calculate the sum of the squares of the elements in a given list. Args: values (List[int]): A list of integers for which the sum of squares ...
magic_instruct_75k
62,848
Write a Python function to process a dictionary containing variable templates and return a new dictionary with the variables replaced by their corresponding values. Each variable template is represented as a key-value pair in the input dictionary, where the key is the variable name and the value is the template string....
Here is the Python code to solve the given problem in the markdown block: ```python def process_variable_templates(input_dict: dict) -> dict: """ Processes a dictionary containing variable templates and returns a new dictionary with the variables replaced by their corresponding values. Args: in...
magic_instruct_75k
62,859
Write a Python function to convert a given volume in cubic meters to liters. The conversion formula is as follows: 1 cubic meter = 1000 liters. The function should take the volume in cubic meters as input and return the equivalent volume in liters, rounded to two decimal places. The code should start with: ```python d...
Here is the Python code to solve the given problem in the markdown block: ```python def convert_volume(vm: float) -> float: """ Converts a given volume in cubic meters to liters. Args: vm (float): The volume in cubic meters to be converted to liters. Returns: float: The equivalent volu...
magic_instruct_75k
62,871
Write a Python function to calculate the remaining budget for carbon emissions based on the initial budget and the total emissions. The function should handle the following cases: - The initial budget and total emissions are both non-negative floating-point numbers. - The initial budget is greater than or equal to the ...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_remaining_budget(initial_budget: float, total_emissions: float) -> float: """ Calculate the remaining budget for carbon emissions based on the initial budget and total emissions. Args: initial_budget (...
magic_instruct_75k
62,872
Write a Python function `update_ocr_interface` that updates the public interface of an Optical Character Recognition (OCR) module. The function should take two parameters: 1. `current_interface` (list of strings): The current public interface of the OCR module. 2. `new_objects` (list of strings): A list of new objects ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def update_ocr_interface(current_interface: List[str], new_objects: List[str]) -> List[str]: """ Updates the public interface of an OCR module by adding new objects to it, ensuring no duplicates. Ar...
magic_instruct_75k
62,902
Write a Python function to find the length of the longest increasing subsequence (LIS) in a given list of integers. The function should return the length of the LIS. The code should start with: ```python from typing import List def length_of_lis(nums: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def length_of_lis(nums: List[int]) -> int: """ Calculate the length of the longest increasing subsequence in a given list of integers. Args: nums (List[int]): The list of integers from which...
magic_instruct_75k
62,905
Write a Python function to parse a given string and extract key-value pairs representing annotations for a crash report. The annotations are provided in the form of a URL and a set of key-value pairs. Your task is to extract the URL and the key-value pairs from the given string and return them in a structured format. ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Tuple import re def parse_annotations(input_string: str) -> Tuple[str, Dict[str, str]]: """ Parses the input string to extract the URL and annotations (key-value pairs). Args: input_string ...
magic_instruct_75k
62,964
Write a Python function to evaluate a given logical expression represented as a string. The logical expression consists of the logical OR operator (`or`) and the boolean values `True` and `False`. The expression may contain spaces, and the input string is guaranteed to be a valid logical expression. The function shoul...
Here is the Python code to solve the given problem in the markdown block: ```python def evaluate_logical_expression(expression: str) -> bool: """ Evaluates a given logical expression represented as a string. The logical expression consists of the logical OR operator (`or`) and the boolean values `True` and...
magic_instruct_75k
62,969
Write a Python function to process a user input string containing three space-separated integers representing dimensions. The function should extract these integers and return them as a tuple. The input string is guaranteed to contain exactly three integers separated by spaces. The code should start with: ```python de...
Here is the Python code to solve the given problem in the markdown block: ```python def process_input(input_string: str) -> tuple: """ Processes a user input string containing three space-separated integers representing dimensions. Args: input_string (str): A string containing three space-separated...
magic_instruct_75k
62,971
Write a Python function to extract the titles of data profiles from their schemas and return them in a specific format. The function should take a dictionary `types` as input, where `types` contains information about different item types and their schemas. Each item type has a `type_info` object containing the schema a...
Here is the Python code to solve the given problem in the markdown block: ```python def extract_profile_titles(types: dict) -> dict: """ Extracts the titles of data profiles from their schemas and returns them in a specific format. Args: types (dict): A dictionary containing information about diffe...
magic_instruct_75k
62,976
Write a Python function `top_three_similarity_scores(jac_similarity)` that takes in a 2D numpy array `jac_similarity` representing the similarity matrix and returns the top three similarity scores in descending order. The function should handle NaN values appropriately and ensure that the top three scores are extracted...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def top_three_similarity_scores(jac_similarity: np.ndarray) -> np.ndarray: """ Extracts the top three similarity scores from a 2D numpy array representing a similarity matrix. Args: jac_similarit...
magic_instruct_75k
62,977
Implement a Python function `quads_to_tris` in the `quad_faces` module that converts a list of quadrilateral faces into a list of corresponding triangles. Each quadrilateral face is represented as a list of 4 vertices, and each triangle should be represented as a list of 3 vertices. The function should be correctly exp...
Here is the Python code to solve the given problem in the markdown block: ```python # quad_faces.py def quads_to_tris(quads): """ Convert quadrilateral faces to triangles. Args: quads (list): List of quadrilateral faces, each represented as a list of 4 vertices. Returns: list: List of triangl...
magic_instruct_75k
62,999
Write a Python function to generate default trigger discovery settings for a network monitoring system based on a predefined template. The function should take a device type as input and return the corresponding default settings for that device type. If the device type is not found in the template, the function should ...
Here is the Python code to solve the given problem in the markdown block: ```python def get_trigger_discovery_settings(device_type: str) -> dict: """ Generates default trigger discovery settings for a network monitoring system based on a predefined template. Args: device_type (str): The type of the...
magic_instruct_75k
63,006
Write a Python function to validate the input parameters for creating a new project in a project management system. The function should check if all the required parameters are present and if they have the correct data types. If any parameter is missing or has an incorrect data type, the function should return an error...
Here is the Python code to solve the given problem in the markdown block: ```python def validateProjectParams(attach: str, description: str, detection_chance: int, project_id: int, version: int, creator: int) -> str: """ Validates the input parameters for creating a new project in a project management system. ...
magic_instruct_75k
63,009
Write a Python function to replace placeholders in a given template string with their corresponding values from a dictionary. The placeholders are in the format `@placeholder@`, where `placeholder` can be any alphanumeric string. The function should return the template with all the placeholders replaced by their corres...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def replace_placeholders(template: str, replacements: Dict[str, str]) -> str: """ Replaces placeholders in a template string with their corresponding values from a dictionary. Args: template...
magic_instruct_75k
63,017
Write a Python function to find the longest word in a given list of strings. If there are multiple words with the same maximum length, return the first occurrence of such a word. The code should start with: ```python from typing import List def find_longest_word(words: List[str]) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_longest_word(words: List[str]) -> str: """ Finds the longest word in a given list of strings. Args: words (List[str]): A list of strings from which to find the longest word. Re...
magic_instruct_75k
63,025
Write a Python script to manage smart plugs in a home automation system using the Kasa smart plug API. The script should include two functions: 1. `kasa_query_plug(host: str) -> dict`: This function should take the host (IP address or hostname) of a smart plug as an argument, make a request to the Kasa smart plug API, ...
Here is the Python code to solve the given problem in the markdown block: ```python import subprocess import requests def kasa_query_plug(host: str) -> dict: """ Query the Kasa smart plug API to retrieve the status of the plug. Args: host (str): The IP address or hostname of the smart plug. R...
magic_instruct_75k
63,042
Write a Python function to parse a C++ source file and extract the author's name and the copyright year from the file header comment. The file header comment is defined as a block of comments at the beginning of the file, enclosed by `/*` and `*/`, and containing the following information: - File name and brief descrip...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple import re def extract_file_info(source: str) -> Tuple[str, str]: """ Extracts the author's name and the copyright year from the file header comment of a C++ source file. Args: source (str):...
magic_instruct_75k
63,049
Write a Python function to join elements from a sequence container into a single string. The function should take a sequence container (e.g., list, tuple, deque) of strings as input and return a concatenated string of all the elements in the container. The function should handle different types of sequence containers a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Sequence def join_sequence_container(container: Sequence[str]) -> str: """ Joins elements from a sequence container into a single string. Args: container (Sequence[str]): A sequence container (e....
magic_instruct_75k
63,092
Write a Python function to determine whether a given list of integers is a palindrome. A palindrome is a sequence that reads the same forwards and backwards. The function should return `True` if the list is a palindrome and `False` otherwise. The code should start with: ```python from typing import List def is_palind...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_palindrome(numero_list: List[int]) -> bool: """ Determine whether the given list of integers is a palindrome. Args: numero_list (List[int]): The list of integers to check. Return...
magic_instruct_75k
63,105
Write a Python function to calculate the total prize amount for each category from a given pandas DataFrame containing prize data. The function should return a new DataFrame with the total prize amounts for each category. The input DataFrame, `prize_data`, has the following columns: - `category`: The category of the p...
Here is the Python code to solve the given problem in the markdown block: ```python import pandas as pd def calculate_total_prize_amount(prize_data: pd.DataFrame) -> pd.DataFrame: """ Calculate the total prize amount for each category from a given DataFrame. Args: prize_data (pd.DataFrame): A Data...
magic_instruct_75k
63,121
Write a Python function to process a list of dictionaries representing API responses and return the sum of "return" values for all responses with a "status" of 400 and a "resp_time" less than or equal to 50. If there are no matching responses, the function should return 0. Each dictionary in the list represents an API ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union, Any def process_api_responses(api_responses: List[Dict[str, Union[str, int, Dict[str, Any]]]]) -> int: """ Processes a list of API response dictionaries and returns the sum of "return" valu...
magic_instruct_75k
63,127
Write a Python function to generate HTML code for displaying a collection of tags as clickable links on a web page. Each tag should be wrapped in an anchor (`<a>`) tag with a specific HTML structure. The function should take a list of tag names and return a string containing the corresponding HTML code. The code shoul...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_tag_links(tags: List[str]) -> str: """ Generates HTML code for displaying a collection of tags as clickable links. Args: tags (List[str]): A list of tag names to be converted in...
magic_instruct_75k
63,138
Write a Python function to manage file and directory operations. The function should provide functionality to create a directory and check if a file exists. The code should start with: ```python import os def create_dir(dir_name: str) -> None: """ Create a directory with the specified name. If the directory al...
Here is the Python code to solve the given problem in the markdown block: ```python import os def create_dir(dir_name: str) -> None: """ Create a directory with the specified name. If the directory already exists, it should handle the situation gracefully. Args: dir_name (str): The name of the dir...
magic_instruct_75k
63,144
Implement a Python function `func_to_test` that satisfies the given unit test case using the `assertEqual` method. The function should take an input parameter and return an expected output based on the provided test case. The starter code is as follows: ```python def func_to_test(input): # Implement the logic for ...
Here is the Python code to solve the given problem in the markdown block: ```python def func_to_test(input): """ Transforms the input into the expected output based on the provided test case. Args: input: The input parameter to be transformed. Returns: The transformed output that match...
magic_instruct_75k
63,167
Write a Python function to construct the full path to a website configuration file based on the given directory, website name, and optional zone name. If the zone name is provided, it should be prefixed with a dot ("."). Additionally, handle the case of incorrect usage by providing an appropriate exit status and messag...
Here is the Python code to solve the given problem in the markdown block: ```python import sys def construct_config_path(sitesAvailableDir: str, sitesName: str, zone: str = None) -> str: """ Constructs the full path to a website configuration file based on the given directory, website name, and optional zone n...
magic_instruct_75k
63,175
Write a Python function `countBits_alternative` that takes an integer `num` as input and returns an array `dp` of size `num+1`, where `dp[i]` represents the number of 1 bits in the binary representation of `i` for all `0 <= i <= num`. The function should not use bitwise operations. 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 def countBits_alternative(num: int) -> List[int]: """ Calculate the number of 1 bits in the binary representation of each number from 0 to num. Args: num (int): The upper limit of the range ...
magic_instruct_75k
63,208
Write a Python function to update the parameters of a neural network using the computed gradients from the backpropagation process. The function should take the network parameters, gradients, and learning rate as inputs and return the updated parameters. The code should start with: ```python from typing import Dict de...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def update_parameters(parameters: Dict[str, float], gradients: Dict[str, float], learning_rate: float) -> Dict[str, float]: """ Update the neural network parameters using the computed gradients and a spe...
magic_instruct_75k
63,240
Write a Python function to determine if you can reach the last index of an array of non-negative integers, where each element represents the maximum jump length at that position. You start at the first index and need to reach the last index. The function should return `True` if it is possible to reach the last index, a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def can_reach_end(arr: List[int]) -> bool: """ Determine if you can reach the last index of an array where each element represents the maximum jump length at that position. Args: arr (List[i...
magic_instruct_75k
63,259
Write a Python function to evaluate a custom arithmetic expression that consists of integers and the operators addition (+) and subtraction (-). The evaluation should follow the rule that operators with the same precedence are evaluated from left to right. The input expression will always be valid and well-formed, cont...
Here is the Python code to solve the given problem in the markdown block: ```python def evaluate_expression(expression: str) -> int: """ Evaluates a custom arithmetic expression consisting of integers and the operators addition (+) and subtraction (-). The evaluation follows the rule that operators with the...
magic_instruct_75k
63,262
Write a Python function to create a mutable array that can store various types of data and a function to create an array with a specified operation. The `MutableArray` type should represent a mutable array that can store various types of data, and the `Any` type should represent any data type. The `arrayWith` function ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any class MutableArray: """ A class representing a mutable array that can store various types of data. Methods: - append(item: Any) -> None: Appends an item to the array. - __getitem__(inde...
magic_instruct_75k
63,269
Write a Python function to filter and sort a list of news articles based on specific criteria. Each news article is represented as a dictionary with keys "title", "category", and "views". The function should: 1. Include articles with a category of "Technology" or "Science". 2. Exclude articles with less than 1000 views...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def filter_news(news_articles: List[Dict[str, any]]) -> List[Dict[str, any]]: """ Filters and sorts a list of news articles based on specific criteria. Args: news_articles (List[Dict[s...
magic_instruct_75k
63,287
Write a Python function to process a JSON file containing information about different rules. The function should read the JSON file, parse its contents, and then return the names of all enabled rules that meet specific conditions. The JSON file contains an array of rule objects, where each rule has the following struc...
Here is the Python code to solve the given problem in the markdown block: ```python import json from typing import List def filter_rules(rules: List[dict]) -> List[str]: """ Filters the rules based on specific conditions and returns the names of the enabled rules that meet the conditions. Args: ru...
magic_instruct_75k
63,303
Write a Python function to remove duplicates from a given list while preserving the order of the elements. The input list may contain elements of various data types, including integers, strings, and others. The function should return a new list containing only the unique elements from the input list, maintaining their ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def remove_duplicates(input_list: List[Any]) -> List[Any]: """ Removes duplicates from the input list while preserving the order of the elements. Args: input_list (List[Any]): A list co...
magic_instruct_75k
63,363
Write a Python function to determine if a given path is unique within its parent's context. The function should take a parent path and a path name, and it should check if the path name is unique among all paths that share the same parent path. The function should return `True` if the path is unique, and `False` otherwi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def is_path_unique(parent_path: str, path_name: str, path_pool: Dict[str, List[str]]) -> bool: """ Determines if a given path name is unique within its parent's context. Args: parent_p...
magic_instruct_75k
63,371
Create a Python function to automate the process of seeding a database for a Ruby on Rails application. The function should read data from a predefined source (e.g., CSV file, JSON file, or hardcoded data within the script) and use this data to populate the database tables. The function should be able to handle differe...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Any import csv import json def seed_database(data_source: str, data_format: str) -> None: """ Automates the process of seeding a database for a Ruby on Rails application. Args: data_s...
magic_instruct_75k
63,396
Write a Python function to extract the hostname from a given payload string. The payload contains a command followed by a hostname, separated by a space. The function should extract the hostname and return it as a string. The payload may contain leading spaces before the command and may not contain a valid hostname. T...
Here is the Python code to solve the given problem in the markdown block: ```python def extract_hostname(payload: str) -> str: """ Extracts the hostname from a given payload string. The payload contains a command followed by a hostname, separated by a space. The function extracts the hostname and retur...
magic_instruct_75k
63,407
Write a Python function to read and print a sequence of strings from a list until an empty string is encountered. The function should correctly handle the case where the list contains an empty string and should print all non-empty strings before terminating. The code should start with: ```python from typing import Lis...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def print_non_empty_strings(strings: List[str]) -> None: """ Prints each non-empty string from the given list until an empty string is encountered. Args: strings (List[str]): A list of strin...
magic_instruct_75k
63,410
Write a Python function to calculate the sum of the first n terms of the Fibonacci sequence using dynamic programming. The function should be efficient and avoid redundant calculations. The code should start with: ```python def fibonacci_sum(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def fibonacci_sum(n: int) -> int: """ Calculate the sum of the first n terms of the Fibonacci sequence using dynamic programming. Args: n (int): The number of terms in the Fibonacci sequence to sum. Returns: ...
magic_instruct_75k
63,417
Write a Python function `custom_choice(data)` that mimics the behavior of the `choice` function from Python's `random` module using only the `randrange` function. The `randrange` function takes parameters similar to the built-in `range` function and returns a random choice from the given range. Your function should tak...
Here is the Python code to solve the given problem in the markdown block: ```python import random def custom_choice(data): """ Selects a random element from a non-empty sequence using only the randrange function. Args: data (sequence): A non-empty sequence (e.g., list, tuple) from which to select ...
magic_instruct_75k
63,426
Write a Python function to count the occurrences of each unique audience category from a list of classifiers. Each classifier string may contain multiple audience categories separated by double colons (`::`). The function should return a dictionary where the keys are the unique audience categories and the values are th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_audience_categories(classifiers: List[str]) -> Dict[str, int]: """ Counts the occurrences of each unique audience category from a list of classifiers. Args: classifiers (List...
magic_instruct_75k
63,430
Write a Python function to unescape specific HTML entities in a given string. The function should replace the following HTML entities with their corresponding characters: - `&lt;` to `<` - `&gt;` to `>` - `&amp;` to `&` - `&quot;` to `"` - `&apos;` to `'` The function should not unescape any other HTML entities. If th...
Here is the Python code to solve the given problem in the markdown block: ```python def unescapeHTML(s: str) -> str: """ Unescapes specific HTML entities in a given string. Args: s (str): The input string containing HTML entities to be unescaped. Returns: str: The unescaped string with...
magic_instruct_75k
63,436
Write a Python function to calculate the Euclidean distance between two points in a 2D plane. The function should take four parameters representing the coordinates of the two points and return the distance as a floating-point number. The code should start with: ```python import math def calculate_distance(x1: float, ...
Here is the Python code to solve the given problem in the markdown block: ```python import math def calculate_distance(x1: float, y1: float, x2: float, y2: float) -> float: """ Calculate the Euclidean distance between two points (x1, y1) and (x2, y2) in a 2D plane. Args: x1 (float): The x-coordina...
magic_instruct_75k
63,465
Write a Python function to process an image represented as a 2D list of pixels. Each pixel is a list `[R, G, B, A]` representing the red, green, blue, and alpha values. The function should iterate through each pixel in the image and set the red, green, and blue values to 0, and the alpha value to 255. The function shou...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def process_image(image: List[List[List[int]]]) -> List[List[List[int]]]: """ Process the given image by setting the red, green, and blue values of each pixel to 0, and the alpha value to 255. Args:...
magic_instruct_75k
63,516
Write a Python function to check for a change in the public IP address of a machine and update a specified file if the IP address has indeed changed. The function should be able to handle both IPv4 and IPv6 addresses. The function should perform the following steps: 1. Retrieve the current public IP address of the mac...
Here is the Python code to solve the given problem in the markdown block: ```python import requests def update_ip_address(file_path: str) -> None: """ Checks for a change in the public IP address and updates the specified file if the IP address has changed. Args: file_path (str): The path to the f...
magic_instruct_75k
63,531
Write a Python function to find the length of the longest substring with the same character in a given string `s`. The function should return the length of the longest such substring. The code should start with: ```python def longest_substring_length(s: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def longest_substring_length(s: str) -> int: """ Finds the length of the longest substring with the same character in a given string. Args: s (str): The input string consisting of lowercase English letters. Ret...
magic_instruct_75k
63,586
Write a Python function to determine if a given integer `x` is a prime number. The function should correctly handle all integers, including negative numbers, zero, and one. The function should be optimized for performance by reducing the number of checks needed to determine if a number is prime. The code should start ...
Here is the Python code to solve the given problem in the markdown block: ```python import math def is_prime(x: int) -> bool: """ Determine if a given integer `x` is a prime number. Args: x (int): The integer to check for primality. Returns: bool: True if `x` is a prime number, False ...
magic_instruct_75k
63,601
Write a Python function to count the occurrences of each type of migration operation from a list of strings. Each string represents a migration operation in the format "migrations.OperationName(model_name='ModelName', ...)". The function should ignore case when counting the operation types. The function should return a...
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[str]) -> Dict[str, int]: """ Counts the occurrences of each type of migration operation from a list of strings. Args: operations (List[s...
magic_instruct_75k
63,620
Write a Python function to dynamically create a new class using the provided name and attributes. The function should be compatible with both Python 2 and Python 3. The function should take three parameters: - `name` (string): The name of the new class to be created. - `attributes` (dictionary): A dictionary containing...
Here is the Python code to solve the given problem in the markdown block: ```python def create_dynamic_class(name: str, attributes: dict, python_version: int) -> type: """ Dynamically creates a new class with the given name and attributes. Args: name (str): The name of the new class to be created. ...
magic_instruct_75k
63,656
Write a Python function to calculate the upper and lower bounds of a range based on a given point and standard deviation. The function should handle the special case where `null` is a placeholder for a specific value. The function should be named `calculateBounds` and should take two parameters: - `point` (integer or f...
Here is the Python code to solve the given problem in the markdown block: ```python def calculateBounds(point, sd): """ Calculate the upper and lower bounds of a range based on a given point and standard deviation. Args: point (int or float): The central point around which the bounds are calculated...
magic_instruct_75k
63,661
Implement a Python function `conclude_iteration_with_range_update` that optimizes voltage tuning for a hardware system. The function should take in several parameters and return specific outputs based on the iteration's results. The function signature is as follows: ```python def conclude_iteration_with_range_update(t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple class TuningResult: def __init__(self, successful: bool, error_type: str = None): self.successful = successful self.error_type = error_type def conclude_iteration_with_range_update(tu...
magic_instruct_75k
63,668
Write a Python function to manage software dependencies for a project. The function should take a list of dependencies and perform the necessary actions to ensure that all dependencies are installed and up to date. The dependencies are represented as strings. The actions to be performed include updating the package man...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def manageDependencies(dependencies: List[str]) -> List[str]: """ Manages software dependencies for a project by performing necessary actions. Args: dependencies (List[str]): A list of strin...
magic_instruct_75k
63,692
Write a Python function to calculate the total amount of money returned on successful transactions from a given list of transactions. Each transaction is represented as a string in the format "amount:status", where "amount" is a positive integer representing the transaction amount and "status" is either "success" or "f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_returned_amount(transactions: List[str]) -> int: """ Calculate the total amount of money returned on successful transactions. Args: transactions (List[str]): A list of strings ...
magic_instruct_75k
63,719
Write a Python function to find the maximum sum of a subarray within a given array. The subarray must be contiguous, and you need to return the maximum sum. The function should handle both positive and negative numbers in the array. The code should start with: ```python from typing import List def max_subarray_sum(ar...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_subarray_sum(arr: List[int]) -> int: """ Find the maximum sum of a contiguous subarray within the given array. Args: arr (List[int]): The input array of integers. Returns: ...
magic_instruct_75k
63,733
Write a Python function to simulate a simple machinery management system. The system should be able to add new machinery, remove existing machinery, and display the details of all machinery in the system. Additionally, the program should be able to test the machinery by invoking a plugin layer and ensure that the machi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict class Machinery: def __init__(self, id: int, name: str, status: str): self.id = id self.name = name self.status = status class MachineryManager: def __init__(self): ...
magic_instruct_75k
63,736
Write a Python function to generate a filename for a word graph based on given input parameters. The filename should follow a specific format that includes the base name, size of the graph, order of the words, and an optional suffix. The function should handle the optional suffix parameter and format the filename corre...
Here is the Python code to solve the given problem in the markdown block: ```python def get_word_graph_filename(ascending_order: bool, size: int, name_base: str, name_suffix: str = "") -> str: """ Generates a filename for a word graph based on the provided parameters. Args: ascending_order (bool): ...
magic_instruct_75k
63,768
Write a Python function to find the intersection of two lists of strings. The intersection of two lists is a new list containing only the elements that are present in both input lists. The function should handle duplicate elements correctly, meaning if an element appears `n` times in both lists, it should appear `n` ti...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List from collections import Counter def find_intersection(list1: List[str], list2: List[str]) -> List[str]: """ Find the intersection of two lists of strings, considering duplicates. Args: list1...
magic_instruct_75k
63,774
Write a Python function to parse a dictionary containing package information and generate a formatted string representing the package details. The package information dictionary will contain the following keys: `name`, `version`, `description`, `url`, `author`, and `author_email`. The function should be named `format_...
Here is the Python code to solve the given problem in the markdown block: ```python def format_package_info(package_info: dict) -> str: """ Formats the package information dictionary into a specific string pattern. Args: package_info (dict): A dictionary containing package information with keys: ...
magic_instruct_75k
63,808
Create a Python function to calculate the average AP score for students in a specific district based on the provided district data. The function should handle edge cases such as empty input and return the correct average score as a floating-point number. The function signature should be: ```python from typing import L...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_average_ap_score(district_data: List[int]) -> float: """ Calculate the average AP score for students in a specific district. Args: district_data (List[int]): A list of integers...
magic_instruct_75k
63,830
Write a Python function to process subscription information obtained from an API response. The function should perform the following steps: 1. Extract the UUID from the `instance_info` JSON. 2. Print the value of the extracted UUID. 3. Retrieve the list of subscriptions for the specified replica (`aws` in this case) us...
Here is the Python code to solve the given problem in the markdown block: ```python import json from typing import Dict, List def process_subscriptions(instance_info: Dict, replica: str) -> None: """ Process subscription information from an API response. Args: instance_info (Dict): A dictionary co...
magic_instruct_75k
63,850
Write a Python function to categorize a list of context processors used in a Django application. Each context processor is represented as a string in the format `module.submodule.function`. The function should return a dictionary where the keys are the module paths (excluding the function name) and the values are lists...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def process_context_processors(context_processors: List[str]) -> Dict[str, List[str]]: """ Categorizes a list of context processors used in a Django application. Args: context_processo...
magic_instruct_75k
63,860
Write a Python function to generate an HTML table from a list of dictionaries. Each dictionary in the list represents a row in the table, with the keys of the dictionary representing the column headers and the values representing the cell data. The function should produce an HTML table string with the appropriate heade...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def generate_html_table(data: List[Dict[str, any]]) -> str: """ Generates an HTML table from a list of dictionaries. Args: data (List[Dict[str, any]]): A list of dictionaries where eac...
magic_instruct_75k
63,884
Write a Python function to determine if a given string `s` matches a given pattern `p`. The pattern can include the following special characters: - `.` Matches any single character. - `*` Matches zero or more of the preceding element. The function should start with: ```python def is_match(s: str, p: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_match(s: str, p: str) -> bool: """ Determine if the string `s` matches the pattern `p`. Args: s (str): The input string to be matched. p (str): The pattern string containing characters and special cha...
magic_instruct_75k
63,919
Write a Python function to process a given configuration dictionary and a list of included modules. The function should return a new dictionary containing only the modules that are present in the includes list and their corresponding datasinks from the sysconfig dictionary. The sysconfig dictionary contains a key "dat...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def process_config(sysconfig: Dict[str, List[str]], includes: List[str]) -> Dict[str, List[str]]: """ Processes a given configuration dictionary and a list of included modules to return a new dicti...
magic_instruct_75k
63,944
Write a Python function to simulate the setup process for a web application, handling the installation of dependencies using npm and managing potential failures during the installation process. The function should: 1. Display a message indicating the start of the setup process. 2. Simulate the installation of dependenc...
Here is the Python code to solve the given problem in the markdown block: ```python import random def setup_web_app(): """ Simulates the setup process for a web application, handling the installation of dependencies using npm and managing potential failures. Steps: 1. Display a message indicating the ...
magic_instruct_75k
63,957
Write a Python function to calculate the maximum amount of water that can be trapped after raining on a given array of bar heights. Each bar has a width of 1 unit. The array is non-empty and each element is a non-negative integer. The function should start with: ```python from typing import List def trap(height: List...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def trap(height: List[int]) -> int: """ Calculate the maximum amount of water that can be trapped after raining on a given array of bar heights. Args: height (List[int]): The array represent...
magic_instruct_75k
63,962
Write a Python function to determine the mode indicator for a given QR code data type. The function should return the corresponding mode indicator value based on the provided data type. The mode indicators are defined as hexadecimal values and are associated with specific data types. The function should handle the foll...
Here is the Python code to solve the given problem in the markdown block: ```python def get_mode_indicator(data_type: str) -> int: """ Returns the mode indicator for a given QR code data type. The mode indicators are defined as follows: - "numeric" -> 0x3 (STRUCTURED_APPEND_VALUE) - "alphanumeric" ...
magic_instruct_75k
63,968
Write a Python function to parse a list of command-line options and return a dictionary containing the parsed options. The command-line options are provided as a list of strings, where each string represents an option or an option-argument pair. An option starts with a hyphen (`-`), and an option-argument pair consists...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def parse_options(opts: List[str]) -> Dict[str, str]: """ Parse a list of command-line options and return a dictionary containing the parsed options. Args: opts (List[str]): A list of ...
magic_instruct_75k
63,971
Write a Python function to validate a credit card number based on a set of rules. The credit card number is provided as a string in the format "XXXX-XXXX-XXXX-XXXX", where each "X" represents a digit (0-9) and the hyphens ("-") are included for readability. The function should return `True` if the credit card number is...
Here is the Python code to solve the given problem in the markdown block: ```python def validateCreditCard(credit_card_number: str) -> bool: """ Validates a credit card number based on a set of rules. Args: credit_card_number (str): The credit card number to validate, in the format "XXXX-XXXX-XXXX-...
magic_instruct_75k
63,986
Create a Python class `ThreadLocalStorage` that provides a unified interface for thread-local storage in a multi-threaded application. The class should allow the application to store and retrieve data specific to each thread. The class should provide the following methods: - `set(value: T) -> None`: Sets the thread-loc...
Here is the Python code to solve the given problem in the markdown block: ```python from threading import local class ThreadLocalStorage: """ Provides a unified interface for thread-local storage in a multi-threaded application. This class allows the application to store and retrieve data specific to each...
magic_instruct_75k
63,987
Write a Python function to parse a list of tuples containing strings representing names in a specific format and return a dictionary with the parsed components of the names. Each tuple contains a string representing a name and a dictionary with keys 'first', 'von', 'last', and 'jr'. The string represents the name in a ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def parse_names(names: List[Tuple[str, Dict[str, List[str]]]]) -> Dict[str, List[str]]: """ Parses a list of tuples containing names and their components into a dictionary. Args: ...
magic_instruct_75k
63,995
Write a Python function to delete a specific system from a list of systems. Each system is represented by a dictionary with the keys "name", "type", and "status". The function should take in the list of systems and the name of the system to be deleted, and then return the updated list with the specified system removed....
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def delete_system(systems: List[Dict[str, str]], system_name: str) -> List[Dict[str, str]]: """ Deletes a specific system from a list of systems based on the system's name. Args: syste...
magic_instruct_75k
63,997
Write a Python function to simulate the creation of a file named "temp" and return the exit status code based on the success or failure of the file creation. If the file creation is successful, the function should return the value of the variable `status`. If the file creation fails, the function should return an appro...
Here is the Python code to solve the given problem in the markdown block: ```python import random def create_temp_file(status: int) -> int: """ Simulates the creation of a file named "temp" and returns the exit status code. Args: status (int): The exit status code to return if the file creation is...
magic_instruct_75k
64,000
Write a Python function to verify the non-recoverable states of a service catalog factory module. The function should take the system under test (`sut`) as a parameter and return a boolean value indicating whether the non-recoverable states match the expected states. The expected non-recoverable states are `"ROLLBACK_C...
Here is the Python code to solve the given problem in the markdown block: ```python def verify_non_recoverable_states(sut) -> bool: """ Verifies if the non-recoverable states of the service catalog factory match the expected states. Args: sut: The system under test, which has a method `get_non_reco...
magic_instruct_75k
64,043
Write a Python function to analyze a given HTML file and extract the unique URLs of CSS files and background images used in the file. The function should return a dictionary containing the count of unique URLs for CSS files and background images. The function should consider both the `href` attribute in the `<link>` ta...
Here is the Python code to solve the given problem in the markdown block: ```python import re from typing import Dict def extract_urls(html: str) -> Dict[str, int]: """ Extracts and counts the unique URLs of CSS files and background images from a given HTML content. Args: html (str): The content o...
magic_instruct_75k
64,048
Write a Python function to shuffle an array of elements using the Fisher-Yates shuffle algorithm. The Fisher-Yates shuffle is an algorithm for generating a random permutation of a finite sequence. It generates a uniformly random permutation of the input array in O(n) time complexity, where n is the size of the array. ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, TypeVar import random T = TypeVar('T') def fisher_yates_shuffle(arr: List[T]) -> None: """ Shuffles the given array in place using the Fisher-Yates shuffle algorithm. The Fisher-Yates shuffle algo...
magic_instruct_75k
64,083
Write a Python function to calculate the total votes received by each party in a voting system. Each party's output is represented as a list of integers, and the goal is to sum the votes for each party. The function should take a list of lists as input, where each inner list represents the votes received by a single pa...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def calculate_total_votes(each_partys_output_wires: List[List[int]]) -> Dict[int, int]: """ Calculate the total votes received by each party in a voting system. Args: each_partys_outpu...
magic_instruct_75k
64,106
Write a Python function to validate version numbers according to the Semantic Versioning (SemVer) specification. The function should ensure that the version number is in the format `MAJOR.MINOR.PATCH`, where `MAJOR`, `MINOR`, and `PATCH` are non-negative integers separated by periods. Additionally, no leading zeros are...
Here is the Python code to solve the given problem in the markdown block: ```python import re def validate_semantic_version(version: str) -> bool: """ Validates whether the given version string adheres to the Semantic Versioning (SemVer) specification. The SemVer specification requires the version number ...
magic_instruct_75k
64,115
Write a Python function to generate a formatted HTML help page from a list of help articles. Each help article is represented as a dictionary with keys "title" and "content". The function should take a list of such dictionaries and produce an HTML page displaying the titles and content of the help articles. The functio...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def format_help_page(articles: List[Dict[str, str]]) -> str: """ Generates a formatted HTML help page from a list of help articles. Args: articles (List[Dict[str, str]]): A list of dic...
magic_instruct_75k
64,118
Write a Python function to evaluate a mathematical expression given as a string. The expression can contain the four basic arithmetic operations: addition (+), subtraction (-), multiplication (*), and division (/). The input expression will be provided as a single string without any spaces. The function should handle t...
Here is the Python code to solve the given problem in the markdown block: ```python def evaluateExpression(expression: str) -> int: """ Evaluates a mathematical expression given as a string. The expression can contain the four basic arithmetic operations: addition (+), subtraction (-), multiplication (*), ...
magic_instruct_75k
64,123
Create a Python class `NetworkObject` that represents a network object. The class should have the following functionalities: 1. Initialize the object with a `name` attribute set to 'Normal'. 2. Provide a method to set the `name` attribute to a new value. 3. Provide a method to retrieve the current value of the `name` a...
Here is the Python code to solve the given problem in the markdown block: ```python class NetworkObject: def __init__(self): """ Initialize the network object with a name attribute set to 'Normal'. """ self.name = 'Normal' def set_name(self, new_name): """ Set th...
magic_instruct_75k
64,124
Write a Python function to calculate the average score for each video based on the scores provided by users. The function should take a list of `VideoScore` objects as input and return a dictionary where the keys are `video_id` and the values are the average scores. Each `VideoScore` object has the following attribute...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict class VideoScore: def __init__(self, video_id: int, score: float): self.video_id = video_id self.score = score def calculate_average_score(video_scores: List[VideoScore]) -> Dict[int, ...
magic_instruct_75k
64,188
Write a Python function to calculate the distribution of scores in a game. The function should take a list of integers representing the scores and return a dictionary where the keys are the unique scores and the values are the frequency of each score. The code should start with: ```python from typing import List, Dict...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def calculate_score_distribution(scores: List[int]) -> Dict[int, int]: """ Calculate the distribution of scores in a game. Args: scores (List[int]): A list of integers representing the...
magic_instruct_75k
64,193
Write a Python function to calculate the average number of stars for a list of GitHub repositories. Each repository is represented as a dictionary with the keys "name" (string) for the repository name and "stars" (integer) for the number of stars the repository has. If the input list is empty, the function should retur...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union def calculate_average_stars(repositories: List[Dict[str, Union[str, int]]]) -> float: """ Calculate the average number of stars for a list of GitHub repositories. Args: reposito...
magic_instruct_75k
64,212
Write a Python function to count the occurrences of a given substring within a larger string, considering overlapping occurrences. The function should take two strings as input: the main string and the substring to be counted. The function should return the count of occurrences of the substring within the main string. ...
Here is the Python code to solve the given problem in the markdown block: ```python def count_substring(string: str, sub_string: str) -> int: """ Counts the occurrences of a given substring within a larger string, considering overlapping occurrences. Args: string (str): The main string in which to ...
magic_instruct_75k
64,222
Write a Python function to count the number of words in a given sentence. A word is defined as a sequence of characters separated by spaces. The function should handle various edge cases, such as sentences with leading or trailing spaces, multiple spaces between words, and empty sentences. The code should start with: ...
Here is the Python code to solve the given problem in the markdown block: ```python def count_words(sentence: str) -> int: """ Counts the number of words in a given sentence. Args: sentence (str): The input sentence to count words from. Returns: int: The number of words in the sentence...
magic_instruct_75k
64,223
Write a Python function to generate an HTML table of buttons based on a given list of button labels and the number of columns to display. Each button should trigger a specific JavaScript function when clicked. The function should take two parameters: 1. `buttons`: a list of strings representing the labels for the butto...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def make_button_table(buttons: List[str], num_columns: int) -> str: """ Generates an HTML table of buttons based on a given list of button labels and the number of columns to display. Args: ...
magic_instruct_75k
64,251
Write a Python function to determine if a given string containing only parentheses, brackets, and braces is balanced. A string is considered balanced if every opening parenthesis, bracket, or brace has a corresponding closing parenthesis, bracket, or brace and they are properly nested. The function should return `True`...
Here is the Python code to solve the given problem in the markdown block: ```python def is_balanced(s: str) -> bool: """ Determine if the given string of parentheses, brackets, and braces is balanced. Args: s (str): The string to check for balanced parentheses, brackets, and braces. Returns: ...
magic_instruct_75k
64,275
Write a Python function to reverse each integer in a given list of integers and return a list of the reversed integers. The function should handle both positive and negative integers correctly. The reversed integer should maintain the sign of the original integer. The code should start with: ```python from typing impo...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_integers(integers: List[int]) -> List[int]: """ Reverses each integer in the given list and returns a list of the reversed integers. Args: integers (List[int]): A list of integer...
magic_instruct_75k
64,294
Write a Python function to count the number of vowels in a given string. The function should be case-insensitive and should ignore non-alphabetic characters. The input string can contain up to 1000 characters. The function should start with: ```python def count_vowels(input_string: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def count_vowels(input_string: str) -> int: """ Counts the number of vowels (a, e, i, o, u) in the input string. The function is case-insensitive and ignores non-alphabetic characters. Args: input_string (str): ...
magic_instruct_75k
64,299
Write a Python function to flatten a list of lists containing integers and return a new list containing all the integers from the input lists in ascending order. The function should handle any number of nested lists and any number of integers within those lists. The code should start with: ```python from typing import...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def flatten_and_sort(lst: List[List[int]]) -> List[int]: """ Flattens a list of lists containing integers and returns a new list containing all the integers in ascending order. Args: lst (Li...
magic_instruct_75k
64,305
Write a Python function to count the occurrences of each release track type in a list of Google Cloud SDK release tracks. The release tracks are represented as strings and can be one of the following: "ALPHA", "BETA", or "GA" (General Availability). The function should return a dictionary containing the count of each r...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_release_tracks(tracks: List[str]) -> Dict[str, int]: """ Counts the occurrences of each release track type in a list of Google Cloud SDK release tracks. Args: tracks (List[st...
magic_instruct_75k
64,318
Write a Python function to automate the process of checking and updating software versions in a package management system. The function should validate the version of a specific software package and prompt for an update if necessary. The function should also check if a specific environment variable is set to a certain ...
Here is the Python code to solve the given problem in the markdown block: ```python def check_and_update_version(env_var: str, current_version: str, required_version: str) -> None: """ Automates the process of checking and updating software versions in a package management system. Args: env_var (st...
magic_instruct_75k
64,341
Write a Python function to apply the logistic function (sigmoid function) to each element of a given input array. The logistic function is defined as: \[ f(x) = \frac{1}{1 + e^{-x}} \] The function should take a NumPy array as input and return a new NumPy array where the logistic function has been applied to each ele...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def apply_logistic_function(input_array: np.ndarray) -> np.ndarray: """ Applies the logistic function (sigmoid function) to each element of the input array. The logistic function is defined as: \[ f(...
magic_instruct_75k
64,367
Write a Python function to translate x86 assembly mnemonics to their corresponding register names. The function should take an x86 assembly mnemonic as input and return the corresponding register name based on the provided mapping. The mnemonics are followed by a suffix indicating the size of the operands, such as "_b"...
Here is the Python code to solve the given problem in the markdown block: ```python def getRegisterName(mnemonic: str) -> str: """ Translates an x86 assembly mnemonic to its corresponding register name. Args: mnemonic (str): The x86 assembly mnemonic to be translated. Returns: str: The...
magic_instruct_75k
64,373
Write a Python function to filter a list of container types based on certain criteria. The function should take in four parameters: `container_type` (string), `backup_engine_name` (string), `fabric_name` (string), and `status` (string). The `container_type` parameter represents the type of container for filtering, and ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_container_types(container_type: str, backup_engine_name: str, fabric_name: str, status: str) -> List[str]: """ Filters a list of container types based on the provided criteria. Args: ...
magic_instruct_75k
64,374
Write a Python function to parse a list of authors' names and emails into a dictionary. Each element in the list is a string containing the author's name followed by their email address enclosed in angle brackets. The function should return a dictionary where the keys are the author names and the values are their corre...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def parse_authors(authors: List[str]) -> Dict[str, str]: """ Parses a list of authors' names and emails into a dictionary. Args: authors (List[str]): A list of strings where each strin...
magic_instruct_75k
64,396
Write a Python function to process a list of tuples, where each tuple contains a hexadecimal number and a byte string. The function should return a dictionary where the keys are the hexadecimal numbers converted to decimal and the values are lists of corresponding byte strings. 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, Tuple, Dict def process_data(data: List[Tuple[int, bytes]]) -> Dict[int, List[bytes]]: """ Processes a list of tuples where each tuple contains a hexadecimal number and a byte string. Returns a dict...
magic_instruct_75k
64,413
Write a Python function to update a nested dictionary representing a build system's response based on a boolean flag indicating whether the build process is completed. The function should modify specific fields within the dictionary if the build process is completed. The function should start with: ```python def updat...
Here is the Python code to solve the given problem in the markdown block: ```python def update_build_info(response: dict, done: bool) -> dict: """ Updates the build information in the response dictionary based on whether the build process is completed. Args: response (dict): A dictionary representi...
magic_instruct_75k
64,426
Write a Python function to preprocess an input image and its corresponding ground truth bounding boxes, labels, and scores for a computer vision application. The function should perform the following operations: 1. Randomly flip the input image and its corresponding bounding boxes horizontally. 2. Shuffle the ground tr...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from typing import Tuple def random_flip(img: np.ndarray, gtboxes: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """ Randomly flip the input image and its corresponding bounding boxes horizontally. Args:...