source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
magic_instruct_75k | 4,703 | Write a Python function to implement the binary search algorithm to find the index of a target value in a sorted list. If the target value is not found in the list, the function should return `None`. The function should start with:
```python
from typing import List, Optional
def binary_search(arr: List[int], target: i... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def binary_search(arr: List[int], target: int) -> Optional[int]:
"""
Implements the binary search algorithm to find the index of a target value in a sorted list.
Args:
arr (List[in... |
magic_instruct_75k | 4,733 | Write a Python function to validate and extract IPv4 and IPv6 addresses from a given input string. The function should return a tuple containing the extracted IPv4 and IPv6 addresses. IPv4 addresses are represented in the standard dot-decimal notation, while IPv6 addresses are represented in the standard colon-hexadeci... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def extract_ip(input_str: str) -> (str, str):
"""
Extracts and validates IPv4 and IPv6 addresses from a given input string.
Args:
input_str (str): The input string to search for IPv4 and IPv6 addresses.
... |
magic_instruct_75k | 4,755 | Write a Python function to parse a given string representing a list of package dependencies and return a dictionary containing the package names as keys and their minimum required versions as values. The input string is formatted as follows:
```
dependencies_str = """
'Pillow>=2.3.0',
'numpy>=1.8.2',
'pytes... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
import re
def parse_dependencies(dependencies_str: str) -> Dict[str, str]:
"""
Parses a given string representing a list of package dependencies and returns a dictionary
containing the package names ... |
magic_instruct_75k | 4,766 | Write a Python function to process a list of integers according to a specific set of rules. The function should:
1. Remove all even numbers from the list.
2. Double the value of each remaining number in the list.
3. Calculate the sum of all the numbers in the modified list.
The function should return the modified list... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def process_list(l: List[int]) -> Tuple[List[int], int]:
"""
Processes a list of integers according to the following rules:
1. Remove all even numbers from the list.
2. Double the value of... |
magic_instruct_75k | 4,784 | Write a Python function to perform a depth-first traversal of a tree and return a list of all descendant nodes' names in the order they are visited. The tree is represented by a `TreeNode` class, which has a name and a list of child nodes. Each child node is also an instance of `TreeNode`. The function should start wit... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
class TreeNode:
def __init__(self, name: str):
self.name = name
self.children = []
def add_child(self, child_node: 'TreeNode'):
self.children.append(child_node)
def get_chil... |
magic_instruct_75k | 4,804 | Write a Python function to generate unique names for virtual directories within a list of metadata directories (metavdirs). Each metavdir is represented by a path, and the function should extract the virtual directories within each metavdir and generate unique names for them. The function should ensure that no two virt... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def get_all_vdirs(path: str) -> List[str]:
"""
Dummy function to simulate the retrieval of virtual directories within a given path.
In a real implementation, this function would interact with the fil... |
magic_instruct_75k | 4,812 | Write a Python function to transpose a given square matrix. The transpose of a matrix is obtained by flipping the matrix over its main diagonal, which means exchanging the row and column indices of the matrix. The function should handle square matrices of any size.
The code should start with:
```python
from typing imp... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def transpose(array: List[List[int]]) -> List[List[int]]:
"""
Transposes a given square matrix.
Args:
array (List[List[int]]): A square matrix represented as a list of lists containing integ... |
magic_instruct_75k | 4,816 | Write a Python function `count_votes(votes_list)` that takes in a list of tuples `votes_list` representing the votes cast in an election. Each tuple contains the voter's ID (a string), the candidate's name (a string), and the voting timestamp (an integer). The function should return a dictionary containing the total nu... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def count_votes(votes_list: List[Tuple[str, str, int]]) -> Dict[str, int]:
"""
Counts the votes for each candidate from a list of votes.
Args:
votes_list (List[Tuple[str, str, i... |
magic_instruct_75k | 4,819 | Write a Python function to evaluate a list of arithmetic expressions represented as strings. Each expression can contain numbers, arithmetic operators (`+`, `-`, `*`, `/`), and parentheses. The function should return a list of integers representing the evaluated results of each expression.
The code should start with:
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def evaluateExpressions(expressions: List[str]) -> List[int]:
"""
Evaluates a list of arithmetic expressions and returns a list of their results.
Args:
expressions (List[str]): A list of str... |
magic_instruct_75k | 4,820 | Write a Python function to calculate the sum of all even numbers in a given list of integers. If the list is empty or contains no even numbers, the function should return 0. The function should be named `sum_of_evens` and should start with:
```python
from typing import List
def sum_of_evens(numbers: List[int]) -> int:... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_of_evens(numbers: List[int]) -> int:
"""
Calculate the sum of all even numbers in a given list of integers.
Args:
numbers (List[int]): A list of integers.
Returns:
int: ... |
magic_instruct_75k | 4,824 | Write a Python function to perform basic operations on a list of dictionaries representing users. Each dictionary contains keys `'id'`, `'username'`, and `'email'`. The function should support inserting a new user, retrieving a user by ID, updating a user's email by ID, and deleting a user by ID. The function should re... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Union
def user_operations(users: List[Dict[str, Union[int, str]]], operation: str, user: Dict[str, Union[int, str]] = None) -> Union[List[Dict[str, Union[int, str]]], str]:
"""
Perform basic CRUD ... |
magic_instruct_75k | 4,833 | Write a Python function `count_mongo_roles(commands: List[str]) -> Dict[str, int]` that takes a list of input commands as strings and returns a dictionary containing the count of nodes for each MongoDB role. Each input command is in the format `docker node update --label-add mongo.role=<role> <node_name>`. The `<role>`... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_mongo_roles(commands: List[str]) -> Dict[str, int]:
"""
Counts the number of nodes for each MongoDB role from a list of Docker Swarm node update commands.
Args:
commands (Lis... |
magic_instruct_75k | 4,837 | Implement a custom comparison method `cmp` for two classes `C` and `D` in Python. The `cmp` method should print the types of the objects being compared and return 0 for all comparisons. The comparison is performed between instances of classes `C` and `D`, which are part of a list `l`.
The code should start with:
```py... | Here is the Python code to solve the given problem in the markdown block:
```python
class C:
def cmp(self, rhs):
"""
Custom comparison method for class C.
Args:
rhs: The object to compare with.
Returns:
int: Always returns 0 for all comparisons.
"""
... |
magic_instruct_75k | 4,839 | Write a Python function to simulate a simple cache system that supports storing and retrieving data based on a given tag. The cache should also maintain a queue of side packets associated with the cache. The function should allow adding data to the cache, retrieving data from the cache, and managing the side packet que... | Here is the Python code to solve the given problem in the markdown block:
```python
from collections import deque
from typing import Any, Dict, List, Optional
class Cache:
def __init__(self):
"""
Initialize the cache with an empty dictionary for storing data and an empty deque for side packets.
... |
magic_instruct_75k | 4,855 | Write a Python function to compare two software version numbers represented as strings in the format "major.minor.patch.build". The function should return an integer indicating whether the first version is greater than, equal to, or less than the second version. The comparison should follow these rules:
1. Compare the ... | Here is the Python code to solve the given problem in the markdown block:
```python
def compare_versions(version1: str, version2: str) -> int:
"""
Compare two software version numbers and return an integer indicating their relationship.
Args:
version1 (str): A string representing the first version ... |
magic_instruct_75k | 4,865 | Write a Python function to count the occurrences of each unique phylum within a list of tuples representing taxonomic ranks. Each tuple contains two strings: the kingdom and the phylum, formatted as 'k__Kingdom' and 'p__Phylum' respectively. The function should return a dictionary where the keys are the phyla and the v... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def count_phylum_occurrences(taxa: List[Tuple[str, str]]) -> Dict[str, int]:
"""
Counts the occurrences of each unique phylum in a list of taxonomic tuples.
Args:
taxa (List[Tup... |
magic_instruct_75k | 4,868 | Write a Python function to automate the setup of RabbitMQ Management API on a server. The function should enable the RabbitMQ Management API using the command-line interface and verify the successful enabling of the API. The function should be able to run on a Unix-based system with RabbitMQ installed.
The code should... | Here is the Python code to solve the given problem in the markdown block:
```python
import subprocess
def enable_rabbitmq_management_api() -> bool:
"""
Automates the setup of RabbitMQ Management API on a server.
This function enables the RabbitMQ Management API using the `rabbitmq-plugins` command
and... |
magic_instruct_75k | 4,887 | Write a Python function to calculate the total number of images to be processed in a computer vision pipeline. The function should take into account the total number of images in the dataset, the number of images processed per GPU, the number of workers (processing units) per GPU, and the number of GPUs used for testin... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_total_images(dataset: int, imgs_per_gpu: int, workers_per_gpu: int, cfg: dict) -> int:
"""
Calculate the total number of images to be processed in a computer vision pipeline.
Args:
dataset (int): Total... |
magic_instruct_75k | 4,898 | Write a Python function to filter a list of SKU names based on a given keyword. The function should return a list of SKUs whose names contain the given keyword, case-insensitively. The function should start with:
```python
from typing import List
def filter_skus_by_keyword(skus: List[str], keyword: str) -> List[str]:
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def filter_skus_by_keyword(skus: List[str], keyword: str) -> List[str]:
"""
Filters a list of SKU names based on a given keyword.
Args:
skus (List[str]): A list of strings representing SKU n... |
magic_instruct_75k | 4,899 | Write a Python function to count the occurrences of each unique plugin interface in a given list of plugin interfaces. Each plugin interface is represented as a string in the list. The function should return a dictionary where the keys are the unique interfaces (case-insensitive) and the values are the count of each in... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_plugin_interfaces(plugin_interfaces: List[str]) -> Dict[str, int]:
"""
Counts the occurrences of each unique plugin interface in a given list.
Args:
plugin_interfaces (List[s... |
magic_instruct_75k | 4,910 | Write a Python function to calculate the average of a list of numbers, excluding any negative numbers. The function should return the average of the positive numbers in the list. If the input list is empty or contains only negative numbers, the function should return 0.
The code should start with:
```python
from typin... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_average(numbers: List[float]) -> float:
"""
Calculate the average of a list of numbers, excluding any negative numbers.
Args:
numbers (List[float]): A list of numbers from whic... |
magic_instruct_75k | 4,932 | Write a Python function `sum_rows_columns(matrix)` that takes a 3x3 matrix (a list of lists) as input and returns a dictionary containing the sums of the elements in each row and each column. The keys of the dictionary should be 'row_1', 'row_2', 'row_3', 'col_1', 'col_2', and 'col_3' to represent the sums of the rows ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def sum_rows_columns(matrix: List[List[int]]) -> Dict[str, int]:
"""
Calculate the sum of elements in each row and each column of a 3x3 matrix.
Args:
matrix (List[List[int]]): A 3x3 ma... |
magic_instruct_75k | 4,938 | Implement a Python class `DriverConfigManager` that manages files associated with different driver configurations. Each driver configuration can have an operational mode (`OpMode`) and a list of files associated with it. The class should support the following operations:
1. **AddFile**: Add a file to the list of files ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
class File:
def __init__(self, file_name: str, file_path: str):
self.file_name = file_name
self.file_path = file_path
class OpMode:
Normal = "Normal"
Safe = "Safe"
Test... |
magic_instruct_75k | 4,952 | Write a Python function to count the number of occurrences of a specific substring within a given string. The function should be named `count_substring` and should take two parameters: `main_string` (a string) and `substring` (a string). The function should return the number of times the `substring` appears in the `mai... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_substring(main_string: str, substring: str) -> int:
"""
Counts the number of occurrences of a specific substring within a given string.
Args:
main_string (str): The string in which to search for the substr... |
magic_instruct_75k | 4,970 | Write a Python function to filter a list of dictionaries based on specific conditions. Each dictionary represents a signal with fields "freqStart", "freqStop", and "description". The function should return a new list containing only the dictionaries that satisfy the following conditions:
1. The difference between the "... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def filter_data(data_list: List[Dict[str, any]]) -> List[Dict[str, any]]:
"""
Filters a list of dictionaries based on specific conditions.
Args:
data_list (List[Dict[str, any]]): A lis... |
magic_instruct_75k | 4,974 | Write a Python function `assign_shape(arena, extent, x_pos, y_pos)` that assigns a shape to a specific position in a 2D arena based on the value of `extent`. If `extent` is less than 0.8, the position is assigned a value of 3, indicating a circle. If `extent` is greater than or equal to 0.8, the position is assigned a ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def assign_shape(arena: List[List[int]], extent: float, x_pos: int, y_pos: int) -> int:
"""
Assigns a shape to a specific position in a 2D arena based on the value of `extent`.
Args:
arena (... |
magic_instruct_75k | 4,983 | Write a Python function to generate a configuration string for a simplified version of the TensorBoard visualization tool used in machine learning. The function should take in a `logdir` path, a `port` number, and a `width` value, and then return a formatted string representing the configuration for the TensorBoard.
T... | Here is the Python code to solve the given problem in the markdown block:
```python
def st_tensorboard(logdir: str, port: int, width: int) -> str:
"""
Generates a configuration string for a simplified version of the TensorBoard visualization tool.
Args:
logdir (str): The path to the log directory.
... |
magic_instruct_75k | 4,986 | Write a Python function to count the total number of nested `<div>` elements in a given HTML code string. The function should parse the HTML string and count all `<div>` elements, including nested ones. The function should start with:
```python
def count_nested_divs(html_code: str) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def count_nested_divs(html_code: str) -> int:
"""
Counts the total number of nested <div> elements in the given HTML code.
Args:
html_code (str): A string representing the HTML code containing nested <div> elements.... |
magic_instruct_75k | 4,997 | Write a Python function to determine if a given string contains a valid set of parentheses. The function should return `true` if the parentheses are properly nested and balanced, and `false` otherwise. The function should handle both open and close parentheses, and any other characters in the input string should be ign... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_valid_parentheses(s: str) -> bool:
"""
Determine if the given string contains a valid set of parentheses.
Args:
s (str): The input string to be checked for valid parentheses.
Returns:
bool: True ... |
magic_instruct_75k | 5,000 | Write a Python function to determine whether the sum of all integers in a given list is even or odd. If the sum is even, the function should return "All good!", and if the sum is odd, the function should return "Odd sum!".
The code should start with:
```python
from typing import List
def check_sum_parity(numbers: Lis... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def check_sum_parity(numbers: List[int]) -> str:
"""
Determines whether the sum of a list of integers is even or odd.
Args:
numbers (List[int]): A list of integers whose sum's parity is to b... |
magic_instruct_75k | 5,017 | Write a Python function to process a list of securities by removing any duplicate securities and sorting the list in ascending order. The function should take a list of strings representing securities and return the processed list.
The code should start with:
```python
from typing import List
def processSecurities(se... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def processSecurities(securities: List[str]) -> List[str]:
"""
Processes a list of securities by removing duplicates and sorting the list in ascending order.
Args:
securities (List[str]): A ... |
magic_instruct_75k | 5,026 | Write a Python function to generate a report based on the results of a system check. The function should process a `result` object that contains information about the host, the task, and the results of the system check. The report should include the host name and a message for each check that was skipped. The function ... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_report(result) -> list:
"""
Generates a report based on the results of a system check.
Args:
result: An object containing the results of a system check, including host, task, and check results.
Ret... |
magic_instruct_75k | 5,030 | Write a Python function to filter and return a subset of network interfaces based on their configuration type. The function should take in a configuration dictionary and a type string as input, and return a list of interfaces that match the specified type. The type string can be one of 'dot1x', 'dot1x_mab', or 'dot1x_p... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Any
def filter_interfaces(configuration: Dict[str, Any], type: str) -> List[str]:
"""
Filters and returns a subset of network interfaces based on their configuration type.
Args:
confi... |
magic_instruct_75k | 5,080 | Write a Python function to perform quantized bias addition on fixed-point numbers. The function should take the quantized input value, the bias value, and the number of integer and fractional bits as inputs, and return the result of the quantized bias addition. The fixed-point representation is specified by the number ... | Here is the Python code to solve the given problem in the markdown block:
```python
def quantized_bias_add(input_val: int, bias: int, int_bits: int, frac_bits: int) -> int:
"""
Perform quantized bias addition on fixed-point numbers.
Args:
input_val (int): The quantized input value.
bias (in... |
magic_instruct_75k | 5,100 | Write a Python function to determine the tiers of tanks in a game based on their level and class. The function should handle special cases where certain tanks have predefined tiers, and apply general rules for other tanks. The function should start with:
```python
def get_tiers(level: int, cls: str, key: str) -> tuple:... | Here is the Python code to solve the given problem in the markdown block:
```python
def get_tiers(level: int, cls: str, key: str) -> tuple:
"""
Determine the tiers of a tank based on its level, class, and key.
Args:
level (int): The level of the tank.
cls (str): The class of the tank (e.g.,... |
magic_instruct_75k | 5,104 | Write a Python function to simulate a student queue for individual meetings with a professor. The function should remove the last student from the queue and update the remaining time for the individual meeting. The function should return a tuple containing the updated list of student names and the remaining time for th... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def remove_last_student(
student_names: List[str], individual_seconds: int, max_individual_seconds: int
) -> Tuple[List[str], int]:
"""
Simulates the removal of the last student from a queue a... |
magic_instruct_75k | 5,125 | Write a Python function `check_component_presence(entities, entity_id, component_name)` that checks whether a specific component is present in a given entity. The function should take the following parameters:
- `entities`: A dictionary where the keys are entity identifiers (integers) and the values are lists of compon... | Here is the Python code to solve the given problem in the markdown block:
```python
def check_component_presence(entities: dict, entity_id: int, component_name: str) -> bool:
"""
Checks whether a specific component is present in a given entity.
Args:
entities (dict): A dictionary where the keys are... |
magic_instruct_75k | 5,143 | Write a Python function to implement a simplified version of a map data structure. The map should support the following operations:
1. Insert a key-value pair into the map.
2. Retrieve the value associated with a given key.
3. Print all key-value pairs in the map.
The code should start with:
```python
class Map:
d... | Here is the Python code to solve the given problem in the markdown block:
```python
class Map:
def __init__(self):
"""
Initialize an empty dictionary to store key-value pairs.
"""
self.data = {}
def insert(self, key, value):
"""
Insert a key-value pair into the m... |
magic_instruct_75k | 5,147 | Create a Python class named `PowerManagementUnit` that simulates the interaction with a Power Management Unit (PMU) through an I2C interface. The class should provide methods to initialize the I2C interface, set up the PMU, read the battery voltage, and enable/disable power output. The class should be designed to mimic... | Here is the Python code to solve the given problem in the markdown block:
```python
class PowerManagementUnit:
"""
A class to simulate the interaction with a Power Management Unit (PMU) through an I2C interface.
Attributes:
sda_pin (int): The pin number for the SDA (Serial Data) line.
scl_p... |
magic_instruct_75k | 5,150 | Write a Python function to generate a SQL CREATE TABLE statement based on a list of field specifications. Each field is represented as a dictionary with keys "type", "name", and "mode". The "type" key represents the data type of the field, the "name" key represents the name of the field, and the "mode" key represents t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def generate_create_table_sql(fields: List[Dict[str, str]], table_name: str = "example_table") -> str:
"""
Generates a SQL CREATE TABLE statement based on the provided list of field specifications.... |
magic_instruct_75k | 5,177 | Create a Python script that automates the deployment process for a .NET Core web application called "NetPips". The script should perform the following steps:
1. Build the .NET Core application.
2. Update the database using Entity Framework Core migrations.
3. Publish the application in release mode to the specified dir... | Here is the Python code to solve the given problem in the markdown block:
```python
import subprocess
import os
def deploy_netpips(project_path: str, publish_dir: str, service_name: str) -> None:
"""
Automates the deployment process for a .NET Core web application called "NetPips".
Args:
project_p... |
magic_instruct_75k | 5,184 | Write a Python function to validate a dictionary containing health survey data. The function should check if the provided data dictionary contains valid boolean values for specific health indicators. The function should return `True` if all the health indicators have valid boolean values, and `False` otherwise.
The fu... | Here is the Python code to solve the given problem in the markdown block:
```python
def validate_health_data(data: dict) -> bool:
"""
Validates the health survey data to ensure that the specified health indicators
have valid boolean values.
Args:
data (dict): A dictionary containing health indi... |
magic_instruct_75k | 5,214 | Write a Python function to find the academic paper citation with the highest page count from a given list of citations. Each citation is in the format "pp.startPage-endPage, year." If there are multiple citations with the same highest page count, return the citation with the earliest year of publication.
The function ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_max_page_citation(citations: List[str]) -> str:
"""
Finds the academic paper citation with the highest page count from a given list of citations.
If there are multiple citations with the sam... |
magic_instruct_75k | 5,246 | Write a bash script to automate the deployment of a Docker image for a Raspberry Pi virtual machine. The script should perform the following tasks:
1. Enable SSH for a Raspberry Pi OS image using a shell script located in the `$SCRIPT_DIR` directory.
2. Build a Docker image with the target `dockerpi-vm` and tag it as `... | Here is the Python code to solve the given problem in the markdown block:
```bash
#!/bin/bash
# Define variables
SCRIPT_DIR="/path/to/script_directory"
RPI_OS="raspios_version"
# Enable SSH for Raspberry Pi OS image
sudo $SCRIPT_DIR/enable-ssh-for-image.sh $SCRIPT_DIR/../raspios/$RPI_OS.img
# Build Docker image with... |
magic_instruct_75k | 5,256 | Write a Python function to extract the version control system (VCS) scheme from a given VCS URL. The VCS scheme is the part of the URL that specifies the version control system being used, such as "git", "hg" (Mercurial), or "svn" (Subversion). The function should handle both HTTP and SSH-based URLs for the VCS schemes... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
VCS_SCHEMES = [
'git',
'git+https',
'git+ssh',
'git+git',
'hg+http',
'hg+https',
'hg+static-http',
'hg+ssh',
'svn',
'svn+svn',
'svn+http',
'svn+https',
'svn+ss... |
magic_instruct_75k | 5,266 | Write a Python function to determine if a given string of parentheses is balanced. A string of parentheses is considered balanced if every opening parenthesis has a corresponding closing parenthesis and they are properly nested. The function should handle three types of parentheses: `()`, `[]`, and `{}`.
The code shou... | Here is the Python code to solve the given problem in the markdown block:
```python
def isBalancedParentheses(s: str) -> bool:
"""
Determine if the given string of parentheses is balanced.
A string of parentheses is considered balanced if every opening parenthesis
has a corresponding closing parenthesi... |
magic_instruct_75k | 5,291 | Write a Python function to validate and transform a provisioning result into host data. The function should take a provisioning result as a dictionary and return the transformed host data if the input is valid. The input provisioning result dictionary will have the following keys:
- "name": representing the name of the... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Optional
def validate_and_transform(prov_result: Dict[str, str]) -> Optional[Dict[str, any]]:
"""
Validates the provisioning result and transforms it into host data if the input is valid.
Args:
... |
magic_instruct_75k | 5,295 | Write a Python function `calculate_sum_and_sequence` that takes a string `a_string` containing only digits and returns a list containing the constructed sequence of additions based on the digits in the string and the total sum of the digits. The sequence should be formatted as a string of digits separated by '+' signs.... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_sum_and_sequence(a_string: str) -> list:
"""
Calculate the sum of the digits in the given string and construct a sequence of additions.
Args:
a_string (str): A string containing only digits.
Retur... |
magic_instruct_75k | 5,332 | Write a Python function to predict the joint trajectory for a reaching and palpation (RTP) task using a pre-trained model. The function should take an input image in the form of a NumPy array, the path to the encoded model, and the path to the predictor model as inputs. The function should return the predicted joint tr... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
from typing import Tuple
class Predictor:
"""
A mock Predictor class to simulate the behavior of a real predictor.
"""
def __init__(self, encoded_model_path: str, predictor_model_path: str):
#... |
magic_instruct_75k | 5,341 | Write a Python function to generate a configuration dictionary for model admins in a web application. The function should take a list of dictionaries, each representing a model admin class, and return a dictionary where the keys are the model names and the values are dictionaries containing the display and behavior con... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Tuple
def generate_model_admin_config(model_admins: List[Dict[str, any]]) -> Dict[str, Dict[str, Tuple[str]]]:
"""
Generates a configuration dictionary for model admins in a web application.
... |
magic_instruct_75k | 5,362 | Write a Python function to find the maximum sum of a contiguous subarray within a given list of integers. The function should achieve a time complexity of O(n), where n is the length of the input list. The function should start with:
```python
from typing import List
def max_subarray_sum(nums: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def max_subarray_sum(nums: List[int]) -> int:
"""
Find the maximum sum of a contiguous subarray within the given list of integers.
Args:
nums (List[int]): The list of integers from which to ... |
magic_instruct_75k | 5,384 | Write a Python function to construct a list of file names based on a given format. The function should take in the parameters `path`, `region`, `x_start`, `y_start`, and `y_len`, and return a list of file names constructed according to the specified format.
The file name format is as follows:
`{path}/{region}_{x_start... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def construct_file_names(path: str, region: str, x_start: int, y_start: int, y_len: int) -> List[str]:
"""
Constructs a list of file names based on the given format.
Args:
path (str): The ba... |
magic_instruct_75k | 5,403 | Write a Python function to find the reverse complement of a given DNA sequence. The DNA sequence is represented as a string containing the characters 'A', 'C', 'G', and 'T'. The reverse complement is obtained by reversing the sequence and replacing each base with its complement: 'A' is replaced by 'T', 'T' is replaced ... | Here is the Python code to solve the given problem in the markdown block:
```python
def reverse_complement(dna: str) -> str:
"""
Returns the reverse complement of a given DNA sequence.
The reverse complement is obtained by reversing the sequence and replacing each base
with its complement: 'A' is repla... |
magic_instruct_75k | 5,406 | Write a Python function to calculate the average score of a series of games, excluding the highest and lowest scores. The function should take a list of integers representing the scores of the games and return the average score, rounded to the nearest integer. The list will contain at least three scores and at most 100... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_average_score(scores: List[int]) -> int:
"""
Calculate the average score of a series of games, excluding the highest and lowest scores.
Args:
scores (List[int]): A list of inte... |
magic_instruct_75k | 5,413 | Write a Python function to determine if a given string is a palindrome. A palindrome is a string that reads the same backward as forward. The function should ignore case and non-alphanumeric characters. The code should start with:
```python
def is_palindrome(s: str) -> bool:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def is_palindrome(s: str) -> bool:
"""
Determine if a given string is a palindrome, ignoring case and non-alphanumeric characters.
Args:
s (str): The input string to check.
Returns:
bool: True if the st... |
magic_instruct_75k | 5,415 | Write a Python function to calculate the frequency of each letter in a given string, ignoring case differences. The function should return a dictionary where the keys are the letters and the values are their respective frequencies. The function should only consider lowercase English letters and ignore any non-alphabeti... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_letter_frequency(input_string: str) -> dict:
"""
Calculate the frequency of each letter in the given string, ignoring case differences.
Args:
input_string (str): The input string consisting of lowercas... |
magic_instruct_75k | 5,416 | Write a Python function to determine whether a target word can be formed by concatenating any combination of words from a given list. Each word from the list can be used multiple times, and the order of the words can be rearranged. The function should return `True` if the target word can be formed, and `False` otherwis... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def can_form_target_word(words: List[str], target: str) -> bool:
"""
Determines whether the target word can be formed by concatenating any combination of words from the given list.
Args:
wor... |
magic_instruct_75k | 5,453 | Write a Python function to sort a dictionary by the length of its keys in descending order. If two keys have the same length, they should appear in the same order as they were in the original dictionary. The function should return a new dictionary with the sorted key-value pairs.
The code should start with:
```python
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def sort_dict_by_key_length(input_dict: Dict[str, int]) -> Dict[str, int]:
"""
Sorts a dictionary by the length of its keys in descending order. If two keys have the same length,
they appear in the s... |
magic_instruct_75k | 5,470 | Write a Python function `generate_token` that generates a unique token for a given username. The token should be in the format "username:timestamp:random_string", where:
- `username` is the input username.
- `timestamp` is the current UTC time in the format "YYYY-MM-DDTHH:MM:SS".
- `random_string` is a 6-character alph... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
import string
from datetime import datetime
def generate_token(username: str) -> str:
"""
Generates a unique token for a given username.
The token is in the format "username:timestamp:random_string", where:
... |
magic_instruct_75k | 5,495 | Write a Python function to find the maximum sum of a contiguous subarray within a given list of integers. The function should efficiently handle both positive and negative integers. The code should start with:
```python
from typing import List
def max_subarray_sum(nums: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def max_subarray_sum(nums: List[int]) -> int:
"""
Find the maximum sum of a contiguous subarray within the given list of integers.
Args:
nums (List[int]): The list of integers from which to ... |
magic_instruct_75k | 5,500 | Write a Python function to filter out invalid messages from a list of Discord messages. An invalid message is defined as one that raises a `discord.errors.NotFound` exception when processed. The function should take a list of messages as input and return a new list containing only the valid messages.
The code should s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
class DiscordErrors:
class NotFound(Exception):
pass
def simulate_message_processing(message: str) -> None:
"""
Simulate the processing of a Discord message.
Raises discord.errors.NotFou... |
magic_instruct_75k | 5,523 | Write a Python function to process a list of data and encode any string elements into bytes, while leaving other data types unchanged. The function should iterate through the list, encode each string element using the `encode()` method, and return a new list with the encoded strings and unchanged other elements.
The c... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def encode_strings(data: List) -> List:
"""
Processes a list of data and encodes any string elements into bytes, while leaving other data types unchanged.
Args:
data (List): A list of elemen... |
magic_instruct_75k | 5,552 | Write a Python function to print a pattern of numbers and spaces based on the given input `num`. The pattern should alternate between odd and even numbers in each row, with the following rules:
- Odd numbers are printed with two spaces after each number.
- Even numbers are preceded by a space and printed without any sp... | Here is the Python code to solve the given problem in the markdown block:
```python
def print_number_pattern(num: int) -> None:
"""
Prints a pattern of numbers and spaces based on the given input `num`.
The pattern alternates between odd and even numbers in each row:
- Odd numbers are printed with two ... |
magic_instruct_75k | 5,567 | Create a Python class `GameEventEmitter` that implements a simple event system for a pet simulation game. The class should allow registering event listeners for specific event types and triggering those events with relevant data. The event types are defined as static string variables in the `GameEvents` class: `PET_SEL... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Callable, Any, Dict, List
class GameEvents:
PET_SELL_EVENT = "petSellEvent"
PET_CANCELSELL_EVENT = "petCancelSellEvent"
PET_INFO_DETAIL_EVENT = "petInfoDetailEvent"
class GameEventEmitter:
def __init... |
magic_instruct_75k | 5,570 | Write a Python function to find the maximum sum of consecutive integers after replacing all spaces with hyphens in each input integer. The function should take a list of integers as input and return the maximum sum of consecutive integers.
The code should start with:
```python
from typing import List
def max_consecut... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def max_consecutive_sum(arr: List[int]) -> int:
"""
Calculate the maximum sum of consecutive integers after replacing all spaces with hyphens in each input integer.
Args:
arr (List[int]): A ... |
magic_instruct_75k | 5,583 | Write a Python function to generate a multiplication table for numbers from 1 to `n`. The function should return a list of lists, where each inner list represents a row in the multiplication table. The function should start with:
```python
from typing import List
def multiplication_table(n: int) -> List[List[int]]:
``... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def multiplication_table(n: int) -> List[List[int]]:
"""
Generate a multiplication table for numbers from 1 to `n`.
Args:
n (int): The upper limit of the multiplication table.
Returns:
... |
magic_instruct_75k | 5,596 | Write a Python function to calculate the sum of all even Fibonacci numbers up to a given limit. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. For example, the first few numbers in the Fibonacci sequence are 0, 1, 1, 2, 3, 5, 8, 13... | Here is the Python code to solve the given problem in the markdown block:
```python
def even_fibonacci_sum(limit: int) -> int:
"""
Calculate the sum of all even Fibonacci numbers up to a given limit.
Args:
limit (int): The upper limit for the Fibonacci numbers to be considered.
Returns:
... |
magic_instruct_75k | 5,607 | Write a Python function to find the antonym of a given word from a predefined list of antonym pairs. If the word is found in the list, the function should return its antonym. If the word is not found, the function should return a message indicating that no antonym is available for the given word.
The function should s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def find_antonym(word: str, antonyms_list: List[Tuple[str, str]]) -> str:
"""
Finds the antonym for a given word from a predefined list of antonym pairs.
Args:
word (str): The word fo... |
magic_instruct_75k | 5,614 | Implement a custom validation decorator in Python that ensures a given text string is not empty and does not consist solely of whitespace characters. The decorator should be used to validate the content of a text string before it is processed by a function. The validation function should raise an `AssertionError` if th... | Here is the Python code to solve the given problem in the markdown block:
```python
def validator(attribute):
"""
A decorator factory that creates a validation decorator for a given attribute.
Args:
attribute (str): The name of the attribute being validated.
Returns:
function: A decora... |
magic_instruct_75k | 5,623 | Write a Python function to simulate the behavior of the `Manager` class from the given C++ code snippet. The function should:
1. Create a `Manager` class that inherits from a `Person` class.
2. Implement a constructor for the `Manager` class that initializes the `salary` and `test` attributes.
3. Implement a method `se... | Here is the Python code to solve the given problem in the markdown block:
```python
class Person:
def func(self):
"""
Prints a message indicating that this is a Person object.
"""
print(f"This is Person, this is {hex(id(self))}")
class Manager(Person):
def __init__(self, salary:... |
magic_instruct_75k | 5,629 | Write a Python function that processes a list of integers and returns two arrays. The first array should contain the original list of integers, while the second array should contain the same integers but in sorted order. The function should handle any list of integers, including empty lists and lists with duplicate val... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def process_list(arr: List[int]) -> Tuple[List[int], List[int]]:
"""
Processes a list of integers and returns a tuple containing the original list and the sorted list.
Args:
arr (List... |
magic_instruct_75k | 5,643 | Write a Python function to count the occurrences of the keyword "then" in a given piece of code. The keyword "then" should only be counted if it appears as a standalone word and not as part of another word (e.g., "thence" or "thenar"). The function should use regular expressions to ensure that "then" is matched as a wh... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def count_then_occurrences(code: str) -> int:
"""
Counts the occurrences of the keyword "then" in a given piece of code.
The keyword "then" is only counted if it appears as a standalone word and not as part of an... |
magic_instruct_75k | 5,661 | Write a Python function that processes a list of module import statements and returns a dictionary containing the imported modules and their corresponding import statements. The function should handle both direct and relative imports and should ignore any exceptions raised during the import process. The function should... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_imports(import_list: list) -> dict:
"""
Processes a list of module import statements and returns a dictionary containing the imported modules and their corresponding import statements.
Args:
import_list ... |
magic_instruct_75k | 5,671 | Write a Python function to convert a string representation of a positive integer to its corresponding integer value without using any built-in conversion functions or libraries. The function should handle only numeric characters (0-9) and should return the integer value represented by the input string.
The code should... | Here is the Python code to solve the given problem in the markdown block:
```python
def to_int(num_str: str) -> int:
"""
Converts a string representation of a positive integer to its corresponding integer value.
Args:
num_str (str): The string representation of a positive integer.
Returns:
... |
magic_instruct_75k | 5,704 | Write a Python function to find the i-th order statistic of a given array of integers. The i-th order statistic is the i-th smallest element in the array. The function should handle duplicate elements and invalid input values for i.
The code should start with:
```python
from typing import List, Optional
import random
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
import random
def partition(arr: List[int], low: int, high: int) -> int:
"""
Partitions the array around a pivot element such that elements less than or equal to the pivot
are on the left, ... |
magic_instruct_75k | 5,713 | Write a Python function to construct a build command for compiling a C source file into an executable. The function should take the source file name, additional C flags, linker flags, and libraries as input and return the complete command to build the executable. The executable should be named after the `NAME` variable... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
NAME = 'fastrouter'
def build_executable(source_file: str, cflags: List[str], ldflags: List[str], libs: List[str]) -> str:
"""
Constructs a build command to compile a C source file into an executable.
... |
magic_instruct_75k | 5,728 | Write a Python function to determine if a given list of integers is sorted in non-decreasing order without using any built-in sorting functions or libraries. The function should return `True` if the list is sorted and `False` otherwise. The function signature should be:
```python
from typing import List
def is_sorted(... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Determines if a given list of integers is sorted in non-decreasing order.
Args:
arr (List[int]): The list of integers to check.
Returns:
... |
magic_instruct_75k | 5,732 | Write a Python function to parse and process football league data. The function should take in a league name and a year as input and return the team standings for that league and year. The team standings should include the teams' names, positions, points, and any other relevant information. The function should handle c... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Union
def team_standings(league: str, year: int, info_all: List[Dict[str, Union[str, int]]]) -> Union[List[Dict[str, Union[str, int]]], str]:
"""
Returns the team standings for the specified leagu... |
magic_instruct_75k | 5,759 | Write a Python function to format a given dictionary representing a publication into a specific string format. The dictionary contains details about the publication such as title, author, whether it is published, and tags. The function should return a formatted string that includes these details in a specific format. I... | Here is the Python code to solve the given problem in the markdown block:
```python
def format_publication(publication: dict) -> str:
"""
Formats a publication dictionary into a specific string format.
Args:
publication (dict): A dictionary containing details about the publication.
Expe... |
magic_instruct_75k | 5,760 | Write a Python function to calculate the sum of the individual digits of a given integer. The function should handle both positive and negative integers. If the input is a negative integer, the function should ignore the negative sign and calculate the sum of the digits.
The code should start with:
```python
def sum_o... | Here is the Python code to solve the given problem in the markdown block:
```python
def sum_of_digits(num: int) -> int:
"""
Calculate the sum of the individual digits of a given integer.
Args:
num (int): The integer whose digits are to be summed.
Returns:
int: The sum of the individual... |
magic_instruct_75k | 5,782 | Write a Python function to simulate a simplified HTTP connection class with methods `make_request` and `is_closed`. The `make_request` method should take three parameters: `method` (a string representing the HTTP method), `request` (a string representing the request URL), and `pack` (a move-only object representing the... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Any, Optional
class MoveOnlyObject:
def __init__(self, value: Any):
self.value = value
def __del__(self):
self.value = None
class Connection:
def __init__(self):
self.closed = Fa... |
magic_instruct_75k | 5,794 | Write a Python function to configure Cross-Origin Resource Sharing (CORS) in a Django settings file by adding a specific origin to the CORS whitelist. The function should take a list of existing origins and a new origin as input, and return the updated list of origins.
The code should start with:
```python
from typing... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def add_cors_origin(existing_origins: List[str], new_origin: str) -> Tuple[str]:
"""
Adds a new origin to the CORS whitelist in a Django settings file.
Args:
existing_origins (List[st... |
magic_instruct_75k | 5,795 | Write a Python function to generate a maze based on a given seed and height. The maze should be represented as a grid of cells, with each cell being either a wall or an open space. The function should output the generated maze to the standard output in a human-readable format, where `#` represents a wall and `.` repres... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def generate_maze(seed: int, height: int) -> List[List[str]]:
"""
Generates a maze based on the provided seed and height.
Args:
seed (int): The seed for the random number gener... |
magic_instruct_75k | 5,817 | Write a Python function to serialize and deserialize a dictionary to and from a JSON string. Additionally, implement functions to read and write the serialized JSON string to a file. The code should start with:
```python
import json
from typing import Dict, Any
def serialize(data: Dict[str, Any]) -> str:
"""
S... | Here is the Python code to solve the given problem in the markdown block:
```python
import json
from typing import Dict, Any
def serialize(data: Dict[str, Any]) -> str:
"""
Serialize a dictionary to a JSON string.
Args:
data (Dict[str, Any]): The dictionary to serialize.
Returns:
str:... |
magic_instruct_75k | 5,818 | Write a Python function to calculate the sum of the squares of all even numbers in a given list of integers. The function should utilize the `numpy` library for efficient array operations. The function should be named `sum_of_squares_of_even_numbers` and should accept a single parameter:
- `numbers`: a list of integers... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def sum_of_squares_of_even_numbers(numbers: list) -> int:
"""
Calculate the sum of the squares of all even numbers in the given list.
Args:
numbers (list): A list of integers.
Returns:
... |
magic_instruct_75k | 5,819 | Write a Python function to print a specific pattern of numbers in a diagonal format. The pattern should start with the number 1 and each subsequent number should be indented by an increasing number of spaces equal to its value minus one. The function should take an integer `n` as input, which represents the number of l... | Here is the Python code to solve the given problem in the markdown block:
```python
def print_diagonal_pattern(n: int):
"""
Prints a diagonal pattern of numbers from 1 to n.
Each number i is printed with i-1 spaces before it.
Args:
n (int): The number of lines to print.
Returns:
No... |
magic_instruct_75k | 5,823 | Write a Python function to process a directory and its subdirectories, performing specific operations based on the type of each item (file, directory, or symbolic link). The function should handle nested directories and display the following information:
1. For each regular file, display the file name and its size in b... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
def process_directory(sources_dir: str):
"""
Process a directory and its subdirectories, displaying information about files, directories, and symbolic links.
Args:
sources_dir (str): The path to the direc... |
magic_instruct_75k | 5,852 | Write a Python function to calculate the total number of unique paths from the top-left corner to the bottom-right corner of an m x n grid. You can only move either down or right at any point in time. The function should start with:
```python
def uniquePaths(m: int, n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def uniquePaths(m: int, n: int) -> int:
"""
Calculate the total number of unique paths from the top-left corner to the bottom-right corner of an m x n grid.
Args:
m (int): The number of rows in the grid.
... |
magic_instruct_75k | 5,884 | Write a Python function to perform an "almost certain" primality check using the Miller-Rabin primality test. The function should determine whether a given integer `n` is almost certainly prime or composite. The function should return `True` if `n` is almost certainly prime, and `False` if it is composite.
The code sh... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
def is_prime(n: int) -> bool:
"""
Determine whether a given integer `n` is almost certainly prime using the Miller-Rabin primality test.
Args:
n (int): The integer to check for primality.
Returns... |
magic_instruct_75k | 5,891 | Write a Python function to extract and return the file names without their extensions from a list of Unix-style file paths. The function should process each file path, extract the file name, remove the file extension, and return a new list containing these file names in the same order as they appear in the input list.
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def extract_file_names(file_paths: List[str]) -> List[str]:
"""
Extracts and returns the file names without their extensions from a list of Unix-style file paths.
Args:
file_paths (List[str]... |
magic_instruct_75k | 5,913 | Write a Python function to process a list of part identifiers and their friendly names. The function should return a dictionary mapping the part identifiers to their corresponding friendly names. The function should handle cases where the lengths of the input lists do not match by returning a dictionary that includes m... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def process_parts(partIds: List[str], partFriendlyNames: List[str]) -> Dict[str, str]:
"""
Processes a list of part identifiers and their friendly names to create a dictionary mapping part identifi... |
magic_instruct_75k | 5,920 | Write a Python function to determine if a given string of parentheses is balanced. A string of parentheses is considered balanced if every opening parenthesis has a corresponding closing parenthesis and they are properly nested. The function should handle three types of parentheses: `()`, `[]`, and `{}`.
The code shou... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_balanced(s: str) -> bool:
"""
Determine if a given string of parentheses is balanced.
Args:
s (str): The string containing parentheses to be checked.
Returns:
bool: True if the parentheses are ba... |
magic_instruct_75k | 5,926 | Write a Python function to process a dictionary containing package data and return a modified dictionary with specific changes. The input dictionary will have keys representing package names and values representing lists of associated files. Your task is to implement a function `process_package_data` that takes this di... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_package_data(package_data: dict) -> dict:
"""
Processes the package data dictionary by removing empty lists of files and sorting the remaining files in lexicographical order.
Args:
package_data (dict): A... |
magic_instruct_75k | 5,932 | Write a Python function called `custom_map` that takes two arguments:
- `func`: A function that takes a single argument and returns a transformed value.
- `lst`: A list of integers.
The `custom_map` function should apply the `func` to each element of the `lst` and return a new list containing the transformed values. T... | Here is the Python code to solve the given problem in the markdown block:
```python
def custom_map(func, lst):
"""
Applies a given function to each element of a list and returns a new list with the transformed values.
Args:
func (function): A function that takes a single argument and returns a tran... |
magic_instruct_75k | 5,994 | Write a Python function to generate a frequency summary of commands from a given list. Each command is represented as a string and may contain wildcard characters. The frequency summary should be displayed in descending order based on the frequency of occurrence. The wildcard character '*' can be used to match any comm... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def generate_frequency_summary(commands: List[str]) -> Dict[str, int]:
"""
Generates a frequency summary of commands from a given list.
Args:
commands (List[str]): A list of command st... |
magic_instruct_75k | 5,996 | Write a Python function to categorize filesystem entries based on their attributes and count the occurrences of each attribute type. Each entry is represented as a space-separated string of attributes. The function should return a dictionary where the keys are the attribute types and the values are the counts of occurr... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def categorize_filesystem_entries(entries: List[str]) -> Dict[str, int]:
"""
Categorizes filesystem entries based on their attributes and counts the occurrences of each attribute type.
Args:
... |
magic_instruct_75k | 6,009 | Create a Python class `PlantDatabase` that efficiently stores and retrieves plant names based on their characteristics. The class should support the following methods:
1. `addPlant(name: str, characteristics: List[str])`: Adds a new plant with the given name and characteristics to the database.
2. `removePlant(name: st... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
class PlantDatabase:
def __init__(self):
"""
Initialize the PlantDatabase with two dictionaries:
- plant_dict: Maps plant names to their characteristics.
- char_dict: Maps cha... |
magic_instruct_75k | 6,011 | Write a Python function to format a given number into a dollar format. The dollar format should include a dollar sign, commas for thousands separators, and two decimal places. The function should handle both integer and float inputs and should round the float to two decimal places.
The code should start with:
```pytho... | Here is the Python code to solve the given problem in the markdown block:
```python
def format_dollars(number: float) -> str:
"""
Formats a given number into a dollar format string.
The dollar format includes a dollar sign, commas for thousands separators,
and two decimal places. The function handles b... |
magic_instruct_75k | 6,012 | Write a Python function `getPercentageValue` that takes an integer `num` as input and returns the corresponding percentage value as a string. If the input integer does not have a corresponding percentage value in the given mapping, the function should return "Not found". The mapping of integers to their corresponding p... | Here is the Python code to solve the given problem in the markdown block:
```python
def getPercentageValue(num: int) -> str:
"""
Returns the percentage value corresponding to the given integer.
Args:
num (int): The integer for which the percentage value is to be found.
Returns:
str: Th... |
magic_instruct_75k | 6,043 | Write a Python function to generate a Fibonacci sequence up to a specified length. The function should take the length of the sequence as its first argument and optional second and third arguments to specify the starting numbers of the sequence. If the second and third arguments are not provided, the sequence should st... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_fibonacci_sequence(length: int, start1: int = 0, start2: int = 1) -> list:
"""
Generates a Fibonacci sequence up to a specified length with optional starting numbers.
Args:
length (int): The length of t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.