Download data/Code/data.jsonl from SUSTech/WildTrace-RL: direct link, hf CLI and curl.
- Browser
- Download file 338 kB
-
https://huggingface.co/datasets/SUSTech/WildTrace-RL/resolve/main/data/Code/data.jsonl
- Command line
-
hf download hf://datasets/SUSTech/WildTrace-RL/data/Code/data.jsonl
-
curl -L -o data.jsonl https://huggingface.co/datasets/SUSTech/WildTrace-RL/resolve/main/data/Code/data.jsonl
338 kB
| {"messages": [{"role": "user", "content": "Given a non-negative integer n, write a function `sum_odd_numbers(n)` that calculates the sum of all odd numbers from 1 to n (inclusive). Do not use any built-in functions or libraries for this task."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of tuples, where each tuple contains information about a k-mer alignment in the format (strand, prob, level_mean, kmer). Your task is to implement a function `parse_alignment_data(data: List[Tuple[str, float, float, str]]) -> List[Dict[str, Union[str, float]]]` that parses this data and returns a list of dictionaries, where each dictionary has the keys 'strand', 'prob', 'level_mean', and 'kmer' corresponding to the values in the input tuples. The output should maintain the same order as the input. Each value in the output should be in the same type as described. For example, the 'strand' should be a string, 'prob' and 'level_mean' should be floats, and 'kmer' should be a string."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of records, where each record is a tuple containing various fields. Your task is to implement a function that takes in the list of records and returns a new list containing only the records that have a specific field (at index `field_index`) equal to a given value. The function should also sort the resulting records by the specified field index in ascending order. If no records match the specified value, return an empty list. Write a function `filter_and_sort_records(records: List[Tuple], field_index: int, value: Any) -> List[Tuple]` that fulfills this requirement."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a list of 3D coordinates representing the positions of different particles in space and a list of corresponding atomic masses of these particles, write a function `calculate_center_of_mass(positions: List[Tuple[float, float, float]], masses: List[float]) -> Tuple[float, float, float]` that calculates the center of mass of the system. The center of mass is defined as the weighted average of the positions of the particles, where each position is weighted by its corresponding mass. The function should return the center of mass as a tuple of three float values (x, y, z). You can assume that the lengths of the positions and masses lists are equal and that they contain at least one element."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function `notify_device_disappearance` that simulates the removal of a device and notifies observers about the event. The function takes three parameters: a list of observers (strings), a dictionary of devices (where keys are device names and values are device IDs), and a device name to be removed. The function should return a list of notifications sent to observers, indicating that the specified device has disappeared. Each observer should receive a notification in the format: 'Device {device_name} has disappeared.'. If the device does not exist in the device list, the observers should not receive any notifications. Implement the function such that it only handles the notification logic without the need for any additional classes."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of integers representing inter-arrival times of events. Your task is to implement a function that computes the actual arrival times of these events. The first event is assumed to arrive at time 0. The arrival time for each event is the cumulative sum of the inter-arrival times starting from the first event. Write a function `get_arrival_times(inter_times: List[int]) -> List[int]` that takes in a list of inter-arrival times and returns a list of arrival times. The list of inter-arrival times will have at least one element and all elements will be non-negative integers."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that verifies the validity of a list of venue categories. The function should take a list of dictionaries, where each dictionary represents a response from a venue API. Each dictionary contains a key 'categories' which holds a list of venue categories. Your task is to implement the `validate_categories` function that checks the validity of each API response. The function should iterate through the list of responses and perform the following checks for each response: 1. Verify that the response contains the key 'categories'. 2. Ensure that the number of categories in the response is greater than 1. The function should return a list of boolean values where each value corresponds to the validity of the respective API response. If the response is valid, the value should be True; otherwise, it should be False."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given an array of integers. Your task is to write a function to calculate the proportion of positive integers in the array. The function should return the proportion as a floating-point number rounded to 6 decimal places. Implement the function `calculate_positive_proportion(arr)` where `arr` is an array of integers. For example, given the array `arr = [1, -2, 3, 0, -4, 5]`, the proportion of positive integers is `3/6 = 0.500000`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function that converts a hexadecimal string into its corresponding ASCII text representation. The input will be a valid hexadecimal string. Write a function named `hex_to_ascii` that takes a single parameter, `hexadecimal`, and returns the decoded ASCII text."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with processing emoji update events from users. Each event contains a user ID and a timestamp indicating when the event occurred. Your goal is to create a function `process_emoji_event(event: Dict[str, Union[str, float]]) -> None` that processes the given event. You need to maintain the last update timestamp for each user. If the timestamp of the current event is greater than or equal to the user's last update timestamp, you should update the user's last update timestamp with the current event's timestamp. If the event's timestamp is less than the user's last update timestamp, the event should be ignored. The `User` class can be assumed to handle the `checkin()` method, which you do not need to implement. The `User` class retains the last update timestamp as a float. You can assume the input will always be in the correct format. The input event is a dictionary containing 'user' (user ID as a string) and 'event_ts' (timestamp as a float)."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function that takes a string as input and returns the reversed version of that string. The function should handle empty strings and special characters correctly. If the input is not a valid string, return an error message indicating that a valid string is required."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Write a function `is_mersenne_prime(n: int) -> bool` that determines if the input integer n is a Mersenne prime number. A Mersenne prime is a prime number that can be expressed in the form 2^p - 1 where p is also a prime number. Your function should return True if n is a Mersenne prime, and False otherwise."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a list of addresses represented as a list of dictionaries, where each dictionary contains 'City' and 'State' keys, implement a function that performs the following tasks: 1. Count the number of distinct states. 2. Identify and count the number of distinct cities within each of these states. 3. Calculate the average number of distinct cities per state. Your function should return a dictionary with the state as the key and the number of distinct cities as the value. Additionally, return the average as a separate output, rounded to 4 decimal points."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with managing a simple inventory system for a warehouse. Each item in the inventory has a unique identifier (item_id), a name, a quantity, and a price. Implement a function called `manage_inventory` that takes a list of inventory operations and returns the final state of the inventory. The operations can be of three types: 'add' to add a new item or update an existing item, 'update_quantity' to change the quantity of an existing item, and 'update_price' to change the price of an existing item. The function should return a dictionary where the keys are item_ids and the values are dictionaries containing the name, quantity, and price of each item. If an item does not exist during an update operation, that operation should be ignored. The input will be a list of tuples, where each tuple consists of the operation type and the relevant parameters. \n\nExample input for the function:\noperations = [\n ('add', '1', 'Widget', 10, 2.50),\n ('add', '2', 'Gadget', 5, 3.00),\n ('update_quantity', '1', 20),\n ('update_price', '2', 2.75),\n ('update_price', '3', 4.00),\n]\n\nExpected output for the example input:\n{\n '1': {'name': 'Widget', 'quantity': 20, 'price': 2.50},\n '2': {'name': 'Gadget', 'quantity': 5, 'price': 2.75}\n}"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a text vectorization function that converts a given document into a numerical representation. The vectorization process involves assigning numerical values to each word in the document based on their frequency within the document. Your goal is to implement a function `vectorize(doc: str) -> List[int]` that takes a string `doc` as input and returns a list of integers representing the vectorized form of the document. The vector should contain the frequency of each word in the order of their first appearance in the document. Assume that the input document contains only lowercase alphabetic characters and spaces."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Write a function `calculate_median(data: List[int]) -> float` that takes a list of integers as input and computes the median value of the list. The median should be calculated by first checking if the list is sorted. If the list is not sorted, it should be sorted before computing the median. The function should not use any built-in functions for sorting or calculating the median. If the list is empty, the function should return 0."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a utility that retrieves the corresponding audio format based on the file extension of a given filename. The utility should utilize a predefined mapping of file extensions to their corresponding audio formats. Implement a function `get_audio_format(filename: str) -> str` that takes a filename as input and returns the corresponding audio format after checking against the mapping. The mapping is as follows: {'flac': 'flac', 'alac': 'm4a', 'aac': 'm4a', 'mp3': 'mp3', 'ogg': 'ogg'}. If the file extension is not found in the mapping, the function should return 'Unknown format'. For example, if the input filename is 'track.flac', the output should be 'flac'. If the input filename is 'song.aac', the output should be 'm4a'. If the input filename is 'file.txt', the output should be 'Unknown format'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a worktime statistics system for a project management tool. The system should calculate and display the average worktime statistics for tasks and inputs for a specific user. The worktime statistics are represented as a list of `WorktimeStatisticsItem` objects, which contain the task or input ID and the corresponding worktime in minutes. Implement a function `calculate_average_worktime_statistics` that takes the following parameters: - `account_id`: A string representing the user account ID for which the worktime statistics are being calculated. - `by_tasks`: A list of `WorktimeStatisticsItem` objects representing the worktime statistics for tasks assigned to the user. - `by_inputs`: A list of `WorktimeStatisticsItem` objects representing the worktime statistics for inputs provided by the user. The function should calculate the average worktime statistics for tasks and inputs separately and return the results as a dictionary with the keys: `tasks_average`: The average worktime for tasks assigned to the user. `inputs_average`: The average worktime for inputs provided by the user. If there are no worktime statistics for tasks or inputs, the corresponding average should be 0. Function signature: `def calculate_average_worktime_statistics(account_id: str, by_tasks: List[WorktimeStatisticsItem], by_inputs: List[WorktimeStatisticsItem]) -> Dict[str, float]`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that retrieves the version number of a specified module. Your goal is to create a function `get_module_version` that takes a module name as input and returns its version number. The version number is represented by the attribute `version` within the module. If the `version` attribute is not found, the function should return \"unknown\". Additionally, if the module has a `key_bindings` attribute, it should be deleted after retrieving the version number. Your function should handle cases where the module does not exist or does not have the `version` attribute gracefully. \n\nFunction Signature: `def get_module_version(module_name: str) -> str:` \n\nFor example, given the input `get_module_version('example_module')`, if `example_module.version` exists, it should return that version number; if it does not exist or if `example_module` cannot be imported, it should return \"unknown\"."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `string_compression(s: str) -> str` that takes a string `s` as input and compresses it by removing consecutive duplicate characters. The function should return a new string where each group of consecutive identical characters is replaced by the character followed by the number of occurrences of that character. For example, given the input 'aabcccccaaa', the output should be 'a2b1c5a3'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `manipulate_strings(input_list)` that takes a list of strings as input and processes it according to the following rules: 1. Remove any empty strings from the input list. 2. Remove any leading or trailing whitespaces from each string. 3. Capitalize the first letter of each string. 4. Sort the modified list in ascending order. The function should return the modified list as output. For example, given the input list `[' apple', 'banana ', ' ', 'orange', 'grape']`, the function should return `['Apple', 'Grape', 'Orange']`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a floating-point number x, implement a function that calculates the Gamma function value using a fixed gamma of 2, following the formula: gamma(x) = (x * exp(-x)) / TAU_2, where TAU_2 is a constant equal to 2. The function should round the result to 14 decimal places. Your function should be defined as follows: def gamma_dis(x: float) -> float: \n\nInput: A single float x (0 <= x <= 1000). \nOutput: A float representing the calculated Gamma value rounded to 14 decimal places."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function called `clipboard_operations` that simulates a simple clipboard manager. The function takes a list of operations, where each operation is either a copy operation or a paste operation. The function should return a list of results for each paste operation. The operations are defined as follows: 'COPY text' means to copy the specified text to the clipboard, and 'PASTE' means to retrieve the current content of the clipboard. If a 'PASTE' operation is called before any 'COPY' operation, it should return an empty string. Implement the function `clipboard_operations(operations: List[str]) -> List[str]` where `operations` is a list of strings representing the clipboard operations."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Design a function `update_high_scores(scores: List[int], new_score: int) -> List[int]` that updates a list of the 5 highest unique scores from a game when a new score is added. The function should take in a list of existing scores and a new score, and it should return a sorted list of the top 5 unique scores in descending order. If the new score is already present, it should not be added again. If there are less than 5 unique scores, the function should return all unique scores sorted in descending order."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `running_total(lst)` that takes a list of integers `lst` and returns a new list containing the running total of the numbers in `lst`. The running total at each index `i` in the output list should be the sum of all elements from index `0` to `i` in the input list."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a string representing a dotted key, you need to replace any segments of the string that are integers with asterisks ('*'). Each segment is separated by a dot ('.'). Write a function `starify(name: str) -> str` that takes this input string and returns a new string where all integer segments have been replaced with asterisks. For example, if the input is 'user.1.profile', the output should be 'user.*.profile'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that filters out specific lines from a given list of strings based on certain criteria. The function should take in a list of strings and a set of ignored namespaces, and return a new list of strings that meet the filtering conditions. The filtering conditions are as follows: 1. Exclude any line that starts with a string from the set of ignored namespaces followed by a colon (ignoring case). 2. Exclude any line that starts with the phrase 'list of' (ignoring case). Implement the function `filter_lines` which takes in the following parameters: - `lines`: A list of strings representing the input lines to be filtered. - `ignored_namespaces`: A set of strings representing the namespaces to be ignored. The function should return a new list of strings after applying the filtering conditions. Function signature: `def filter_lines(lines: List[str], ignored_namespaces: Set[str]) -> List[str]`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a Python function that filters out hidden files and directories from a given dictionary. Hidden files and directories are those whose names start with a dot ('.'). The function should take a dictionary as input and return a new dictionary containing only the non-hidden items. The function signature is: `def filter_hidden(x: dict) -> dict:`. For example, given the input dictionary: `{'file1.txt': 'contents1', '.hidden_file': 'contents2', 'folder': {'file2.txt': 'contents3', '.hidden_folder': {'file3.txt': 'contents4'}}}`, the function should return `{'file1.txt': 'contents1', 'folder': {'file2.txt': 'contents3'}}`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given two lists of integers, `verts_before` and `verts_after`, which represent the indices of vertices in a mesh before and after a transformation, respectively. Your task is to implement a function that takes these two lists and returns a new list where each element at index `i` in the `verts_after` list corresponds to the vertex label from the `verts_before` list based on the mapping defined by their indices. If an index in `verts_after` does not exist in `verts_before`, it should be represented as -1. Implement the function `map_vertex_labels(verts_before: List[int], verts_after: List[int]) -> List[int]:` that outputs the new list of vertex labels."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that determines if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Implement a function `is_palindrome(s: str) -> bool` that takes a string `s` as input and returns `True` if `s` is a palindrome, and `False` otherwise. Your function should handle empty strings and should ignore all non-alphanumeric characters. For example, 'A man, a plan, a canal: Panama' should return True."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given an array of integers representing nuclear charges, write a function `get_valence(Z: List[int]) -> List[float]` that converts each nuclear charge to its corresponding valence using a fixed mapping. The valence for each nuclear charge is defined as follows: 1 maps to 0.1, 2 maps to 0.2, 3 maps to 0.3, and so on up to 10 which maps to 1.0. For any nuclear charge greater than 10, return 1.0. The function should return a list of floats representing the valence of each atom based on the input array. Note that the valence values need to be in angstroms (conversion factor is already applied). If the input list is empty, return an empty list."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that simulates the execution of a command-line tool. The function should take a list of strings as input, where the first string represents the name of the tool and the subsequent strings are arguments to be passed to the tool. The function should return a simulated output of the tool based on the tool name provided. If the tool is 'myplugin', the function should return 'myplugin executed with arguments: arg1, arg2'. For any other tool name, the function should return 'unknown tool'. Implement the function `run_tool(tool_arguments: List[str]) -> str:` where `tool_arguments` is a list of strings as described. "}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Write a function `check_anagram(text1: str, text2: str) -> bool` that determines whether two given strings are anagrams of each other. Two strings are considered anagrams if they can be rearranged to form each other by using the same characters with the same frequency. The function should return `True` if they are anagrams, and `False` otherwise."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Write a function `convertPascalToBar(pascal: float) -> float` that converts a given pressure from Pascals to Bar. The conversion formula is as follows: 1 Bar is equal to 100,000 Pascals. The function should return the pressure in Bar as a float."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a hexadecimal color string in the format '#RRGGBB', where RR, GG, and BB are two-digit hexadecimal numbers representing the red, green, and blue color components, respectively, implement a function `parse_color(hex_color)` that converts the hexadecimal color string to a dictionary containing the normalized RGB values. Each value in the dictionary should be a float between 0 and 1, representing the intensity of the respective color component. The keys in the dictionary should be 'r', 'g', and 'b'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that simulates a simple control system for a quantity. The function should accept an initial value, a list of operations, and return the final value of the quantity after performing all operations. The operations can include setting a new value, incrementing the quantity by a specified amount, and decrementing it by a specified amount. All operations must adhere to the following constraints: the initial value, the amount to increment, and the amount to decrement must be non-negative integers.\n\nImplement the function `simulate_control_system(initial_value: int, operations: List[Tuple[str, int]]) -> int` where:\n- `initial_value` is the starting value of the quantity (a non-negative integer).\n- `operations` is a list of tuples, where each tuple consists of an operation type (a string) and an amount (a non-negative integer). The operation types can be 'set', 'increment', or 'decrement'.\n\nThe function should return the final value of the quantity after applying all operations in the order they are given."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a list of strings representing tags, implement a function `unique_tags(tags: List[str]) -> List[str]` that returns a list of unique tags sorted in alphabetical order. Each tag is a non-empty string consisting of alphanumeric characters and underscores. The input list may contain duplicates and empty strings, which should be ignored. The output should not contain any duplicates and must be sorted in ascending order."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `valid_ISBN10(isbn: str) -> bool` that checks if a given string is a valid ISBN-10 number according to the standard ISBN-10 validation rules. An ISBN-10 is considered valid if it is either a 10-digit number or a 9-digit number followed by an 'X'. The checksum is calculated by multiplying each digit by its position (1 to 10) and taking the sum modulo 11. If the checksum equals zero, the ISBN is valid. Your function should return `True` if the ISBN is valid and `False` otherwise."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a color represented as a tuple or list containing three values, determine if the color is in a valid RGB format. The color can be either in the range of 0 to 255 for integers or in the range of 0.0 to 1.0 for floats. Your task is to implement the function `is_color_rgb(color)` that takes a single parameter, `color`, and returns `True` if the color is valid in RGB format and `False` otherwise. The color is valid if it meets one of the following criteria: 1. All three values are integers between 0 and 255 (inclusive), or 2. All three values are floats between 0.0 and 1.0 (inclusive)."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with managing a collection of image files and their associated tags. Write a function `tag_images(input_files: List[str], database: Optional[Dict[str, List[str]]], extra_tags: Optional[List[str]] = None) -> Tuple[Dict[str, List[str]], List[str]]`. The function should take the following parameters: \n\n- `input_files`: A list of image file names (strings) that need to be tagged. \n- `database`: A dictionary where each key is a file name (string) and the value is a list of tags (strings) associated with that file. If the file is not present in the database, it should not be included in the output. \n- `extra_tags`: An optional list of additional tags (strings) to be added to each image file. If provided, these tags should be appended to the existing tags in the database for each file. \n\nThe function should return a tuple containing two elements: \n1. A dictionary of updated tags for each image file, formatted the same way as the `database` parameter. \n2. A list of file names (strings) that were successfully updated with tags. \n\nIf an image file in `input_files` does not exist in the `database`, it should not be included in the output dictionary or the list of updated files."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function that performs a linear search to find the index of a specific target element in a given list of integers. The function should return the index of the target element if it exists in the list; otherwise, return -1. The function signature should be: def linear_search(array: List[int], target: int) -> int."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a vector represented as a list of numbers, implement a Python function `magnitude(v)` that calculates the magnitude of the vector. The magnitude of a vector is defined as the square root of the sum of the squares of its elements. For example, for a vector `v = [x1, x2, ..., xn]`, the magnitude is computed as `√(x1² + x2² + ... + xn²)`. Your function should handle vectors of any length, including the empty vector, which should return 0.0. You may assume that the input will always be a list of numbers (integers or floats)."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a Python function that simulates the process of creating new partitions for a Kafka topic. Your function should take in the topic name, the number of partitions to be added, and a list of partition assignments that specify how the new partitions are distributed across brokers. The function should return a string indicating the success or failure of the operation. If the partition creation is successful, return 'Partitions created successfully for topic: <topic>'. If the creation fails, return 'Failed to create partitions for topic: <topic>'. The function signature should be: `def simulate_partition_creation(topic: str, num_partitions: int, partition_assignments: List[List[int]]) -> str:`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that generates a secure secret key. The secret key should be a random string of 50 characters chosen from the predefined set of characters: 'abcdefghijklmnopqrstuvxyz01234567890_-!*'. Your function should return the generated secret key as a string. Implement the function `generate_secret_key()` which takes no parameters and outputs the generated key."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a grid of size m x n (1-indexed) where you can only move either down or right from a given cell. Write a function `count_paths(m: int, n: int) -> int` that returns the total number of distinct paths from the top-left corner (1, 1) to the bottom-right corner (m, n)."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a configuration dictionary that represents repositories, write a function `get_repo_paths` that takes a dictionary as input and returns a list of repository paths. The input dictionary has the following structure: it contains a key 'repos' which maps to another dictionary. Each key in this inner dictionary represents a repository name, and the values can be any type (they are not relevant for this task). Your function should return a list of keys from the 'repos' dictionary. If the input dictionary does not contain the key 'repos', return an empty list. \n\nFunction signature: `def get_repo_paths(config: dict) -> list:`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function that takes an array of integers as input and returns the maximum integer value found in that array. The function should handle both positive and negative integers, as well as arrays with a single element. If the array is empty, the function should return None."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement the bubble sort algorithm to sort a given list of integers in ascending order. You need to write a function that takes a list of integers as input and returns the sorted list."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `contains_decimal(sequence)` that takes an iterable object `sequence` as input and returns `True` if the sequence contains at least one decimal (floating-point) number. Otherwise, return `False`. The input can contain elements of various types, including integers, strings, and floats."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `generate_json_objects(heights: List[float], widths: List[float], lengths: List[float]) -> List[Dict[str, float]]` that takes three lists of floats: `heights`, `widths`, and `lengths`. Each list contains non-zero positive numbers representing the dimensions of objects. The function should return a list of dictionaries, where each dictionary contains the keys 'Height', 'Width', and 'Length' with their respective values from the input lists. If the lengths of the input lists are not equal or if any dimension is not a non-zero positive number, the function should raise a `ValueError`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `match_domains(email: str) -> bool` that takes an email address as input and returns True if the email address is valid and ends with one of the following domains: .edu, .gov, or any international domain that does not end with .com. The function should ensure that it does not match email addresses with subdomains or parent domains attached to the specified TLDs. For example, 'test@sub.example.edu' or 'test@parent.example.gov' should return False."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `heaviside_function(x)`, that takes a list of numbers `x` and returns a new list containing the evaluations of the Heaviside function for each element in `x`. The Heaviside function is defined as follows: \n- If the input is less than 0, the output should be 0. \n- If the input is greater than 0, the output should be 1. \n- If the input is equal to 0, the output should be 0.5. \nYou need to handle a list of integers and/or floats. Your function should have the following signature: `def heaviside_function(x: List[float]) -> List[float]:`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function to parse a configuration for a machine learning model. The configuration is specified as a dictionary where the keys represent various settings for the model, and the values represent the respective values for those settings. Your goal is to extract specific information from this configuration dictionary. Write a function `parse_model_configuration` that takes a dictionary `config_dict` as input and returns a dictionary containing the following information: the maximum gradient norm specified by the 'max_gradient_norm' key, the batch size specified by the 'batch_size' key, the size of each model layer specified by the 'size' key, the word embedding size specified by the 'word_embedding_size' key, the number of layers in the model specified by the 'num_layers' key, the maximum input vocabulary size specified by the 'in_vocab_size' key, the maximum output vocabulary size specified by the 'out_vocab_size' key, the data directory specified by the 'data_dir' key, the training directory specified by the 'train_dir' key, and the maximum training data size specified by the 'max_train_data_size' key. If any key is missing in the input dictionary, the corresponding value in the output dictionary should be None."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Write a function called `hello_world` that returns the string 'Hello, World!'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a polynomial function f(x) = 3x^4, implement a function `derivative(n)` that calculates the n-th derivative of the function without using any libraries or packages. The function should return the derivative as a string in the format 'ax^b', where 'a' is the coefficient and 'b' is the exponent. If the derivative is zero, return '0'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Write a function `find_multiples(num: int, start: int, end: int) -> List[int]` that returns a list of all multiples of a specific integer `num` that lie within the inclusive range from `start` to `end`. The function should return an empty list if there are no multiples in that range."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function `create_trade(**kwargs)` that accepts keyword arguments and initializes a dictionary representing a trade. The dictionary should include the keys 'book', 'created_at', and 'amount'. The 'created_at' value should be converted to ISO 8601 format (yyyy-mm-ddThh:mm:ss) if it is provided as a datetime object. Your function should return this dictionary. If a key is not provided in kwargs, its value should be set to None. Your task is to implement the `create_trade` function to meet the specified requirements."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "In a basketball game, Jan scored 3 points more than Salah. Meanwhile, Cindy outperformed both and succeeded in scoring 22 points, which is actually double the points Jan managed to score. Write a function `find_salah_score()` that returns the score of Salah based on this information."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a string of text, write a function that analyzes the text to determine the frequency of each unique word. A word is defined as a sequence of non-whitespace characters. The function should ignore the case of the letters and remove any punctuation marks from the text. The output should be a dictionary containing each unique word in lowercase as keys and their corresponding frequencies as values. The dictionary should not be sorted. Implement the function `word_frequency(text: str) -> dict`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that checks if a given word can be constructed from a collection of smaller words (sub-words). The function should take two parameters: a list of words (sub-words) and a target word. Your goal is to determine if the target word can be formed by concatenating the words in the list. Each word in the list can be used multiple times. Implement the function `can_construct_from_subwords(subwords: List[str], target: str) -> bool`. You can assume that all inputs consist of lowercase letters (a-z)."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a recursive function `calc_factorial(x)` that computes the factorial of a non-negative integer `x`. The function should handle the following conditions: if `x` is negative, it should return an error message 'Error: Cannot compute factorial for negative numbers'. If `x` is zero, it should return 1. If `x` is greater than 12, it should return 'Error: Computation of factorial for this number may cause integer overflow'. Additionally, if the input is not an integer, the function should return 'Error: Please input an integer'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `fib(n)` that computes the nth Fibonacci number using an efficient algorithm. The Fibonacci sequence is defined as follows: F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2) for n >= 2. Your implementation should handle large values of n (up to 10^6) efficiently. The function should return the nth Fibonacci number."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function `add_variant_to_existing_lines(lines: List[int], variant_quantity: int) -> int` that simulates adding a variant to existing lines of stock. Each stock line has a certain available quantity, represented as a list of integers. Your function should take in two parameters: a list of integers `lines`, where each integer represents the available quantity of a stock line, and an integer `variant_quantity`, which represents the total quantity of the variant to add. The function should add the variant to the stock lines by increasing the quantity of each line by the available amount, starting from the line with the highest quantity, until the total desired variant quantity has been added or there are no more lines left to add from. The function should return the quantity of the variant that could not be fulfilled due to insufficient available stock lines. If the total quantity can be fulfilled, return 0. Note: The function should not modify the original lines list."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given two strings, `nodetypecategory` and `acceptedtypecategory`. Your task is to implement a function `mapTypeCategoriesToSubnetName(nodetypecategory: str, acceptedtypecategory: str) -> Optional[str]` that returns a name for a subnet that accepts `nodetypecategory` as a child type and can be created in a container whose child type is `acceptedtypecategory`. If `nodetypecategory` and `acceptedtypecategory` are the same, return None, as there is no need for a subnet to accommodate it. If the mapping between these two categories has not been defined, also return None. For the purpose of this problem, you can assume the following mappings are predefined: {'A': 'Subnet1', 'B': 'Subnet2', 'C': 'Subnet3'}. If the mapping does not exist, return None."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given two lists of strings, `text_match` and `text_diff`. Your task is to implement a function `process_text_embedding` that processes these lists into a tensor-like structure. For the purpose of this problem, assume that the function will convert the strings in `text_match` into a list of their lengths and the strings in `text_diff` into a list of their lengths as well. The function should return two lists of integers: one for the lengths of the strings in `text_match` and another for the lengths of the strings in `text_diff`. Each input list will contain at least one string and at most 100 strings. The function signature should be: `def process_text_embedding(text_match: List[str], text_diff: List[str]) -> Tuple[List[int], List[int]]:`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of points, where each point is represented as a tuple (timestamp, x, y). Your task is to identify and count the number of discontinuous points based on the following criteria: A point is considered discontinuous if the timestamp difference between it and the previous point exceeds a specified time threshold, or if the distance between the two points exceeds a specified distance threshold. Implement a function that takes in the following parameters: a list of points, a time threshold, and a distance threshold. The function should return the count of discontinuous points. The distance between two points (x1, y1) and (x2, y2) can be calculated using the Euclidean distance formula: sqrt((x2 - x1)^2 + (y2 - y1)^2)."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a string representing a non-negative integer, write a function `incrementString` that increments the integer by 1 and returns the result as a string. The function should not convert the string to an integer for the increment operation. The input string will have a length between 1 and 1000 characters, and it represents a valid non-negative integer. For example, given `numString = '123'`, the function should return `'124'`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You need to implement a function that takes a string input representing an integer and returns the equivalent integer value. The input string can contain leading or trailing whitespace, and may optionally start with a '+' or '-' sign. If the input string is valid, return the integer; if the input is invalid (e.g., it contains non-numeric characters), return None. The input string will not exceed 100 characters in length. Write a function `convert_to_int(s: str) -> Optional[int]` where `s` is the input string."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function that converts all lowercase letters in a given string to uppercase. Additionally, replace specific symbols and numeric characters in the string with their corresponding word representations in a non-native language. The mappings are as follows: '&' to 'et', '@' to 'arobase', '1' to 'un', and the newline escape sequence '\\n' to 'newline'. The function should handle any other characters without modification. Write a function named `translate_string` that takes a single string argument and returns the transformed string."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `age_calc` that takes a single parameter `age`. The function should check if the provided `age` is of type `int`. If it is not an integer, the function should raise a `TypeError` with the message 'The age should be an integer'. If it is an integer, the function should return the age incremented by 5."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function named `count_subsequences` that determines the number of non-intersecting subsequences of a given substring within a primary string. The function should take two strings as input: the primary string and the substring, and return an integer representing the count of non-overlapping occurrences. For example, if the primary string is 'abcabc' and the substring is 'abc', the function should return 1 because there is only one way to choose the substring without overlaps. If the substring is not found, the function should return 0. If the substring is empty, return 1, as there is one way to form an empty subsequence. The function signature is as follows: `def count_subsequences(字符串: str, 子字符串: str) -> int:`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a 2D array of integers representing labels in an image, where 0 indicates the background. Your task is to merge labels that are below a specified minimum size with their connected neighbors. The connectivity can be either 4 or 8. If a label has no connected neighbors or is below the minimum size, it should be assigned to the background (0). Write a function `merge_labels_below_minsize(labels: List[List[int]], min_size: int, connectivity: int = 8) -> List[List[int]]` that implements this functionality. The function should return the updated 2D label array after merging the labels. Note that the input 2D array will not contain negative integers and will only include non-negative integers as labels."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a list of geographical locations represented by their latitude and longitude, write a function `find_next_closest_location(locations: List[Tuple[float, float]]) -> List[Tuple[float, float]]` that returns a list of the next closest location for each location in the input list. The distance between locations should be calculated using the Haversine formula. Each location is represented as a tuple of (latitude, longitude). You should return the next closest location for each input location. If there is no other location available, return None for that location."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `hex_to_character(hex_str: str) -> str` that converts a given hexadecimal string `hex_str` into its equivalent ASCII or Unicode character. The function should validate the input to ensure it is a valid hexadecimal number and falls within the valid range for Unicode (0 to 1114111). If the input is invalid or cannot be converted, the function should return `None`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with analyzing the imports from various modules in a game development framework. Your goal is to create a function named `analyze_imports` that takes no parameters and returns a dictionary containing the counts of classes and functions imported from specified modules. The function should consider six modules: 'group', 'props', 'balls', 'object', 'buttons', and 'entities'. Each module's count of classes and functions is initially set to zero. Your function should return a dictionary where each key is a module name and the corresponding value is the count of classes and functions imported from that module. For simplicity, assume that each module contains no imported classes or functions. For example, the output for the modules should look like this: { 'group': 0, 'props': 0, 'balls': 0, 'object': 0, 'buttons': 0, 'entities': 0 }."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a positive integer `num` consisting only of digits 6 and 9, implement a function that returns the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6) along with the index of the digit that was changed. If no change is needed, return -1 as the index. The function signature should be: `def maximum69Number(num: int) -> Tuple[int, int]:`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a list of strings in dot notation, convert it into a nested dictionary structure. Each string represents a path where the last part of the string is a leaf node (set to True) and all preceding parts are nested dictionaries. Write a function `dot_to_dict(values: List[str]) -> Dict[str, Union[bool, Dict]]` that takes a list of strings and returns the corresponding nested dictionary. For example, the input `['token.pos', 'token._.xyz']` should return `{'token': {'pos': True, '_': {'xyz': True}}}`. The input list may contain duplicate paths, but the output should only include unique paths."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function that calculates the number of uppercase vowel characters located at prime number positions within a given string. The positions are considered to be 1-based indexing, meaning the first character in the string is at position 1. An uppercase vowel is defined as one of the characters 'A', 'E', 'I', 'O', or 'U'. Your function should return the total count of such characters. Write a function `count_upper_prime(s)` that takes a string `s` as input and returns an integer representing the count of uppercase vowels at prime positions."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `prime_number(n)` that checks if a given integer `n` is a prime number. If `n` is a prime number, the function should return `True` and `None`. If `n` is not a prime number, the function should return `False` and the smallest divisor of `n` greater than 1. The function should handle edge cases efficiently and ensure an optimized solution."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `generate_password(length: int, upper_case: bool, lower_case: bool, numbers: bool, special_chars: bool) -> str` that generates a random password based on the specified parameters. The password should have a length of `length` characters and include uppercase letters, lowercase letters, digits, and special characters according to the boolean flags provided. If none of the flags are set to True, the function should raise a ValueError. Use secure random generation to ensure the password is suitable for security-sensitive applications."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of log entries represented by a list of dictionaries, where each dictionary contains the following keys: 'timestamp' (an integer representing the time of the log entry), 'level' (a string representing the severity level of the log entry, which can be 'INFO', 'WARNING', or 'ERROR'), and 'message' (a string representing the content of the log entry). Your task is to implement a function `filter_logs` that takes in this list of log entries and a severity level as input. The function should return a list of log messages that match the given severity level. If there are no matching log messages, return an empty list. The function signature is as follows: `def filter_logs(logs: List[Dict[str, Union[int, str]]], severity_level: str) -> List[str]:`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a bubble sort algorithm that sorts an array containing numeric strings and numbers in ascending order based on their numeric representation. The algorithm should include an optimization that stops the sorting process if no elements were swapped during a pass. Additionally, each pass should cover one less element than the previous pass since the last elements become sorted after each iteration. For instance, sorting the array `[9, '5', 7, '11', 2]` should yield `[2, '5', 7, 9, '11']`. Please implement a single function called `bubble_sort(lst)` that takes a list `lst` as an argument and returns the sorted list."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of words and a predefined set of valid words (the dictionary). Your task is to implement a function that returns a set of words from the input list that are present in the valid words dictionary. Implement the function `known(words: List[str]) -> Set[str]` where `words` is a list of strings. The function should return a set containing only the words that are recognized as valid. Note that the comparison is case-sensitive. You can assume that the list contains only lowercase letters and that the valid words set is defined as follows: `VALID_WORDS = {'apple', 'banana', 'orange', 'grape', 'pear'}`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function to verify whether a given token is present in a specified blocklist. The blocklist is represented as a set of strings, each string being a token. Your function should return a boolean value: `True` if the token is in the blocklist, and `False` if it is not. Implement the function `check_token_in_blocklist(token: str, blocklist: set) -> bool` which takes a token and a blocklist as input parameters."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given two lists of numerical values, one representing the actual stock prices over a series of trading days and the other representing the predicted stock prices for those same days. Write a function `compare_prices(actual: List[float], prediction: List[float]) -> List[str]` that compares the actual prices with the predicted prices and returns a list of strings indicating whether the prediction was 'Correct' (if the predicted price is equal to the actual price), 'Underestimated' (if the predicted price is less than the actual price), or 'Overestimated' (if the predicted price is greater than the actual price) for each corresponding trading day. If the lengths of the two lists are not equal, return a list containing the string 'Error: Input lists must be of the same length'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that simulates the process of updating a Virtual Machine Interface (VMI) with specific details. The function should take in a VMI object and a list of Virtual Network (VN) objects. Each VMI object contains the following attributes: 'portgroup_key' (a string), 'vm_model' (a string), and 'vn_model' (a string). The function should update the VMI's attributes based on the provided VN objects and return a list of updated VMI objects. The function should ensure that the portgroup_key is set to 'dvportgroup-1' and the vn_model of the VMI matches the name of the first VN object in the list. The function signature should be: `def update_vmi(vmi: VMI, vn_list: List[VN]) -> List[VMI]:`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a password validation function. The function `validate_password` takes a password as input and checks if it adheres to the following rules: 1. It must be at least 8 characters long. 2. It must contain at least one uppercase letter, one lowercase letter, one digit, and one special character from the set `!@#$%^&*`. The function should return `True` if the password is valid and `False` otherwise. Implement the function `validate_password(password: str) -> bool`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a Python function that takes a dictionary representing HTTP headers as input and returns a new dictionary with the headers sorted in alphabetical order by their keys. If two headers have the same key, they should appear in the same order as in the original dictionary. The function should have the following signature: `def sort_headers(headers: dict) -> dict:`. For example, given the input dictionary: `{ 'Content-Type': 'text/html', 'Authorization': 'Bearer token', 'Accept': 'application/json' }`, the function should return `{ 'Accept': 'application/json', 'Authorization': 'Bearer token', 'Content-Type': 'text/html' }` as the headers are sorted alphabetically by their keys."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a dictionary containing four keys: 'Yte', 'Ytr', 'Xtr', and 'Xte'. Each key maps to a list of integers. Your task is to implement a function that returns a new dictionary that contains the same keys, but the values are transformed as follows: 'Yte' should contain the sum of all integers in the list, 'Ytr' should contain the maximum integer in the list, 'Xtr' should contain a list of the integers multiplied by 2, and 'Xte' should contain the length of the list. Implement the function `transform_inputs(data: Dict[str, List[int]]) -> Dict[str, Union[int, List[int]]]` where `data` is the input dictionary. The output should be a dictionary with the specified transformations."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a 2D list of non-negative integers representing pairwise distances between points, write a function that computes the radius of a hypersphere for each point based on the median of the distances to all other points. Each point's radius is defined as the median of the distances from that point to all other points. The input list will always contain at least one point. If the number of distances is odd, return the middle value; if even, return the lower middle value. Implement the function `compute_hypersphere_radii(distances: List[List[int]]) -> List[int]` where `distances[i][j]` represents the distance from point `i` to point `j`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a camera configuration function for a robotics project. The function should create a camera object based on the provided parameters and return it. The parameters for the function are as follows: \n- `pipeline`: A string representing the pipeline for camera processing. \n- `index`: An integer representing the camera index. \n- `leftOrRight`: A string indicating whether the camera is for the left or right side. \n- `gray_resolution`: A string specifying the resolution for grayscale images. \n- `controlInputGray`: A boolean indicating whether grayscale control input is enabled. \n\nThe function should return a dictionary representing the camera object with the fields: 'index', 'position', 'resolution', and 'control_input'. The 'position' field should contain the value of 'leftOrRight', the 'resolution' field should contain the value of 'gray_resolution', and the 'control_input' field should reflect the value of 'controlInputGray'. You need to implement the function `createAndConfigureCamera(pipeline, index, leftOrRight, gray_resolution, controlInputGray)`. "}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a positive integer d, return the count of reduced proper fractions for d such that n < d and the greatest common divisor (gcd) of n and d is 1. A reduced proper fraction is defined as a fraction where the numerator is less than the denominator and both are positive integers that share no common factors other than 1. Implement the function count_reduced_proper_fractions(d) that takes an integer d (1 ≤ d ≤ 1,000,000) and returns the count of such fractions."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of dates as strings in the format 'YYYY-MM-DD' and a level as an integer. Your task is to implement a function `process_dates(dates: List[str], level: int) -> List[str]` that processes the given dates based on the provided level. The function should return a new list containing the dates that are formatted as 'Level X: YYYY-MM-DD', where X is the given level. If the level is negative, the function should return an empty list. If the list of dates is empty, the function should also return an empty list."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Write a function `generate_sequence()` that produces a six-character string containing at least one lowercase alphabetical character and one numeral digit. The other four characters can be any combination of lowercase letters and digits. The final string should have its characters arranged in a random order to ensure unpredictability."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function to delete a specific item from a list of IoT gateway IDs. The function `delete_gateway` should take a list of gateway IDs and a specific gateway ID to delete. If the gateway ID is not found in the list, the function should simply return the original list without any modification. Your task is to implement the `delete_gateway` function to handle the deletion of gateway IDs from the list."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of `restrictions`, which are integers representing unique identifiers for view restrictions on a page. You are also given a list of `passed_restrictions`, which are integers that represent the restrictions that the user has already passed. Your task is to write a function `check_access(restrictions: List[int], passed_restrictions: List[int]) -> bool` that returns `True` if the user has access to the page (i.e., they have passed all the restrictions), and `False` otherwise. A user does not have access if any restriction in the `restrictions` list is not present in the `passed_restrictions` list."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a custom logging handler in Python that suppresses log messages. Your goal is to create a function named `custom_null_handler` that takes a list of log messages as input and returns an empty list, effectively suppressing all log messages. The function should not perform any other actions or modifications to the input. Your implementation should be compatible with Python 3.5.0. "}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a program to determine if a loan can be approved based on the monthly installment amount and the available monthly budget. Write a Python function `loan_approval` that takes two parameters: `installment` (float): the monthly installment amount for the loan, and `monthly_budget` (float): the available monthly budget for loan repayment. The function should return a string: 'Loan approved' if the monthly installment is less than or equal to the available monthly budget, and 'Loan rejected' if the monthly installment exceeds the available monthly budget."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of integers and a corresponding list of frequencies for each integer. Your task is to implement a function that calculates the weighted average of the integers, handling any potential errors. The function should raise a ValueError if the lengths of the two lists are not equal, if either list is empty, or if the sum of the frequencies is zero. Implement a function called 'weighted_average' that takes two parameters: a list of integers 'numbers' and a list of integers 'frequency'. Return the weighted average as a float."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that determines whether a given number is a prime number. A prime number is defined as a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. Your function should take an integer as input and return True if the number is prime, and False otherwise. Implement the function `is_prime(num: int) -> bool`. For example, if the input is 5, the output should be True, and if the input is 4, the output should be False."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a simple caching mechanism for managing string data associated with unique keys. Your goal is to implement a function called `simple_cache` that takes two parameters: a list of keys and a list of values. The function should create a cache that stores the key-value pairs. If a key is accessed (retrieved), it should return the corresponding value. If a key is not found in the cache, it should return 'Key not found'. The function should also provide a way to update the value for an existing key. If the same key is provided with a new value, the cache should update it. If a key is not passed during the update, the function should ignore that request. The function should return a dictionary representing the cache state after processing all operations. Your implementation should consider the following: \n1. If a key is accessed that does not exist in the cache, return 'Key not found'. \n2. If an update is attempted with a new value, update the cache accordingly. \n3. The input lists will contain unique keys and corresponding values. \n\nImplement the function `simple_cache(keys: List[str], values: List[str]) -> Dict[str, str]` to meet the requirements described above."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function that converts a binary string into its decimal equivalent. The input will be a binary string consisting of only '0's and '1's. The function should return an integer representing the decimal value of the binary string."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that compares two sets of numerical data and calculates the average value for each set. The function should take in two lists of numerical values and return a tuple containing the average of the first set and the average of the second set. If a set is empty, its average should be considered as 0. Write a function `calculate_averages(values1, values2)` that takes in the following parameters: `values1`: A list of numerical values representing the first set of data. `values2`: A list of numerical values representing the second set of data. The function should return a tuple (average1, average2), where average1 is the average of values1 and average2 is the average of values2."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You need to create a function `generate_webrtc_link(ip_addr: str, port: int) -> str` that generates a WebRTC connection URL based on the given IP address and port number. The format of the generated URL should be 'https://<ip_addr>:<port>/webrtc'. Implement this function such that it takes in a string `ip_addr` representing the IP address of the WebRTC AVD and an integer `port` representing the port number. The function should return the generated URL as a string. If the provided IP address or port is invalid (e.g., an empty string or a port outside the range 1-65535), return 'Invalid IP or Port'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of dictionaries, where each dictionary represents a node with various attributes. Each node contains a 'name' attribute which is a string. Your task is to write a function that takes this list of dictionaries and returns a list of unique names of the nodes. If the input list is empty, you should return an empty list. Implement the function `get_unique_names(node_list: List[Dict[str, Any]]) -> List[str]`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of integers where each integer represents a threshold value. Your task is to implement a function `get_threshold(threshold_id: int, thresholds: List[int]) -> int` that retrieves a threshold value from the list based on the provided `threshold_id`. If the `threshold_id` is out of the bounds of the list (i.e., less than 0 or greater than or equal to the length of the list), the function should raise an `IndexError`. The function should return the threshold value corresponding to the `threshold_id`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function called `greet` that returns a string greeting the world with the message 'Hello world!'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of strings representing game titles. Your task is to implement a function that removes a specified game title from the list. If the game title exists in the list, remove the first occurrence of that title and return True. If the game title does not exist in the list, return False. The function should be case-insensitive when checking for the existence of the game title. The function signature is: `def remove_game(titles: List[str], game: str) -> bool:`. The input list can contain titles in mixed case, and you must maintain the original case for the remaining titles after removal."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function `generate_calendar_days(title: str, start_date: str, end_date: str, weekdays: List[bool]) -> Dict[str, None]` that generates a calendar mapping for a specified range of dates. The function should take the following parameters: \n\n- `title` (str): The title of the calendar. \n- `start_date` (str): The start date of the calendar in 'YYYY-MM-DD' format. \n- `end_date` (str): The end date of the calendar in 'YYYY-MM-DD' format. \n- `weekdays` (List[bool]): A list of 7 boolean values indicating whether to include each day of the week, starting from Monday. \n\nThe function should return a dictionary where the keys are the dates (in 'YYYY-MM-DD' format) from `start_date` to `end_date` that fall on the specified weekdays, and the values are all `None`. If a date does not fall on a specified weekday, it should not be included in the dictionary. \n\nFor example, if `start_date` is '2021-01-01', `end_date` is '2021-01-07', and `weekdays` is [True, True, False, False, False, False, False], the function should return a mapping for January 1st and 2nd, but not for the other days."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that generates a command for synchronizing files and directories using the `rsync` utility. The function should take in the source path, destination path, and an optional flag for relative synchronization. The generated command should include options for deleting extraneous files from the destination, displaying overall progress, preserving timestamps, and optionally using relative paths. Your task is to implement the `generate_rsync_command` function according to the following signature: `def generate_rsync_command(from_path: str, to_path: str, relative: bool = False) -> str:`. The `generate_rsync_command` function should return a string representing the complete `rsync` command based on the input parameters. The command should include the following options: 1. `--delete`: to delete extraneous files from the destination path. 2. `--info=progress2`: to display overall progress information during synchronization. 3. `--times`: to preserve timestamps. 4. `from_path`: the source path from which files and directories will be synchronized. 5. `to_path`: the destination path to which files and directories will be synchronized. 6. `--relative` (optional): if the `relative` flag is True, include this option to use relative paths during synchronization."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that processes a given list of file names and returns a list of all the Python files present in that list. You should exclude any files that are not Python files. The function should take a list of file names as input and return a list of Python file names. \n\nFunction signature: `def find_python_files(file_names: List[str]) -> List[str]:` \n\nFor example, given the following list of file names: `['file1.py', 'file2.txt', 'file3.py', 'file4.cpp']`, calling `find_python_files(['file1.py', 'file2.txt', 'file3.py', 'file4.cpp'])` should return `['file1.py', 'file3.py']`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given an unsorted list of integers, write a function that finds the frequency of each unique element and returns a list of elements sorted in descending order based on their frequency. If multiple elements have the same frequency, they should be sorted in ascending order based on their numerical value. Implement a function `sort_elements_by_frequency(lst: List[int]) -> List[int]` that takes a list of integers and returns the sorted list of elements."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Write a function to calculate the factorial of a given non-negative integer n using recursion. The function should return the factorial value. You can assume that the input n will be a non-negative integer."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a Python function that takes a list of integers and returns a new list containing only the even integers from the original list. The function should preserve the order of the even integers as they appeared in the input list. You should create a function called `filter_even_numbers` that takes in one parameter: a list of integers. The function should return a list of even integers. The function should have the following signature:\n\n```python\ndef filter_even_numbers(numbers):\n # Your implementation here\n``` \n\nFor example, given the input `filter_even_numbers([1, 2, 3, 4, 5, 6])`, the output should be `[2, 4, 6]`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a Python function that simulates the creation of a simple 3D wrapper object. The wrapper is designed to take two input strings representing the names of objects (e.g., 'source_cube' and 'target_cube') and returns a tuple containing a wrapper name and a base name. The wrapper name is generated by concatenating the two input names with the prefix 'wrap_' and the base name is simply the target name. Your function should meet the following requirements:\n- It should accept two strings as input, representing the names of the source and target objects.\n- It should return a tuple containing the wrapper name and the base name.\n- If the input strings are empty or not valid, the function should raise a ValueError.\n- If the creation of the wrapper name and base name fails for any reason, the function should return None for both values."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with designing a function to manage bookings for a tutoring center. The function should accept a list of bookings, where each booking is represented as a tuple containing the day index, hour, room name, and type of booking (either 'tutorial' or 'pool'). The function should return two dictionaries: one for tutorial bookings and another for pool bookings. Each dictionary should map a tuple of (day index, hour) to a list of room names. If there are no bookings for a specific day and hour, that entry should not be included in the dictionary. Implement the function `manage_bookings(bookings: List[Tuple[int, int, str, str]]) -> Tuple[Dict[Tuple[int, int], List[str]], Dict[Tuple[int, int], List[str]]]` where the input bookings are a list of tuples, and the output is a tuple containing two dictionaries: tutorial bookings and pool bookings."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with representing a geographical location with specific attributes. Implement a function called `get_location_details` that takes the following parameters: `id` (integer), `latitude` (float), `longitude` (float), `design_number` (string), `creation_date` (string), and returns a formatted string containing the details of the location including the id, latitude, longitude, design number, and creation date in the following format: 'Location ID: {id}, Latitude: {latitude}, Longitude: {longitude}, Design Number: {design_number}, Creation Date: {creation_date}'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given two dictionaries, old_hashes and new_hashes, where the keys are filenames (strings) and the values are their corresponding hash values (strings). Write a function `is_modified` that takes a filename as input and returns True if the file has been modified, meaning its hash in new_hashes is different from the hash in old_hashes. If the file does not exist in old_hashes, it is also considered modified and should return True. If the file exists in both dictionaries and the hashes are the same, return False. The function signature is: `def is_modified(old_hashes: dict, new_hashes: dict, filename: str) -> bool:`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that simulates the behavior of a checkbox widget in a graphical user interface (GUI) application. The function should allow for enabling and disabling the checkbox, setting its initial state, and toggling its state. Your task is to implement the function `simulate_checkbox(enabled: bool, default: bool, toggle_count: int) -> str` which returns the current state of the checkbox as 'checked' or 'unchecked' after toggling it a specified number of times. The parameters are as follows: \n- `enabled`: a boolean indicating whether the checkbox is enabled (True) or disabled (False). \n- `default`: a boolean indicating the initial state of the checkbox (True for checked, False for unchecked). \n- `toggle_count`: an integer representing how many times the toggle action should be performed. The toggle action should only occur if the checkbox is enabled. If the checkbox is disabled, its state should remain unchanged regardless of the toggle count. \nThe function should return the final state of the checkbox after performing the toggles."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function that computes the power of a number x raised to the exponent n. The function should handle cases where n can be zero or negative and should ensure that the time complexity is O(log n). Your function should be defined as follows: def power(x: float, n: int) -> float."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of probabilities, p, representing the likelihood of selecting each corresponding index from a list of items. Your task is to implement a function named `draw_index` that randomly selects an index based on the given probabilities. The input list `p` will contain non-negative numbers that represent the probabilities of each index being selected. You should ensure that the probabilities sum up to 1. The function should return an integer representing the selected index. If the probabilities do not sum up to 1, the function should raise a ValueError. The function signature is as follows: `def draw_index(p: List[float]) -> int:`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a boolean value `b`, implement a function `boolean_to_string(b: Optional[bool]) -> Optional[str]` that converts the boolean value to its string representation. If `b` is None, the function should return None. If `b` is True, return the string 'true'. If `b` is False, return the string 'false'. The function should be able to handle inputs of type Optional[bool]."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given the lengths of the two bases of a trapezoid and its height, implement a function `calculate_area(base1: float, base2: float, height: float) -> float` that calculates the area of the trapezoid. The area can be calculated using the formula: (base1 + base2) * height / 2."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `my_recursive_function(data: List[int], transform_func: Callable[[int], int]) -> List[int]` that takes a list of integers `data` and a transformation function `transform_func`. The function should recursively apply `transform_func` to each element in `data` and return a new list containing the transformed elements. If `data` is empty, return an empty list."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Write a function `fibonacci_max(numbers: List[int]) -> int` that takes a list of six integers and returns the maximum value among those integers that belong to the Fibonacci sequence. If there are no Fibonacci numbers in the input, return -1."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that processes a given layout and extracts fields from it. The layout is represented as a list, where each element can be either a string or a nested list of strings. Your task is to write a function `extract_fields(layout)` that extracts all the strings from the layout, including those in nested lists, and returns them as a flat list of fields. If the input layout is not a valid list, the function should return an empty list. For example, for the input layout = ['field1', ['field2', 'field3'], 'field4'], the function should return ['field1', 'field2', 'field3', 'field4']."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `calculate_and_validate_grades(grade_list)` that takes a list of integers representing the grades of a student in various courses. The function should first validate each grade to ensure it is between 0 and 100. If any grade is outside this range, the function should return a list containing the erroneous grade and a boolean indicating that an error occurred. Next, the function should compute the final average grade from the valid grades and also check if this average is between 0 and 100. If the average is invalid, return the average and the error status as True. If all grades are valid, return the final average and an error status of False."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function called `add_player` that takes in a player's name, their address text, and an optional RSSI value (received signal strength indication). The function should add the player's name and address text to a global list called `players`. If the RSSI value is provided, it should also be added to a secondary global list called `rssi_values`. If no RSSI value is provided, then the secondary list should not be updated. Implement the function such that it does not return anything, but it modifies the global lists `players` and `rssi_values` accordingly. The input parameters are as follows: 1. `name` (str): the name of the player. 2. `addr_text` (str): the address text of the player. 3. `rssi` (Optional[int]): the RSSI value of the player, which is None if not provided."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a custom decorator in Python that logs the execution time of a function. The decorator should log the start and end time of the function execution, along with the function name and its arguments. Additionally, the decorator should handle both positional and keyword arguments. You need to implement the `log_execution_time` decorator and apply it to a function `add_numbers` that takes two integers as arguments and returns their sum. The decorator should log the execution time and details when the `add_numbers` function is called. Your task is to define the decorator and ensure it works correctly with the provided function."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a list of positive integers, implement a function `unique_odd_sum_elements(x)` that returns a sorted list of unique elements that have an odd digit sum and do not occur more than once in the input list. The final list should be sorted in ascending order. Each element in the result must be unique based on its appearance in the input list. For example, if the input list contains the same number multiple times, it should not appear in the output list if its digit sum is odd. If no such elements exist, return an empty list."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that processes a list of temperature readings and determines the average temperature. The function should handle potential errors such as an empty list and non-numeric values. The function should return the average temperature as a float if the list is valid, otherwise return a specific error message. Your function should be defined as follows:\n\n```python\ndef average_temperature(readings: List[Union[int, float]]) -> Union[float, str]:\n```.\n\n### Input\n- `readings` (List[Union[int, float]]): A list of numeric values representing temperature readings.\n\n### Output\n- Returns the average temperature as a float if the input list is valid, or returns \"Error: Input list is empty\" if the list is empty, or returns \"Error: Non-numeric value found\" if there are any non-numeric values in the list."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that processes a list of integers and returns the sum of all the even numbers in the list. However, there's a catch - you must implement the function without using any conditional statements (if, else, etc.) or the modulo operator (%). Your task is to implement the function `sum_even_numbers` which takes a list of integers as input and returns the sum of all the even numbers in the list. For example, given the input list [1, 2, 3, 4, 5, 6], the function should return 12 (which is the sum of 2, 4, and 6)."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of device parameters represented as dictionaries, where each dictionary contains keys 'driver', 'patched_driver', and 'vendor'. Your task is to implement a function `set_device_parameters(params: List[Dict[str, str]]) -> None` that modifies each dictionary in the list by adding a new key 'status' with the value 'configured'. The function does not need to return anything. For example, if the input list is [{'driver': 'FTOSDriver', 'patched_driver': 'PatchedFTOSDriver', 'vendor': 'ftos'}], the output should modify the input list to [{'driver': 'FTOSDriver', 'patched_driver': 'PatchedFTOSDriver', 'vendor': 'ftos', 'status': 'configured'}]."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function called `dynamic_serialize` that takes in a Python object `data` and a string `format`. The function should serialize the `data` using the appropriate serialization method based on the `format` string and return the serialized data. The function should support the following serialization formats: - If `format` is 'pickle', the function should serialize the data using the pickle library. - If `format` is 'json', the function should serialize the data using the json library. The function should handle the following scenarios: - If the `format` is not 'pickle' or 'json', the function should raise a `ValueError` with the message 'Invalid format specified'. - If the required modules are not available, the function should raise an `ImportError` with the message 'Required module not found'. You can assume that the necessary imports for the modules are already provided in the code snippet."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given two lists of integers, `graph` and `subgraph`, determine if `subgraph` is a spanning subgraph of `graph`. A subgraph is considered spanning if it contains all unique elements from `graph`. Implement a function `is_spanning(graph: List[int], subgraph: List[int]) -> bool` that returns True if `subgraph` contains all the unique elements of `graph`, otherwise return False. The input lists may contain duplicates and are not sorted."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Write a function `extract_unique_words(text: str) -> set` that takes a string `text`, extracts all unique words from it while ignoring punctuation marks, and returns them in a set. The function should treat words as case-insensitive, meaning 'Word' and 'word' are considered the same. Punctuation marks include characters such as '.', ',', '!', '?', etc. The input string will not be empty."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function that generates the Fibonacci sequence up to the 'n-th' position, where 'n' is a non-negative integer provided as an argument. The function should return the 'n-th' Fibonacci number. The Fibonacci sequence is defined as follows: F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2) for n > 1. Do not worry about handling any input validation within the function."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a staircase with 'n' steps. You can reach the top of the staircase by taking either 1 or 2 steps at a time. Your task is to implement a function `countWays` that takes an integer `n` as input and returns the total number of distinct ways to reach the top of the staircase. For example, if there are 4 steps, the possible ways to reach the top are: {1, 1, 1, 1}, {1, 1, 2}, {1, 2, 1}, {2, 1, 1}, and {2, 2}. Therefore, the function should return 5."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of dictionaries where each dictionary represents a bot with the following attributes: 'user_id', 'bot_id', 'mu', 'sigma', 'score', 'games_played', 'version_number', 'language', 'update_time', 'compile_status', and 'organization_id'. Your task is to implement a function `rank_bots(bots: List[Dict[str, Union[int, float, str]]]) -> List[Dict[str, Union[int, str]]]` that returns a list of bots ranked by their scores in descending order. Each bot in the output should include the same attributes as the input, along with an additional attribute 'bot_rank' representing their rank based on the score. If there are ties in scores, they should be assigned the same rank. The ranks should start from 1 for the highest score. If a bot's score is 0 or less, it should be excluded from the output. The input list will not be empty."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of 2D coordinates representing the corners of a contour in a 2D space, along with the dimensions of a rectangular area (width and height). Your task is to determine if the contour touches any of the corners of the rectangle. If it does, you need to add the corresponding corner point to the contour. The corners of the rectangle are defined as: (0, 0), (0, height), (width, height), (width, 0). The function should return the modified contour, which includes the new corner point if it was added. If the contour does not touch any corners, return the original contour unchanged. The coordinates of the contour are provided in a list of tuples.\n\nFunction Signature: `def close_corner_contour(contour: List[Tuple[int, int]], shape: Tuple[int, int]) -> List[Tuple[int, int]]:`\n\nInput:\n- `contour`: A list of tuples representing the coordinates of the contour, where each tuple has the form (x, y).\n- `shape`: A tuple of two integers (width, height) representing the dimensions of the rectangular area.\n\nOutput:\n- Returns a list of tuples representing the modified contour with the added corner point, if applicable."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a string representing a font name in SHX format. Your task is to map it to its corresponding True Type Font (TTF) file name according to a predefined mapping. The mapping is as follows: 'TXT' -> 'txt_____.ttf', 'ARIAL' -> 'arial.ttf', 'VERDANA' -> 'verdana.ttf', 'COMIC' -> 'comic.ttf', 'TIMES' -> 'times.ttf'. If the provided font name does not exist in the mapping, return the input string as it is, but converted to lowercase. Implement a function called 'resolve_shx_font_name' that takes a string 'font_name' as input and returns the mapped TTF file name or the lowercase version of the input string if not found."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are working on a bioinformatics project that involves processing genetic data. Your task is to implement a function `generate_batch_file(gene_name: str, location: str, threshold: int, start: int, end: int) -> str` that generates a batch file for processing genetic data. The function should take the following parameters: \n1. `gene_name` (a string) - the name of the gene.\n2. `location` (a string) - the location of the gene in the format 'chromosome:position'.\n3. `threshold` (an integer) - a threshold value for processing.\n4. `start` (an integer) - the start position for processing.\n5. `end` (an integer) - the end position for processing.\n\nThe function should simulate the creation of a batch file by returning the filename where the batch file would be saved. The filename should follow the format `./IGV_Snapshots/{gene_name}/{location.replace(':', '_')}.bat`. Ensure that the directory path is created in the output but do not actually create any files. You only need to return the filename as a string. \n\nExample:\nInput: `gene_name=\"BRCA1\", location=\"chr17:41242896\", threshold=5, start=41242800, end=41242850`\nOutput: `\"./IGV_Snapshots/BRCA1/chr17_41242896.bat\"`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that validates a comma-separated string of email addresses. The function should ensure that each email address in the string is valid according to a specific validation rule. An email address is considered valid if it follows the standard email format: it should contain one '@' symbol, a domain name, and a top-level domain that is at least two characters long. Your function should take a single string argument containing the comma-separated email addresses. If any email address fails validation, the function should return a list of error messages indicating which email addresses are invalid. If the input is not a string, the function should return an error message stating that the input is invalid. Implement the function `validate_comma_separated_emails(value)` that performs this validation."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that simulates a simple robotic system that can move in a grid. The grid is represented by a 2D list where '0' indicates an empty cell and '1' indicates an obstacle. The robot starts at the top-left corner of the grid (0, 0) and can only move right or down. Your task is to determine if there is a path from the top-left corner to the bottom-right corner of the grid, avoiding obstacles. Implement the function `is_path_possible(grid: List[List[int]]) -> bool` that returns `True` if a path exists and `False` otherwise. The input grid will always be a non-empty 2D list with dimensions ranging from 1x1 to 100x100."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that generates a cache key for a web application based on a user account ID. The key format for caching the verification codes is defined as follows: `VCODE_KEY = 'VCode-%s'`, where `%s` is a placeholder for the user account ID. Your task is to implement a function `generate_cache_key(user_id)`, which takes a user account ID as input and returns the formatted cache key. For example, if the user account ID is `12345`, the function should return `VCode-12345`. Implement the function without using any external resources."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of integers representing the values of some operations. Your task is to identify if the sequence of operations corresponds to a specific pattern defined as follows: The operation sequence must consist of exactly three operations with the following types in order: 'reduce_mean', 'sub', and 'mul'. Additionally, the 'sub' operation must take as input the output of the 'reduce_mean' operation and the original input value. If the sequence matches this pattern, return True; otherwise, return False. Implement the function `is_matching_pattern(operations: List[str]) -> bool` where `operations` is a list of strings representing the operations. The function should return a boolean value indicating whether the operations match the specified pattern."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You need to implement a function that initializes a directory service object based on a given node name. The function should accept a single parameter, 'nodename', which is a string representing the name of the directory service node. If the node name is not empty and contains only alphanumeric characters and underscores, the function should return a dictionary representing the initialized object with a key 'node_name' set to the value of 'nodename'. If the node name is invalid (empty or contains invalid characters), the function should return None. Write a function `initialize_directory(nodename: str) -> Union[dict, None]` that performs this operation."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a string `s` and an integer `k`, remove all occurrences of any character that appears consecutively `k` or more times in the string. Return the modified string after all such characters have been removed. If no characters remain, return an empty string. For example, given the string 'aaabbbcc' and k=3, the result should be 'cc'. Your function should be defined as: `def remove_consecutive_characters(s: str, k: int) -> str:`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given an integer x, write a function `solve(x)` that reverses the digits of the integer and returns the reversed integer. If the reversed integer exceeds the 32-bit signed integer range, return 0. The function should handle both positive and negative integers. For example, if the input x is 123, the function should return 321. If the input x is -123, the function should return -321."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a URL query string that may contain parameters for 'style' and 'locale'. Write a function that takes this query string as input and returns the values associated with the 'style' and 'locale' parameters. If a parameter is not present, return 'None' for that parameter. The input query string will always start with a '?', and parameters will be separated by '&'. Each parameter is in the format 'key=value'. Your function should handle cases where parameters may be present in any order or may be missing entirely. \n\nFunction Signature: `def retrieve_url_args(query: str) -> Tuple[Optional[str], Optional[str]]:` \n\nExample: \n- Input: `'?style=modern&locale=en'` \n- Output: `('modern', 'en')` \n\n- Input: `'?locale=fr'` \n- Output: `(None, 'fr')` \n\n- Input: `'?style=classic&foo=bar'` \n- Output: `('classic', None)'`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a time in milliseconds, write a function that converts this time into a string format representing hours, minutes, and seconds. The output should be in the format 'HH:MM:SS'. If the input is less than 0, return '00:00:00'. For inputs greater than or equal to 0, the function should correctly format the time regardless of how many hours or minutes it represents. Implement the function `convert_milliseconds_to_time(milliseconds: int) -> str`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with developing a Python function that simulates data retrieval and processing from a hypothetical data source. The function should take the following input parameters: a list of data items, a batch size, and a processing function. The goal is to retrieve data in batches of the specified size and process each batch using the provided processing function. The function should return a list of processed results from each batch. The processing function will be a callable that takes a list of items and returns a processed result. Write a function `process_data_in_batches(data, batch_size, process_function)` that implements this behavior."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a 2D array of positive integers, calculate the mean of each column and return the results as a 1D array. The mean should be rounded down to the nearest integer. The input will be a matrix of shape (m, n) where m is the number of rows and n is the number of columns. You need to implement a function `column_mean(matrix: List[List[int]]) -> List[int]` that takes the matrix as input and returns a list of integers representing the mean of each column."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that simulates a simple bank account. The function should take a list of operations, where each operation is either a deposit (represented by a tuple ('deposit', amount)) or a withdrawal (represented by a tuple ('withdraw', amount)). The function should return the current balance of the account after performing all operations and the total number of transactions (deposits and withdrawals). The initial balance of the account is provided as an input parameter. If a withdrawal exceeds the current balance, that transaction should not be executed. Implement the function `simulate_bank_account(initial_balance: int, operations: List[Tuple[str, int]]) -> Tuple[int, int]` which returns a tuple containing the final balance and the total number of transactions."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Write a function `remove_duplicates(input_list)` that takes a list of elements and returns a set of unique integers derived from the list. The function should handle erroneous inputs by only including valid integers in the final set. If an element cannot be converted to an integer, it should be ignored. The input list may contain integers, floats, and strings. Any element that cannot be converted to an integer should be excluded from the result. For example, given the input list [1, 2, '3', 3, 3, 4, 'a', 7.8], the output should be {1, 2, 3, 4}."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given two dictionaries, `dict_a` and `dict_b`, which may contain nested dictionaries as values. Write a function `merge_dicts(dict_a, dict_b)` that merges `dict_b` into `dict_a`. The merging process should handle the following rules: If a key exists in both dictionaries and both values are dictionaries, merge them recursively. If a key exists in both dictionaries but the value in `dict_b` is not None, override the value in `dict_a`. If a key exists only in `dict_a`, retain its value. If a key exists only in `dict_b` and its value is not None, include it in the result. The function should return the merged dictionary."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Write a function `cryptic_code(length)` that generates a secure cryptic code of the specified length. The code should include uppercase letters, lowercase letters, numbers, and special characters. The function must validate the input to ensure that it is a positive integer. If the input is invalid, the function should raise a ValueError with an appropriate message. The function should return the generated code as a string."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with measuring the electrical properties of a circuit. Write a function `measureProperties` that simulates measuring both resistance and frequency based on the given parameters. The function will take the following parameters: `board` (an integer), `switch` (an integer), `Range` (a string, defaulting to 'AUTO'), and `Resolution` (a string, defaulting to 'AUTO'). The function should return a tuple containing the measured resistance (float) and frequency (float). For the purpose of this simulation, you can assume the following calculations: resistance is calculated as `board * 10 + switch`, and frequency is calculated as `board * 100 + switch * 10`. Both resistance and frequency should be returned as floats. Your function should not perform any I/O operations."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that simulates managing a book's reading progress. The function should take three parameters: the author of the book (a string), the initial location of the book (a string), and the number of pages to turn (an integer). The function should return a dictionary containing the author's name, the current location of the book, and the final page number after turning the specified number of pages. The initial page number starts at 0. If the number of pages to turn is negative, the function should return the initial state without any modifications. Implement the function `manage_book(author: str, location: str, pages_to_turn: int) -> dict:`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function `check_keep_alive_timeout(client_timeout: int, server_timeout: int) -> str` that determines whether a client will maintain its connection with the server based on their keep-alive timeouts. The function takes two parameters: `client_timeout` (an integer representing the keep-alive timeout of the client in seconds) and `server_timeout` (an integer representing the keep-alive timeout of the server in seconds). If the client timeout is longer than or equal to the server timeout, the function should return 'Connection Maintained'. Otherwise, it should return 'New Connection Required'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a string containing multiline text that may include newline characters. Write a function `format_multiline_string(s: str) -> str` that formats this string into a single line by replacing all newline characters with a space, and ensuring that there are no extra spaces between words. The output should be a well-formatted single-line string. \n\nExample: \n\nInput: 'Hello\\nWorld\\nThis is a test.' \nOutput: 'Hello World This is a test.' \n\nInput: 'Line 1\\n\\nLine 2' \nOutput: 'Line 1 Line 2'"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with determining if a given string represents an error status in a logging system. Implement a function that checks if the input string is equal to 'error'. The function should return True if the input string is 'error', and False otherwise. Your function should have the following signature: `def is_error(splunk_record_key: str) -> bool:`. \n\n### Input \n- A single string `splunk_record_key` (1 <= len(splunk_record_key) <= 100) that may contain any printable ASCII characters.\n\n### Output \n- Return a boolean value: True if the input string is 'error', False otherwise."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of distances and a list of revenues corresponding to different nodes. Your task is to find the optimal alpha value between 0.0 and 1.0 (inclusive) that maximizes the overall savings calculated using the formula: saving = distance_saving * (1 - alpha) + revenue * alpha. You need to test alpha values at intervals of 0.1. Your function should return the alpha value that results in the highest total revenue. Write a function `find_best_alpha(distances: List[float], revenues: List[float]) -> float:` that takes two lists as input and returns a float representing the best alpha value."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with generating a SQL ORDER BY clause from a list of fields and their corresponding sort orders. Implement a function `generate_order_by(fields: List[str], sort_orders: List[str], table_pre: str = '') -> str` that takes the following parameters: \n\n- `fields`: A list of strings representing the fields by which to sort. \n- `sort_orders`: A list of strings representing the sort order for each field, which can be either 'ASC' for ascending or 'DESC' for descending. \n- `table_pre`: (Optional) A string representing the table prefix to prepend to each field name. \n\nThe function should return a string representing the complete ORDER BY clause for SQL. If the input list `fields` is empty, return an empty string. If any sort order is invalid (not 'ASC' or 'DESC'), the function should raise a ValueError. \n\nExample:\nInput: `fields = ['name', 'age']`, `sort_orders = ['ASC', 'DESC']`, `table_pre = 'users'`\nOutput: `ORDER BY users.name ASC, users.age DESC`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `score_person(age: int, city: str) -> int` that takes an individual's age and city of residence as input and returns a score based on the following criteria: If the person is under 30 and lives in 'Los Angeles', then score = 10; If the person is under 30 and does not live in 'Los Angeles', then score = 7; If the person is 30 or older and lives in 'Los Angeles', then score = 5; If the person is 30 or over and does not live in 'Los Angeles', then score = 2."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that simulates the response of a webhook when an account is created. The function should accept two parameters: `entity_id` (a string representing the unique ID of the account) and `entity_name` (a string representing the name of the account). The function should return an XML string that contains the account's information. The XML should have a root element named `response` and should contain a child element named `org_name` with the value set to `entity_name`. Additionally, the XML should include a child element named `account_id` with the value set to `entity_id`. Implement the function `generate_webhook_response(entity_id: str, entity_name: str) -> str` that adheres to this specification."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `intricate_frequency_analyzer(test: str) -> dict` that takes in a string composed of space-separated characters, including uppercase and lowercase alphabets, numeric characters, and punctuation. The function should return a dictionary featuring the highest frequency character(s), in lowercase for alphabets, followed by their count. If multiple characters exhibit the same occurrence, return all of them. The function should treat upper and lower case letters identically. If the input string is empty, return an empty dictionary."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a list of dictionaries representing users, each containing 'name', 'age', 'profession', and 'location', implement a function `filter_users` that filters the users based on their profession, and returns a list of users who are of the specified profession and fall within a given age range (inclusive). The function signature is: `def filter_users(data: List[Dict[str, Union[str, int]]], profession: str, min_age: int, max_age: int) -> List[Dict[str, Union[str, int]]]:`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a string representing a file path, write a function that checks if the path is valid. A valid path contains only alphanumeric characters, underscores, hyphens, and periods. The function should return True if the path is valid and False otherwise. For example, 'valid_path.txt' is valid, while 'invalid/path.txt' is not. Implement the function `is_valid_path(path: str) -> bool`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function that takes a list of strings as input and returns a new list containing the concatenation of the 9th and 10th characters from each string. If a string is less than 10 characters long, it should be ignored. The function should also raise a ValueError if the input is not a list or if any element in the list is not a string. Write the function named `extract_chars(lst)`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a string that contains information about various queues in a specific format. Each queue's details are separated by the phrase 'Display Queue details'. The details for each queue include its label, current depth, maximum depth, and type in the following format: 'QUEUE(label)', 'CURDEPTH(depth)', 'MAXDEPTH(depth)', and 'TYPE(type)'. Write a function `get_queues_labels(queue_labels_data: str) -> Dict[str, Dict[str, str]]` that parses this string and returns a dictionary where each key is a queue label, and the value is another dictionary containing the keys 'curdepth', 'maxdepth', and 'type'. Each of these should map to their respective parsed values. If any of the required details are missing for a queue, it should not be included in the output. The input string will always be well-formed but may vary in the number of queues. For example, given the input string: 'Display Queue details QUEUE(queue1) CURDEPTH(5) MAXDEPTH(10) TYPE(typeA) Display Queue details QUEUE(queue2) CURDEPTH(3) MAXDEPTH(8) TYPE(typeB)', the output should be: {'queue1': {'curdepth': '5', 'maxdepth': '10', 'type': 'typeA'}, 'queue2': {'curdepth': '3', 'maxdepth': '8', 'type': 'typeB'}}."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with updating an internal list with the contents from a provided list. Write a function `update_internal_list(list_name: str, new_items: List[str]) -> List[str]` that takes in a list name and a list of new items. It should merge the new items into the internal list (which starts off empty) and return the updated internal list. If the list name already exists, replace its current contents with the new items. The internal list should not contain duplicate items after the update. The function should maintain the order of items as they are added. \n\nFunction Signature: `def update_internal_list(list_name: str, new_items: List[str]) -> List[str]:` \n\n**Input:** \n- `list_name`: A string representing the name of the list to be updated. \n- `new_items`: A list of strings representing the new items to be added to the list. \n\n**Output:** \n- Return a list of strings representing the updated internal list after the new items have been added. \n\n**Constraints:** \n- The length of `new_items` will be at most 1000. \n- Each item in `new_items` is a non-empty string and has at most 100 characters. \n- The `list_name` will be a non-empty string with at most 100 characters."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of state variable names and a list of invocation contexts, represented as dictionaries. Each dictionary contains various state variables as keys. Your task is to implement a function `deduce_state_variables(state_names: List[str], contexts: List[Dict[str, Any]]) -> Dict[str, Any]` that deduces and returns the first invocation context that contains all the specified state variable names. If no such context exists, return an empty dictionary. The function should perform the following: 1. Iterate over each context in the list. 2. Check if all the state variable names are present in the current context. 3. If found, return the context as a dictionary. 4. If no context meets the criteria after checking all, return an empty dictionary. You can assume that the input lists will always be valid and the state variable names will be unique. The function signature is: `def deduce_state_variables(state_names: List[str], contexts: List[Dict[str, Any]]) -> Dict[str, Any]:`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given an integer representing a precision level (or None), implement a function that converts this integer into a list containing that integer if it is not None, or an empty list if it is None. The function should return this list. The integer will be between 0 and 100 inclusive, and None represents no precision. Write a function `convert_precision(precision: Optional[int]) -> List[int]:` that achieves this."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that simulates a simplified file locking mechanism. The function should take two parameters: a list of strings `keys` representing the keys for the files, and a string `path` representing the directory path where the lock files would theoretically be stored. The function should return a list of boolean values where each boolean indicates whether the lock for the corresponding file key can be acquired. A lock can be acquired if the corresponding key has not been locked previously (meaning no other key in the keys list is the same as the current key). Two identical keys in the list cannot both be locked. Implement the function `can_acquire_locks(keys: List[str], path: str) -> List[bool]`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `process_and_find_min_odd_index(arr: List[int]) -> int` that takes a list of unique integers and performs the following operations: First, sort the array in ascending order without using built-in sort functions. Then, swap the values at even and odd indices. Finally, return the smallest integer from the odd indices of the modified array. The input list of integers can include negative numbers."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a Python function that processes a list of strings representing USB endpoints and returns the first OUT endpoint found. An OUT endpoint is a type of USB endpoint used for sending data from the host to the device. Each USB endpoint is represented by a string in the format \"type, direction, endpoint_number\", where \"type\" is either \"IN\" or \"OUT\", \"direction\" is either \"input\" or \"output\", and \"endpoint_number\" is a positive integer. Write a function `find_out_endpoint(endpoints: List[str]) -> str` that takes a list of endpoint strings as input and returns the first OUT endpoint found. If no OUT endpoint is present in the input list, the function should return an empty string."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You need to implement a function that takes a string representing JSON data and returns the corresponding dictionary. The string will be well-formed and contain valid JSON. Implement the function `parse_json_string(json_string: str) -> dict:`. The function should handle decoding the JSON string and returning the dictionary representation of it."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that processes a list of event signals and their corresponding handlers. The function should take two parameters: a list of event signals and a dictionary that maps each event signal to its handler function. The function should return a list of results obtained by invoking each handler function corresponding to the event signals in the order they appear in the list. If an event signal does not have an associated handler, it should return 'No handler' for that signal. Each handler function is assumed to take no parameters and return a string. \n\nWrite a function named `process_events` that implements this functionality."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given two integers x and y, write a function `compute_root(x, y)` that returns the y-th root of x. You can assume that x is a non-negative integer and y is a positive integer. The function should handle cases where the result is not an integer by returning a float value. If y is greater than x, the function should return 0.0."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a simple hash table that supports basic operations of inserting, retrieving, and removing key-value pairs using a separate chaining method to handle collisions. Your hash table should be able to store integer values associated with string keys. You need to implement a function `hash_table_operations(operations: List[Tuple[str, str, int]]) -> List[Optional[int]]` that takes a list of operations and returns a list of results from the `get` operations. Each operation in the list is a tuple containing three elements: the operation type ('insert', 'get', or 'remove'), the key (a string), and the value (an integer for 'insert' operations, or -1 for 'get' and 'remove' operations). The function should return a list of results where each `get` operation returns the value associated with the key, or None if the key is not found. For `insert` operations, the function should not return anything. For `remove` operations, the function should also not return anything. The hash function is defined as the sum of the ASCII values of the characters in the key modulo the size of the table."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that simulates a simple banking operation. The function should accept an initial transaction limit and a series of operations in the form of tuples. Each operation can either be a deposit or a withdrawal. The function should return the final balance after applying all the operations, while ensuring that deposits and withdrawals do not exceed the specified transaction limit and that withdrawals do not exceed the current balance. If an operation cannot be completed due to the limits, it should simply be ignored. Your task is to implement the function `final_balance(act_limit: float, operations: List[Tuple[str, float]]) -> float`, which will return the final balance in the account. The initial balance starts at 0. The operations will be given as a list of tuples where each tuple consists of a string ('deposit' or 'withdraw') and a float representing the amount. The function should enforce the transaction limit for both deposits and withdrawals."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of command line arguments as strings that would typically be passed to a program. Your task is to parse these arguments and return a dictionary where the keys are the argument names (without the leading '--') and the values are the corresponding argument values. If an argument is provided multiple times, the last occurrence should be used. If an argument is not provided, its value in the dictionary should be None. Implement a function `parse_command_line_args(args: List[str]) -> Dict[str, Optional[str]]`, where `args` is a list of strings representing command line arguments. For example, for input `['--gpu', '0', '--out', 'output.txt', '--gpu', '1']`, the output should be `{'gpu': '1', 'out': 'output.txt'}`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function that takes three coefficients of a quadratic equation, a, b, and c, and returns the two roots of the equation ax^2 + bx + c = 0. The roots should be returned as a tuple of complex numbers. If the roots are real, they should still be returned as complex numbers with an imaginary part of 0. The function should handle cases where the discriminant is negative, indicating that the roots are complex. The function signature is: def solve_quad_equ(a: float, b: float, c: float) -> tuple."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a custom exception class and implementing a function that simulates searching for a package in a package management system. Your custom exception class, named `PackageNotFoundError`, should inherit from the `Exception` class and accept a package name as an argument. The exception should raise a message in the format: \"Package {package_name} not found\". Implement a function called `find_package` that takes two arguments: a list of available packages and a package name to search for. If the package is found in the list, the function should return the package name. If the package is not found, the function should raise a `PackageNotFoundError` with the package name that was not found."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of directed edges represented as pairs of integers in the form of a 2D array, where each pair (i, j) signifies a directed edge from node i to node j. Your task is to create a new list of edges that includes both the original edges and their reverse counterparts, while ensuring that no duplicate edges are present in the final result. The output should be a list of unique edges sorted in ascending order, meaning that if (i, j) exists, (j, i) should also be included, but only if it does not already exist as an edge. Note that self-loops (edges where i equals j) should not be included in the final list. Implement a function `add_edges_reverse_indices(edge_indices: List[List[int]]) -> List[List[int]]` that takes the list of edges and returns the desired output."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with calculating the volume of a truncated prism given the dimensions of two triangular bases and the height of the prism. Implement the function `run_truncated_prism_volume(a1, b1, c1, a2, b2, c2, h)` that takes the lengths of the sides of the first triangle (a1, b1, c1), the lengths of the sides of the second triangle (a2, b2, c2), and the height of the prism (h). The function should return the volume of the truncated prism rounded to two decimal places. If the dimensions provided do not form valid triangles or if the height is less than or equal to zero, return 'Invalid parameters'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a directed graph represented as an adjacency list and a start node. Your task is to implement a breadth-first search (BFS) algorithm to find the shortest path from the start node to a target node. Write a function `shortest_path(graph, start, target)` that takes in the following parameters: - `graph`: A dictionary representing the graph in the form of an adjacency list. The keys are the nodes, and the values are lists of neighboring nodes. - `start`: A string representing the start node from which the search begins. - `target`: A string representing the target node to reach. The function should return a list representing the shortest path from the start node to the target node. If there is no path from the start node to the target node, return an empty list."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `prime_numbers(n)` that takes an integer `n` as input and returns a list of all prime numbers up to and including `n`. A prime number is defined as a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. The function should handle edge cases and return an empty list for values of `n` less than 2."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `is_palindrome_string(s: str) -> bool` that checks if a given string forms a palindrome, while ignoring spaces, punctuation, and case sensitivity. The function should return True if the cleaned string is a palindrome and False otherwise. A palindrome is defined as a string that reads the same forwards and backwards."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `Fibonacci(n: int) -> int` that returns the nth Fibonacci number. The Fibonacci sequence is defined as follows: F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2) for n > 1. The function should handle cases where n is a non-negative integer (0 or greater)."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that retrieves the logarithmic scale factor for a given time unit. The time units can be one of the following: 'fs' (femtoseconds), 'ps' (picoseconds), 'ns' (nanoseconds), 'us' (microseconds), 'ms' (milliseconds), or 'sec' (seconds). The function should return the logarithm base 10 of the scale factor for the specified unit. If the provided unit is invalid, the function should raise a ValueError. Write a function `get_log_time_scale(units: str) -> int` that takes a string representing the time unit and returns the corresponding logarithmic scale factor."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of dictionaries, where each dictionary represents the state of a system with the following keys: 'pcad_mode', 'clocking', 'fep_count', and 'ccd_count'. Write a function `find_modifiable_states(state_data: List[Dict[str, Union[str, int]]]) -> Tuple[List[int], List[List[int]]]` that returns two things: 1) a list of indices representing states that meet the following criteria: 'pcad_mode' is 'NPNT', 'clocking' is 1, 'fep_count' is equal to 'ccd_count', and 'fep_count' is less than 4; 2) a list of all permutations of 0s and 1s, where each row represents a single case (combination), and each column represents the number of chips to be added for each state indexed by the returned list of indices. The first element in the returned list of permutations should represent 0's for each modifiable state, representing the baseline case."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement the function `BurrowsWheelerTransform(string: str) -> str` that applies the Burrows-Wheeler Transform (BWT) method to a given string. The BWT is achieved by generating all circular permutations of the input string, sorting them, and returning the last column of the sorted permutations. For example, if the input string is 'abcdabcd', the function should return the BWT of that string."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a list of integers representing the payoffs of a game for each player, write a function `calculate_social_welfare(payoffs: List[int], mix: List[float]) -> float` that calculates the expected social welfare of a mixed strategy profile. The `payoffs` list contains the payoffs for each player, and the `mix` list contains the probabilities of selecting each strategy for each player, where the length of `mix` is equal to the length of `payoffs`. The expected social welfare is calculated as the dot product of the `payoffs` and `mix` lists. The function should return the expected social welfare as a float. The input constraints are as follows: the length of `payoffs` and `mix` will be equal and at least 1, and the probabilities in `mix` will sum up to 1."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that manages a simple in-memory settings dictionary for a hypothetical application. The settings dictionary should be initialized with a token when the function is called. The function should provide two capabilities: fetching the current settings and updating the settings with new key-value pairs. The function signature is as follows: `def manage_settings(token: str, updates: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:`. The function should return the updated settings dictionary. If no updates are provided, it should return the settings with the original token only. Your task is to implement the function to meet these requirements."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that fills in missing IDs in a given dictionary structure. The function should take in a dictionary representing a mapping of sheet names to rows, where each row maps to an ID that may be either an integer or None. The function should fill in any None IDs with incremental values starting from a provided highest ID, ensuring that each filled ID is unique and sequential. The function should return a new dictionary with the missing IDs filled in. Implement the function `fill_missing_ids(id_map: Dict[str, Dict[int, Optional[int]]], highest_id: int) -> Dict[str, Dict[int, int]]` where `id_map` is defined as described above and `highest_id` is the starting point for filling in missing IDs. The returned dictionary should have the same structure as the input but with all None values replaced with unique incremental IDs."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with converting a list of numeric values into a list of floating-point numbers. Write a function `convert_to_float` that takes a list of integers or floats as input and returns a new list containing the same numbers converted to floats. The function should handle both integers and floats in the input list. If the input list is empty, return an empty list. \n\nFunction Signature: `def convert_to_float(values: List[Union[int, float]]) -> List[float]:`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given two positive integers, implement a function `compute_gcd(a: int, b: int) -> int` to compute and return their Greatest Common Divisor (GCD). The GCD of two integers is the largest positive integer that divides both numbers without leaving a remainder."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with calculating the center of mass of a system of particles in a 3D space. Given a list of particles' coordinates in 3D space and their respective masses, your function should compute the center of mass of these particles. The center of mass can be calculated using the formula: COM = (Σ(mass_i * position_i)) / (Σ(mass_i)), where position_i is the coordinate of the i-th particle and mass_i is its mass. Implement a function `compute_center_of_mass(coordinates: List[List[float]], masses: List[float]) -> List[float]` that takes two parameters: a list of coordinates where each coordinate is a list of three floats representing the x, y, and z positions of the particles, and a list of floats representing the masses of the particles. The function should return a list of three floats representing the coordinates of the center of mass."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function `process_string(data: str) -> str` that takes a string as input and returns a new string with all characters converted to uppercase. Your function should handle any string input, including empty strings. For example, if the input is 'hello world', the output should be 'HELLO WORLD'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that simulates changing the background color based on button clicks. You will implement a function called `choiceColor` that takes a string argument `button_label`. The function should return the corresponding background color as a string based on the following mappings: 'DARK' corresponds to 'black', 'PURPLE' corresponds to 'purple', 'BLUE' corresponds to 'blue', and 'GREEN' corresponds to 'green'. If the input does not match any of these labels, the function should return 'invalid color'. Implement the function `choiceColor(button_label: str) -> str`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `shared_chars_count(str1, str2)` that takes two strings as input and returns a dictionary containing the characters that are present in both strings, ignoring case. The keys of the dictionary should be the shared characters, and the values should be the number of occurrences of each shared character in both strings. The function should also handle special characters and numbers. For example, given the strings 'Mango#2' and 'Watermelon#3', the function should return a dictionary with the shared characters and their minimum counts in both strings."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Write a function that converts a given string into its binary representation. Each character in the string should be represented by its binary ASCII value, and the binary values should be separated by a single space. Implement the function `string_to_binary(s: str) -> str`, where `s` is the input string. The output should be a string of binary numbers."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of documents, where each document is represented as a list of tokens (words). Your task is to create a function that transforms these documents into a 2D array where each row corresponds to a document and each column corresponds to a specific word vector representation of the tokens in that document. The function should take three parameters: a list of lists of tokens (documents), a dictionary that maps each unique token to a predefined word vector (a list of floats), and the dimensionality of the word vectors. If a token is not present in the dictionary, its corresponding vector should be a zero vector. The output should be a 2D array (list of lists) containing the document vectors. The function signature should be: `def create_doc_vectors(documents: List[List[str]], word_vectors: Dict[str, List[float]], n_dim: int) -> List[List[float]]:`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `get_user_data(user_id: int) -> dict` that takes a user ID as an integer and returns a dictionary containing user data fetched from a simulated API. The API endpoint is `http://api.example.com/user/{user_id}`. For the purpose of this exercise, simulate the API response with a predefined dictionary for specific user IDs. If the user ID does not correspond to any predefined data, return an empty dictionary."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `calculate_shape_properties` that takes in a shape type (either 'circle' or 'rectangle') and the corresponding dimensions (either radius for a circle or width and height for a rectangle) and returns a tuple of (area, perimeter). The function should raise a ValueError if the dimensions provided are invalid (e.g., negative or zero values)."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a 2D list (matrix) representing a table of data where each element is a number. Implement a function `delete_row_and_column(matrix: List[List[int]], row: int, col: int) -> List[List[int]]` that removes the specified row and column from the matrix, returning a new matrix without the deleted row and column. If the specified row or column is out of bounds, return the original matrix unchanged. The matrix will not be empty and will contain at least one row and one column."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a string `s` that consists of lowercase letters, and you need to determine if it is a palindrome. A string is considered a palindrome if it reads the same backward as forward. Implement a function `is_palindrome(s: str) -> bool` that returns `True` if `s` is a palindrome, and `False` otherwise. For example, if the input string is 'racecar', the output should be `True`. If the input string is 'hello', the output should be `False`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a float number 'x' and a float number 'sigma'. Implement a function called 'gmof' that computes the Geman-McClure error function using the formula: (sigma^2 * x^2) / (sigma^2 + x^2). Your function should return the computed value as a float. The inputs 'x' and 'sigma' will always be non-negative numbers. Please implement the function with the signature: def gmof(x: float, sigma: float) -> float:"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a URL redirection function for a web application. The function should take a host name and a request path as input, and return the appropriate redirect URL based on the following conditions: \n\n1. If the host is 'www.dalme.org' or 'public.dalme.org', return 'https://dalme.org' + request_path. \n2. If the host is 'www.127.0.0.1.sslip.io:8443' or 'public.127.0.0.1.sslip.io:8443', return 'https://127.0.0.1.sslip.io:8443' + request_path. \n3. If the host is 'www.example.com' or 'public.example.com', return 'https://example.com' + request_path. \n4. If the host is 'www.test.org' or 'public.test.org', return 'https://test.org' + request_path. \n5. For any other host, return 'https://' + host + request_path.\n\nImplement a function called `redirect_url(host, request_path)` to satisfy these conditions."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a list of bounding boxes, each represented as a tuple of two points (top-left and bottom-right coordinates), and a corresponding list of confidence scores for each bounding box, write a function `filter_person_boxes(bounding_boxes: List[Tuple[Tuple[int, int], Tuple[int, int]]], scores: List[float], threshold: float) -> List[Tuple[Tuple[int, int], Tuple[int, int]]]` that returns a list of bounding boxes that correspond to the category 'person' and have confidence scores greater than or equal to the given threshold. The input lists are guaranteed to have the same length. Each bounding box is defined by its top-left corner (x1, y1) and bottom-right corner (x2, y2). If no bounding boxes meet the criteria, return an empty list."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a positive integer `n` representing the number of items. You need to determine the total number of ways to select any number of items from these `n` items. Each selection can either include or exclude each item. Implement the function `count_selections(n: int) -> int` that returns the total number of ways to select items. The result should be computed as 2^n, which represents each item being either included or excluded in a selection. Your function should handle cases where `n` is large, but will not exceed 30. Assume `n` is guaranteed to be a valid positive integer."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that takes a nested dictionary as input and returns a flattened dictionary. A nested dictionary is a dictionary where the values can be either simple values (like integers or strings) or other dictionaries. Your function should concatenate the keys of nested dictionaries into a single key using a dot ('.') as a separator. For example, if the input dictionary is {'a': 1, 'b': {'c': 2, 'd': 3}}, the output should be {'a': 1, 'b.c': 2, 'b.d': 3}. Implement the function `flatten_dict(nested_dict)` that takes a dictionary and returns a flattened dictionary."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that processes a list of integers and returns the sum of all the even numbers in the list. The function should also handle any exceptions that may occur during the processing of the list. If an exception occurs, the function should print the exception and continue processing the remaining elements in the list. Your task is to implement the `sum_even_numbers` function, which takes a list of integers (or other types) as input and returns the sum of all the even numbers in the list. If an exception occurs, the function should catch the exception, print it, and continue processing the remaining elements. If no exceptions occur, the function should return the sum of all the even numbers. Function Signature: `def sum_even_numbers(numbers: List[int]) -> int:`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `cubed_product(lst)` that computes the product of the cubed values of the individual integer elements in a given list. The list should only contain integers between -10 and 10 inclusive. If any element is not an integer or is out of the specified range, the function should return an error message indicating that all elements must be integers between -10 and 10. The function should handle any unexpected errors gracefully and return a generic error message. The output should be the computed product of cubed values or an error message if the input is invalid."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of dictionaries, each representing metadata about a trial containing assay records. Each dictionary contains a 'cimac_id' and a list of 'records' which are dictionaries of cell counts for different cell types. Your task is to implement a function `combine_cell_counts(trial_metadata: List[Dict[str, Any]]) -> List[Dict[str, Any]]` that processes this list of dictionaries to create a combined summary of cell counts. The output should be a list of dictionaries where each dictionary corresponds to a unique 'cimac_id' and contains cell types as keys with their respective counts as values. If a 'cimac_id' has multiple records, sum the counts for each cell type. The function should return the result as a list of dictionaries sorted by 'cimac_id'. Example input and output are provided below:\n\nInput:\n[\n {'cimac_id': 'sample1', 'records': [{'CellSubset': 'T cells', 'Count': 10}, {'CellSubset': 'B cells', 'Count': 5}]},\n {'cimac_id': 'sample2', 'records': [{'CellSubset': 'T cells', 'Count': 8}, {'CellSubset': 'NK cells', 'Count': 3}]},\n {'cimac_id': 'sample1', 'records': [{'CellSubset': 'T cells', 'Count': 2}, {'CellSubset': 'B cells', 'Count': 4}]} \n]\n\nOutput:\n[\n {'cimac_id': 'sample1', 'T cells': 12, 'B cells': 9},\n {'cimac_id': 'sample2', 'T cells': 8, 'NK cells': 3}\n]"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a list of integers `x` and a set of integers `inArray`, write a function `filter_and_sort` that filters the elements from `x` which are also present in `inArray`, adds them to `inArray`, and returns the sorted list of unique elements from `inArray`. The function should maintain the integrity of the original `inArray` set while returning the sorted result. For example, if `x = [3, 5, 2, 7, 5]` and `inArray = {2, 5, 8, 10}`, the function should return `[2, 5]` as the output since those are the elements from `inArray` that are also in `x`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of tuples representing operations in a CIGAR string format. Each tuple consists of an operation type (represented as an integer) and a length (represented as an integer). The operation types are as follows: 0 for matches, 1 for mismatches, 2 for insertions, 7 for deletions, and 8 for padding. Write a function `parse_cigar(cigarlist: List[Tuple[int, int]], ope: int) -> List[List[int]]` that takes in a list of operations `cigarlist` and an operation type `ope`. The function should return a list of lists containing the occurrences and indices of the specified operation in the alignment. The first element in each sublist should be the length of the operation, and the second element should be the cumulative length of all previous operations. If the operation type does not exist in the list, return an empty list."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that takes a list of strings and removes any trailing whitespace from each string. Your function should return the list of processed strings after trimming the trailing whitespace. Implement the function `trim_trailing_whitespace(strings)` where `strings` is a list of strings. The function should not print anything and should return the modified list directly."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given two strings, determine if they are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once. Ignore spaces and letter casing when evaluating the anagrams. Implement a function `is_anagram(s1: str, s2: str) -> bool` that returns True if the strings are anagrams and False otherwise."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that manages a list of display fields for a user profile in an e-commerce application. The function should support adding and removing fields from the display list, and also returning the current list of display fields. Additionally, you need to ensure that the display links are only associated with fields that exist in the display fields list. The function will take a list of operations to perform, each operation being a tuple where the first element is a string indicating the type of operation ('add' or 'remove') and the second element is the field name. Your task is to implement a function `manage_user_profile(operations: List[Tuple[str, str]]) -> List[str]` that returns the final list of display fields after performing all operations. The initial display fields are `['user', 'refund_granted', 'shipping_address', 'billing_address', 'payment', 'coupon']`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that takes a string as input, which is expected to be a base64-encoded representation of some text. Your function should decode this base64 string and return the decoded text. If the input is not a valid base64 string, your function should return an error message indicating that the input is invalid. Implement the function `decode_base64(encoded_string: str) -> str` where `encoded_string` is the base64-encoded text. The function should return the decoded text if successful, or an error message if the input is invalid."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that simulates the addition of a new field to a database model in a migration operation. The new field is called 'published', and it is a Boolean field that defaults to False. Your function should take a dictionary representing the current state of the model and add the 'published' field to it. The function should return the updated dictionary with the new field included. If the 'published' field already exists in the model, the function should return the original dictionary without any changes. Please implement a function named `add_published_field(model_dict: dict) -> dict` where `model_dict` is the current state of the model as a dictionary. The function should modify the model dictionary only when the 'published' field is not present."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a string `user_key` which contains a combination of alphanumeric characters and special symbols, and a context string `context`. Your task is to implement a function `get_token(context: str, user_key: str) -> str` that processes the `user_key` by removing all special symbols and returning the cleaned version of `user_key` prefixed by the `context`. The cleaned `user_key` should only contain alphanumeric characters. If there are no valid alphanumeric characters in `user_key`, the function should return just the `context`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a simulation of a multi-armed bandit problem. In this problem, an agent is presented with a row of slot machines (bandits), each with a fixed probability of providing a reward when pulled, determined by its index. Your goal is to implement the function `pull_bandit(bandit_index: int, num_bandits: int) -> int`, which simulates pulling a specified bandit and returns a reward. The reward is defined as 1 with probability `bandit_index / num_bandits` and 0 otherwise. The function should work as follows: given an integer `bandit_index`, return a reward based on the probability associated with that bandit index. The function should not use any external libraries and should handle edge cases such as invalid bandit indices gracefully by returning 0. Note that the bandit indices range from 0 to `num_bandits - 1`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a string 's'. Your task is to determine whether the provided string can be classified as 'happy' or not. A 'happy' string is defined by the following characteristics: It must have a minimum length of three characters, every individual character within the string must occur at least twice, no consecutive characters can be identical, and every group of three successive characters in the string must be unique. Implement the function `is_happy(s: str) -> bool` that returns True if the string is happy, and False otherwise."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Design a function that processes a provided nested list, where each inner list consists of string elements. The function should perform the following operations: (1) Remove any duplicate string elements within each inner list, (2) Sort each inner list in ascending lexicographical order, taking into account case sensitivity, (3) Replace any non-ASCII printable string elements with a space, and (4) Replace any string elements that are palindromes with the string 'PALINDROME'. Your function should return a new nested list with the processed results."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `char_at_index(s: str, index: int) -> str` that takes a string `s` and an integer `index` as input. The function should return the character at the specified index in the string. If the index is out of bounds, the function should return an empty string. The function should be able to handle Unicode characters. Please ensure that the function can handle both positive and negative indices, where a negative index counts from the end of the string. If the index is negative and its absolute value exceeds the length of the string, return an empty string as well."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with simulating a simple text-based game where a player navigates through a series of rooms, collecting items. Each room contains a unique identifier, a description, and a list of items that can be found in it. Implement a function called `collect_items(rooms: List[Tuple[int, str, List[str]], player_room: int) -> List[str]` that takes a list of rooms (each represented as a tuple of an integer ID, a string description, and a list of strings representing items) and the player's starting room ID. The function should return a list of all items that the player can collect starting from the specified room, including items from all connected rooms. For simplicity, assume the player can move freely between all rooms without any obstacles. The rooms are connected in a way that allows the player to reach all of them from the starting room."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of integers representing the indices of thermodynamic entries in a database. Your task is to implement a function that finds the minimum and maximum valid entry indices from the list. A valid entry index is any index that is greater than zero. The function should return a tuple containing two integers: the minimum valid index and the maximum valid index. If there are no valid indices in the list, return (-1, -1). The input list may contain duplicates and negative values. \n\nImplement the function: \n\n```python\n def find_min_max_indices(entries: List[int]) -> Tuple[int, int]:\n```"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with managing a list of interrupt service routines (ISRs) represented as strings in the format 'NVIC_<PERIPHERAL_NAME>_IRQ'. Your goal is to implement a function `manage_isrs(operations: List[Tuple[str, str]]) -> List[str]` that processes a sequence of operations to register, unregister, and invoke ISRs. Each operation is a tuple containing an action ('register', 'unregister', or 'invoke') and the ISR name. The function should return the list of currently registered ISR names after processing all operations. The initial state contains no registered ISRs. \n\nExample operations: \n- Registering an ISR: ('register', 'NVIC_CAN1_RX1_IRQ') \n- Unregistering an ISR: ('unregister', 'NVIC_CAN1_RX1_IRQ') \n- Invoking an ISR: ('invoke', 'NVIC_CAN1_RX1_IRQ') \n\nAfter processing a sequence of operations, the function should return the final list of registered ISRs."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a Python function that performs namespace flattening on a nested dictionary. Namespace flattening involves transforming a nested dictionary into a flattened dictionary, where the keys are concatenated with a specified delimiter to represent the original nested structure. Write a function `flatten_dict(d, delimiter='.')` that takes a nested dictionary `d` and an optional delimiter (default is '.') and returns a flattened dictionary. The function should handle arbitrary levels of nesting and should concatenate keys using the specified delimiter. For example, given the input dictionary `{'x': {'y': 5, 'z': {'a': 10}}}`, the output should be `{'x.y': 5, 'x.z.a': 10}`."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a function that determines which files should be ignored based on the name of a directory. Implement the function `ignore_files(directory: str) -> List[str]` that takes in a string `directory` representing the name of a directory and returns a list of strings that are the names of files to be ignored. The rules for ignoring files are as follows: If the directory name is 'material', ignore the files ['mkdocs_theme.yml', 'main.html', '404.html']. If the directory name is 'partials', ignore the file ['integrations']. If the directory name is 'images', ignore the file ['favicon.png']. For any other directory name, return an empty list."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a dictionary representing a multi-sector design with the following structure: {'unpacked_designation': <string>, 'sectors': [<dict1>, <dict2>, ...]}. Each sector dictionary can contain any key-value pairs. Your task is to implement a function `process_designation(designation_dict: Dict[str, Union[str, List[Dict]]]) -> List[Tuple[str, Dict]]` that takes in this dictionary and returns a list of tuples. Each tuple should contain the unpacked designation and one of the sector dictionaries. The returned list should have one tuple for each sector. If the input dictionary does not contain the 'unpacked_designation' or 'sectors' keys, the function should return an empty list. \n\nFor example, if the input is {'unpacked_designation': 'Design A', 'sectors': [{'sector_id': 1}, {'sector_id': 2}]}, the output should be [('Design A', {'sector_id': 1}), ('Design A', {'sector_id': 2})]."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `largest_prime_factor(n: int) -> int` that returns the largest prime factor of the given integer 'n'. The function should handle both positive and negative integers. It is guaranteed that the absolute value of 'n' is greater than 1 and is not a prime number. The function should efficiently determine the prime factors of 'n'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `generate_sequence(starting_number: int, step: int) -> List[int]` that generates a sequence of natural numbers starting from `starting_number` and increases each subsequent number by `step`. The function should return the first `n` numbers of the sequence as a list. The parameters `starting_number` and `step` are positive integers, and `n` is a positive integer indicating how many numbers to generate. Assume that the input is always valid."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a dictionary representing various parameters of a vehicle, where keys are categories such as 'powertrain' and 'size', and the values are lists of options available in those categories. Your task is to write a function that checks if certain parameters are absent from the provided options. Specifically, your function should take in a dictionary called `scope` and return True if 'BEV' is not present in the list of values for the 'powertrain' key, and 'Large' is not present in the list of values for the 'size' key. If either 'BEV' or 'Large' is found, return False. If the 'powertrain' or 'size' keys do not exist in the dictionary, assume that their values are empty lists. Implement the function with the signature: `def check_vehicle_parameters(scope: dict) -> bool:`"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function to calculate the Body Mass Index (BMI) and categorize it into one of the following categories: 'Underweight' (BMI < 18.5), 'Normal weight' (18.5 <= BMI < 25), 'Overweight' (25 <= BMI < 30), or 'Obese' (BMI >= 30). Implement a function `bmi_category(weight: float, height: float) -> str` that takes in weight (in kilograms) and height (in meters) as input, calculates the BMI using the formula BMI = weight / (height^2), rounds it to two decimal places, and returns the corresponding category as a string. Ensure that both weight and height are positive numbers. If either weight or height is non-positive, the function should raise a ValueError with the message 'Weight and height must be positive numbers'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with visualizing the iterations involved in solving Lambert's problem, which is a classic problem in orbital mechanics. Your function should take as input a list of tuples representing iteration points in two-dimensional space, where each tuple contains an x-coordinate and a y-coordinate. Your function should return a list of the x-coordinates and a list of the y-coordinates separated from the input data. Implement a single function named `visualize_iterations` that takes the input list of iteration points and outputs two lists: one for x-coordinates and another for y-coordinates. The input list will be non-empty. "}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Write a function called `create_nim_board` that takes an integer `n` as input and creates a multi-stacked Nim game board represented as a list of lists. The board should consist of `n` stacks, where each stack is a list of integers representing stones. The number of stones in each stack should be a random integer between 1 and `n`, inclusive, and the stones in each stack should be arranged in a random order. The function should return the constructed board."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of celestial coordinates represented as tuples of (x, y) and a frame type. Implement a function that takes a list of such coordinates and a frame type, and returns a new list with the equinox values adjusted based on the frame type. For 'icrs' frame, the equinox is simply the index of the coordinate in the list as a string. For 'fk4' frame, the equinox should be the string 'J' followed by the index of the coordinate. If the frame type is not recognized, return an empty list. Your function should be defined as follows: \n\n```python\ndef adjust_equinox(coordinates: List[Tuple[float, float]], frame: str) -> List[str]:\n```"}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that constructs a string representation of a network host. The function should take two parameters: the host's name and its endpoint. The function should return a string in the format 'Host(name, endpoint)', where 'Host' is a constant string representing the class name, 'name' is the host's name passed to the function, and 'endpoint' is the host's endpoint passed to the function. Implement the function `host_string(name: str, endpoint: str) -> str` to achieve the desired output."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Implement a function `classify_text(text: str) -> str` that classifies the input text as 'Spam' or 'Not Spam' based on predefined keywords. The function should return 'Spam' if the text contains any of the following keywords: 'offer', 'free', 'win', 'click', 'subscribe'. Otherwise, it should return 'Not Spam'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are given a list of integers and a target integer. Your task is to determine if there are two distinct indices in the list such that the sum of the integers at those indices equals the target integer. Implement a function named `find_pair_with_sum` that takes in two parameters: a list of integers `nums` and an integer `target`. The function should return a boolean value: `True` if such a pair exists, and `False` otherwise."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a string input, return the string with 'Hello, ' prefixed to it. Implement a function called `greet(name: str) -> str` that takes a single parameter `name`, which is a string. The function should return the greeting message as a new string. For example, if the input is 'Alice', the output should be 'Hello, Alice'."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given an array of integers, write a function that finds the minimum sum of five negative numbers in that array. If the array contains fewer than five negative numbers, the function should raise a ValueError. Implement the function `min_sum_of_five(arr)` where `arr` is the input list of integers."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Given a list of elements, write a function that removes duplicate elements while maintaining the original order of the first occurrence of each element. The function should take a list of items and return a new list containing only the distinct elements. The function should be able to handle both hashable and non-hashable elements by providing an optional key function that converts elements into a hashable type. If no key function is provided, the elements themselves should be used for comparison. Implement the function `remove_duplicate_elements(items, key=None)` where `items` is a list of elements and `key` is an optional function. The output should be a list of distinct elements in the order they first appeared in the input list."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "Write a function `is_perfect_square(n: int) -> bool` that checks if a given non-negative integer `n` is a perfect square. A perfect square is an integer that is the square of an integer. For example, 0, 1, 4, 9, 16 are perfect squares, while 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15 are not. The function should return `True` if `n` is a perfect square, and `False` otherwise."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that can handle data serialization into plain text or YAML format. The function should take two parameters: `data`, which is the data to be serialized, and `format`, which specifies the serialization format (either `1` for plain text or `2` for YAML). If the `format` parameter is not `1` or `2`, the function should raise a `ValueError`. If `format` is `1`, the function should return the `data` as a string. If `format` is `2`, the function should return the data serialized in YAML format. Implement the function `serialize_data(data: Any, format: int) -> str` according to these requirements."}], "membership_label": 1} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that simulates the execution of a custom program within a virtualization management tool. The function will take three string inputs: `python_executable_path`, `custom_path`, and `custom_program`. Your function should construct a command string to represent the execution of the custom program using the specified Python executable. The command string should be formatted as follows: '<python_executable_path> -t <custom_path>/share/virt-manager/<custom_program>'. The function should return this command string. Implement the function `simulate_execution(python_executable_path: str, custom_path: str, custom_program: str) -> str` that returns the constructed command string."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function that takes an integer and returns the cube of that integer. The function should be named `cube` and should accept a single parameter `n`, which is the integer to be cubed. The output should be an integer representing the cubed value of `n`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of email addresses, implement a function `is_spam(email: str, dataset: List[Dict[str, Union[str, int]]]) -> bool` that determines whether the provided email address is classified as spam based on a given dataset. The dataset consists of dictionaries containing email addresses and their corresponding classes, where a class of 1 indicates spam and 0 indicates not spam. The function should return True if the email is classified as spam, and False otherwise."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of skills and a list of interests that a volunteer possesses. Your task is to create a function called `create_profile` that takes two lists as input: `skills` (a list of strings representing the skills) and `interests` (a list of strings representing the interests). The function should return a dictionary with two keys: 'skills' and 'interests', where the value for 'skills' is a list of unique skills and the value for 'interests' is a list of unique interests, both sorted in alphabetical order. If either list is empty, the corresponding key in the dictionary should have an empty list as its value."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of integers, determine if the elements are monotonically increasing or decreasing under certain conditions. The function should check for the following: if the elements form an arithmetic progression or a geometric progression, if they follow the Fibonacci sequence, if all elements are prime numbers, and whether strictness and zero-crossing apply. The function should return True if the conditions are met, otherwise return False. The function signature is: `def monotonic_advanced_prime_fib(l: list, strict: bool = False, zero_crossing: bool = False, progression: str = None, fibonacci: bool = False, prime: bool = False):`"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that calculates the total number of elements in a series of octree levels and returns a list of formatted strings representing the dimensions and total elements in each level. Each octree level is represented by a tuple of dimensions (width, height). Your function should take a list of tuples representing the dimensions of various octree levels and an integer indicating the starting index for the levels. The function should return a list of strings in the format '(width, height) = total_elements', where total_elements is the product of width and height. The function should only include levels starting from the specified index. Write a function `calculate_octree_levels_info(levels: List[Tuple[int, int]], start_level: int) -> List[str]` that implements this functionality."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with updating a dictionary of parameters. Write a function `update_params(old_param: Dict[str, Any], new_param: Dict[str, Any], errors: str = 'raise') -> Dict[str, Any]` that takes in the following three arguments: \n1. `old_param`: A dictionary representing the old parameters. \n2. `new_param`: A dictionary representing new parameters that you want to use to update the old ones. \n3. `errors`: A string that can either be 'raise' or 'ignore'. If 'raise', the function should raise an exception if any key in `new_param` does not exist in `old_param`. If 'ignore', the function should simply ignore those keys. \n\nThe function should return a new dictionary that is a copy of `old_param`, updated with the values from `new_param` where the keys exist in `old_param`. If `errors` is set to 'raise' and a key from `new_param` does not exist in `old_param`, an exception should be raised. \n\nExample:\nIf `old_param` is `{'a': 1, 'b': 2}` and `new_param` is `{'a': 3, 'c': 4}` with `errors` set to 'raise', the function should raise an exception because 'c' is not a recognized parameter. If `errors` is set to 'ignore', the function should return `{'a': 3, 'b': 2}`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are implementing a version control system where you need to track objects based on their version numbers. Write a function `object_has_version(key: str, version_number: int) -> None` that takes a string `key` representing the object and an integer `version_number` representing the version number of the object. The function should store the association between the object and its version number. If the version number is not already present in the system, it should be added, and the object should be associated with that version number. If the version number already exists, the object should be added to the existing set of objects associated with that version number. The function does not return anything."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that validates an event data dictionary. The function should ensure that the event data meets certain criteria before it can be considered valid. The function should accept a dictionary called `event_data`, which contains the following fields: `description`, `tablename`, `name`, `pipeline_names`, `id`, and `updated_by`. The function must perform the following validations: 1. Ensure that the `description` field is not None. 2. Ensure that the length of the `tablename` field does not exceed 8000 characters. 3. Ensure that the `name` field is not None. 4. Ensure that the `pipeline_names` field is not None. 5. Ensure that the `id` field is a positive integer. 6. Ensure that the `updated_by` field is not None. If any of the validations fail, the function should raise a `ValueError`. Otherwise, it should return True, indicating that the event data is valid. Write a function `validate_event_data(event_data)` that implements this logic."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given two lists of vertical values, `u` and `v`, representing measurements at various depths, and a target depth, implement a function `vertical_interpolation(u: List[float], v: List[float], depth: List[float], target_depth: float) -> Tuple[List[float], List[float]]` that performs linear interpolation to estimate the values of `u` and `v` at the specified `target_depth`. The function should return two lists containing the interpolated values of `u` and `v` at the `target_depth`. If the `target_depth` is below or above the range of the provided depths, return an empty list for that dimension. The `depth` list is guaranteed to be sorted in ascending order."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given an integer value, implement a function that finds the smallest exponent such that 2 raised to that exponent is greater than or equal to the absolute value of the integer. The function should return this exponent. The input integer can be either positive, negative, or zero. Your task is to write a function `next_power_of_two(value: int) -> int` that accomplishes this. For example, if the input is -8, the output should be 4, since 2^4 is 16, which is greater than 8. If the input is 0, the output should be 0, since 2^0 is 1, which is greater than or equal to 0."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that evaluates whether a physics event passes a specific cut criterion based on a hypothesis validity check and the sum of delta R values for gen-matched particles. Write a function `applyCut(isHypoValid: bool, genMatchSumDR: float) -> bool` that takes in two parameters: a boolean `isHypoValid` indicating whether the hypothesis is valid, and a float `genMatchSumDR` representing the sum of delta R values. The function should return `True` if the event passes the cut criteria, which is defined as the hypothesis being valid and the `genMatchSumDR` value being less than 999. Otherwise, it should return `False`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a Python function that processes a dictionary and logs its contents. The function should take in a dictionary called `responseDictionary`, log its contents with a custom logging utility, and then return the original dictionary. The logging should simulate the action of logging without needing any external resources. Implement the function `process_and_log` that accepts the `responseDictionary` as an argument. The function will log the dictionary with a log message 'APIs status' and then return the original `responseDictionary`. Note: You do not need to implement the logging utility; just simulate its call. The function should adhere to the following requirements: 1. Log the status of the `responseDictionary` using a simulated logging function. 2. Return the original `responseDictionary` unchanged."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given an array of non-zero integers, implement a function that calculates the product of the distinct signs of those integers multiplied by the sum of their distinct absolute values. If the array is empty or contains a zero, the function should return None. Write a function `prod_signs(arr)` that takes the array as input and returns the required value."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of strings representing the content of each cell in a worksheet. Your task is to implement a function that resizes the columns of the worksheet to fit the content inside the cells of the columns. The function should return a list of integers representing the optimal width for each column based on the longest string in that column. The width of a column is defined as the length of the longest string in that column. Implement the function `autosize_columns(cells: List[List[str]]) -> List[int]`. \n\nInput: A list of lists of strings, where each inner list represents the cells in a row of a worksheet. \nOutput: A list of integers representing the optimal widths for each column."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that takes in a list of integers and returns a new list containing only the unique elements from the original list, maintaining their original order. Write a function called `remove_duplicates` that fulfills this requirement. The function should have the following signature: `def remove_duplicates(nums: List[int]) -> List[int]:`. \n\n**Input:** A list of integers `nums` where `1 <= len(nums) <= 1000` and `-10^6 <= nums[i] <= 10^6`. \n**Output:** A list of integers containing only the unique elements from the input list, in the order they first appeared."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a dictionary where the keys are public key IDs (strings) and the values are x.509 certificate data (strings), implement a function that returns a list of all public key IDs in the dictionary. The function should only return the keys that have non-empty certificate data. The function signature is: `def get_non_empty_cert_ids(cert_dict: Dict[str, str]) -> List[str]:`. Your task is to implement this function."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function `generate_efficientnet_b6_model(pretrained: bool, num_classes: int, in_chans: int) -> str` that simulates the creation of an EfficientNet-B6 model configuration. The function should take three parameters: `pretrained`, a boolean indicating whether the model should be initialized with pretrained weights; `num_classes`, an integer specifying the number of output classes for the model; and `in_chans`, an integer representing the number of input channels (typically 3 for RGB images). The function should return a string description of the model configuration, summarizing whether it's pretrained, the number of output classes, and the number of input channels. The output string should be formatted as: 'EfficientNet-B6 Model: Pretrained: {pretrained}, Num Classes: {num_classes}, In Channels: {in_chans}'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that converts a given string of HTML content into a formatted plain text output. The function should strip out all HTML tags, decode any HTML entities (like & to &), and return the plain text result. The HTML content may contain various tags like <p>, <strong>, <em>, <br>, etc., and the function should handle them appropriately. Implement the function `convert_html_to_text(html_content)` that takes a string of HTML content as input and returns a string of plain text."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that simulates the updating or creation of a camera object based on provided details. The camera objects are represented by a dictionary, where the keys are the camera names and the values are dictionaries containing the camera attributes: 'is_demo', 'rtsp', and 'area'. Your function should take in the name of the camera, a boolean flag indicating whether it is a demo camera, the RTSP URL, and the area covered by the camera. If the camera with the given name already exists in the camera dictionary, its attributes should be updated with the provided RTSP URL and area. If the camera does not exist, a new camera entry should be created with the provided details. Implement the function `process_camera_object` that takes the parameters and modifies the camera dictionary accordingly. The function should return the updated camera dictionary. \n\nFunction Signature: `def process_camera_object(cameras: dict, name: str, is_demo: bool, rtsp: str, area: str) -> dict`"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that simulates writing an emotional state to a database. The function `write_emotion` should take four parameters: `happy`, `anger`, `bored`, and `confused`, which represent the intensity of each emotion (as integers). The function should return a dictionary containing these emotions with their corresponding values. Ensure that the dictionary keys are 'happy', 'anger', 'bored', and 'confused'. The values in the dictionary should be the same as the input parameters. For example, if the function is called with `write_emotion(5, 2, 0, 1)`, it should return {'happy': 5, 'anger': 2, 'bored': 0, 'confused': 1}."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that simulates a simple database connection management system. The function should handle opening and closing the database connection, and it should provide an interface for executing SQL queries. Implement the function `manage_database_connection(actions: List[str]) -> List[str]` where `actions` is a list of strings representing actions to be performed on the database connection. The possible actions are: 'open', 'close', and 'execute <query>'. The function should return a list of strings representing the output messages for each action. The behavior is as follows: \n- If 'open' is called when the connection is closed, return 'Database connection opened' and change the connection status to open. \n- If 'close' is called when the connection is open, return 'Database connection closed' and change the connection status to closed. \n- If 'execute <query>' is called when the connection is open, return 'Executed query: <query>'. If the connection is closed, return 'Error: Database connection is closed'. \nYou can assume that the input will always be valid and in the specified format."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function that takes a multi-dimensional nested list and transforms it into a flat list. The function should be able to handle varying levels of nested lists, ensuring that the relative order of the elements is maintained in the output. For example, given the input [[1, 2], [3, [4, 5], 6], [7, [8, [9, 10]]]], the output should be [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a sentence consisting of words separated by spaces, write a function `sort_sentence(sentence: str) -> str` that sorts the words in the sentence in alphabetical order and returns them as a single string with words separated by a single space. The input will be a string, and the output should also be a string. Note that the sorting is case-sensitive, meaning that uppercase letters will come before lowercase letters in the sorted order. If the sentence is empty, return an empty string."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are working on a game development project where various objects and elements in the game world are represented using bitmasks. Each object or element has a unique identifier represented by a BitMask32 value. Your task is to create a function that can determine whether a given bitmask value contains a specific subset of flags. Implement a function `checkBitmaskSubset(bitmask, subset)` that takes in a bitmask value and a list of subset flags, returning True if the bitmask contains all the flags in the subset, and False otherwise. The flags are defined as follows: GhostBitmask = 2048, PathFindingBitmask = 536870912, PickerBitmask = 4096, CeilingBitmask = 256, FloorEventBitmask = 16, PieBitmask = 256, PetBitmask = 8, CatchGameBitmask = 16, CashbotBossObjectBitmask = 16, FurnitureSideBitmask = 32, FurnitureTopBitmask = 64. For example, if the input bitmask is 272 (CeilingBitmask | PetBitmask) and the subset is [CeilingBitmask, PetBitmask], the function should return True."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Create a function called `filter_numbers` that takes a list of integers and returns a new list containing only the numbers that occur exactly once in the input list and are not prime numbers."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that parses a given GitHub repository URL and extracts the repository owner and repository name. The function should handle various formats of GitHub repository URLs and return the extracted information in a structured format. Write a function `parse_github_url(url: str) -> dict` that takes a GitHub repository URL as input and returns a dictionary containing the extracted information. The input URL can be in the format \"https://github.com/owner/repository\", \"https://www.github.com/owner/repository\", \"git@github.com:owner/repository.git\", or \"git://github.com/owner/repository.git\". The function should return a dictionary with the following keys: - \"owner\": the owner of the repository - \"repository\": the name of the repository If the repository cannot be parsed, the function should return None. Assume that the input URL is always valid and points to an existing GitHub repository."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `contains_float(sequence)` that takes a list called `sequence` as input and returns `True` if there is at least one floating-point number in the list. The list may contain various data types, including integers, strings, and floats. If there are no floating-point numbers in the list, the function should return `False`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function `load_unique_messages(messages: List[Tuple[str, str, str, str, str]], unique: bool) -> List[Tuple[str, str, str, str, str]]` that processes a list of message tuples. Each tuple contains five elements: sender, recipients, timestamp, subject, and body. If the `unique` parameter is set to `True`, the function should return a list of messages without duplicate signatures. A signature is defined as a tuple containing the sender, recipients, timestamp, subject, and body of a message. If `unique` is set to `False`, the function should return all messages as they are. The input list may contain duplicates. The function should return a list of messages, preserving the order in which they first appeared. You may assume that the input list will never be empty."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that analyzes the status of a networked instance. The function should take in a dictionary `instance_data` containing information about the instance and return `None` if the instance is running but appears to be unreachable externally, or a list of IP addresses if the instance is reachable. The `instance_data` dictionary contains the following keys: \n- `networkInterfaces`: a list of network interfaces associated with the instance, each containing information about access configurations. \n- `status`: the status of the instance, which can be 'RUNNING' or other values not relevant to this problem. \n- `name`: the name of the instance. \n\nThe function should perform the following steps: \n1. Extract the IP addresses from the `instance_data` dictionary by iterating through the `networkInterfaces` and collecting the `natIP` from the `accessConfigs`. \n2. Filter out any `None` values from the collected IP addresses. \n3. If no IP addresses are found and the instance status is 'RUNNING', return `None`. \n4. If IP addresses are found, return the list of IP addresses. \n\nYour task is to implement the Python function `analyze_instance_data(instance_data)` that adheres to the above specifications."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a destination address represented as a string. Implement a function `trace_route(dest: str, hops: int, queries: int, timeout: int, ttl: int, wait: int) -> str` that simulates a traceroute to the given destination address. The function should return a string that describes the traceroute result. The string should include the destination address and the number of hops taken. The parameters are as follows: \n- `dest`: a string representing the destination address (1 <= len(dest) <= 100). \n- `hops`: an integer representing the maximum number of hops allowed (1 <= hops <= 30). \n- `queries`: an integer representing the number of queries to send (1 <= queries <= 10). \n- `timeout`: an integer representing the timeout for each query in seconds (1 <= timeout <= 5). \n- `ttl`: an integer representing the Time-To-Live value (1 <= ttl <= 255). \n- `wait`: an integer representing the wait time in milliseconds (1 <= wait <= 1000). \nThe return string should be formatted as follows: 'Tracing route to {dest} with {hops} hops, {queries} queries, timeout {timeout}s, ttl {ttl}, wait {wait}ms.'"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given an integer `hour_angle_sunrise` that represents the hour angle of sunrise in degrees, write a function `sunlight_duration(hour_angle_sunrise)` that returns the duration of sunlight in minutes. The duration of sunlight is calculated as 8 times the `hour_angle_sunrise`. The input will be in the range of -180 to 180 degrees (inclusive)."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that manipulates a URL. Your function should take in a URL as input and return a string that formats the URL in a specific way. The formatted URL should start with 'URL: ' followed by the provided URL. The function signature should be: `def format_url(url: str) -> str:`. For example, if the function is called with `format_url('https://example.com')`, it should return 'URL: https://example.com'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of numerical inputs, implement a function that computes the product of their absolute values, after rounding down to the nearest integer. Any values exceeding 100 should be excluded from the computation. Write a function `compute_absolute_product(lst)` that takes a list of numbers and returns the resulting product."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `decimal_to_ternary(n: float) -> Tuple[str, int]` that converts a decimal number to its ternary (base 3) representation. The function should take a single parameter `n`, which can be either an integer or a float. If the input is not of type integer or float, the function should return an appropriate error message. For negative numbers, the function should return the ternary representation with a leading minus sign. For floating numbers, limit the precision of the ternary representation to four decimal places. Additionally, the function should return the count of the digit '2' in the ternary representation. The output should be a tuple containing the ternary representation as a string and the count of '2's. If the input is zero, return '0' for the ternary representation and 0 for the count of '2's."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that simulates enabling an addon in a software system. The function `enable_addon(addon_module_name: str) -> str` takes a single string parameter representing the name of the addon to be enabled. The function should return a message indicating the status of the addon. If the addon name is 'add_mesh_extra_objects', return 'Addon enabled: add_mesh_extra_objects'. For any other addon name, return 'Addon not found: {addon_module_name}'. Implement this function."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function `parse_section(section: str) -> List[str]` that takes a string representing a section name and returns a list containing two strings: the component and the section. The section can either be a simple name or a name prefixed with the component separated by a forward-slash. The valid components are 'main', 'contrib', and 'non-free'. If the section does not have a valid component, it should default to 'main'. If the section name is prefixed with a valid component, return that component and the section name. If it contains an invalid component, return 'main' and replace the '/' in the section with an underscore '_'. \n\nFor example: \n- If the input is 'non-free/python', the output should be ['non-free', 'python']. \n- If the input is 'invalid/section', the output should be ['main', 'invalid_section']. \n- If the input is 'python', the output should be ['main', 'python']. \n\nFunction Signature: `def parse_section(section: str) -> List[str]:`"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given an array of integers, implement a function `longestIncreasingSubsequence(arr)` that returns the length of the longest increasing subsequence in the array. An increasing subsequence is a sequence of numbers where each subsequent number is greater than the previous one. For example, the longest increasing subsequence of the array [10, 22, 9, 33, 21, 50, 41, 60] is [10, 22, 33, 50, 60], which has a length of 5."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a method within the Student class that counts how many Student instances have been created. Every time a Student object is initialized, the count should increment by one. Additionally, you should implement a class method that returns the total number of Student objects instantiated. Your implementation should only include this single function within the class framework provided below. \n\nclass Student:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n def get_total_students(cls):\n # Your implementation goes here"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function to determine the appropriate test script to call based on given command-line arguments and configuration settings. Write a function `select_test_script(sys_argv, config)` that takes a list of command-line arguments `sys_argv` and a list of configuration strings `config`. The function should return the name of the test script to call based on the following conditions: 1. If the command-line argument contains 'msvc', the function should return 'alltests_msvc.bat'. 2. If the command-line argument does not contain 'msvc', the function should return 'alltests_gcc.bat'. 3. If the configuration variable `config` at index 0 is equal to 'standalone_singleabi', the returned script name should be prefixed with 'standalone_'. 4. If none of the above conditions are met, the function should return 'test_all'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that simulates a query operation on a database. The function `execute_query` should accept a string parameter `query_string` which represents a SQL query and return a string indicating the status of the query execution. If the query string starts with 'SELECT', the function should return 'Query executed successfully'. For any other type of SQL command (like 'INSERT', 'UPDATE', 'DELETE'), the function should return 'Query execution failed'. Your implementation should handle leading and trailing whitespace in the query string. \n\nWrite the function signature: `def execute_query(query_string: str) -> str:`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a vote counting system for an event. You need to create a function `vote_counting(votes: List[Tuple[str, str]]) -> Dict[str, int]` where `votes` is a list of tuples. Each tuple contains a voting `option` (a string) and a `name` (a string) representing a vote for that option. Your function should return a dictionary where the keys are the voting options and the values are the counts of votes received for each option. If an option has no votes, it should not appear in the dictionary. Implement the function so that it processes the input list and counts the votes accordingly."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a trigonometric function defined as: h(x, y) = 3sin(x) + 4cos^2(y), implement a function that calculates the value of h for given inputs x and y. The function should take two parameters, x and y, which are floating-point numbers, and return the computed value of h(x, y)."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a dictionary representing genetic variant information. Each variant is represented as a dictionary that contains an 'INFO' key, which itself is a dictionary. Your task is to implement a function that retrieves the minor allele frequency (MAF) from the 'INFO' dictionary of the variant. If the 'MAF' key does not exist in the 'INFO' dictionary, return None. Implement the function `get_maf(variant: dict) -> float`. The input variant will always be a dictionary structured as follows: { 'INFO': { 'MAF': <float> or absent } }."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that finds the closest symbol to a given position in a text editor. The function takes in a list of tuples, where each tuple contains a region (represented as a pair of integers) and a symbol (a string). The region represents the start and end positions of the symbol in the text editor. Your goal is to find the symbol that is closest to a specified position in the text editor and return it. Assume that the input list of symbols is non-empty and that the position is within the range of the text editor. Implement the function with the following signature: `def find_closest_symbol(symbols: List[Tuple[Tuple[int, int], str]], position: int) -> str:`"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a nested list of integers `a`. Write a function `modify_list(a)` that modifies the list in place according to the following rules: for each element at position (i, j), if both i and j are greater than 0, replace the element with the value of the element at position (i-1, j-1). Otherwise, keep the element unchanged. The function should return the modified list. For example, given the input `a = [[1,2,2],[3,2,3],[3,4,1]]`, the output should be `[[1, 2, 2], [3, 1, 3], [3, 2, 1]]`. Please implement this function."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of integers representing the sales figures of a company for each month in a year. Your task is to write a function `calculate_quarterly_average(sales_data)` that takes in a list of 12 integers, where each integer represents the sales figure for a specific month (from January to December). The function should return a new list containing the average sales for each quarter. The quarters are defined as follows: Quarter 1 includes January, February, and March; Quarter 2 includes April, May, and June; Quarter 3 includes July, August, and September; and Quarter 4 includes October, November, and December. The average should be calculated using integer division. For example, given the input [1200, 1500, 1800, 2000, 2200, 2500, 2700, 3000, 3300, 3600, 3900, 4200], the function should return [1500, 2233, 3000, 3900]."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `create_book(title: str, author: str, publication_year: int) -> dict` that takes in the title, author, and publication year of a book and returns a dictionary representing the book with keys 'title', 'author', and 'publication_year'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function that converts a given decimal number to its ternary notation. The function should take a single integer parameter and return a string that represents the ternary (base-3) equivalent of the decimal number. If the input is 0, the function should return '0'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a 3x3 matrix represented as a list of lists, write a function `sum_rows_columns(matrix)` that calculates the sum of elements in each row and each column of the matrix. The function should return a dictionary with keys 'row_1', 'row_2', 'row_3', 'col_1', 'col_2', and 'col_3', where each key corresponds to the sum of the respective row or column. For example, for the input matrix [[1, 2, 3], [4, 5, 6], [7, 8, 9]], the function should return {'row_1': 6, 'row_2': 15, 'row_3': 24, 'col_1': 12, 'col_2': 15, 'col_3': 18}."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that performs a search on a list of strings. The function should take two parameters: a list of strings `items` and a string `query`. The function should return a list of strings that contain the `query` as a substring, case-insensitively. If the `query` is empty or if there are no matches, return an empty list. Implement the function `search_items(items: List[str], query: str) -> List[str]`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Define a function `create_animal(species: str, weight: float) -> dict` that takes a species as a string and a weight as a float and returns a dictionary representation of an animal with the keys 'species' and 'weight'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with developing a function that takes a list of form URLs as input and returns a list of unique forms extracted from these URLs. Each form URL is a string that may contain the same form multiple times, but the output list should contain each form only once. Implement the function `get_unique_forms(form_urls: List[str]) -> List[str]`, which receives a list of strings and returns a list of unique form URLs. The order of the unique forms in the output list should match the first occurrence in the input list. You can assume that the input list will not be empty and will only contain valid URLs."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a 2D array (list of lists) representing an arena with different shapes denoted by integers. Your task is to implement a function `assign_shape(extent, x_pos, y_pos)` that takes in the extent (a floating-point number), and the coordinates (x_pos and y_pos) of a position in the arena. The function should assign a number to the specified position based on the value of `extent`: if `extent` is less than 0.8, the position should be assigned a value of 3 (indicating a circle); if `extent` is greater than or equal to 0.8, the position should be assigned a value of 4 (indicating a square). The function should return the assigned number."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that takes in a dictionary of parameters for a clustering algorithm. The function should validate the parameters to ensure that they meet certain criteria. Specifically, the parameter dictionary must contain a key 'n_clusters' with a value greater than 0. Additionally, if the dictionary contains a key 'max_iter', its value must be a positive integer. If these conditions are not met, the function should raise a ValueError with a specific error message. Implement the function `validate_clustering_params(params: dict) -> None:` which raises a ValueError with the message 'Invalid parameter: n_clusters must be greater than 0' if 'n_clusters' is not greater than 0, and 'Invalid parameter: max_iter must be a positive integer' if 'max_iter' is present but not a positive integer."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with validating configuration settings for a bot application. You need to implement a function called `validate_bot_config` that checks if the provided configuration settings are valid. The configuration settings will be passed as parameters to the function. The parameters are as follows: \n- `API_ID`: an integer representing the API ID for the bot. It should not be equal to 123. \n- `API_HASH`: a string representing the API hash for the bot. It should not be an empty string. \n- `BOT_TOKEN`: a string representing the bot token. It should not be an empty string. \n- `STATUS_UPDATE_CHANNEL_ID`: an integer representing the channel ID for status updates. It should not be equal to -100. \n\nThe function should return `True` if all settings are valid, otherwise it should raise a `ValueError` with an appropriate error message indicating which setting is invalid or missing."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a string, implement a function that returns the first three unique alphabetic characters found in the string. The function should treat uppercase and lowercase letters as equivalent and ignore any non-alphabetic characters. If there are fewer than three unique alphabetic characters, the function should return all unique characters found in the order they appear. Implement this in a function with the signature: `def first_three_unique_chars(input_string: str) -> str`. For example, given the input string 'Hello, World!', the function should return 'Hel' as the first three unique characters are 'H', 'e', and 'l'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given an array of integers, implement a function `length_of_LIS(nums)` that returns the length of the longest increasing subsequence in the array. An increasing subsequence is a sequence of numbers where each number is greater than the previous one. If the array is empty, the function should return 0."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `calculate_total_cost(cart_items: List[Dict[str, Union[str, float]]]) -> float` that takes a list of shopping cart items, where each item is represented as a dictionary containing the item's name and price. The function should return the total cost of all items in the cart. Each item in the list has the structure: {'name': 'item_name', 'price': item_price}. If the list is empty, the function should return 0."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that determines the version of a software plugin given its module name as a string. The function should check if the module can be imported and return the module's version if it exists, otherwise return None. Implement the function `get_plugin_version(module_name: str) -> Optional[str]`. The version of the module can be accessed via the `__version__` attribute. If the module cannot be imported or the attribute does not exist, return None. Note that the version should be a string, and if the module does not have a version, return None. Your implementation should handle the cases where the module does not exist gracefully."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given an array of integers, write a function that returns the number of distinct integers present in the array. For example, in the array [14, 12, 13, 11, 15], the function should return 5 because all numbers are distinct."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `create_object()` that initializes an object with three attributes: `attribute1`, `attribute2`, and `attribute3`. The function should return a dictionary containing these attributes, initialized to `None`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `calculate_area` that calculates the area of a specified shape based on input parameters. The function should take in the following parameters: \n- `shape` (string): Represents the shape for which the area needs to be calculated. It can be either 'rectangle' or 'circle'. \n- `width` (float): Represents the width of the rectangle or the diameter of the circle. \n- `height` (float, optional): Represents the height of the rectangle. This parameter is only applicable when calculating the area of a rectangle. \n\nThe function should return the area of the specified shape. For a rectangle, the area is calculated as `width * height`, and for a circle, the area is calculated as `π * (diameter/2)^2`. If an invalid shape is provided or if height is not provided for rectangle, the function should raise a ValueError."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that processes a simulated response from a web request. The function should take a dictionary that simulates the response object and return the appropriate type based on the response properties. The response may contain the following properties: 'status_code', 'request', 'headers', and 'text'. Your function should behave as follows:\n\n- If the 'status_code' is 200 and the 'Content-Type' in the headers is 'application/json', return the parsed JSON content from the response.\n- If the 'status_code' is 204, return None.\n- If the 'status_code' is 400, 401, 404, or 422, raise a custom exception with relevant error messages. The error messages should be based on the 'status_code' and any additional information provided in the response.\n- For any other status codes, the function should raise an HTTPError.\n\nImplement the function `process_response(response: dict) -> dict or str or None` that takes a response dictionary as input and returns the appropriate output based on the above rules."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a string, implement a function `string_analysis(s: str) -> Tuple[int, bool, str]` that returns a tuple containing the count of vowels in the string, a boolean indicating if the string is a palindrome, and the reversed version of the string. The function should handle empty strings and can contain any combination of lower and upper case letters."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of strings representing the names of news providers that a user is subscribed to, implement a function `delete_news_site(news_sites: List[str], news_name: str) -> List[str]` that removes the specified `news_name` from the list. If the `news_name` is not found in the list, return the original list unchanged. The function should return the updated list of news providers after the removal operation. If the list is empty, it should return an empty list."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a URL routing system for a web application. Your job is to create a function that takes a URL as input and returns the name of the view function that matches the given URL based on predefined URL patterns. The URL patterns are defined using regular expressions and capture certain parameters from the URL. If no pattern matches, the function should return 'Not Found'. The URL patterns are as follows: \n1. Matches '/appleupdate/<serial>' returns 'appleupdate'. \n2. Matches '/raw/<serial>' returns 'raw'. \n3. Matches '/submit/<submission_type>' returns 'submit'. \n4. Matches '/warranty/<serial>' returns 'warranty'. \n5. Matches '/ip' returns 'lookup_ip'. \n6. Matches '<submission_type>' returns 'submit'.\n\nFunction Signature: `def match_url(url: str) -> str`.\n\nInput:\n- `url` (1 <= len(url) <= 100): A string representing the URL to be matched.\n\nOutput:\n- Return the name of the view function that matches the given URL."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of users represented by their usernames, implement a function that returns a list of unique usernames sorted in alphabetical order. Each username is a string and the function should ensure that there are no duplicates in the final list. The input will be a list of strings where each string represents a username. The output should be a list of unique usernames sorted in ascending order."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that takes a word and a list of its pronunciations, and yields pairs of the word and its corresponding pronunciations. The function should handle the case where the number of pronunciations may be less than, equal to, or greater than 5. If there are fewer than 5 pronunciations, the function should yield 'Not Available' for the remaining pairs. If there are more than 5 pronunciations, the function should only yield the first 5 pairs. Your function should return an iterator of tuples, where each tuple contains a word and its pronunciation. Please implement the function `generate_word_pronunciations(word: str, pronunciations: List[str]) -> Iterator[Tuple[str, str]]`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a job schema validator. A job schema is defined by a name and a list of required fields it must contain. Your goal is to write a function `validate_job_schema(schema_name: str, schema_fields: List[str], data: Dict[str, Any]) -> bool` that takes three parameters: a string `schema_name` representing the name of the job schema, a list of strings `schema_fields` representing the required fields, and a dictionary `data` representing the job data. The function should return `True` if the `data` contains all the fields defined in `schema_fields`, and `False` otherwise. The function should not consider any fields in `data` that are not defined in `schema_fields`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that retrieves all the values from a specific column in a given dataset. The dataset is represented as a list of dictionaries, where each dictionary contains key-value pairs corresponding to column names and their respective row values. Your function should accept the dataset and a column name as input, and return a list of values for that column. If the specified column name is not found in the dataset, the function should raise a KeyError with an appropriate error message. Write a single function named `get_column_values` that takes two parameters: `data` (a list of dictionaries) and `column_name` (a string)."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function called `merge_sorted_arrays` that takes two sorted lists of integers and merges them into a single sorted list. The function should maintain the order of elements from the original lists. Write a function that accepts two lists of integers and returns a merged sorted list. Both input lists may contain duplicate values. You can assume that the input lists will be non-empty."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `is_happy(s: str) -> Union[bool, str]` that determines if a given string `s` is 'happy'. A string is considered 'happy' if it meets the following criteria: 1. It contains only lowercase alphabets, 2. Its length is at least 3, 3. No three consecutive characters are the same, and 4. The count of any character that appears an odd number of times is zero, and the count of characters that appear an even number of times is at most three. If the string contains invalid characters or is less than 3 characters long, return the message 'Error: Invalid Input. Please enter only lowercase alphabets.'"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with writing a function that generates commands to configure a Virtual Routing and Forwarding (VRF) instance. The function should accept a list of VRF names and a configuration action ('add' or 'delete'). Based on the action, it should return a list of command strings to either add or delete the specified VRF instances. If the action is 'add', the command format should be 'sudo config vrf add <VRF-name>'. If the action is 'delete', the command format should be 'sudo config vrf del <VRF-name>'. If the input list of VRF names is empty, return an empty list. Your function should be named `generate_vrf_commands` and have the following signature: `def generate_vrf_commands(vrf_names: List[str], action: str) -> List[str]:`"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that takes a list of strings as input and cleans up the names in the list according to a predefined mapping. The mapping is as follows: 'str' -> 'string', 'bool' -> 'boolean', 'int' -> 'integer'. Your function should return a new list where all occurrences of these names are replaced according to the mapping. If a name does not match any of the keys in the mapping, it should remain unchanged. Implement the function `clean_type_names(type_names: List[str]) -> List[str]` that performs this task.\n\n### Input\n- A list of strings `type_names` (1 <= len(type_names) <= 100), where each string is a name to be cleaned up.\n\n### Output\n- A new list of strings with the cleaned type names according to the predefined mapping."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of tasks, where each task is represented as a dictionary with the keys 'name', 'author', and 'completed'. Write a function `get_task_by_id(tasks: List[Dict[str, Union[str, bool]]], task_id: int) -> Dict[str, Union[str, bool]]` that retrieves a task from the list using its index (task_id) and returns the task as a dictionary. If the task_id is out of range, return an empty dictionary. The `tasks` list is guaranteed to contain at least one task. Each task is guaranteed to have the keys 'name', 'author', and 'completed'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that translates a given text message from English to emoji language. The emoji language is represented by a dictionary where English words or phrases are mapped to their corresponding emoji symbols. Implement a function `translate_to_emoji(input_str: str, emoji_dict: dict) -> str` that takes a string input in English and a dictionary of emoji mappings. The function should translate the input string to emoji language using the provided dictionary. If a word or phrase in the input does not have a corresponding emoji in the dictionary, it should remain unchanged in the output. Note that the translation should be case-insensitive. The function should return the translated string. For example, given the dictionary `emoji_dict = {'hello': '👋', 'world': '🌍'}` and the input string `Hello, world!`, the output should be `👋, 🌍!`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that simulates a simple messaging service. The function `message_service(messages)` takes a list of messages, where each message is represented as a dictionary with the keys 'sender', 'receiver', and 'message'. Your task is to return a dictionary that maps each user to a list of messages they have received. Each user should have their own entry in the dictionary, and the messages should be in the order they were received. If a user has not received any messages, they should not appear in the output dictionary. \n\nFunction Signature: `def message_service(messages: List[Dict[str, str]]) -> Dict[str, List[str]]:`"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `math_operations` that accepts two integers `int1` and `int2` and returns a dictionary containing the results of the following operations: addition, subtraction, multiplication, division (as a float), and modulo. If `int2` is zero, the division result should be 'undefined' instead of a float. The function should return the dictionary with keys 'addition', 'subtraction', 'multiplication', 'division', and 'modulo'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that checks if a given URL can be correctly reversed based on a predefined mapping of URL names to their corresponding paths. Write a function called `reverse_url` that takes a single argument `url_name`, a string representing the name of the URL, and returns the corresponding path as a string. If the URL name does not exist in the predefined mapping, the function should return None. The predefined mapping is as follows: 'plok:blog_list' -> '/list/', 'plok:post_detail' -> '/post/<int:id>/', and 'plok:about' -> '/about/'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function `exponential_backoff(max_retries: int, initial_delay_sec: float, delay_growth_factor: float, max_delay_sec: float) -> List[float]`. This function simulates a retry mechanism for a process that fails, where the wait time between retries increases exponentially based on the initial delay and growth factor. The function should return a list of delay times for each retry attempt until the maximum number of retries is reached. The delays should be calculated as follows: the first delay is `initial_delay_sec`, and each subsequent delay is calculated as `previous_delay * delay_growth_factor`, capped at `max_delay_sec`. If `max_retries` is 0, return an empty list. Constraints: `max_retries` (0 <= max_retries <= 100), `initial_delay_sec` (0 < initial_delay_sec <= 60), `delay_growth_factor` (1.0 < delay_growth_factor <= 5.0), `max_delay_sec` (0 < max_delay_sec <= 120)."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of file names and a search pattern in the form of a string that may contain a wildcard character '*'. Your task is to implement a function that returns a set of file names that match the given pattern. The wildcard character '*' can represent zero or more characters in the file names. You need to consider the following: 1. The search pattern will always contain one '*' character; 2. The list of file names will only contain valid strings without any special characters other than the file extension. Implement the function `match_files(file_names: List[str], pattern: str) -> Set[str]` where `file_names` is a list of strings representing the file names and `pattern` is a string containing the search pattern. The output should be a set of matched file names."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that simulates the processing of an image by an external command-line tool. The function should take two string parameters: an input image path and an output image path. Instead of actually processing the image, the function will simply return a success message indicating that the image has been processed and saved to the output path. You can assume that the function will always receive valid input paths. Implement the function `process_image(input_image_path: str, output_image_path: str) -> str` that returns a message in the format: 'Processed image from {input_image_path} and saved to {output_image_path}'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function `read_dictionary_data(raw_bytes: bytes, num_values: int, converted_type: Optional[str]) -> List[Any]`. This function takes in three parameters: a byte string `raw_bytes`, an integer `num_values`, and an optional string `converted_type`. The function should decode the `raw_bytes` into a list of values. If `converted_type` is provided and not None, the function should convert the values accordingly. Otherwise, it should return the values as they are. The conversion process will be simplified for this task by assuming that if `converted_type` is 'int', each byte in `raw_bytes` corresponds to an integer value; if it is 'str', each byte corresponds to a string value derived from the bytes. If `converted_type` is None, return the values directly as a list of integers. The function should return a list of decoded values based on the input parameters."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `flatten_and_sort(nested_list)` that takes a nested list, potentially containing integers and non-integer elements, and returns a sorted list of all the integers found within the nested structure. The function should handle varying depths of sublists and filter out any non-integer elements. For example, given the input `nested_list = [[1, [2, 3], 'a'], [4, [5, 6, ['b', 7]]], [8, 'c', [9, 10]]]`, the output should be `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a tuple of area codes and a tuple of places associated with those area codes. Your task is to implement a function that takes in a tuple of area codes and returns a tuple of states corresponding to those area codes. If an area code does not exist in the provided area codes, return 'BAD AREA CODE' for that entry. The function should handle multiple area codes and return the results in the same order as the input. Write a function `get_states(area_codes)` that performs this task. \n\nExample: \nIf the input is `area_codes = ('123', '456', '789')` and `all_areacodes = ('123', '456', '111')` with `all_places = ('California', 'Texas', 'Florida')`, the output should be `('California', 'Texas', 'BAD AREA CODE')`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of anchors represented as rectangles in the format [x1, y1, x2, y2], where (x1, y1) is the top-left corner and (x2, y2) is the bottom-right corner. Write a function `shift_anchors(anchors: List[List[int]], direction: str) -> List[List[int]]` that shifts these anchors in the specified direction. The direction can be one of the following: 'center', 'top', 'bottom', 'left', or 'right'. If the direction is 'center', the anchors should remain unchanged. For 'top', the anchors should shift upwards by half of their height. For 'bottom', they should shift downwards by half of their height. For 'left', they should shift left by half of their width, and for 'right', they should shift right by half of their width. The function should return a new list of anchors after applying the shift. Ensure that the function does not modify the input list directly."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that simulates waiting for a user event based on a given mask. The function should take an integer mask, an optional key represented as a string, an optional mouse position represented as a tuple of (x, y) coordinates, and a boolean indicating whether to clear the event buffer before waiting. The function should return an integer based on the provided mask, and if the key or mouse parameters are provided, they should influence the return value. Specifically, return 1 if the key is not None, return 2 if the mouse coordinates are provided, and return 3 if flush is True and no other events are triggered. Otherwise, return 0. Implement the function with the signature `def wait_event(mask: int, key: Optional[str], mouse: Optional[Tuple[int, int]], flush: bool) -> int:`"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `check_anagram(string1: str, string2: str) -> bool` that determines if two distinct strings are anagrams of each other. An anagram is defined as a rearrangement of the letters of one string to form another string. The function should not use any built-in Python functions for sorting or comparison. You may assume both strings contain only lowercase letters and are non-empty."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of monthly temperature readings and a corresponding list of monthly precipitation readings for a specific region. Your task is to calculate the average temperature and total precipitation for the months where the temperature is above a certain threshold. Implement a function `calculate_average_and_total(temperature_list: List[float], precipitation_list: List[float], threshold: float) -> Tuple[float, float]` that returns a tuple containing the average temperature and total precipitation for the months where the temperature is greater than the threshold. If no months meet the criteria, return (0.0, 0.0)."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a specific number of students in a class and the ratio of boys to girls in the form of a string (for example, '3:4'), write a Python function `calculate_students(total_students: int, ratio: str) -> List[int]` that calculates the number of boys and girls in the class based on the provided ratio. The function should return a list containing the number of boys and girls respectively. If the ratio is invalid or the total number of students is less than 1, your function should return an empty list."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Create a function that takes a list of strings and/or nested lists of strings up to N levels deep and returns a single list containing all the strings in a flattened format. Ensure that the function can handle errors and edge cases correctly. If the input is not a list, or if the list contains elements that are neither strings nor lists, the function should raise a ValueError."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of integers representing the heights of columns in a histogram. Write a function `max_rectangle_area(heights: List[int]) -> int` that calculates the area of the largest rectangle that can be formed in the histogram. The rectangle must be formed by contiguous columns, and its height is determined by the shortest column in that range. The function should return the maximum area of such a rectangle."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that processes a list of product dictionaries and extracts specific information about each product. Each product dictionary contains details about a particular product, and your function needs to extract and store relevant details in a result dictionary for easy access. You are given a list of product dictionaries, where each dictionary has the following structure: { 'product_name': 'Example Product', 'price': 99.99, 'availability': true }. Your task is to implement a function called `extract_product_info` that takes a list of these product dictionaries and returns a dictionary where the keys are the product names and the values are dictionaries containing the price and availability of each product. The function should return an empty dictionary if the input list is empty."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that calculates the total number of frames in a cycle based on the frames in one cycle and how many times all the other frames of the cycle repeat. Write a function `calculate_total_frames` that takes in two parameters: `frames_in_cycle` (integer): the number of frames in one cycle, and `other` (optional integer): how many times all the other frames of a cycle repeat. The default value for `other` is 1 if not provided. The function should return the total number of frames in the cycle, which is calculated as the sum of `frames_in_cycle` and the product of `frames_in_cycle` and `other`. For example, if `frames_in_cycle` is 10 and `other` is 3, the total number of frames in the cycle would be calculated as 10 + (10 * 3) = 40."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that simulates a simple context creation process. The function `create_context(policy: str, name: str) -> str` takes two parameters: a policy (a string describing the policy) and a name (a string representing the context name). The function should return a string that describes the created context in the format 'Context created with policy: [policy] and name: [name]'. If the name is an empty string, the function should raise a ValueError with the message 'Context name cannot be empty.'. Please implement this function."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given two strings, `corpus` and `directory`. Your task is to create a function `copy_files(corpus: str, directory: str) -> List[str]` that simulates copying all characters from the `corpus` string into a new string `directory`. The `directory` string should contain all characters from `corpus`, and if the same character appears multiple times in `corpus`, it should also appear the same number of times in `directory`. The function should return a list where each element is a character from the `directory` string. \n\nFor example, if `corpus` is 'abc' and `directory` is 'xyz', the output should be ['a', 'b', 'c'] since it copies the characters from `corpus`, ignoring the `directory` string's initial content. \n\nFunction Signature: `def copy_files(corpus: str, directory: str) -> List[str]:`"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of summoner spell names represented as strings. Your task is to implement a function that returns a new list containing only the names of the summoner spells that start with the letter 'F'. The function should preserve the order of the spells from the input list. If no spells start with 'F', return an empty list. Write a function signature as follows: `def filter_f_spells(spells: List[str]) -> List[str]:` where `spells` is the input list of summoner spell names. "}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that initializes a configuration object for an application. The function should accept the following parameters: `name` (a string representing the application name), `host` (a string representing the host address), `port` (an integer representing the port number), `tls` (a boolean indicating whether TLS is enabled), `username` (a string for the username), and `password` (a string for the password). The function should return a dictionary containing these parameters as key-value pairs. Implement a function `initialize_app(name: str, host: str, port: int, tls: bool, username: str, password: str) -> dict`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that generates a specific string format based on two input parameters: location_id and conversation_id. The function should take in a list of two integers, where the first integer represents the location_id and the second integer represents the conversation_id. The function should return a string in the following format: 'set convo_hidden_{location_id}_{conversation_id} false'. Implement a function named 'generate_conversation_string' that takes a list of two integers and returns the formatted string."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that formats a price given as a decimal number into a string representation with a maximum of 10 digits, including 2 decimal places. The function should take a single parameter, `price`, which is a decimal number. If the input exceeds the maximum of 10 digits or cannot be represented with 2 decimal places, return 'Invalid price'. Otherwise, return the price formatted as a string with two decimal places. Write the function `format_price(price: Decimal) -> str:` to achieve this."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of summoner data and a profile name. Each summoner in the list is represented as a dictionary containing the following keys: 'profileIconId' (an integer), 'summonerLevel' (an integer), and 'duration' (an integer representing playtime for matches). Your task is to implement a function `generate_summoner_summary(summoners: List[Dict[str, Union[int, str]]], profile_name: str) -> Dict[str, Union[str, int]]` that returns a summary of the summoner's profile. The summary should include: 1) 'profileIconPath' - a string that represents the profile icon path based on the 'profileIconId', 2) 'name' - the given profile name, 3) 'level' - the total summoner level, which is the sum of all summoner levels in the input, and 4) 'Playtime' - the total playtime which is the sum of all match durations associated with the summoner. The profile icon path can be represented as \"path/to/icon/\" + str(profileIconId). If there are no summoners in the list, return an empty dictionary."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that evaluates the value of an integer variable, \"M\", and returns a specific message based on its value. Your function should take a single integer parameter, \"M\", and return the following messages: \n- If \"M\" is less than 10, return \"Value of M is too small\". \n- If \"M\" is between 10 and 20 (inclusive), return \"Value of M is just right\". \n- If \"M\" is greater than 20, return \"Value of M is too large\". \n\nImplement the function `evaluate_m(m: int) -> str` that adheres to the above requirements."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given two matrices A and B, both of dimensions m x n, write a function `compare_matrices(A: List[List[int]], B: List[List[int]]) -> bool` that checks if the two matrices are equal. Two matrices are considered equal if they have the same dimensions and all corresponding elements are equal. The function should return True if the matrices are equal, and False otherwise."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with generating a sequence based on a third-order linear recurrence relation. Given the first three terms of the sequence, a0, a1, and a2, and the coefficients a3, a4, and a5, your goal is to implement a function that returns the n-th term of the sequence. The sequence is defined as follows: a(0) = a0, a(1) = a1, a(2) = a2, and for n >= 3, a(n) = a3*a(n-1) + a4*a(n-2) + a5*a(n-3). Write a function `nth_term(a0: int, a1: int, a2: int, a3: int, a4: int, a5: int, n: int) -> int` that returns the n-th term of the sequence."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a unique identifier for a switch, represented as an integer, and a boolean flag indicating whether to raise an exception when the switch is missing. Your task is to implement a function `get_switch_status(switch_id: int, exception_when_missing: bool) -> str` that retrieves the status of the switch. If the switch exists, return 'active' or 'inactive' based on its status. If the switch does not exist and `exception_when_missing` is True, raise a ValueError with the message 'Switch not found'. If the switch does not exist and `exception_when_missing` is False, return 'switch not found'. The status of the switches is as follows: Switch ID 1 is 'active', Switch ID 2 is 'inactive', and Switch ID 3 is 'active'. Any other switch ID is considered missing."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a simple function that simulates the behavior of a GUI application with two buttons: \"OK\" and \"Cancel\". The function should take two boolean parameters, `ok_clicked` and `cancel_clicked`, which represent whether the \"OK\" button or the \"Cancel\" button was clicked, respectively. Based on the values of these parameters, your function should return a specific string: \\n- If `ok_clicked` is True and `cancel_clicked` is False, return the string \"OK clicked\". \\n- If `ok_clicked` is False and `cancel_clicked` is True, return the string \"Cancel clicked\". \\n- If both are False, return the string \"No action\". \\nImplement the function `get_action(ok_clicked: bool, cancel_clicked: bool) -> str` that fulfills the specified conditions."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that constructs a URL based on a given endpoint and an object type. The function should accept two parameters: an endpoint (a string) and an object type (a string). It should return a formatted URL string in the form: '{endpoint}/{object_type}'. Write a function 'create_url' that implements this behavior."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of questions for an exam, where each question has a score associated with it. You also have a list of submitted choices, which indicates whether a question was answered correctly or not. Your task is to implement a function `calculate_exam_grade(questions: List[Tuple[int, bool]]) -> int` that calculates the grade of the exam as a percentage. Each question is represented as a tuple containing two elements: the first element is the score of the question (a positive integer), and the second element is a boolean indicating whether the answer was correct (True) or incorrect (False). The function should return the grade as an integer percentage. If there are no questions, return 0%."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function called `is_prime(n)` that determines if a given integer `n` is a prime number. A prime number is defined as a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. Your function should return `True` if `n` is prime, and `False` otherwise. The function should handle negative numbers and zero appropriately, returning `False` for any non-positive integers."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that processes a string representing an edition indicator. Your function should take a string input, and if the string contains the substring 'ed.', it should return the string with 'ed.' removed. If the substring 'ed.' is not present in the string, your function should return an error message 'IgnoreKey'. Write a function `process_edition(edition_str: str) -> str` that implements this logic. The input will always be a single string."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a dictionary representing a geographical site, implement a function `get_lat_lng(site)` that retrieves the latitude and longitude of the site from the 'org_coordinates' key. The function should return a tuple of (latitude, longitude) if the 'org_coordinates' key is present and contains the keys 'lat' and 'lon'. If 'org_coordinates' is missing or does not contain these keys, return None. The input will be a dictionary with potentially nested keys. Your function should handle the input gracefully without throwing an error. Example input: {'org_coordinates': {'lat': 34.0522, 'lon': -118.2437}} should return (34.0522, -118.2437)."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function that merges two nested dictionaries. The function should recursively combine the dictionaries such that if a key exists in both dictionaries and its value is a dictionary in both cases, the values should be merged. If the value is not a dictionary in one of them, the value from the second dictionary should overwrite the value from the first dictionary. If a key exists in only one dictionary, it should be included in the result. The function should take two dictionaries as input and return the merged dictionary."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function named `validate_recovery` that takes three parameters: `file_a_size` (an integer representing the size of the first file), `file_b_size` (an integer representing the size of the second file), and `recovered_state` (a string representing the state of the recovered data object). Your function should return a boolean value: True if both files have non-zero sizes and the recovered state is 'second'; otherwise, return False. Implement the function without any class or external dependency."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function `format_message(message: str) -> str` that formats a given message by prepending a predefined hostname '[MyHost]' to it. The function should return the formatted message. For example, if the input message is 'Hello, World!', the output should be '[MyHost] Hello, World!'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that calculates the number of snapshots with the same hash and the number of lost snapshots from a list of file snapshots. Each snapshot can be represented by its relative path, modification time, file size, and an optional hash value. Given a list of tuples, where each tuple contains the relative path, modification time, file size, and an optional hash value (or None if the snapshot is lost), implement a function `get_snapshot_counts(snapshot_list: List[Tuple[str, int, int, Optional[str]]]) -> Tuple[int, int]` that returns a tuple containing the number of snapshots with the same hash and the number of lost snapshots. A snapshot is considered 'lost' if its hash value is None."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of sentences and a list of character names. Your task is to implement a function that returns a dictionary where each key is a character name and the corresponding value is a list of sentences that contain that character's name. The comparison should be case-insensitive and only whole words should be matched (i.e., 'John' should match 'John' but not 'Johnson'). Implement the function `compare_character_sentences(sentenceList: List[str], majorCharacters: List[str]) -> Dict[str, List[str]]`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of sentences, write a function `get_vocabulary(sentences: List[str]) -> Tuple[List[str], Dict[str, int]]` that computes the vocabulary of the provided sentences. The function should return a tuple containing two elements: a sorted list of unique words in descending order of their frequency and a dictionary that maps each word to its count in the sentences. Words are defined as sequences of alphabetic characters and should be case-insensitive. For example, 'Hello' and 'hello' should be considered the same word. Ignore any punctuation or whitespace. The output list should only contain unique words sorted by their frequency, with ties broken by the order they first appeared in the sentences."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that simulates a simple decision-making process based on user input. The function should take a string input that represents the user's choice to either continue with a predefined action or to initiate a new action. The function should return a message based on the user's input. If the input is 'Y' or 'y', the function should return 'Starting the data scrapping process...'. If the input is 'N' or 'n', it should return 'Exiting the process.'. For any other input, the function should return 'Invalid input. Please enter Y or N.'. Implement the function `process_decision(user_input: str) -> str`, where `user_input` is the input string from the user."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given two integer arrays A and B, your task is to implement a function that returns the maximum number of uncrossed lines that can be drawn between the two arrays. A line can be drawn between A[i] and B[j] if A[i] == B[j], and the lines must not intersect. Each number from both arrays can only be part of one line. Implement the function `maxUncrossedLines(A: List[int], B: List[int]) -> int`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with writing a function that takes a file name as input and simulates loading a database dump from that file. The function should return a string indicating the success or failure of the operation. If the file name ends with '.sql', return 'Database dump loaded successfully.' If the file name does not end with '.sql', return 'Invalid file type. Please provide a SQL dump file.' Write a function named `load_database_dump` that implements this behavior."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of integers, implement a function that returns a new list containing only the unique elements from the original list while preserving the original order. The function should take one parameter, a list of integers, and return a list of integers. For example, if the input list is [1, 2, 2, 3, 4, 4, 5], the output should be [1, 2, 3, 4, 5]."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a value, implement a function `template_check` that checks if the value is a string that equals 'true' (case-insensitive). If the value is a string, return `True` if it equals 'true' (case insensitive), otherwise return `False`. If the value is not a string, return the value as is. For instance, `template_check('True')` should return `True`, and `template_check('false')` should return `False`. If the input is an integer, like `template_check(1)`, it should return `1`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that takes a dictionary of integers and a multiplier as input. The function should return a new dictionary where each value in the original dictionary is multiplied by the given multiplier. If the input dictionary is empty or None, the function should return an empty dictionary. Implement the function 'multiply_values(dictionary: dict, num: int) -> dict'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that checks for overlap between two rectangles in a 2D space. The function takes in the positions and dimensions of the two rectangles and returns a boolean value indicating whether the rectangles overlap or not. The function signature is as follows: `def check_overlap(position1, dim1, position2, dim2):`. Where `position1` and `position2` are tuples representing the (x, y) coordinates of the top-left corner of each rectangle. `dim1` and `dim2` are tuples representing the (width, height) dimensions of each rectangle. The function should return `True` if any part of the two rectangles overlap; otherwise, it should return `False`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of integers and decimals, implement a function that returns the list in a surprising arrangement. The surprising arrangement should obey these instructions: Begin with the greatest value, followed by the smallest among the rest, and continue this pattern by alternating between the next greatest and the next smallest numbers that have not been added to the output. Your function must manage occurrences of 'None' values by excluding them from the final result. Implement the function as follows: \n\ndef alternative_max_min(lst): \n pass\n\nExamples:\n- alternative_max_min([1, 2, 3, 4]) should return [4, 1, 3, 2]\n- alternative_max_min([5, 5, 5, 5]) should return [5, 5, 5, 5]\n- alternative_max_min([]) should return []\n- alternative_max_min([-2, 1.5, 3.5, -1]) should return [3.5, -2, 1.5, -1]\n- alternative_max_min([None, 2, 3.7, -1]) should return [3.7, -1, 2]"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function that takes a list of video titles and a search keyword, and returns a list of titles that contain the keyword (case insensitive). The function should be named `search_videos` and it should accept two parameters: a list of strings `titles` and a string `keyword`. The function should return a list of strings consisting of the matching titles."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given an array of integers, `nums`, and an array of `requests` where each request is represented as a pair of indices `[starti, endi]`, write a function that returns the maximum total product of all requests among all permutations of `nums`. The product of any two adjacent elements in the permutation should not exceed `10^5`, and the product of any two elements in the permutation should not exceed `10^6`. The result should be returned modulo `10^9 + 7`. Implement the function `max_product(nums: List[int], requests: List[List[int]]) -> int`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a custom function that serializes a dictionary representing an Airtable model. The Airtable model has four fields: 'base', 'table', 'category', and 'api_key'. Your function should take a dictionary with these four keys and return a serialized string in the format: \"base: <base>, table: <table>, category: <category>, api_key: <api_key>\". Implement a function named 'serialize_airtable' that performs this serialization. If any of the required fields are missing from the input dictionary, return an error message: 'Missing fields in input dictionary.'"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given two points in a 2D plane represented by their coordinates (x1, y1) and (x2, y2), write a function `calculate_distance(x1: float, y1: float, x2: float, y2: float) -> float` that calculates the Euclidean distance between the two points. The Euclidean distance is defined as the square root of the sum of the squared differences between the corresponding coordinates. The function should return the distance as a float, rounded to two decimal places."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function that performs the bubble sort algorithm on a given list of integers. The function should take a list as input and return a new sorted list in ascending order. The original list should remain unchanged."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Write a function `compare_strings` that takes two strings as input and returns a list of indices where the two strings differ. If the strings are of different lengths, the function should only compare up to the length of the shorter string. The comparison should be case-sensitive. The output should include the indices of differing characters as well as any indices in the longer string beyond the length of the shorter string. The function should handle empty strings appropriately."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `advanced_filter(lst)` that takes a list of integers `lst`, which may include negative numbers and zeros. The function should return a new sorted list containing only the even numbers that meet the following criteria: they must be located at non-prime indices, they must be divisible by 3 or 7, and they must have a prime number either preceding or following them in the list. The output list should be sorted in ascending order. \n\nExample:\n advanced_filter([2, 7, -14, 11, 13, 0, 30]) ==> [-14, 0]"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a simple interpreter error handling system. Your goal is to create a custom exception class called `UndefinedVariableError` that inherits from a base exception class called `InterpreterRuntimeError`. This exception should be raised when the interpreter encounters an undefined variable during the execution of a program. Additionally, implement a function called `interpret` that takes a dictionary of variables and a list of commands as input. The function should iterate through the list of commands and raise an `UndefinedVariableError` if it encounters a variable that is not present in the provided dictionary. The commands are expected to be in the format 'print variable_name'. If the variable is defined in the dictionary, the function should simply continue without raising an error. Please implement the `UndefinedVariableError` class and the `interpret` function according to the specified requirements."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that checks if a user exists based on their user ID from a list of user dictionaries. The function should take a list of user dictionaries and a user ID as parameters. Each user dictionary contains a 'userId' key. The function should return `True` if a user with the given user ID exists in the list, and `False` if it does not. Implement the function `check_user(users: List[Dict[str, int]], userId: int) -> bool:` where `users` is a list of user dictionaries and `userId` is the integer ID to check."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that simulates adding a file information entry with some default values. The function should accept a dictionary containing file attributes and update it with default values for 'updated_at', 'file_index', and 'id'. The 'path' attribute must be provided as a byte string. Implement the function `add_file_info(file_info: dict) -> dict` that accepts a dictionary of file attributes and returns a new dictionary that includes the original attributes along with the default values. If 'path' is not of type bytes, your function should raise a ValueError. The default values are: 'updated_at' = 0, 'file_index' = 0, and 'id' = 111. The function should return the updated dictionary containing all attributes."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a shape represented as a dictionary with a key 'lineWidth' that defines the width of the line associated with that shape. Write a function `applyLineWidth(shape: dict, lineWidth: float) -> None` that updates the 'lineWidth' of the provided shape dictionary with the given value. The function should not return anything. The shape dictionary will always have a 'lineWidth' key, which is a float. It is guaranteed that the input lineWidth will also be a float. Your task is to implement the function to update the dictionary in place."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of integers, write a function that returns the maximum sum of any contiguous subarray within the list. A contiguous subarray is defined as a sequence of elements that are consecutive in the array. You need to implement a single function `max_subarray_sum(arr: List[int]) -> int` that takes in a list of integers and outputs an integer representing the maximum sum of any contiguous subarray."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with generating a command string based on provided parameters. Write a function `generate_command_string` that accepts keyword arguments representing different parameters and constructs a command string in the following format: 'command --param1 value1 --param2 value2 ...'. If a parameter is not provided, it should not appear in the command string. The order of parameters in the command string should follow the order they are passed to the function. The function should return the final command string. For example, given the input parameters `param1='value1'` and `param2='value2'`, the output should be 'command --param1 value1 --param2 value2'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Write a function called `is_geometric_progression` that takes a list of numbers as input and returns a boolean indicating whether the numbers form a geometric progression. A sequence of numbers is said to be in geometric progression if the ratio between consecutive elements is constant. The function should return False if the list contains fewer than two elements."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that compares two version numbers represented as strings and determines which version is greater. The version numbers are in the format 'x.y.z', where x, y, and z are non-negative integers, and may also contain fewer than three segments (e.g., '1.0' is equivalent to '1.0.0'). The function should return 1 if the first version is greater, -1 if the second version is greater, and 0 if they are equal. Create a function called 'compare_versions(version1, version2)' where: - 'version1' and 'version2' are strings representing the version numbers to be compared. "}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function in Python that checks if two strings are anagrams of each other. The comparison should be case-insensitive and should consider special characters and numbers as well. The function should return True if the strings are anagrams, and False otherwise."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a string, write a function that counts the total number of palindromic substrings of all lengths in the string. A palindromic substring is a substring that reads the same forward and backward. The function should take a single string as input and return the count of all palindromic substrings."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `intersperse` that accepts a list of integers `numbers` and a single integer `delimiter`. The function should return a new list with the integer `delimiter` inserted between each pair of consecutive elements in `numbers`. If `delimiter` is negative, you should skip the absolute value of `delimiter` number of elements from the beginning of the list before performing the insertion. If the resulting list is empty, return an empty list."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a Python function that calculates the average score for a given set of students based on their performance in a series of tests. The function should take in a dictionary containing the test scores for each student and return a new dictionary with the average score for each student. Additionally, the function should allow for the option to specify the type of average to be calculated (e.g., mean, median, mode). The function signature should be: `def calculate_average_scores(scores, average_type='mean'):`. The `scores` parameter is a dictionary where the keys are the student names and the values are lists of test scores. The `average_type` parameter is a string specifying the type of average to be calculated and defaults to 'mean' if not specified."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a dictionary of constants where the keys are constant values and the values are their corresponding names as strings. Write a function `get_constant_name(constant_dict: Dict[int, str], value: int) -> str` that returns the name of the constant associated with the given value. If the value does not exist in the dictionary, return the string 'ERROR_CONSTANT_NAME_NOT_FOUND'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a positive integer n, write a function `find_divisors(n)` that returns a list of all unique numbers that divide evenly into n. The output list should be sorted in ascending order."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a program that simulates a simple game using a 5x5 grid. The game involves a player navigating through the grid to reach a goal while avoiding obstacles. The player's position and the goal position are represented by specific indices on the grid (for example, (0, 0) for the top-left corner). The obstacles are represented by their respective indices on the grid as well. The player can move up, down, left, or right within the grid, but cannot move through the obstacles. Implement a function `simulate_game(player_start, goal_position, obstacles)` that takes the player's starting position, the goal's position, and a list of obstacle positions as input. The function should return a string indicating the result of the game: 'Goal reached!' if the player reaches the goal, 'Game over - collided with an obstacle!' if the player collides with an obstacle, or 'Game in progress' if the player can continue to move. The function should simulate a single move based on a given direction (up, down, left, right) and update the player's position accordingly. You can assume the player starts at player_start, and the inputs are valid. The grid is defined as a 5x5 matrix with indices ranging from (0, 0) to (4, 4)."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a simple OAuth authentication mechanism. Your goal is to create a function named `oauth_response` that simulates the responses for different OAuth-related actions based on given parameters. The function should take the following parameters: \n- `action` (str): A string indicating the type of action. It can be one of the following: 'authorize', 'emailconfirm', 'bindsuccess', 'require_email', 'oauthlogin'. \n- `params` (dict): A dictionary containing parameters needed for the specified action. \n\nThe function should return a string response based on the action and parameters provided as follows: \n- If the action is 'authorize', return 'OAuth authorization view'. \n- If the action is 'emailconfirm', return 'Email confirmation for id {id} with sign {sign}', where 'id' and 'sign' are obtained from params. \n- If the action is 'bindsuccess', return 'OAuth binding success for id {oauthid}', where 'oauthid' is obtained from params. \n- If the action is 'require_email', return 'Require email view for id {oauthid}', where 'oauthid' is obtained from params. \n- If the action is 'oauthlogin', return 'OAuth login view'. \n\nIf the action is not recognized, return 'Invalid action'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that checks if a user has the necessary authorization headers based on their provided username and password. The function should accept three parameters: a URL (string), a username (string or None), and a password (string or None). If either the username or password is None, the function should return an empty dictionary indicating that no authorization is present. If both username and password are provided, the function should return a dictionary with a single key 'Authorization' and the value formatted as 'Basic <base64_encoded_credentials>', where '<base64_encoded_credentials>' is the base64 encoding of 'username:password'. Implement a function called `get_authorization_header(url: str, username: Optional[str], password: Optional[str]) -> Dict[str, str]`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "In a Python project utilizing the Django web framework, you need to update the way primary key fields are specified in your models due to a change in the framework. The previous primary key field was represented by a string, and you need to convert this string to a new format that specifies the usage of `BigAutoField`. Write a function `convert_to_new_auto_field(old_auto_field: str) -> str` that takes an old primary key field representation as input and returns the new format for specifying the primary key field. The new format should always use `BigAutoField` from the same module as the old field. For example, if the input is 'django.db.models.AutoField', the output should be 'from django.db.models import BigAutoField'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of integers representing the ages of a group of people. Write a function that takes this list and returns a new list containing only the ages that are greater than or equal to 18. The output list should maintain the original order of the ages. Implement the function `filter_adult_ages(ages: List[int]) -> List[int]:` where `ages` is a list of integers. For example, given the input `ages = [12, 18, 20, 15, 22, 30]`, the function should return `[18, 20, 22, 30]`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Write a function `factorial_array(input_array)` that takes an array of non-negative integers and returns a new array containing the factorial of each integer. If the input array contains any non-integer or negative values, the function should raise a `TypeError` with the message 'Input array should only contain non-negative integers.'"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that generates a random 32-bit integer. Your task is to implement the `generate_int32` function that takes no arguments and returns a 32-bit integer initialized with a non-string value. The generated integer must be within the range of a signed 32-bit integer (-2147483648 to 2147483647). Your function should return the initialized 32-bit integer."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function `create_api_app` that takes a dictionary `global_conf` and an arbitrary number of keyword arguments `local_conf`. The function should determine the API version from `global_conf` and return a dictionary of routes associated with their respective controllers based on the API version. The possible API versions are 'v2.0' and 'v3.0'. For 'v2.0', the function should return a dictionary with the route '/log/single' mapped to a string 'v2_logs.Logs()'. For 'v3.0', the function should return a dictionary with the route '/logs' mapped to a string 'v3_logs.Logs()'. If the API version is not recognized, return an empty dictionary. The function signature should be: `def create_api_app(global_conf: dict, **local_conf) -> dict:`"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of respondents' voting data from the 1992 U.S. Presidential election, implement a function that counts the number of respondents who voted for each candidate: Bill Clinton, George H.W. Bush, and Ross Perot. The input is a list of strings where each string represents the vote choice of a respondent (either 'Clinton', 'Bush', or 'Perot'). Your function should return a dictionary with the candidate names as keys and the respective counts as values. The dictionary should include all three candidates, even if a candidate received zero votes."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `encrypt_data(data: str) -> str` that encrypts the given string data using a simple substitution cipher, where each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. The function should take a string `data` as input and return the encrypted string. Assume that the input will only contain lowercase letters and spaces. Spaces should remain unchanged. For example, if the shift is 3, 'a' would be replaced by 'd', 'b' would become 'e', and so on. Wrap around to the beginning of the alphabet as needed (e.g., 'y' becomes 'b', 'z' becomes 'c')."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with processing a specific row name in an administrative statistics system. Your function should accept a string `row_name` which can only be one of the following three options: 'orioks_scheduled_requests', 'orioks_success_logins', or 'orioks_failed_logins'. If the provided `row_name` is valid, the function should return a success message in the format 'Row name {row_name} processed successfully.'. If the `row_name` is invalid, the function should raise a ValueError with the message 'Invalid row name. Must be one of: orioks_scheduled_requests, orioks_success_logins, orioks_failed_logins.'. Implement a function `process_row_name(row_name: str) -> str` that accomplishes this."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function `extract_metadata` that takes a string representing a range of commits and returns a list of metadata extracted from those commits. The metadata is represented as a dictionary with keys 'commit_id', 'author', and 'message'. Each commit in the string is separated by a newline character, and the fields are separated by a comma. For example, the input string 'abc123,John Doe,Fixed issue\\ndef456,Jane Smith,Added feature' should return a list containing two dictionaries: [{'commit_id': 'abc123', 'author': 'John Doe', 'message': 'Fixed issue'}, {'commit_id': 'def456', 'author': 'Jane Smith', 'message': 'Added feature'}]. If the input string is empty, return an empty list."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that retrieves constant values based on the input provided. The function should accept either a string or an integer as an argument. If the input is a string, it should return the corresponding constant value based on the uppercase version of the input string. If the input is an integer, it should return the constant value if it matches one of the predefined constants. If the input is of any other type or does not match any constant, the function should return None. The constants to be used are: 'NEAREST' which corresponds to 0, 'BILINEAR' which corresponds to 1, and 'BICUBIC' which corresponds to 2. Implement the function `get_interpolation_method(value)` that performs this task."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Design a function that assigns a specific value to a variable and validates it. Implement the function `assign_and_validate` which assigns a 16-bit binary string representation of the number `8` to the variable `my_binary`. The function should also include error handling to check if the assigned value correctly represents the number `8` in binary. If the assigned value does not correctly represent the number `8`, raise a ValueError."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that converts a given bytearray into a hexadecimal string representation. The function should take a bytearray as input and return a string where each byte is represented by its two-digit hexadecimal equivalent, concatenated together. For example, if the input is a bytearray containing the bytes [255, 16], the output should be the string 'ff10'. Write a function named 'bytearray_to_hex' that takes a bytearray as an argument and returns the corresponding hexadecimal string."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a string 's' consisting of characters 'a', 'b', and 'c', determine if the string can be represented in the form 'a^i b^j c^k' where i, j, k >= 0. This means that the string must start with zero or more 'a's, followed by zero or more 'b's, and end with zero or more 'c's. Implement a function `is_valid_format(s: str) -> bool` that returns True if the string follows this format, and False otherwise. For example, the string 'aaabbccc' is valid while 'abcabc' is not. The function should handle an empty string as invalid."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given an array of non-repeating integers, implement a function to find the 3rd largest number in the array without using any inbuilt sorting function. You may assume that the array will always have at least three elements."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that takes a list of integers and returns a new list containing only the even numbers from the original list, in the same order they appeared. Write a function named 'filter_even_numbers' that accepts a single parameter 'numbers', which is a list of integers, and returns a list of integers. If there are no even numbers, return an empty list."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a string, implement a function `replace_words(base_string: str, replacements: Dict[str, str]) -> str` that replaces all occurrences of words in the base string according to the provided replacements dictionary. The function should return the modified string without directly modifying the original string and without using any built-in replace functions. For example, if the input is `base_string` as 'Bye World' and `replacements` as {'Bye': 'Hello'}, the output should be 'Hello World'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a string `s` consisting of characters including parentheses '(', ')', and other characters, determine if the order of the parentheses is valid. A string of parentheses is considered valid if every opening parenthesis has a corresponding closing parenthesis and they are correctly nested. Return `True` if the string is valid and `False` otherwise. For example, in the string 'a(b)c', the parentheses are valid, while in 'a(b(c', they are not. The input string can be empty, but it should be handled accordingly. Please implement a function `valid_parentheses(s: str) -> bool`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Write a function `update_prices(documents: List[Dict[str, Union[str, bool]]]) -> List[Dict[str, Union[str, bool, int]]]` that takes a list of documents where each document is represented as a dictionary containing fields 'date' (as a string in the format 'YYYY-MM-DD'), 'is_discounted' (as a boolean), and 'price' (as an integer). The function should update the 'price' field to 200 for all documents where the 'date' field is older than 5 years from today and 'is_discounted' is false. The function should return the updated list of documents. If any error occurs during the process, it should handle the exception and return the original list of documents without any modifications."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function to generate a unique image name for a given image header, frame number, and file extension. The function should take in three parameters: `imgheader` (string), `frame` (integer), and `ext` (string). The function should return a formatted string that combines these parameters into a unique image name in the format `imgheader_frame.ext`. Additionally, the function should ensure that the generated image name is unique by checking against a provided dictionary of existing image names. If the generated image name already exists in the dictionary, you need to append a numeric suffix to make it unique. The suffix should start from 1 and be incremented until a unique name is created. Your task is to implement the function `form_imgname(imgheader, frame, ext, image_id_dict)` that returns a unique image name."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given two lists of integers, `list1` and `list2`, and a target integer `target`. Your task is to implement a function `find_pairs(list1: List[int], list2: List[int], target: int) -> List[Tuple[int, int]]` that returns all unique pairs of integers `(a, b)` such that `a` is from `list1`, `b` is from `list2`, and `a + b` equals `target`. Each pair should be represented as a tuple and the order of pairs in the output list does not matter. If no pairs are found, return an empty list."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of integers, write a function `compute_product(list_nums)` that computes the cumulative multiplication of all numbers in the list. The function should return the final product of the numbers. The input list will contain only positive integers."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that processes a list of integers and returns a new list containing only the unique elements from the original list in the order they first appeared. The function should handle both positive and negative integers and maintain the original order of the unique elements. Write a function `unique_elements(input_list)` that takes a list of integers `input_list` and returns a list of unique integers."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function to calculate the total area of rectangles in a 2D space. Each rectangle is represented by a tuple of four integers: (x1, y1, x2, y2), where (x1, y1) represents the coordinates of the bottom-left corner and (x2, y2) represents the coordinates of the top-right corner. Your function should take a list of rectangles as input and return the total area covered by all rectangles, assuming that they do not overlap. If two rectangles overlap, only the area of the outermost rectangle should be counted. Implement the function `calculate_total_area(rectangles)` that takes a list of rectangles as input and returns the total area of the rectangles accounting for overlaps. Example: For the input `rectangles = [(1, 1, 3, 3), (2, 2, 4, 4)]`, the total area is 7, as the area of the overlapping section is counted only once."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of strings, where each string represents a line of text. Each line may contain a JSON object or it may be an invalid JSON string. Your task is to write a function that processes this list and returns a new list containing either the parsed JSON object as a dictionary for valid JSON strings, or the string 'Invalid JSON' for lines that cannot be parsed. Implement the function `process_json_lines(input_data: List[str]) -> List[Union[dict, str]]` where `input_data` is a list of strings representing the input lines. The output should be a list of dictionaries or 'Invalid JSON' strings corresponding to the input lines."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of integers representing the heights of buildings in a city skyline. Your task is to implement a function `generate_skyline(heights: List[int]) -> List[Tuple[int, int]]` that returns a list of tuples, where each tuple contains two integers: the position of the building and its height. The skyline is represented by the highest points of the buildings from left to right. If two buildings have the same height, only the leftmost one should be included in the result. The input list is guaranteed to be non-empty and contain only positive integers. The output should be the skyline points in the order they appear from left to right."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of numerical quantities, implement a function `calculate_values(numbers)` that returns a tuple containing the maximum value, minimum value, and arithmetic mean of the list. The maximum value is the highest number in the list, the minimum value is the lowest number in the list, and the arithmetic mean is the total sum of the numbers divided by the count of numbers in the list. If the list is empty, return (None, None, None)."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given the first term of an arithmetic progression (AP) and a positive integer n, write a function that calculates the nth term of the progression where each term is double the previous term. The first term is provided as an integer. Implement a function called `find_nth_term` that takes in two parameters: an integer `a` (the first term of the progression) and an integer `n` (the term position), and returns the nth term in the progression."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that analyzes version changes and determines the type of change (breaking, minor, micro, or no change) based on the input version information and the provided change details. You are given a dictionary called `version_info` that contains two keys: 'version', which is a string representing the version in the format 'YYYY.MINOR.MICRO', and 'change_details', which is another dictionary containing boolean flags for the type of changes. Your task is to create a function `analyze_version_change(version_info)` that takes in the `version_info` dictionary and returns a string indicating the type of change based on the following criteria: if 'is_breaking_change' is True, return 'breaking'; if 'is_minor_change' is True and 'is_breaking_change' is False, return 'minor'; if 'is_micro_change' is True and both previous flags are False, return 'micro'; otherwise, return 'no change'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a player's exhaustion level represented as an integer. The player has a chance to create a fire, which can reduce their exhaustion. When creating a fire, the player expends a random amount of labor between 5 and 10. After expending labor, there is a 75% chance that the fire is successfully set (represented by a boolean value 'traps_set' being True). Write a function `make_fire(exhaustion: int) -> Tuple[int, bool]` that returns a tuple containing the new exhaustion level after expending labor and a boolean indicating if the fire was successfully set. The fire cannot set if the exhaustion drops below 0. If the player does not have enough exhaustion to create a fire after labor, the exhaustion level should remain unchanged and the fire is not set. Note that the random behavior should not be part of your implementation; instead, you can assume that the labor will always be 7 and the success rate is 75%."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given two lists of numbers, `train` and `test`. Your task is to standardize the `test` list using the mean and standard deviation of the `train` list. The standardization formula is given by: standardized_value = (value - mean) / std_dev. If the standard deviation of the `train` list is zero, use a small value of 0.001 instead. Implement a function `standardize_data(train: List[float], test: List[float]) -> List[float]` that returns the standardized `test` list. The input lists can contain both positive and negative floating-point numbers."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `selection_sort` that takes a list of integers as input and sorts the list in ascending order using the selection sort algorithm. The function should modify the input list in place and return nothing. The selection sort algorithm works by repeatedly finding the minimum element from the unsorted portion of the list and swapping it with the first unsorted element until the entire list is sorted."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that renames a given file name from 'TestFile' to 'CloudFile'. The function should take a single string as input, which represents the current name of the file. If the input name is 'TestFile', the function should return 'CloudFile'. If the input name is anything else, it should return the input name unchanged. Your task is to implement this function."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of integers, write a function `find_max_difference(arr: List[int]) -> int` that returns the maximum difference between any two elements in the list, where the larger element comes after the smaller one. If the list has fewer than two elements, return 0."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a non-negative integer n, implement a function `sum_of_first_n(n)` that calculates the sum of the first n natural numbers. The function should return the result efficiently using a mathematical formula instead of a loop."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given an integer `seconds`, write a function `gradual_brightness(seconds: int) -> List[int]` that simulates the brightness levels of a light bulb as it gradually increases from 0 to 254 over the specified time in seconds. The function should return a list of brightness levels, where the first element is 0 and the last element is 254. The brightness level should increase in equal increments over the duration specified by `seconds`. The number of brightness levels should be 255, including 0 and 254. If `seconds` is less than or equal to 0, return an empty list."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a binary matrix represented as a 2D list, where each element is either 0 or 1. Your task is to remove specific rows and columns from this matrix based on the provided indices. The indices are given as a list of integers, and each index corresponds to a row and a column in the matrix which should be removed. After removing the specified rows and columns, return the resulting matrix. If the resulting matrix is empty, return an empty list. Write a function called `remove_rows_and_columns(indices_to_remove: List[int], matrix: List[List[int]]) -> List[List[int]]` that performs this operation.\n\n### Input\n- `indices_to_remove`: A list of integers (0-indexed) representing the row and column indices to be removed from the matrix.\n- `matrix`: A 2D list of integers representing the binary matrix.\n\n### Output\n- Returns a 2D list representing the matrix after the specified rows and columns have been removed."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a string `doc` which represents a conversation or text input. Your task is to implement a function `transformations(doc: str) -> List[str]` that returns a list of strings representing various transformations of the input string. The function should apply the following transformations: 1) If the string contains the phrase 'like', return 'Do you like this?'. 2) If the string contains the phrase 'why', return 'Can you elaborate on why?'. 3) If the string contains the phrase 'think', return 'What do you think about this?'. If none of these phrases are present, return an empty list. The transformations should be applied in the order listed above, and the output should only include the transformations that match the input string. The output list should not contain duplicate messages."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with writing a function that processes messages in a chat application. Your function should accept a message object as input and return a boolean value indicating whether to process the message or ignore it. A message should be processed if it is either sent via direct message (DM) or if it is sent in a designated announcements channel. The message object contains two properties: 'guild' (which is None if it's a DM and an object otherwise) and 'channel_id' (an integer representing the channel ID). The designated announcements channel ID is given as an input parameter. Implement the function `should_process_message(msg: dict, announcements_channel_id: int) -> bool` where 'msg' is a dictionary containing the keys 'guild' and 'channel_id'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Write a function `generate_permutations(N)` that takes an integer N as input and returns a list of all possible permutations of the distinct integers from 1 to N. The result should be a list of tuples, where each tuple represents a unique permutation of the integers."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with updating a list of services based on given parameters. Each service can have its status toggled (enabled or disabled), deleted, or updated with new context root or protocol information. Implement a function `update_services(service_ids: List[int], change_type: int, value: Union[str, Dict[str, Any]]) -> str` that takes in the following parameters: \n- `service_ids` (List[int]): A list of service IDs that need to be updated. \n- `change_type` (int): An integer representing the type of change to be made (1 for enabling, 2 for disabling, 3 for deleting, 4 for updating context root, 5 for updating protocol, 6 for setting all). \n- `value` (Union[str, Dict[str, Any]]): A string or dictionary holding the new values for the update (e.g., new context root or protocol). \n\nThe function should return a message indicating the result of the operation, such as 'The service has been enabled.', 'The service has been deleted.', 'The services have been updated.', etc. If no service IDs are provided or an invalid change type is given, the function should return 'No services to update.' or 'Invalid change type.' respectively."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that adds an appointment to a schedule. The function should take a list of existing appointments (strings representing the appointments) and a new appointment (a string) as input. The function should then check if the new appointment is already in the list of existing appointments. If it is not present, the function should add it to the list and return the updated list. If it is already present, the function should return the original list without modifying it. Write a function called `add_appointment` that implements this logic. The function signature is: `def add_appointment(existing_appointments: List[str], new_appointment: str) -> List[str]:`. "}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a representation for an energy bus in a simulation framework. Your job is to define a function that initializes a bus object based on a given label. Write a function called `initialize_energy_bus(label)` that takes a string `label` as input and returns a dictionary representing the bus object for the energy system with the specified label. The bus object should be represented as a dictionary with a single key-value pair, where the key is 'label' and the value is the input label. \n\nExample: \nInput: \ninitialize_energy_bus('water_output') \nOutput: \n{'label': 'water_output'}"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of integers, write a function `find_max_even(numbers)` that returns the maximum even number from the list. If there are no even numbers, return -1. The function should handle an empty list and return -1 in that case as well. \n\nFunction Signature: `def find_max_even(numbers: List[int]) -> int:` \n\n### Input: \n- A list of integers `numbers` where 1 <= len(numbers) <= 10^5 and -10^9 <= numbers[i] <= 10^9.\n\n### Output: \n- An integer representing the maximum even number found in the list or -1 if no even numbers exist."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function that takes a list of unique integers and an integer n. The function should find the number with the greatest number of divisors, including divisors of those divisors, up to n-levels deep. In case of a tie in terms of divisor counts, the function should return the smallest number. Define the function as follows: def find_max_divisors(numbers: List[int], n: int) -> int:"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that simulates a simple database query operation by extracting specific fields from a list of records. Each record is represented as a dictionary containing various fields. Your function should take a list of records and a field name as input and return a list of values corresponding to that field from each record. If the field does not exist in a record, it should return None for that record. Implement the function `extract_field(records: List[Dict[str, Any]], field_name: str) -> List[Optional[Any]]`. \n\n**Input:** \n- `records`: A list of dictionaries where each dictionary represents a record with various fields. \n- `field_name`: A string representing the name of the field to be extracted. \n\n**Output:** \n- A list of values corresponding to the specified field from each record, with None for missing fields."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given an operator sign and two floating-point numbers, implement a function that performs the specified operation on the two numbers. The supported operations are addition ('+'), subtraction ('-'), multiplication ('*'), and division ('/'). If the operator is not supported, the function should raise a ValueError. Your function should be defined as follows: `def perform_operation(operator_sign: str, num1: float, num2: float) -> float:`. The function should return the result of the operation as a float."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `create_password(num_chars: int, prev_password: Optional[str] = None) -> str` that generates a strong password. The password must consist of a mix of symbols, numbers, uppercase letters, and lowercase letters. If a previous password is provided, the new password should have a length that is increased by half the length of the previous password. Additionally, the function must ensure that no two consecutive characters in the password are the same. The password should be randomly generated each time the function is called."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `shaker_sort(nums)` that sorts a list of integers in ascending order using the cocktail shaker sort algorithm. Your implementation should also be able to handle nested lists by sorting each sublist independently. The function should return the sorted list. For example, given the input `[4, 3, 2, 1]`, the output should be `[1, 2, 3, 4]`. If the input is a nested list like `[[4, 3, 2, 1], [3, 2, 1, 0]]`, the output should be `[[1, 2, 3, 4], [0, 1, 2, 3]]`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `insert_and_get_min` that takes a list of integers as input, inserts them into a priority queue implemented using a circular doubly linked list, and returns the minimum element from the priority queue after all insertions. The priority queue should maintain the order such that the minimum element can be efficiently retrieved. If the input list is empty, the function should return `None`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `multiply(x: int, y: int) -> int` that returns the product of two integers x and y without using standard multiplication operators. Ensure that the function correctly handles cases where x or y may be negative. For example, given x = 3 and y = -7, the function should return -21."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `arithmetic_operation(num1: int, num2: int, operation: str) -> Union[int, float, str]` that performs an arithmetic operation on two integers based on the given operation. The function should support four operations: 'add', 'subtract', 'multiply', and 'divide'. If the operation is division and the second number is zero, the function should return 'Error: Cannot divide by zero'. You may assume that the inputs are valid integers. Please implement this function without including any additional classes or methods."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given an unordered array of integers, write a function that partitions the array around a pivot element. The function should select the last element of the array as the pivot and rearrange the elements in the array such that all elements less than or equal to the pivot are on the left side of the pivot, and all elements greater than the pivot are on the right side. The function should return the index of the pivot after partitioning. The input to the function will be the array and its left and right indices. Your function should have the following signature: `def partition(arr: List[int], left: int, right: int) -> int:`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Write a function `create_pyramid(levels: int) -> List[List[int]]` that constructs a pyramidical structure with a specified number of levels. Each level `i` of the pyramid should contain `i` random integers selected from the range of 1 to 15. The total number of integers in the pyramid should not exceed 21. If the pyramid cannot be completed with the given number of levels while respecting this limit, return the pyramid with the available levels filled. The integers should be generated randomly each time the function is called."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `perform_operation` that takes three parameters: two integers `num1` and `num2`, and a string `operation` which can be 'add', 'subtract', 'multiply', or 'divide'. The function should perform the specified operation on the two numbers and return the result. If the operation is 'divide' and `num2` is zero, return the string 'Error: Division by zero is undefined'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of integers representing the prices of a stock on different days. Write a function `max_profit(prices: List[int]) -> int` that returns the maximum profit you can achieve from buying and selling the stock on those days. You may complete at most one transaction (i.e., buy one and sell one share of the stock). Your function should return 0 if no profit can be made. The input list will contain at least one price. The prices will be non-negative integers."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a variable number of arguments, implement a function `print_args` that returns a string containing all the input arguments concatenated together, separated by commas. The function should handle any type of input arguments, converting them to strings if necessary. The output should not include any trailing commas. For example, if the input is (1, 'apple', 3.5), the output should be '1, apple, 3.5'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a string that represents a zone file containing DNS records. Your task is to implement a function that parses this zone file and returns a list of records. Each record is represented as a dictionary with the following keys: 'type' (the type of the DNS record, such as 'A', 'AAAA', 'CNAME', etc.), 'name' (the domain name), 'value' (the record value), and 'ttl' (the time-to-live). The zone file consists of multiple lines where each line represents a single DNS record. Lines that start with a '#' character are comments and should be ignored. Each record line is formatted as follows: 'name ttl type value'. For example: 'www.example.com 3600 A 192.0.2.1'. If the input string is empty or contains only comments, return an empty list."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a string message that contains an error message. Write a function `format_error_message(msg: str) -> str` that formats the error message by ensuring it ends with a newline character. If the input string is None, return the string 'No error message provided.' instead. Your function should return the formatted error message."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that accepts a JSON string representation of an OpenAPI specification and a package name. The function should extract the title of the API from the JSON structure and return it. If the title does not exist, return 'No Title Found'. The JSON structure will always contain a top-level key 'info' which in turn contains a key 'title'. Write a function `extract_api_title(json_str: str, package_name: str) -> str` that implements this behavior."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that simulates a simplified dual blob store system. The function should take two lists of strings representing blobs to be written to the primary and secondary stores, respectively. The primary store processes all write requests immediately, while the secondary store processes blobs asynchronously. However, if the secondary store cannot keep up with the primary store, it will start discarding writes once the number of queued writes exceeds a specified limit. Your task is to implement the function `dual_blob_store_simulation(primary_blobs: List[str], secondary_blobs: List[str], max_queue_size: int) -> Tuple[List[str], List[str]]`, which returns a tuple of two lists: the first list contains the blobs that were successfully written to the primary store, and the second list contains the blobs that were successfully written to the secondary store. If the secondary store's write queue is full, the excess blobs should be discarded. The function should handle the case where the secondary store is slower than the primary. The primary store should never discard any writes. The input parameters are as follows: 1. `primary_blobs`: A list of strings representing blobs to be written to the primary store. 2. `secondary_blobs`: A list of strings representing blobs to be written to the secondary store. 3. `max_queue_size`: An integer representing the maximum number of blobs that can be queued for the secondary store. "}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `validate_spin(value: int) -> int` that validates the input value of a spin. The function should return the input value if it is valid. A valid spin is defined as an integer that is either -1, 0, or 1. If the input value is not an integer, or if it is outside the range of -1 to 1, the function should raise a `ValidationError` with the message 'spin must be among -1, 1 or 0 (undefined)' or 'spin must be integer' respectively. Please implement this function without using any external resources."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that processes a list of deployment IDs. Given a list of deployment IDs, your function should return a list containing the IDs of deployments that are marked as 'inactive'. A deployment ID is considered 'inactive' if it is an even number. Implement the function `filter_inactive_deployments(deployment_ids: List[int]) -> List[int]` that takes a list of integers representing deployment IDs and returns a new list containing only the even deployment IDs. Note that the input list can contain duplicate IDs, and the output list should also contain duplicates if the corresponding deployment ID appears multiple times in the input list. The input list will have at least one deployment ID and at most 1000 deployment IDs."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `sphere_segment_volume(radius: float, angle: float) -> float` that calculates the volume of a segment of a sphere given its radius and the central angle in degrees. The function should return `None` if the radius is negative or if the angle is outside the range of 0 to 360 degrees. For valid inputs, use the formula for the volume of a sphere segment, which is given by: (2/3) * π * (radius^3) * (angle/360)."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of integers, write a function `find_median` that returns the median of the list. The median is defined as the middle value when the list is sorted. If the list has an even number of elements, return the average of the two middle values. The input list can contain both positive and negative integers, and you are guaranteed that the list will not be empty. Please implement the function `find_median(nums: List[int]) -> float`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `selection_sort(arr: List[int], ascending: bool) -> List[int]` that sorts an array of integers using the selection sort algorithm. The function should take two parameters: an array of integers `arr` and a boolean `ascending`. If `ascending` is True, the function should sort the array in ascending order; if False, it should sort the array in descending order. The function should return the sorted array. If the input array is empty, return an empty array."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list composed of strings that include various types of brackets: '()', '{}', '[]', and '<>', determine if the sequence of brackets is valid. A valid sequence is one where every opening bracket has a corresponding and correctly ordered closing bracket. Implement a function called `intricate_brackets(lst)` that takes a single parameter `lst`, a list of strings, and returns 'Yes' if the brackets are correctly nested and closed, otherwise return 'No'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of country names. Your task is to implement a function that takes this list as input and returns a list of unique country names in alphabetical order. Write a function `unique_sorted_countries(countries: List[str]) -> List[str]` where `countries` is a list of strings representing country names. The function should return a new list containing each country name only once, sorted in alphabetical order."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that processes a product menu and updates the quantities based on user input. The function should take a list of products, where each product is represented as a dictionary with 'id', 'name', 'price', and 'quantity' keys. The function should also take a list of integers representing the updated quantities for each product. Your function should update the quantities in the product list and return the updated product list. Additionally, it should log any changes made to the product quantities using a logger. Implement the function `update_product_quantities(products: List[Dict[str, Union[int, str, float]]], quantities: List[int]) -> List[Dict[str, Union[int, str, float]]]` that performs this task. The logger should be configured to log changes to the console."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given an integer representing a size in bytes, implement a function that converts this size into a human-readable format using appropriate units (Bytes, KB, MB, GB, TB). The function should round the size to one decimal place and return the string formatted as '<size> <unit>'. If the size is zero, the function should return '0 Bytes'. The function should handle sizes up to 1 TB. Write a function 'fmt_bytes(size_bytes: int) -> str' where 'size_bytes' is a non-negative integer."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of words, implement a function that returns a list of all the words that are palindromes. A palindrome is a word that reads the same forwards and backwards. For example, 'madam' is a palindrome while 'hello' is not. Your function should be case-sensitive and should only include words that are exactly the same when reversed. Implement the function `find_palindromes(words)` where `words` is a list of strings."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that simulates the toggling of a button's state in a user interface. The function `toggle_button_state(current_state: str) -> str` takes the current state of a button as input, which can either be 'enabled' or 'disabled'. If the button is currently 'enabled', the function should return 'disabled', and if it is 'disabled', the function should return 'enabled'. Your goal is to implement this function that will correctly toggle the button state based on the provided input."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a boolean value representing whether a sort operation should be performed on a dataset. Your task is to implement a function `perform_sort` that takes a boolean parameter `should_sort`. If `should_sort` is True, return the string 'Sorting data...'; otherwise, return 'No sorting needed.'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that takes a dictionary representing application configuration settings and returns a formatted string that describes these settings in a human-readable format. The dictionary will have string keys and values that can be strings, integers, or booleans. Your function should iterate through the dictionary and create a string where each key-value pair is represented as 'key: value'. Each pair should be on a new line. If the value is a boolean, it should be represented as 'True' or 'False'. The function should handle empty dictionaries and return an empty string in such cases. Please implement the function `format_config(conf: dict) -> str`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with managing visual and audio stimuli associated with specific markers in a psychological experiment. Implement a function named `get_stimuli_by_marker` that takes a list of visual stimuli and a list of audio stimuli, each represented as dictionaries, along with a marker string. The function should return a list of names of all stimuli (both visual and audio) that are associated with the specified marker. Each visual stimulus dictionary will contain the keys 'name', 'rating', and an optional 'marker'. Each audio stimulus dictionary will contain the keys 'name' and an optional 'marker'. If no stimuli are associated with the marker, return an empty list."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a Python function that simulates a simplified version of a task execution system. The function will take a list of task operations and execute them in the specified order. Each task operation is represented as a dictionary with 'execute' and 'undo' keys, where the values are functions to be executed and reversed, respectively. The function should execute the 'execute' function of each task in the list, and if any task fails, it should roll back the executed tasks by calling their 'undo' functions in reverse order. The function should return True if all tasks are successfully executed, and False if any task fails and the rollback is performed. You are required to implement the function `execute_tasks(operations)` where: operations: A list of task operations, each represented as a dictionary with 'execute' and 'undo' keys. Function Signature: `def execute_tasks(operations: List[Dict[str, Callable]]) -> bool:`"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a database path (dbpath) represented as a string and a cutoff radius (cutoff) represented as a float. Your task is to create a function `get_data_info(dbpath: str, cutoff: float) -> str` that returns a string containing the database path and the cutoff radius formatted as 'Database Path: {dbpath}, Cutoff Radius: {cutoff}'. For example, if the inputs are 'path/to/db' and 1.5, the output should be 'Database Path: path/to/db, Cutoff Radius: 1.5'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that simulates drawing rectangles on a canvas. The function should accept a list of rectangles, where each rectangle is represented as a tuple containing the coordinates of the top-left corner (x, y), width, and height. Your function should return the total area covered by all the rectangles, assuming that rectangles may overlap. The input will be a list of tuples, and the output will be a single integer representing the total area covered. Implement the function `calculate_total_area(rectangles: List[Tuple[int, int, int, int]]) -> int:` where `rectangles` is a list of tuples, with each tuple formatted as (x, y, width, height)."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a Python function that calculates the average price of materials based on a given list of materials. Each material is represented as a tuple containing its name and price. Your function should take a list of these tuples as input and return the average price of all materials rounded to two decimal places. Additionally, your function should print the total number of materials provided in the list. If the input list is empty, your function should return 0.00 as the average price."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function to compare two version numbers represented as strings in the format \"x.y.z\" where x, y, and z are non-negative integers. Your function should take two version strings as input and determine their relationship. The function should return one of the following strings: \"Equal\" if the current version is equal to the target version, \"Greater\" if the current version is greater than the target version, and \"Less\" if the current version is less than the target version. Implement the function `compare_versions(current_version, target_version)` that fulfills this requirement."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with modifying a data structure that represents a chat message in a chat application. Each chat message is represented as a dictionary with the following keys: 'sender', 'receiver', 'message', and 'timestamp'. Your task is to implement a function that takes a list of chat messages and adds a new field 'new_field' to each message, setting its value to an empty string. The function should return the modified list of chat messages. Each message will be represented as a dictionary. Write a function named 'add_new_field_to_messages' that takes a list of dictionaries and returns a list of dictionaries with the new field added."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Write a function `extract_middle(input_val)` that takes an input parameter `input_val`. The function should return the middle character of the string if the length of the string is odd. If the length of the string is even, it should return the two middle characters. The function should also handle erroneous input by returning 'Invalid input' for non-string data types or empty strings."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a list of integers representing the expected values of a certain process. Your task is to implement a function to sort the list of expected values in non-decreasing order using a custom sorting algorithm. You cannot use any built-in sorting functions or libraries. Write a function `customSort(expected: List[int]) -> List[int]` that takes in a list of integers `expected` and returns a new list containing the elements of `expected` sorted in non-decreasing order. For example, given the input `expected = [5, 2, 8, 1, 3]`, the function should return `[1, 2, 3, 5, 8]`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given an integer `num`, write a function that calculates the sum of all integers from `num` to 0 (inclusive) if `num` is negative, or from 0 to `num` (inclusive) if `num` is positive. Implement the function `calculate_sum(num: int) -> int` to accomplish this. The function should return the calculated sum. For example, if `num` is 5, the function should return 15 (the sum of 0 + 1 + 2 + 3 + 4 + 5). If `num` is -3, the function should return -6 (the sum of -3 + -2 + -1 + 0)."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of integer labels, you need to remap these labels based on their frequency. The most frequent label should be assigned the label 0, the second most frequent label should be assigned the label 1, and so on. If multiple labels have the same frequency, assign the smaller label value first. Write a function `relabel(labels: List[int]) -> List[int]` that takes a list of integer labels and returns a new list of relabeled integers according to the aforementioned rules. The input list can contain negative and positive integers, and may include duplicates."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given an IP address in string format. Your task is to implement a function that identifies whether the given IP address is a valid IPv4 address, a valid IPv6 address, or neither. If it is a valid IPv4 address, return 'ip address <ip>'. If it is a valid IPv6 address, return 'ipv6 address <ip>'. If it is not a valid IP address, return 'invalid address: <ip>'. A valid IPv4 address consists of four decimal numbers (0-255) separated by dots. A valid IPv6 address consists of eight groups of four hexadecimal digits separated by colons. Implement the function `addrstr(ip: str) -> str`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a string that represents the contents of a file. Your task is to implement a function that reads the content of the string in chunks and returns the concatenated result. Additionally, you need to track the reading progress using a progress indicator. Implement a function `read_content(content: str, chunk_size: int) -> str` that reads the given content in chunks of the specified size. The function should return the complete content after reading it in chunks. The function should also print the progress as it reads each chunk. If the `chunk_size` is greater than the length of the content, it should return the whole content without any progress updates. If the `chunk_size` is less than or equal to zero, return an empty string. Example usage: read_content('Hello, world!', 5) should return 'Hello, world!'."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given a list of site identifiers and a parameter code, generate a request URL for accessing water service data. The request URL should be formatted as follows: 'https://waterservices.usgs.gov/nwis/site?sites={}¶meterCd={}&siteOutput=Expanded&format={}'. Implement a function `generate_request_url(sites: List[str], parameter_cd: str, format: str) -> str` that takes three arguments: a list of site identifiers (strings), a parameter code (string), and a format type (string). The function should return the constructed request URL as a string."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function that takes a multi-dimensional list of mixed values (both numeric and non-numeric) and returns a sorted list of distinct numeric values. The function should remove all non-numeric values and handle duplicate numeric values by placing them next to each other in the sorted output. You may assume that the input list contains distinct numeric values, but there may be irrelevant non-numeric values interspersed. The output should be a single sorted list of numeric values only. For example, given the input [[5, 'b', 3, 2, 1], [4, 'c', 3, 1, 2], [1, 'a', 2, 4, 5]], the output should be [1, 2, 3, 4, 5]."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function `setup_logging(verbose: int) -> str` that configures a simple logging system based on the given verbosity level. The function should return a message indicating the logging level that has been set. The logging levels are defined as follows: If `verbose` is 0, the logging level should be 'WARNING'. If `verbose` is 1, the logging level should be 'INFO'. If `verbose` is greater than 1, the logging level should be 'DEBUG'. Your function should handle any integer input for `verbose` and return the corresponding logging level as a string. Implement the function without using any external libraries or resources."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a string representing a file path. Write a function `is_executable_file(file_path: str) -> bool` that checks if the file at the given path is an executable file. An executable file is defined as one that is not a directory and has the executable permission. For simplicity, assume that any file path that ends with '.exe' or '.sh' is considered an executable file. Your function should return `True` if the file is executable, and `False` otherwise. Note that you do not need to check the actual file system; you can determine if a file is executable based purely on its name. "}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a simple data structure to manage a workspace for a computational environment. The workspace is represented as a dictionary that stores variables and their corresponding values. Your goal is to create a function `manage_workspace(instructions)` that processes a given set of instructions to manipulate the workspace. The function should accept a list of instructions, where each instruction is a tuple. The first element of the tuple is a string indicating the operation (`'add'`, `'delete'`, or `'run'`) and the subsequent elements depend on the operation: \n- For `'add'`, the next two elements are the variable name (string) and its value (integer). \n- For `'delete'`, the next element is the variable name (string) to be deleted. \n- For `'run'`, the next element is a function that takes the workspace dictionary and performs operations on it. \nThe function should return the final state of the workspace after processing all instructions. \nIf an error occurs during a run operation (like accessing a non-existing variable), it should simply be caught and logged, but the function should continue processing subsequent instructions."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a dictionary representing a batch of molecular data. Each entry in the dictionary may contain the following keys: 'num_atoms' (a list of integers representing the number of atoms in each molecule), 'mol_size' (a list of integers representing the size of each molecule), 'energy' (a list of floats representing the energy levels of the molecules), and 'weights' (a list of floats representing the weights of the molecules). Implement a function `process_molecular_data(batch: dict) -> dict` that processes this batch of data and returns a new dictionary containing the following keys: 'fp' (a list of pooled fingerprints, which is a list of zeros of the same length as 'num_atoms'), 'conf_fps' (a list of lists where each internal list contains a single fingerprint for each molecule), 'learned_weights' (a list of learned weights, which is the same as 'weights'), and optionally 'energy' (a list of lists where each internal list contains energy levels split by molecule size). If the 'energy' key is not present in the input batch, do not include it in the output. You can assume that 'num_atoms' and 'mol_size' will always have the same length."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with implementing a function that simulates a color-changing mechanism based on a predefined sequence. The function takes in a string representing the current color and returns the next color in the sequence. The sequence of colors is as follows: WHITE -> RED -> GREEN -> BLUE -> WHITE. Implement a function `next_color` that receives a color as input and returns the next color in the sequence. If the input color is WHITE, the function should return RED. If the input color is BLUE, the function should return WHITE."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with creating a function that initializes a global configuration dictionary for a program. The function 'initialize_configuration' should take a single parameter named 'data' which is a dictionary containing a key 'config' that maps to another dictionary. Your function should set a global variable 'CONFIG' to the value of 'data['config']'. Write the function such that it does not return any value but updates the global variable. The input will always contain the 'config' key with valid data. The global variable 'CONFIG' should be accessible after the function call."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a SQL update statement in the form of a string, and your task is to write a function that extracts and returns the name of the column being updated. The SQL update statement will always follow the format: 'update <table_name> set <column_name> = <new_value>'. The column name will not contain any spaces or special characters. Implement the function `extract_column_name(sql)` that takes a string `sql` representing a SQL update statement as input and returns the name of the column being updated."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Implement a function `check_number(n: int, shouldPrintAllPrimeDivisors: bool) -> Union[str, List[int]]` that takes a whole number `n` and a boolean `shouldPrintAllPrimeDivisors`. The function should return 'prime' if `n` is a prime number, or 'composite' if `n` is a composite number. If `shouldPrintAllPrimeDivisors` is true and `n` is composite, the function should additionally return a list of all prime divisors of `n`. The function should handle input up to 10^6 efficiently."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are working on a bioinformatics project that involves processing gene data. You need to implement a function that determines if a provided gene list contains any duplicate genes. Your task is to create a function `has_duplicate_genes` that takes a list of genes as a parameter and returns True if there are any duplicates, and False otherwise. The input list can contain any string representing gene names, and the function should handle an empty list as well. \n\nWrite the function signature: `def has_duplicate_genes(genes: List[str]) -> bool:`."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are given a string containing digits from 2-9. Each digit maps to a set of possible letters as shown in the following mapping: 2 -> \"abc\", 3 -> \"def\", 4 -> \"ghi\", 5 -> \"jkl\", 6 -> \"mno\", 7 -> \"pqrs\", 8 -> \"tuv\", 9 -> \"wxyz\". Write a function to return all possible letter combinations that the given string could represent. The order of the combinations does not matter. The input string will not contain any 0 or 1. Function signature: `def letter_combinations(digits: str) -> List[str]:`"}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "You are tasked with converting a given message (a string) into a proper formatted email string according to the following rules: 1. If the message contains any newline characters, they should be replaced with the carriage return and line feed sequence (\\r\\n). 2. The output should also ensure that the message starts with 'From: sender@example.com\\r\\n' and ends with '\\r\\n' for proper email formatting. Write a function `format_email(message: str) -> str` that takes a message as input and returns the formatted email string."}], "membership_label": 0} | |
| {"messages": [{"role": "user", "content": "Given an integer n, implement a function that generates an n x n identity matrix. An identity matrix is a square matrix with ones on the main diagonal and zeros elsewhere. For example, the 3x3 identity matrix is:\n\n[[1, 0, 0],\n [0, 1, 0],\n [0, 0, 1]].\n\nYour function should return the identity matrix as a list of lists.\n\nFunction signature:\n\ndef generate_identity_matrix(n: int) -> List[List[int]]:\n\nInput:\n- A single integer n (1 <= n <= 1000) representing the size of the identity matrix.\n\nOutput:\n- A list of lists representing the n x n identity matrix."}], "membership_label": 0} | |