source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
magic_instruct_75k
40,913
Write a Python function to process a list of occurrences from a theater management system and return a dictionary containing information about the shows and their corresponding castings. The function should organize the data based on show identifiers and include occurrence and casting information for each show. The fu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Tuple def get_act_casting() -> List[Tuple[str, str]]: """ Simulates fetching casting information for a show. Returns: List[Tuple[str, str]]: A list of tuples where each tuple contains...
magic_instruct_75k
40,917
Write a Python function `process_data(visual_conf, rel_coll_data)` that processes data from a collection of dictionaries and returns a specific result based on the given criteria. The function should take in a dictionary `visual_conf` and a list of dictionaries `rel_coll_data`. Each dictionary in `rel_coll_data` repres...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Tuple def process_data(visual_conf: Dict[str, str], rel_coll_data: List[Dict[str, any]]) -> List[Tuple[str, str]]: """ Processes data from a collection of dictionaries and returns a specific resul...
magic_instruct_75k
40,920
Write a Python function to simplify a given file path by resolving the special characters '.' and '..', which represent the current directory and the parent directory, respectively. The function should return the simplified absolute path. The code should start with: ```python def simplify_path(path: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def simplify_path(path: str) -> str: """ Simplifies a given file path by resolving the special characters '.' and '..'. Args: path (str): The input file path to be simplified. Returns: str: The simplifi...
magic_instruct_75k
40,955
Create a Python class `ChemicalElement` that represents a chemical element with the ability to store and manipulate its properties. The class should have the following specifications: - A constructor that initializes the element with its `symbol`, `name`, `atomic_number`, `atomic_mass`, and a dictionary of `properties`...
Here is the Python code to solve the given problem in the markdown block: ```python class ChemicalElement: """ Represents a chemical element with properties such as atomic number, atomic mass, and additional properties. Attributes: symbol (str): The chemical symbol of the element. name (str...
magic_instruct_75k
40,967
Create a Python function to implement a service registry system for a microservices architecture. The service registry should efficiently store and retrieve information about various services, including their names, versions, and endpoints. The system should support adding a new service and querying for the endpoint of...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Optional class ServiceRegistry: def __init__(self): """ Initialize the service registry as an empty dictionary. """ self.registry: Dict[str, Dict[str, str]] = {} def add...
magic_instruct_75k
40,983
Write a Python function to process a list of user-reported issues and check for a specific issue. If the issue is not present in the list, the function should add it to the list. The function should return the updated list of user issues after processing the given issue. The code should start with: ```python from typi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def process_issue(user_issues: List[str], issue_to_check: str) -> List[str]: """ Processes a list of user-reported issues and checks for a specific issue. If the issue is not present in the list, it ...
magic_instruct_75k
41,008
Write a Python function to sort a list of tuples based on the second element of each tuple in ascending order. The function should take a list of tuples as input and return a new list of tuples sorted according to the second element. The code should start with: ```python from typing import List, Tuple, Any def sort_b...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Any def sort_by_second_element(lst: List[Tuple[Any, Any]]) -> List[Tuple[Any, Any]]: """ Sorts a list of tuples based on the second element of each tuple in ascending order. Args: ls...
magic_instruct_75k
41,012
Write a Python function to find all company names in a given list that contain a specified keyword as a substring. The search should be case-insensitive. The function should start with: ```python from typing import List def find_matching_companies(keyword: str, company_list: List[str]) -> List[str]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_matching_companies(keyword: str, company_list: List[str]) -> List[str]: """ Find all company names in a given list that contain a specified keyword as a substring. Args: keyword (st...
magic_instruct_75k
41,027
Write a Python function to calculate the remaining battery percentage of a smartwatch based on the current battery level. The smartwatch has a base power level of 150 units. The function should take the current battery level as a parameter and return the remaining battery percentage as an integer, rounded down to the n...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_battery_percentage(current_battery_level: int) -> int: """ Calculate the remaining battery percentage of a smartwatch based on the current battery level. Args: current_battery_level (int): The current ...
magic_instruct_75k
41,037
Create a Python class `ProviderManager` that manages provider information for a task management system. The class should handle different scenarios for provider names and store additional task configuration, update information, and address details. The class should have the following attributes and methods: - **Attrib...
Here is the Python code to solve the given problem in the markdown block: ```python class ProviderManager: """ A class to manage provider information for a task management system. Attributes: provider_name (str): The primary provider name. provider_name_sub (str): The secondary provider nam...
magic_instruct_75k
41,039
Write a Python function to find the integer in a list that is closest to a given target number. The function should take a target number and a list of integers as input and return the nearest integer from the list. The function should handle input validation to ensure that the list contains only valid integers. The co...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_nearest_integer(target: int, integer_list: List[int]) -> int: """ Find the integer in the list that is closest to the given target number. Args: target (int): The target number to w...
magic_instruct_75k
41,057
Write a Python function to construct a URL using the provided date components and download an XML file from the constructed URL using the `requests` library. The function should save the downloaded file in a specified directory with a filename in the format `cuaca_besok_$tanggal$bulan$tahun.xml`. The function should t...
Here is the Python code to solve the given problem in the markdown block: ```python import os import requests def download_weather_data(certificate_path: str, user_agent: str, day: str, month: str, year: str, save_directory: str) -> None: """ Downloads weather data from a specific URL and saves it to a file. ...
magic_instruct_75k
41,059
Write a Python function to shuffle the elements of a given list based on a boolean mask. The mask indicates which elements should be included in the shuffle. The function should return a new list containing the shuffled elements based on the mask. The code should start with: ```python from typing import List import ra...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def shuffle_with_mask(data: List[int], mask: List[bool]) -> List[int]: """ Shuffles the elements of a given list based on a boolean mask. Args: data (List[int]): The list of el...
magic_instruct_75k
41,071
Write a Python function to determine the precision of a 2-component vector type (vec2) based on predefined precision macros for both floating-point and integer types. The function should handle the cases where the precision macros are not defined and provide a default precision for the vector types. The precision macr...
Here is the Python code to solve the given problem in the markdown block: ```python def get_vec2_precision(is_float: bool, highp: bool = False, mediump: bool = False, lowp: bool = False) -> str: """ Determine the precision of a 2-component vector type (vec2) based on predefined precision macros. Args: ...
magic_instruct_75k
41,080
Write a Python function to process the results of a SPARQL query and return a dictionary containing specific information. The function will take in the SPARQL query results and a timestamp as input. The SPARQL query results will be in the form of a list of dictionaries, where each dictionary represents a binding of var...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def process_sparql_results(results: List[Dict], timestamp: str) -> Dict[str, List[str]]: """ Processes the results of a SPARQL query and returns a dictionary containing specific information. A...
magic_instruct_75k
41,081
Write a Python function to simulate a simple client-server interaction where the client sends a request to the server, and the server responds with a modified message. The client function, `send_request_to_server`, should take a message as input and send it to the server. The server function, `respond_to_client`, shoul...
Here is the Python code to solve the given problem in the markdown block: ```python def send_request_to_server(message: str) -> str: """ Simulates sending a message to a server and receiving a response. Args: message (str): The message to be sent to the server. Returns: str: The respon...
magic_instruct_75k
41,083
Write a Python function to process a list of tuples representing database query conditions and return a dictionary containing the processed conditions. Each tuple in the input list represents a condition in the format `(field, operator, value)`. The function should handle the following operators: `'='`, `'>'`, `'<'`, `...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Any def process_conditions(conditions: List[Tuple[str, str, Any]]) -> dict: """ Processes a list of tuples representing database query conditions and returns a dictionary containing the processed...
magic_instruct_75k
41,129
Write a Python function to parse a list of strings representing metadata for Python packages and return a dictionary containing the metadata information. Each string in the list represents a key-value pair in the format "key :: value". The function should ignore any strings that do not conform to this format. If a key ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union def parse_metadata(metadata: List[str]) -> Dict[str, Union[str, List[str]]]: """ Parses a list of strings representing metadata for Python packages and returns a dictionary. Each string...
magic_instruct_75k
41,152
Write a Python function to generate a unique identifier for an application by processing its name and version. The unique identifier should be created by removing all spaces from the application name and appending the application version. The function should handle any input errors and return the unique identifier as t...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_unique_identifier(app_name: str, app_version: str) -> str: """ Generates a unique identifier for an application by removing spaces from the application name and appending the application version. Args: ...
magic_instruct_75k
41,169
Write a Bash script that automates the creation and population of files based on the given requirements. The script should perform the following actions: 1. Create a file named `$FILE-04` and populate it with the string "ABCDEFGHIJKLMNOPQRSTUVWXYZ" without a newline at the end. 2. Create a file named `$FILE-05` and pop...
Here is the Python code to solve the given problem in the markdown block: ```bash #!/bin/bash # Define the variables FILE_04="file-04" FILE_05="file-05" FILE_06="file-06" FILE_08="file-08" FILE_09="file-09" TESTDIR="/path/to/testdir" # Create and populate file-04 echo -n "ABCDEFGHIJKLMNOPQRSTUVWXYZ" > "$FILE_04" # C...
magic_instruct_75k
41,201
Create a Python class that implements a simple caching mechanism for frequently accessed data. The class should efficiently store and retrieve answers to a set of questions based on the question index. Additionally, the class should support dynamic updates to the answers. The class should have the following properties...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional class QuestionCache: """ A simple caching mechanism for frequently accessed data. This class stores and retrieves answers to a set of questions based on the question index. It also sup...
magic_instruct_75k
41,216
Write a Python function to simulate the behavior of the given Bash script. The function should: 1. Set a variable `SNAP_DATA` to the directory path `/usr/share/nginx/`. 2. Print the concatenated string "test" followed by the value of the `SNAP_DATA` variable. The code should start with: ```python def simulate_bash_scr...
Here is the Python code to solve the given problem in the markdown block: ```python def simulate_bash_script(): """ Simulates the behavior of a Bash script that sets a variable and prints a concatenated string. This function sets the variable `SNAP_DATA` to the directory path `/usr/share/nginx/` and prints...
magic_instruct_75k
41,229
Write a Python function to normalize a given text by converting it to lowercase and replacing line breaks with spaces. The function should handle text strings of varying lengths, ensuring that all characters are in lowercase and all line breaks are replaced by spaces. The code should start with: ```python def normaliz...
Here is the Python code to solve the given problem in the markdown block: ```python def normalize_text(text: str) -> str: """ Normalizes the given text by converting it to lowercase and replacing line breaks with spaces. Args: text (str): The input text to be normalized. It contains alphanumeric ch...
magic_instruct_75k
41,241
Write a Python function to process and analyze the kinematic constraints and parameters of a robot. The function should take in the following variables as input: - `robot_kinconstr_exist`: A boolean indicating whether the robot's kinematic constraints exist. - `robot_NKCP`: An integer representing the number of kinemat...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Union def analyze_robot_kinematics(robot_kinconstr_exist: int, robot_NKCP: int, robot_KCP: str, robot_NMPVFIXB: int, robot_NMPVFLOATB: Union[str, int], robot_NTAUJFIXBREGNN: int) -> dict: """ Analyzes the kin...
magic_instruct_75k
41,254
Write a Python function to implement the Insertion Sort algorithm to sort an array of integers in ascending order. The Insertion Sort algorithm works by iteratively building a sorted portion of the array, one element at a time. At each iteration, the algorithm takes the next unsorted element and inserts it into its cor...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def InsertionSort(arr: List[int]) -> List[int]: """ Sorts an array of integers in ascending order using the Insertion Sort algorithm. Args: arr (List[int]): The unsorted array of integers. ...
magic_instruct_75k
41,263
Write a Python function to identify the cells that are walls in a maze grid based on the given width and height of the grid, the starting cell `start`, the set of non-wall cells `non_walls`, and the set of open cells `open_set`. The function should return a set containing the cells that are walls. The code should star...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Set, Tuple def identify_walls(width: int, height: int, start: Tuple[int, int], non_walls: Set[Tuple[int, int]], open_set: Set[Tuple[Tuple[int, int], Tuple[int, int]]]) -> Set[Tuple[int, int]]: """ Identify th...
magic_instruct_75k
41,282
Write a Python function `retrieve_session_info` that retrieves and organizes information from multiple experimental sessions for further analysis. Each session contains information about the position of probes' electrodes and the number of trials conducted. The function should take in the `one` object, which represents...
Here is the Python code to solve the given problem in the markdown block: ```python def retrieve_session_info(one): """ Retrieves and organizes information from multiple experimental sessions. Args: one: An object representing the data retrieval interface. Returns: dict: A dictionary w...
magic_instruct_75k
41,302
Write a Python function to count the number of unique signatures in a given list of signatures. A signature is considered unique if it does not match any other signature in the list, including itself. The function should take a list of strings as input and return an integer representing the count of unique signatures. ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_unique_signatures(signatures: List[str]) -> int: """ Counts the number of unique signatures in a given list of signatures. Args: signatures (List[str]): A list of strings where eac...
magic_instruct_75k
41,324
Write a Python function to complete the RGB values for a given color dictionary. The dictionary contains colors as keys and their corresponding RGB values as values. The RGB values are represented as a dictionary where the keys are strings (e.g., '2', '5', '8') and the values are either integers (representing incomplet...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def complete_rgb_values(color_dict: Dict[str, Dict[str, int]]) -> Dict[str, Dict[str, List[int]]]: """ Completes the RGB values for a given color dictionary. Args: color_dict (Dict[str...
magic_instruct_75k
41,329
Write a Python function to manage synonyms for words. The function should support adding new synonyms, checking if two words are synonyms, and counting the number of synonyms for a given word. The function should handle multiple commands as described below. The code should start with: ```python from typing import List...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def manage_synonyms(commands: List[Tuple[str, str, str]]) -> List[str]: """ Manages synonyms for words based on a list of commands. Args: commands (List[Tuple[str, str, str]]): A list...
magic_instruct_75k
41,336
Write a Python function to find the highest score achieved in a game given a list of integers representing the scores. If the input list is empty, the function should return 0. The function should be efficient and handle edge cases appropriately. The code should start with: ```python from typing import List def highe...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def highest_score(scores: List[int]) -> int: """ Returns the highest score achieved in the game from a list of scores. Args: scores (List[int]): A list of integers representing the scores ac...
magic_instruct_75k
41,350
Write a Python function called `oddTuples` that takes a tuple as input and returns a new tuple containing every other element of the input tuple, starting with the first element. The function should not use any built-in Python functions to solve this problem. The code should start with: ```python def oddTuples(aTup): `...
Here is the Python code to solve the given problem in the markdown block: ```python def oddTuples(aTup): """ Returns a new tuple containing every other element of the input tuple, starting with the first element. Args: aTup (tuple): The input tuple from which to extract every other element. Re...
magic_instruct_75k
41,364
Write a Python function to calculate the final score based on a list of integers representing game scores. The final score is determined by summing the highest three scores in the list. If the list contains fewer than three scores, the final score is the sum of all the scores in the list. The function should start wit...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_final_score(scores: List[int]) -> int: """ Calculate the final score based on the highest three scores in the list. Args: scores (List[int]): A list of integers representin...
magic_instruct_75k
41,368
Write a Python function to count the occurrences of each unique test requirement in a given list of test requirements. Each test requirement is represented as a string, and the function should ignore any leading or trailing whitespace in the test requirement strings. The function should be named `count_test_requirement...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_test_requirements(test_requirements: List[str]) -> Dict[str, int]: """ Counts the occurrences of each unique test requirement in a given list of test requirements. Args: test...
magic_instruct_75k
41,379
Write a Python function to categorize a list of security-related strings based on their structure and count the occurrences of each category. Each string consists of three parts separated by colons (`:`). The first part represents the category, the second part represents the subcategory or type, and the third part repr...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def categorize_security_strings(strings: List[str]) -> Dict[str, int]: """ Categorizes a list of security-related strings based on their structure and counts the occurrences of each category. ...
magic_instruct_75k
41,385
Create a Python function to efficiently send arrays of objects to a remote server. The function should handle the transmission process and any potential errors that may occur during communication. The function should be part of a class `BRequest_RemoteArrayTypes23_sendArraysObject` that simulates the behavior of a remo...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any class BRequest_RemoteArrayTypes23_sendArraysObject: """ A class to manage the sending of arrays of objects to a remote server. This class simulates the behavior of a remote array management sys...
magic_instruct_75k
41,390
Write a Python function to track TV show episodes by organizing them by season. The function should take a list of episode strings as input, where each string is in the format "SxEx" (e.g., "S1E3" for season 1, episode 3). The function should return a dictionary where the keys are the season numbers and the values are ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict import re def track_episodes(episode_list: List[str]) -> Dict[str, List[int]]: """ Track TV show episodes by organizing them by season. Args: episode_list (List[str]): A list of episod...
magic_instruct_75k
41,418
Write a Python function to parse a given HTTP request string and extract the headers from it. The headers are enclosed within a pair of curly braces `{}`. Each header is represented as a key-value pair separated by a colon `:`. The function should return a dictionary containing the extracted headers. The function sign...
Here is the Python code to solve the given problem in the markdown block: ```python def extract_headers(http_request: str) -> dict: """ Extracts the headers from a given HTTP request string and returns them as a dictionary. Args: http_request (str): The HTTP request string containing headers enclos...
magic_instruct_75k
41,421
Write a Python function to find the length of the longest increasing subsequence (LIS) within a given sequence of integers. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. An increasing subsequence is a subsequen...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def longest_increasing_subsequence(nums: List[int]) -> int: """ Calculate the length of the longest increasing subsequence in the given list of integers. Args: nums (List[int]): The list of ...
magic_instruct_75k
41,445
Write a Python function to count the number of "AlterField" operations performed on a specific model from a list of migration operations. Each migration operation is represented as a tuple containing the model name and the type of operation. The model name is a string, and the type of operation is one of the following:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def count_field_alterations(migrations: List[Tuple[str, str]], model_name: str) -> int: """ Counts the number of "AlterField" operations performed on a specific model from a list of migration oper...
magic_instruct_75k
41,446
Create a Python function that simulates a message handling system for a messaging application. The system should support adding various types of additions to messages, such as emojis, images, or files. Each addition has specific methods that can be applied to it. The function should take a list of message additions and...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Any def handle_messages(additions: List[Dict[str, Any]], actions: List[str]) -> List[Any]: """ Simulates a message handling system that supports adding various types of additions to messages. ...
magic_instruct_75k
41,449
Write a Python function to process a given string containing tag expressions and evaluate the enclosed arithmetic expressions. Each tag expression is enclosed within curly braces and consists of a tag name followed by an optional expression enclosed within parentheses. The tag name and expression are separated by a com...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import re def process_tag_expressions(s: str) -> List[Tuple[str, int]]: """ Processes a given string to extract and evaluate tag expressions. Args: s (str): A string containing tag ex...
magic_instruct_75k
41,481
Write a Python function to perform a binary search on a sorted array of distinct integers to determine if a target value is present in the array. If the target is found, return its index; otherwise, return -1. The function should be efficient and use the binary search algorithm to achieve this. The code should start w...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def search(nums: List[int], target: int) -> int: """ Perform a binary search on a sorted array to find the index of a target value. Args: nums (List[int]): A sorted list of distinct integers...
magic_instruct_75k
41,563
Write a Python function `extract_server_info` that processes a dictionary containing server parameters and SSL headers. The function should extract specific values from the dictionary and return them in a specific format. The function should follow these specifications: - The `server_params` dictionary will contain key...
Here is the Python code to solve the given problem in the markdown block: ```python def extract_server_info(server_params: dict) -> str: """ Extracts and formats server information from a dictionary containing server parameters and SSL headers. Args: server_params (dict): A dictionary containing se...
magic_instruct_75k
41,564
Write a Python function to calculate the average score of a game from a given list of integers representing the scores. The function should return the result rounded to the nearest integer. The code should start with: ```python from typing import List def calculate_average_score(scores: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_average_score(scores: List[int]) -> int: """ Calculate the average score of a game from a list of integers representing the scores. The result is rounded to the nearest integer. Ar...
magic_instruct_75k
41,565
Implement a circular buffer data structure in Python. A circular buffer, also known as a ring buffer, is a fixed-size buffer that overwrites old data with new data when the buffer is full. Your task is to create a class `CircularBuffer` that supports the following operations: 1. `push_back(value)`: Adds a new element t...
Here is the Python code to solve the given problem in the markdown block: ```python class CircularBuffer: def __init__(self, capacity: int): """ Initialize the circular buffer with the given capacity. Args: capacity (int): The maximum number of elements the buffer can hold. ...
magic_instruct_75k
41,570
Write a Python function to determine if all the opening HTML tags in a given string of HTML code have corresponding closing tags in the correct order. The function should return `True` if all tags are correctly matched, and `False` otherwise. The HTML tags are represented in the format `<tag>` for opening tags and `</t...
Here is the Python code to solve the given problem in the markdown block: ```python def htmlTagMatching(htmlCode: str) -> bool: """ Determines if all the opening HTML tags in the given string of HTML code have corresponding closing tags in the correct order. Args: htmlCode (str): The string of HTML...
magic_instruct_75k
41,593
Write a Python function `find_next_section(sections_base, sec, section)` that takes in the following parameters: - `sections_base`: A list of section names. - `sec`: The current section name. - `section`: The target section name. The function should return the next section name after the target section. If the target ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_next_section(sections_base: List[str], sec: str, section: str) -> Optional[str]: """ Finds the next section name after the target section in a list of section names. Args: ...
magic_instruct_75k
41,599
Write a Python function to determine the possible return values of a closure based on the combinations of input values. The closure captures a weak reference to `self` and uses a switch statement to determine the return value based on the values of various properties and selections. The input values are selections from...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def determine_return_values( preferences_pinNameFont_selection: int, preferences_componentNameColorForSchematic_selection: int, preferences_componentNameFontForSchematic_selection: int, pr...
magic_instruct_75k
41,634
Create a Python class `SubscriptionManager` that manages user subscriptions to various services. Each service has a unique identifier (`service_id`) and a name (`service_name`). The class should support the following methods: 1. `subscribe(user_id, service_id, service_name)`: Subscribes the user with the given `user_i...
Here is the Python code to solve the given problem in the markdown block: ```python class SubscriptionManager: def __init__(self): """ Initialize the SubscriptionManager with an empty dictionary to store user subscriptions. """ self.subscriptions = {} # Dictionary to store user subs...
magic_instruct_75k
41,637
Write a Python function to automate the setup of a MySQL server on a Linux system. The function should perform the following tasks: 1. Create the necessary directories for MySQL data, runtime, and log files: `/var/lib/mysql`, `/var/run/mysqld`, and `/var/log/mysql`. 2. Add specific configuration entries to the MySQL co...
Here is the Python code to solve the given problem in the markdown block: ```python import os def setup_mysql_server(): """ Automates the setup of a MySQL server on a Linux system by creating necessary directories and updating the MySQL configuration file. This function performs the following tasks: 1...
magic_instruct_75k
41,652
Create a Python function to validate and process command-line parameters for a graphics application. The function should extract and validate specific parameters from the command line using a mock `cli_parser` class. The function should perform the following tasks: 1. Check if there is at least one anonymous argument p...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional class cli_parser: def __init__(self, args: List[str]): self.args = args def get_anonymous_args(self) -> List[str]: return [arg for arg in self.args if not arg.startswith("--")]...
magic_instruct_75k
41,666
Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock at most once, given a list of integers representing the daily stock prices. If it is not possible to make any profit, the function should return 0. The code should start with: ```python from typing import List d...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_profit(prices: List[int]) -> int: """ Calculate the maximum profit that can be obtained by buying and selling a stock at most once. Args: prices (List[int]): A list of integers repre...
magic_instruct_75k
41,673
Write a Python function to merge overlapping intervals from a given list of intervals. Each interval is represented as a list of two integers, where the first integer is the start of the interval and the second integer is the end of the interval. The function should return a new list of non-overlapping intervals after ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_intervals(intervals: List[List[int]]) -> List[List[int]]: """ Merges overlapping intervals from a given list of intervals. Args: intervals (List[List[int]]): A list of intervals, w...
magic_instruct_75k
41,679
Write a Python function to extract specific information from a given Protocol Buffers (protobuf) file represented in Python syntax. The function should take a dictionary representing the protobuf file as input and return a dictionary containing the following information: 1. The number of nested types defined in the pro...
Here is the Python code to solve the given problem in the markdown block: ```python def extract_protobuf_info(code_snippet: dict) -> dict: """ Extracts specific information from a given Protocol Buffers (protobuf) file represented in Python syntax. Args: code_snippet (dict): A dictionary representi...
magic_instruct_75k
41,690
Write a Python function to generate a unique license key for software products based on given input parameters. The function should take in the following parameters: - `productCode`: A string representing the product code (e.g., "PROD123"). - `numLicenses`: An integer representing the number of licenses to generate. - ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random import string def generate_license_keys(productCode: str, numLicenses: int, licenseLength: int) -> List[str]: """ Generates a list of unique license keys for a software product. Args: ...
magic_instruct_75k
41,707
Write a Python function to sort a log file containing various types of entries. Each entry in the log file is represented as a string. The function should return a list of log entries sorted based on specific criteria. The log entries are formatted as follows: - Each entry consists of a unique identifier, followed by ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_logs(in_log: List[str]) -> List[str]: """ Sorts a log file containing various types of entries based on specific criteria. Args: in_log (List[str]): A list of log entries where each...
magic_instruct_75k
41,715
Write a Python function to generate an HTML output string based on a given integer `n`. The function should produce `n` rows of HTML `<div>` elements, each with a class attribute `"row"`. The HTML output should be returned as a single string. The code should start with: ```python def generate_html_output(n: int) -> st...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_html_output(n: int) -> str: """ Generates an HTML output string with `n` rows of `<div>` elements, each with a class attribute "row". Args: n (int): The number of rows to generate. Returns: ...
magic_instruct_75k
41,720
Write a Python function to automate the installation of a tool called `cfssl-certinfo` on a Linux system. The tool is provided as a binary file named `cfssl-certinfo_linux-amd64` and needs to be made executable and placed in the `/usr/local/bin` directory. Additionally, the `/usr/local/bin` directory needs to be added ...
Here is the Python code to solve the given problem in the markdown block: ```python import os import shutil def install_cfssl_certinfo(binary_path: str) -> None: """ Automates the installation of the cfssl-certinfo tool on a Linux system. This function performs the following tasks: 1. Makes the cfssl-...
magic_instruct_75k
41,723
Write a Python function to merge two dictionaries, `default_config` and `provided_config`, such that the resulting dictionary contains all keys from both dictionaries, with values from `provided_config` taking precedence over those in `default_config` if there is a conflict. The function should start with: ```python de...
Here is the Python code to solve the given problem in the markdown block: ```python def merge_config(default_config: dict, provided_config: dict) -> dict: """ Merges the default configuration with the provided configuration, giving precedence to the provided settings. Args: default_config (dict): T...
magic_instruct_75k
41,728
Write a Python function to generate a string representation of method parameter declarations and template parameter declarations. The function should take in a list of `MethodParamInfo` objects for method parameters and a list of `TemplateParamInfo` objects for template parameters. Each `MethodParamInfo` object contain...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, NamedTuple class MethodParamInfo(NamedTuple): name: str type: str class TemplateParamInfo(NamedTuple): name: str type: str def params_call_decls(params: List[MethodParamInfo]) -> str: """ ...
magic_instruct_75k
41,729
Write a Python function to generate a health report for a fleet of vehicles. The function should take a list of vehicle objects and return a dictionary where the keys are the vehicle IDs and the values are the health statuses of the corresponding vehicles. Each vehicle object is represented as a dictionary with the key...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def report_health(vehicles: List[Dict[str, str]]) -> Dict[str, str]: """ Generates a health report for a fleet of vehicles. Args: vehicles (List[Dict[str, str]]): A list of vehicle obj...
magic_instruct_75k
41,749
Write an asynchronous Python function to simulate a simple broadcast messaging system. The function should take in a list of messages and a list of admin IDs, and then broadcast each message to all the admins. Additionally, the function should only allow authorized users to send broadcast messages. The function should ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List async def broadcast_messages(messages: List[str], admin_ids: List[int], sender_id: int) -> None: """ Simulates a broadcast messaging system where each message is sent to all admin IDs. Args: ...
magic_instruct_75k
41,769
Write a Python function to find the length of the longest substring of a given string `s` such that every character in this substring appears at least `k` times. The function should be named `longestSubstring` and should take two parameters: a string `s` and an integer `k`. The function should return an integer represe...
Here is the Python code to solve the given problem in the markdown block: ```python def longestSubstring(s: str, k: int) -> int: """ Finds the length of the longest substring of `s` such that every character in this substring appears at least `k` times. Args: s (str): The input string. k (i...
magic_instruct_75k
41,776
Write a Python function to determine the type of disk associated with a given image ID. The function should take in the image ID as a string and return the corresponding disk type as a string. The disk type is determined based on a predefined dictionary `DISK_TYPE`, which maps disk types to their respective storage int...
Here is the Python code to solve the given problem in the markdown block: ```python def get_disk_type(image_id: str) -> str: """ Determine the type of disk associated with a given image ID. Args: image_id (str): The image ID for which to determine the disk type. Returns: str: The disk ...
magic_instruct_75k
41,780
Write a Python function to automate the deployment process for a web application. The deployment process involves pulling the latest changes from a Git repository and restarting a process manager for the application. The function should perform the following steps: 1. Pull the latest changes from the `master` branch of...
Here is the Python code to solve the given problem in the markdown block: ```python import subprocess def deploy_web_application(): """ Automates the deployment process for a web application by pulling the latest changes from a Git repository and restarting a process managed by `pm2`. Steps: 1. Pu...
magic_instruct_75k
41,849
Write a Python function to modify the default options for an ADMMEqual solver based on the input arguments. The function should take in a dictionary of default options and two boolean flags, `LinSolveCheck` and `NonNegCoef`. The function should modify the `default_options` dictionary to set the `LinSolveCheck` option i...
Here is the Python code to solve the given problem in the markdown block: ```python def modify_admm_options(default_options: dict, LinSolveCheck: bool = False, NonNegCoef: bool = False) -> dict: """ Modifies the default options for an ADMMEqual solver based on the input arguments. Args: default_opt...
magic_instruct_75k
41,859
Write a Python function to automate the packaging of an Electron application using the `electron-packager` tool. The function should perform the following steps: 1. Check if the `electron-packager` tool is installed. 2. If the tool is not installed, prompt the user to install it using npm. 3. Execute the packaging comm...
Here is the Python code to solve the given problem in the markdown block: ```python import subprocess import sys def package_electron_app(app_dir: str, app_name: str, platform: str = "darwin", arch: str = "x64") -> None: """ Automates the packaging of an Electron application using the `electron-packager` tool....
magic_instruct_75k
41,868
Write a Python function to determine whether one string is an anagram of another string. 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 return `True` if the second string is an anagram of the firs...
Here is the Python code to solve the given problem in the markdown block: ```python def is_anagram(s: str, t: str) -> bool: """ Determines whether the string t is an anagram of the string s. Args: s (str): The first string to compare. t (str): The second string to compare. Returns: ...
magic_instruct_75k
41,879
Write a Python function to calculate the number of likes and comments for each time period (day, week, and month) based on the given data sets. The function should take three data sets as input: `day_message`, `week_message`, and `month_message`, each representing the messages posted on a daily, weekly, and monthly bas...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def calculate_likes_comments(day_message: List[Dict[str, str]], week_message: List[Dict[str, str]], month_message: List[Dict[str, str]]) -> Dict[str, Dict[str, int]]: """ Calculate the number of li...
magic_instruct_75k
41,892
Write a Python function to process a list of objects and generate a new list of dictionaries based on certain conditions. Each object in the input list is represented as a dictionary with various attributes. The function should create a new dictionary for each object, containing specific attributes from the original ob...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union def process_objects(input_list: List[Dict[str, Union[str, Dict[str, int]]]]) -> List[Dict[str, Union[str, int]]]: """ Processes a list of objects and generates a new list of dictionaries bas...
magic_instruct_75k
41,919
Write a Python function to extract all values associated with a specific key from a nested JSON object. The JSON object is represented as a nested structure of dictionaries and lists. The function should traverse the nested structure recursively and collect all values associated with the given key. The code should sta...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def extract_values(json_obj: List[Dict], key: str) -> List[str]: """ Extracts all values associated with a specific key from a nested JSON object. Args: json_obj (List[Dict]): A nested...
magic_instruct_75k
41,925
Write a Python function to compute a new array `ans` where each element `ans[i]` is the product of all elements in the input array `nums` except `nums[i]`. The solution should have a time complexity of O(n) and should not use division. The code should start with: ```python from typing import List def productExceptSel...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def productExceptSelf(nums: List[int]) -> List[int]: """ Compute a new array where each element is the product of all elements in the input array except the element at the current index. Args: ...
magic_instruct_75k
41,929
Write a Python function to analyze the structure of a given HTML file and identify the number of unique CSS classes used within the `<style>` tags. The function should handle multiple `<style>` tags and nested CSS classes. The function should start with: ```python import re def countCSSClasses(html: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python import re def countCSSClasses(html: str) -> int: """ Counts the number of unique CSS classes used within the <style> tags in a given HTML content. Args: html (str): The HTML content to analyze. Returns: ...
magic_instruct_75k
41,942
Write a Python function to calculate the size of a button in a graphical user interface (GUI) based on its content and a maximum width constraint. The function should take into account the current size of the button and the maximum width, and then adjust the button's size to fit the content while respecting the maximum...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple def calculateButtonSizeToFit(frame: Tuple[int, int], maxWidth: int) -> Tuple[int, int]: """ Calculate the new size of a button in a GUI based on its content and a maximum width constraint. Args: ...
magic_instruct_75k
41,948
Write a Python function to determine whether a given text contains a GitHub URL. A GitHub URL is defined as a web address that starts with "https://github.com/". The function should return `True` if the text contains a GitHub URL and `False` otherwise. The function should be robust enough to handle various text inputs,...
Here is the Python code to solve the given problem in the markdown block: ```python import re def containsGitHubURL(text: str) -> bool: """ Determine whether the given text contains a GitHub URL. Args: text (str): The text to analyze for the presence of a GitHub URL. Returns: bool: Tr...
magic_instruct_75k
41,953
Write a Python function to update the usage statistics of a device in a device management system. Each device is represented by a dictionary with the following structure: ```python device = { 'name': 'Laptop', 'serial': 'ABC123', 'times': 0, 'use_time': 0 } ``` Where: - `name` (string): the name of th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union def update_device_stats(devices: List[Dict[str, Union[str, int]]], serial: str, time_used: int) -> List[Dict[str, Union[str, int]]]: """ Update the usage statistics of a device in the device...
magic_instruct_75k
41,978
Write a Python function to process a list of strings representing metadata for a software library. The function should extract relevant information from the metadata and return it in a structured format. Each string in the `metadata` list represents a line of metadata in the format "key: value". The keys and values are...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def process_metadata(metadata: List[str]) -> Dict[str, str]: """ Processes a list of strings representing metadata for a software library and returns a dictionary containing the extracted infor...
magic_instruct_75k
41,988
Write a Python function to extract a specific directory path from a given command-line argument string. The command-line argument string follows the format `--ref_embed_dir <directory_path>`, where `<directory_path>` represents the path to the directory. Your function should parse the input string and return the extrac...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Union def extract_directory_path(input_str: str) -> Union[str, None]: """ Extracts the directory path specified after the "--ref_embed_dir" flag from a command-line argument string. Args: input_s...
magic_instruct_75k
41,990
Write a Python function to simulate the behavior of a filter used in a particle tracking algorithm for high-energy physics experiments. The filter processes subclusters of strips in a silicon tracker and makes decisions based on the shape of the subclusters. The function should take a subcluster of strips (a list of st...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union def applyStripSubClusterShapeSeedFilter(subcluster: List[float], params: Dict[str, Union[int, float]]) -> bool: """ Simulates the behavior of a filter used in a particle tracking algorithm f...
magic_instruct_75k
41,992
Write a Python function to simulate a simple counter that increments a variable `i` by 1 and prints the value of another variable `Output`. The function should initialize the variables `i` and `Output` with specific values, increment `i`, and then print `Output`. The function should be designed to produce the output `1...
Here is the Python code to solve the given problem in the markdown block: ```python def increment_and_print(): """ Simulates a simple counter that increments a variable `i` by 1 and prints the value of another variable `Output`. This function initializes the variable `i` with the value 0 and the variable `...
magic_instruct_75k
42,010
Write a Python function to reverse a singly linked list using a recursive approach. The function should take the head of the linked list as input and return the head of the reversed linked list. The linked list is defined by the `ListNode` class, which has a value (`val`) and a reference to the next node (`next`). The...
Here is the Python code to solve the given problem in the markdown block: ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def reverseList(head: ListNode) -> ListNode: """ Reverses a singly linked list using a recursive approach. Args: ...
magic_instruct_75k
42,024
Write a Python function to generate a 2D grid map with randomly distributed terrain types based on given parameters. The function should handle invalid input by raising appropriate exceptions. The function should start with: ```python from typing import List import random def map_gen(width: int, height: int, density: ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def map_gen(width: int, height: int, density: float, seed: int, num_terrain_types: int) -> List[List[int]]: """ Generates a 2D grid map with randomly distributed terrain types based on the ...
magic_instruct_75k
42,066
Write a Python function to construct a POST request object based on the given data. The function should take in the request headers, parent URL, parent URL metadata, and POST data (if applicable), and return a dictionary representing the POST request object. The POST request object should have the following structure: ...
Here is the Python code to solve the given problem in the markdown block: ```python def construct_post_request(headers: dict, parent_url: str, parent_url_metadata: dict, post_data: dict = None) -> dict: """ Constructs a POST request object based on the given data. Args: headers (dict): A dictionary...
magic_instruct_75k
42,112
Write a Python function `generate_query_and_message` that constructs an SQL query and generates a message based on the order type and other parameters. The function should take the following parameters: - `places`: A list containing two elements representing the starting and ending places for the transportation. - `Ord...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_query_and_message(places, Order_Type, waybill_id, commodity, industry): """ Constructs an SQL query and generates a message based on the order type and other parameters. Args: places (list): A list cont...
magic_instruct_75k
42,114
Write a Python function to parse a JSON-like string and convert it into a nested dictionary structure. The JSON-like string can contain objects (delimited by curly braces `{}`), arrays (delimited by square brackets `[]`), and primitive values (strings, numbers, booleans, and null). The function should handle nested str...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Any, Dict, List def parse_json_like(json_str: str) -> Dict[str, Any]: """ Parses a JSON-like string and converts it into a nested dictionary structure. Args: json_str (str): The JSON-like string ...
magic_instruct_75k
42,119
Write a Python function to simulate a simple task scheduler that allows the execution of multiple tasks concurrently. Each task will be represented by a function, and the scheduler should execute these tasks in separate threads to ensure non-blocking execution. The scheduler should have the following functionalities: 1...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Callable, List import threading class TaskScheduler: def __init__(self): self.tasks: List[Callable[[], None]] = [] def add_task(self, task: Callable[[], None]) -> None: """ Add a new ...
magic_instruct_75k
42,148
Write a Python function to construct command-line commands for optimizing and verifying HSAIL (Heterogeneous System Architecture Intermediate Language) code. The function should take the input and output file paths as arguments and return a dictionary containing the constructed command strings. The command templates in...
Here is the Python code to solve the given problem in the markdown block: ```python def construct_commands(input_file: str, output_file: str) -> dict: """ Constructs command-line commands for optimizing and verifying HSAIL code. Args: input_file (str): The path to the input HSAIL file. outp...
magic_instruct_75k
42,168
Write a Python function to extract specific information from a list of software license texts. Each license text follows a specific format and contains information about the copyright year, licensee's name, license type, and expiry date. The function should return a list of dictionaries, where each dictionary contains ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict import re def extract_license_info(license_texts: List[str]) -> List[Dict[str, str]]: """ Extracts specific information from a list of software license texts. Args: license_texts (List...
magic_instruct_75k
42,171
Write a Python function to generate an orthogonal weight matrix of size `n x n` using NumPy. An orthogonal weight matrix is a square matrix where the rows are orthonormal vectors, commonly used in machine learning for weight initialization in neural networks. The function should follow these steps: 1. Generate a rando...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def generate_orthogonal_weight_matrix(n: int) -> np.ndarray: """ Generate an orthogonal weight matrix of size n x n using NumPy. Args: n (int): The size of the orthogonal weight matrix. Retu...
magic_instruct_75k
42,197
Write a Python function to update the status of a cooperation in a database. The function `update_cooperation_status` takes four parameters: `cooperation_id` (the ID of the cooperation to be updated), `new_status` (the new status to be set), `old_status` (the current status that must match for the update to occur), and...
Here is the Python code to solve the given problem in the markdown block: ```python def update_cooperation_status(cooperation_id: int, new_status: str, old_status: str, cur_db_util=None) -> int: """ Update the status of a cooperation in the database. Args: cooperation_id (int): The ID of the cooper...
magic_instruct_75k
42,220
Write a Python function to create a vector model for natural language processing. The function should take a language parameter `lang` and return a dictionary representing the vector model for the specified language. Each word in the language should be mapped to its corresponding vector, represented as a list of numeri...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def get_vector_model(lang: str) -> Dict[str, List[float]]: """ Returns a vector model for the specified language. The vector model is a dictionary where each key is a word in the language ...
magic_instruct_75k
42,244
Write a Python function to extract all the lines of a comment block from a given string and remove any leading or trailing whitespace from each line. The comment block starts with `/*` and ends with `*/`. The function should return a list of strings, where each string represents a line from the comment block without le...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def extract_comment_block(comment: str) -> List[str]: """ Extracts all the lines of a comment block from a given string and removes any leading or trailing whitespace from each line. Args: c...
magic_instruct_75k
42,245
Write a Python function to calculate the list of tick positions for a visualization, where the ticks are evenly spaced along a line. The function should take two parameters: `tick_distance` and `num_pos_ticks`. The positive tick positions are calculated using the formula `i * tick_distance` for `i` in the range from 1 ...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_tick_positions(tick_distance: int, num_pos_ticks: int) -> list: """ Calculate the list of tick positions for a visualization. The tick positions are evenly spaced along a line, with both positive and negative ...
magic_instruct_75k
42,280
Write a Python function to validate whether a given string is a valid GUID (Globally Unique Identifier) according to the specified format. A GUID is a 32-character hexadecimal string, typically formatted with hyphens in the pattern "8-4-4-4-12" (e.g., "550e8400-e29b-41d4-a716-446655440000"). The function should return ...
Here is the Python code to solve the given problem in the markdown block: ```python import re def is_valid_guid(input_string: str) -> bool: """ Validate whether the given string is a valid GUID (Globally Unique Identifier) according to the specified format. Args: input_string (str): The string to ...
magic_instruct_75k
42,282
Write a Python function to calculate the number of active peers for a given upstream server in a streaming service. The function should take in the name of the upstream server and return the count of active peers. The function should interact with a streaming service API, which provides a method `get_stream_status()` t...
Here is the Python code to solve the given problem in the markdown block: ```python def count_active_peers(upstream: str) -> int: """ Calculate the number of active peers for a given upstream server in a streaming service. Args: upstream (str): The name of the upstream server. Returns: ...
magic_instruct_75k
42,331
Write a Python function to transform a list of strings by replacing a placeholder string `"%NAME%"` with a user-provided name in each of the input strings. The function should return a new list containing the transformed strings. The code should start with: ```python from typing import List def replace_name_placeholde...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def replace_name_placeholder(input_list: List[str], name: str) -> List[str]: """ Transforms a list of strings by replacing the placeholder "%NAME%" with a given name. Args: input_list (List[...
magic_instruct_75k
42,366
Write a Python function `process_results` that processes the results of a series of operations and returns a modified data structure based on the given rules. The input to the function is a dictionary `s` containing two keys: "success" and "failed". The value corresponding to the "success" key is a list of elements, wh...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Union def process_results(s: dict, e: bool) -> Union[Tuple[List, bool], List[Tuple]]: """ Processes the results of a series of operations and returns a modified data structure. Args: ...
magic_instruct_75k
42,385
Write a Python function named `ConvertTo64BitInteger` that takes a `Variant` object as input and returns the converted 64-bit integer value. The function should handle the following data types: `double`, `float`, `int32`, and `int64`. For `double` and `float` data types, the function should perform a direct typecast to...
Here is the Python code to solve the given problem in the markdown block: ```python class Variant: def __init__(self, value, data_type): self.value = value self.data_type = data_type def GetValue(self): return self.value def ConvertTo64BitInteger(variant: Variant) -> int: """ C...
magic_instruct_75k
42,411
Write a Python function to calculate the sum of the digits of a given positive integer `n`. The function should handle integers in the range from 1 to \(10^9\). The code should start with: ```python def digit_sum(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def digit_sum(n: int) -> int: """ Calculate the sum of the digits of a given positive integer `n`. Args: n (int): The positive integer whose digits' sum is to be calculated. Returns: int: The sum of the...