source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
magic_instruct_75k | 19,357 | Create a Python class `Inventory` to manage a store's inventory. The class should have the following functionalities:
1. `add_item`: A method to add a new item to the inventory. If the item already exists, the quantity should be updated.
2. `remove_item`: A method to remove a specified quantity of an item from the inve... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Tuple
class Inventory:
def __init__(self):
"""
Initialize an empty inventory.
"""
self.items: Dict[int, Tuple[str, int, float]] = {}
def add_item(self, id: int, name: st... |
magic_instruct_75k | 19,363 | Create a Python class hierarchy for a logging system that supports logging messages at different levels of severity (INFO, WARNING, ERROR) and to multiple destinations (console, file, network). The system should be flexible and extensible, allowing for easy integration with existing and future components of the applica... | Here is the Python code to solve the given problem in the markdown block:
```python
from abc import ABC, abstractmethod
from typing import List
class LogLevel(ABC):
"""
Abstract base class for log levels.
Methods:
get_level: Returns the string representation of the log level.
"""
@abstract... |
magic_instruct_75k | 19,384 | Write a Python function to calculate the winning bid for an auction. The function should take a list of bids as input and return the highest bid. If there are no bids, the function should return 0. The code should start with:
```python
from typing import List
def calculate_winning_bid(bids: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_winning_bid(bids: List[int]) -> int:
"""
Calculate the winning bid for an auction.
Args:
bids (List[int]): A list of integers representing the bids placed in the auction.
... |
magic_instruct_75k | 19,401 | Write a Python function to organize a list of data files into a dictionary based on their file extensions. Each file is represented as a tuple containing the file name and its extension. The function should return a dictionary where the keys are the file extensions and the values are lists of file names with the corres... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def organize_files(data_files: List[Tuple[str, str]]) -> Dict[str, List[str]]:
"""
Organizes a list of data files into a dictionary based on their file extensions.
Args:
data_fi... |
magic_instruct_75k | 19,405 | Write a Python function to check whether a given list of integers is sorted in non-decreasing order. The function should return `True` if the list is sorted in non-decreasing order, and `False` otherwise. The function should handle edge cases such as empty lists and single-element lists.
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 is_sorted(arr: List[int]) -> bool:
"""
Checks whether 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 | 19,418 | Write a Python function to optimize the configuration of a PyTorch data loader for a machine learning pipeline. The function should take the number of classes as input and return a dictionary with optimized settings for batch size, shuffling, pinning memory, and the number of worker processes. The goal is to maximize d... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def optimize_data_loader(num_classes: int) -> dict:
"""
Optimize the configuration of a PyTorch data loader for a machine learning pipeline.
Args:
num_classes (int): The number of classes in the dataset... |
magic_instruct_75k | 19,430 | Write a Python function to parse and structure software license information from a given string. The input string contains the maintainer's name and email, separated by `" <<EMAIL>>"`, followed by the license type and its optional parameters, separated by `":"`. The function should return a dictionary with keys "mainta... | Here is the Python code to solve the given problem in the markdown block:
```python
def parse_license_info(info: str) -> dict:
"""
Parses a string containing software license information and returns a dictionary with structured data.
The input string is expected to follow the format:
"maintainer <<EMAI... |
magic_instruct_75k | 19,445 | Write a Python function `format_params_string` that takes a dictionary `params` as input and returns a formatted string representing the key-value pairs. The function should handle nested dictionaries by concatenating the keys with a dot (.) to represent the hierarchy. The output string should be formatted as follows:
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def format_params_string(params: Dict) -> str:
"""
Formats a dictionary with nested dictionaries into a string where each key-value pair is represented on a new line.
Nested keys are concatenated wit... |
magic_instruct_75k | 19,448 | Write a Python function `sockCount(unique_pile, ar)` that takes in a list `unique_pile` containing unique sock colors and another list `ar` representing a sequence of socks. The function should return a list containing the count of each unique sock color in the `ar` list, in the same order as the colors appear in the `... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sockCount(unique_pile: List[int], ar: List[int]) -> List[int]:
"""
Counts the occurrences of each unique sock color in the `ar` list, in the same order as the colors appear in the `unique_pile` list.... |
magic_instruct_75k | 19,449 | Write a Python function to extract unique class names from a given HTML code snippet. The function should take the HTML code as input and return a list of unique class names found within the code. The class names should be returned in the order of their first occurrence in the HTML code.
The code should start with:
``... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def extract_class_names(html_code: str) -> List[str]:
"""
Extracts unique class names from a given HTML code snippet.
Args:
html_code (str): The HTML code snippet from which to ext... |
magic_instruct_75k | 19,452 | Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock at most once, given a list of integers representing the daily stock prices. If it is not possible to make any profit, the function should return 0.
The code should start with:
```python
from typing import List
d... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def maxProfit(prices: List[int]) -> int:
"""
Calculate the maximum profit that can be obtained by buying and selling a stock at most once.
Args:
prices (List[int]): A list of integers repres... |
magic_instruct_75k | 19,454 | Write a Python function to find the maximum value in a given list of integers. The function should handle an empty list by returning `None`. The code should start with:
```python
from typing import List, Optional
def find_max(arr: List[int]) -> Optional[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
from typing import List, Optional
def find_max(arr: List[int]) -> Optional[int]:
"""
Find the maximum value in a given list of integers.
Args:
arr (List[int]): The list of integers from which to find the maximum ... |
magic_instruct_75k | 19,477 | Write a Python function to group a list of triplets by their phase identifier. Each triplet is represented as a tuple of three elements, where the first element is the phase identifier (a string) and the remaining two elements are the data associated with that phase. The function should take a list of triplets as input... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict, Any
def group_triplets(triplets: List[Tuple[str, Any, Any]]) -> Dict[str, List[Tuple[str, Any, Any]]]:
"""
Groups a list of triplets by their phase identifier.
Args:
triplets (... |
magic_instruct_75k | 19,514 | Write a Python function to convert 3D coordinates from a non-standard camera tracking format to a standard format. The non-standard format has the y-axis pointing up and the z-axis pointing backward, while the standard format has the y-axis pointing down and the z-axis pointing forward. The function should take a list ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def convert_coordinates(camera_data: List[Tuple[float, float, float]]) -> List[Tuple[float, float, float]]:
"""
Converts 3D coordinates from a non-standard camera tracking format to a standard for... |
magic_instruct_75k | 19,516 | Write a Python function to find the common elements between two lists of strings, preserving the order of their first occurrence in the first list. The function should return a new list containing these common elements.
The code should start with:
```python
from typing import List
def common_elements(list1: List[str]... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def common_elements(list1: List[str], list2: List[str]) -> List[str]:
"""
Returns a list of common elements between two lists of strings, preserving the order of their first occurrence in the first list.... |
magic_instruct_75k | 19,534 | Write a Python function to manage email delivery using a mail server. The function should handle connecting to the mail server and delivering email messages. The function should include proper error handling for cases where the user is not connected to the mail server.
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 Optional
class EmailManager:
def __init__(self, mail_server: str):
"""
Constructor for initializing the mail server connection.
Args:
mail_server (str): The URL of the mail se... |
magic_instruct_75k | 19,543 | Write a Python function to simulate the movement of a player in a grid. The function should take the current position of the player as input and return the direction in which the player should move next. The possible directions are 'Stay', 'North', 'West', 'East', and 'South'. The function should make random decisions ... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
def simulate_movement(current_position: tuple) -> str:
"""
Simulates the movement of a player in a grid by randomly selecting a direction.
Args:
current_position (tuple): A tuple of two integers repre... |
magic_instruct_75k | 19,560 | Write a Python function to manage the auto-update functionality of a software application. The function should allow users to enable or disable bi-weekly auto-update checks and customize the frequency of auto-updates. The function should return a dictionary indicating the current settings.
The code should start with:
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def manage_auto_updates(enable_biweekly: bool, update_frequency: int) -> Dict[str, bool]:
"""
Manages the auto-update functionality of a software application.
Args:
enable_biweekly (bool): A... |
magic_instruct_75k | 19,561 | Write a Python function to configure proxy settings based on user input. The function should take three arguments: proxy type, proxy address, and port number. If the function is called with fewer than three arguments, it should raise a `ValueError` with the message "No Proxy configuration provided". If the function rec... | Here is the Python code to solve the given problem in the markdown block:
```python
def configure_proxy(proxy_type: str, proxy_address: str, port_number: int) -> str:
"""
Configures proxy settings based on the provided arguments and returns a formatted string representing the proxy configuration.
Args:
... |
magic_instruct_75k | 19,568 | Write a Python function to calculate the ending coordinates for a swipe gesture in a mobile game. The swipe gesture moves a game piece from one cell to another on a grid-based layout. The ending coordinates are determined based on the given parameters and a specific formula.
The function should start with:
```python
d... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculateSwipeCoordinates(TIME_COEFF: float, COORD_Y_START_SCAN: int, PIECE_BASE_HEIGHT_HALF: int, PIECE_BODY_WIDTH: int, SWIPE_X1: int, SWIPE_Y1: int) -> (int, int):
"""
Calculate the ending coordinates for a swipe gesture ... |
magic_instruct_75k | 19,578 | Write a Python function to parse a given HTML text and extract the content within the `<span>` tags. The function should return a list of strings containing the text within the `<span>` tags in the order they appear in the HTML text. The function should handle HTML text with newlines and spaces within and between the `... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def extract_span_content(html_txt: str) -> List[str]:
"""
Extracts the content within the <span> tags from the given HTML text.
Args:
html_txt (str): A string containing valid HTML... |
magic_instruct_75k | 19,592 | Write a Python function to generate an HTML form for managing categories in a content management system. The form should allow users to edit the name, description, slug, and status of a category. The form should be pre-populated with the current values of the category being edited.
The function should have the followi... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_category_form(category: dict) -> str:
"""
Generates an HTML form for managing a category in a content management system.
Args:
category (dict): A dictionary containing the properties of the category.
... |
magic_instruct_75k | 19,623 | Write a Python function to generate a list of unique random numbers within a specified range. The function should take two parameters: `start` and `end`, representing the inclusive range within which the random numbers should be generated. The function should return a list of unique random numbers within the specified ... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
def generate_unique_random_numbers(start: int, end: int) -> list:
"""
Generates a list of unique random numbers within the specified range [start, end].
Args:
start (int): The inclusive start of the r... |
magic_instruct_75k | 19,635 | Write a Python function to increment the value of a given variable by 1 using both the traditional addition method and the shorthand increment operator. The function should accept an integer as input and return a tuple containing the incremented value using both methods.
The code should start with:
```python
def incre... | Here is the Python code to solve the given problem in the markdown block:
```python
def increment_by_one(value: int) -> tuple:
"""
Increments the given integer by 1 using both traditional addition and shorthand increment operator.
Args:
value (int): The integer value to be incremented.
Returns... |
magic_instruct_75k | 19,645 | Write a Python function to simulate a simple state machine with three states: 0, 1, and 2. The state machine transitions between states based on the input. The transition rules are as follows:
- If the current state is 0 and the input is "A", transition to state 1.
- If the current state is 0 and the input is "B", tran... | Here is the Python code to solve the given problem in the markdown block:
```python
def state_transition(current_state: int, input: str) -> int:
"""
Simulate a state machine with three states (0, 1, 2) and two inputs ("A", "B").
The function returns the next state based on the current state and input.
... |
magic_instruct_75k | 19,646 | Write a Python function to process a list of tweet dictionaries and extract specific information from each tweet. The function should take a list of tweet dictionaries as input and return a list of tuples, where each tuple contains the tweet's creation date, tweet ID, and cleaned text. The `clean_tweet` function is pro... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Tuple
def clean_tweet(text: str) -> str:
"""
Removes any single quotes from the given text.
Args:
text (str): The text to be cleaned.
Returns:
str: The cleaned text with ... |
magic_instruct_75k | 19,667 | Implement a Python function to read and validate a custom file format called RSM (Random Scale Model). The RSM file format contains various data structures, including key frames for scaling and volume boxes for defining the volume of the model. The function should read a 4-byte magic value from the input stream and val... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import BinaryIO
class RSM:
def __init__(self):
"""
Initialize the RSM class with member variables set to 0.
"""
self.m_scale_key_frames = 0
self.m_volume_boxes = 0
def _read(... |
magic_instruct_75k | 19,675 | Implement a 2D array data structure in Python that supports the following operations:
1. **create**: Initializes the 2D array with a given number of rows and columns.
2. **get**: Retrieves the value at a specific position in the array.
3. **set**: Updates the value at a specific position in the array with a given value... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
class TwoDArray:
def __init__(self, rows: int, cols: int):
"""
Initializes the 2D array with the specified number of rows and columns.
Args:
rows (int): The number of row... |
magic_instruct_75k | 19,683 | Write a Python function to sort a list of strings, where each string represents a pair of a word and a number separated by a comma. The number represents the length of the word. The list should be sorted based on the length of the word in ascending order. If two words have the same length, they should be sorted lexicog... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sort_words_by_length(words: List[str]) -> List[str]:
"""
Sorts a list of strings, where each string represents a pair of a word and a number separated by a comma.
The number represents the length... |
magic_instruct_75k | 19,693 | Write a Python function to find the longest substring of consecutive, non-repeating characters within a given string. If there are multiple substrings with the same length, return the first one found. If there are no non-repeating substrings, return an empty string.
The function should start with:
```python
def longes... | Here is the Python code to solve the given problem in the markdown block:
```python
def longest_non_repeating_substring(s: str) -> str:
"""
Finds the longest substring of consecutive, non-repeating characters within the given string.
Args:
s (str): The input string to search for the longest non-rep... |
magic_instruct_75k | 19,697 | Write a Python function to find the maximum profit that can be obtained by buying and selling a stock at most once, given a list of integers representing the stock prices on different days. If it is not possible to make any profit, return 0. The function should efficiently solve the problem using the provided `int_max`... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def maxProfit(prices: List[int]) -> int:
"""
Calculate the maximum profit that can be obtained by buying and selling a stock at most once.
Args:
prices (List[int]): A list of integers repres... |
magic_instruct_75k | 19,709 | Write a Python function `process_location_data(params, query)` that processes user location data based on certain parameters. The function will take in two dictionaries, `params` and `query`, as input. The `params` dictionary contains a key "location_id" representing the location identifier, and the `query` dictionary ... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_location_data(params: dict, query: dict) -> tuple:
"""
Processes user location data based on given parameters.
Args:
params (dict): A dictionary containing the key "location_id".
query (dict): A ... |
magic_instruct_75k | 19,746 | Write a Python function to simulate a file handling system that opens and manages multiple files using different file handlers. The function should take a file name as input and return a list of strings representing the file names opened using the respective handlers. The file handlers are represented by the variables ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def open_files(file_name: str) -> List[str]:
"""
Simulates opening a file using three different file handlers and returns a list of strings
representing the file names opened using the respective han... |
magic_instruct_75k | 19,748 | Implement a Python function to detect and log changes in window features when new tabs are inserted into a tab strip model. The function should check if the window features have changed since the last observation and log the window metrics using a provided logging function if they have changed.
The code should start w... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Any
def log_window_metrics_ukm_entry(window_features: Dict[str, Any]) -> None:
"""
Simulates logging window metrics using the UKM system.
Args:
window_features (Dict[str, Any]): The win... |
magic_instruct_75k | 19,752 | Write a Python function to parse a given metadata dictionary and extract specific information from it. The metadata dictionary contains details about a Python module, including its name, description, authors, date, license, references, and type. Your function should extract and return the following information:
1. The ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Any
def extract_module_info(metadata: Dict[str, Any]) -> Dict[str, Any]:
"""
Extracts specific information from a given metadata dictionary about a Python module.
Args:
metadata (Dict... |
magic_instruct_75k | 19,761 | Write a bash script to automate the process of fetching information for a specific package from a given URL. The script should handle the download of the package information and provide appropriate error handling in case the download fails. The script should:
1. Create a temporary file to store the package information.... | Here is the Python code to solve the given problem in the markdown block:
```bash
#!/bin/bash
# URL for the package information
PKGURL="https://example.com/package-info"
# Function to handle download failure
fail() {
echo "Error: Failed to download package information from $PKGURL" >&2
exit 1
}
# Create a te... |
magic_instruct_75k | 19,762 | Write a Python function to generate a header based on the provided context and namespace. The function should take two arguments: the context and the namespace. If the namespace is provided, it should be included in the header; otherwise, only the context should be included. The header should be returned as a string.
... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_header(context: str, namespace: str = None) -> str:
"""
Generates a header based on the provided context and namespace.
Args:
context (str): The context to include in the header.
namespace (str,... |
magic_instruct_75k | 19,764 | Write a Python function to extract the indices of specific headers from a given dataset header string based on a specified task. The dataset header is a string containing tab-separated headers, and the relevant headers for each task are stored in a dictionary called `relevant_headers` with task names as keys and lists ... | Here is the Python code to solve the given problem in the markdown block:
```python
def extract_header_indices(dataset_header: str, relevant_headers: dict, task_name: str) -> list:
"""
Extracts the indices of specific headers from a given dataset header string based on a specified task.
Args:
datas... |
magic_instruct_75k | 19,829 | Write a Python function to process a list of strings and modify each string based on specific conditions. The function should take in a list of strings and return a modified list based on the following rules:
1. If a string contains the word "should" followed by the word "be" within the same sentence, the function sho... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def process_strings(strings: List[str]) -> List[str]:
"""
Processes a list of strings and modifies each string based on specific conditions.
Args:
strings (List[str]): A list of st... |
magic_instruct_75k | 19,839 | Write a Python function to add an integer to a given dictionary under a specific key. The function should take a dictionary and an integer as input and return the updated dictionary with the integer added under the key `'mapVersion'`.
The code should start with:
```python
def add_int_to_dict(pms: dict, mapVersion: int... | Here is the Python code to solve the given problem in the markdown block:
```python
def add_int_to_dict(pms: dict, mapVersion: int) -> dict:
"""
Adds an integer to the given dictionary under the key 'mapVersion'.
Args:
pms (dict): The dictionary to which the integer should be added.
mapVers... |
magic_instruct_75k | 19,864 | Write a Python function to generate a list of commands for a package management system. The system uses two custom commands: `createpkg` and `installpkg`. The function should take a list of tuples, where each tuple contains a package name and version, and return a list of strings representing the commands to create and... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def generatePackageCommands(packages: List[Tuple[str, str]]) -> List[str]:
"""
Generates a list of commands to create and install packages based on the given list of package names and versions.
... |
magic_instruct_75k | 19,882 | Write a Python function to simulate the dynamic loading of a shared library and calling a function from it. The function should load a shared library named "libotel-cpp-lib-test_world.so" from the "../src/" directory, retrieve a function named "world" from the library, and call it. The function "world" takes no argumen... | Here is the Python code to solve the given problem in the markdown block:
```python
import ctypes
import os
def simulate_dynamic_loading():
"""
Simulates the dynamic loading of a shared library and calls a function from it.
This function loads a shared library named "libotel-cpp-lib-test_world.so" from th... |
magic_instruct_75k | 19,891 | Write a Python function to simulate rolling two six-sided dice a specified number of times and return the frequency of each possible sum from 2 to 12. The function should take an integer `num_rolls` as input, which represents the number of times the dice should be rolled. The function should return a dictionary where t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
import random
def dice_simulation(num_rolls: int) -> Dict[int, int]:
"""
Simulate rolling two six-sided dice a specified number of times and return the frequency of each possible sum.
Args:
... |
magic_instruct_75k | 19,902 | Write a Python function to calculate the total number of unique ways to climb a staircase with a given number of steps, where you can climb either 1 or 2 steps at a time. The function should use dynamic programming to efficiently compute the result.
The code should start with:
```python
def count_ways_to_climb(n: int)... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_ways_to_climb(n: int) -> int:
"""
Calculate the total number of unique ways to climb a staircase with n steps,
where you can climb either 1 or 2 steps at a time.
Args:
n (int): The number of steps in t... |
magic_instruct_75k | 19,906 | Write a Python function to apply a binary mask to a sequence of loss values, effectively masking out certain tokens from contributing to the overall loss during training of a sequence-to-sequence model. The function should take two inputs: a list of loss values and a list of binary mask values. The function should retu... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def apply_loss_mask(loss_values: List[float], loss_mask: List[int]) -> List[float]:
"""
Applies a binary mask to a sequence of loss values, setting the loss values corresponding to masked tokens to 0.
... |
magic_instruct_75k | 19,949 | Write a Bash script to automate the setup of a Vault server using Docker. The script should perform the following tasks:
1. Start a Vault server using Docker with a specified version and configuration.
2. Copy the policy files `policy-no-root.hcl` and `policy-delete-only.hcl` to the Vault container.
3. Wait for 3 secon... | Here is the Python code to solve the given problem in the markdown block:
```bash
#!/bin/bash
# Define environment variables
VAULT_VERSION="1.8.0"
VAULT_CONTAINER_NAME="vault-server"
DIR="$(pwd)"
# Start Vault server using Docker
docker run --name ${VAULT_CONTAINER_NAME} -d \
-e "VAULT_DEV_LISTEN_ADDRESS=0.0.0.0:82... |
magic_instruct_75k | 19,991 | Write a Python function to manage the health checks and startup of Docker containers. The function should check if a specified container is running and if its health status is "healthy". If the container fails to meet these criteria, the function should perform cleanup and display an error message. Otherwise, it should... | Here is the Python code to solve the given problem in the markdown block:
```python
import subprocess
def check_container_health(container_name: str, node_name: str, elasticsearch_version: str, network_name: str, http_port: int) -> None:
"""
Manages the health checks and startup of a Docker container.
Arg... |
magic_instruct_75k | 19,999 | Write a Python function to find all keys in a nested configuration dictionary that have a specific value. The function should return a list of keys in dot-separated format, indicating their hierarchical position within the dictionary. The keys in the output list should be ordered lexicographically.
The code should sta... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Any
def find_keys_by_value(config: Dict[str, Any], value: Any) -> List[str]:
"""
Find all keys in a nested configuration dictionary that have a specific value.
Args:
config (Dict[str,... |
magic_instruct_75k | 20,031 | Create a Python class `BankAccount` that simulates a simple bank account. The class should have methods for depositing funds, withdrawing funds, and checking the current balance. Additionally, the class should keep track of the total number of transactions (deposits and withdrawals) made on the account. The class shoul... | Here is the Python code to solve the given problem in the markdown block:
```python
class BankAccount:
"""
A class to simulate a simple bank account.
Attributes:
balance (float): The current balance of the account.
transaction_count (int): The total number of transactions (deposits and with... |
magic_instruct_75k | 20,032 | Write a Python function to calculate the diffusion-limited evaporation based on the given formula. The function should take two input parameters: `deficit_on_top_layers` and `soil_diffusion_constant`, and return the calculated diffusion-limited evaporation rounded to 2 decimal places.
The code should start with:
```py... | Here is the Python code to solve the given problem in the markdown block:
```python
def diffusion_limited_evaporation(deficit_on_top_layers: float, soil_diffusion_constant: float) -> float:
"""
Calculate the diffusion-limited evaporation based on the given formula.
Args:
deficit_on_top_layers (floa... |
magic_instruct_75k | 20,052 | Write a Python function to simulate the data collection process for an underwater vehicle's thrusters. The function should iterate through each thruster and PWM value, run trials, reset the thrusters, and maintain the data structure. Finally, calculate the total time required for the entire data collection process.
Th... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def simulate_data_collection(data: Dict, TRIAL_LENGTH: int, RESET_TIME: int, CALM_TIME: int, MEASUREMENT_PERIOD: int) -> int:
"""
Simulate the data collection process for an underwater vehicle's thruster... |
magic_instruct_75k | 20,054 | Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock on different days. You are only allowed to complete at most one transaction (i.e., buy one and sell one share of the stock). The function should take a list of integers `prices` representing the stock prices on di... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def maxProfit(prices: List[int]) -> int:
"""
Calculate the maximum profit that can be obtained by buying and selling a stock on different days.
Args:
prices (List[int]): A list of integers r... |
magic_instruct_75k | 20,058 | Write a Python function to process a generator that yields wallpaper items parsed from a web page using Scrapy. Each wallpaper item is represented as a dictionary containing details such as the image URL, title, and tags. The function should take the generator as input and return a list of these wallpaper items.
The w... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Generator, Dict, Union, List
def process_wallpaper_items(items_gen: Generator[Dict[str, Union[str, List[str]]], None, None]) -> List[Dict[str, Union[str, List[str]]]]:
"""
Processes a generator that yields wa... |
magic_instruct_75k | 20,067 | Write a Python function to calculate the number of bins required to bin a given contig FASTA sequence based on a specified bin length. The function should take the contig FASTA sequence and the desired bin length as input and return the number of bins needed to bin the sequence. The number of bins required for a contig... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def cal_num_bins(contig_fasta: str, binned_length: int) -> int:
"""
Calculate the number of bins required to bin a given contig FASTA sequence based on a specified bin length.
Args:
contig_fasta (str): ... |
magic_instruct_75k | 20,068 | Write a Python function to retrieve specific environment parameters for a given universe, domain, and task in a reinforcement learning setting. The environment parameters are stored in a nested dictionary structure, and the function should handle the retrieval of these parameters based on the provided universe, domain,... | Here is the Python code to solve the given problem in the markdown block:
```python
def get_environment_params(universe: str, domain: str, task: str) -> dict:
"""
Retrieves specific environment parameters for a given universe, domain, and task.
Args:
universe (str): The universe for which to retrie... |
magic_instruct_75k | 20,069 | Write a Python function to extract all the comments from a given string containing a series of comments in a programming language. Each comment starts with `//` and ends at the end of the line. The function should return a list of strings containing all the comments present in the code. If no comments are found, the fu... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def extractComments(code: str) -> List[str]:
"""
Extracts all the comments from a given string containing a series of comments in a programming language.
Each comment starts with `//` and ends at the... |
magic_instruct_75k | 20,079 | Write a Python function to process a given input string and return a modified version of it. The function should handle exceptions and ensure that the returned result is in lowercase and stripped of any leading or trailing whitespace. The function should adhere to the following requirements:
- If an `sr.UnknownValueErr... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_input(input_string: str) -> str:
"""
Processes the input string by handling exceptions and returning a modified version.
Args:
input_string (str): The input string to be processed.
Returns:
... |
magic_instruct_75k | 20,097 | Write a Python function to parse a given JSON object representing a digital claim and extract specific information from it. The JSON object contains various fields such as 'claim', 'context', 'cptId', 'expirationDate', 'id', and 'issuanceDate'. Your task is to extract the 'id' and 'expirationDate' from the JSON object ... | Here is the Python code to solve the given problem in the markdown block:
```python
def extract_claim_info(claim_json: dict) -> tuple:
"""
Extracts the 'id' and 'expirationDate' from a given JSON object representing a digital claim.
Args:
claim_json (dict): A dictionary representing the JSON object... |
magic_instruct_75k | 20,099 | Write a Python function to transform an array of integers such that each element in the new array is the sum of itself and all previous elements in the input array. The function should be efficient and work well for large input arrays.
The code should start with:
```python
from typing import List
def upgrade(arr: Lis... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def upgrade(arr: List[int]) -> List[int]:
"""
Transforms an array of integers such that each element in the new array is the sum of itself and all previous elements in the input array.
Args:
... |
magic_instruct_75k | 20,105 | Write a Python function to calculate the area of a 2D polygon given its vertices. The vertices are represented as a list of 2D points in the form `(x, y)`. The function should return the area of the polygon as a floating-point number. The vertices are listed in clockwise or counterclockwise order, and the last vertex i... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def calculate_polygon_area(vertices: List[Tuple[float, float]]) -> float:
"""
Calculate the area of a 2D polygon given its vertices.
Args:
vertices: A list of tuples where each tuple ... |
magic_instruct_75k | 20,109 | Write a Python function to generate a string containing the actions to be performed by a release management script based on the version number and a boolean flag indicating whether the release is published. The function should return a string that includes the deletion of the draft release, removal of associated artifa... | Here is the Python code to solve the given problem in the markdown block:
```python
def release_actions(version: str, published: bool) -> str:
"""
Generate a string containing the actions to be performed by a release management script.
Args:
version (str): The version number of the release.
... |
magic_instruct_75k | 20,117 | Write a Python function to process a list of commands and their arguments, and return the final state of a system based on the commands executed. The commands are represented as strings in a list, where each string contains a command and its arguments separated by spaces. The commands can be "add", "remove", "update", ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_commands(commands: List[str]) -> List[str]:
"""
Processes a list of commands and returns the final state of the system.
Args:
commands (List[str]): A list of strings where each s... |
magic_instruct_75k | 20,119 | Write a Python function `M` that takes an integer parameter and performs a series of mathematical operations. The function should handle potential exceptions and return a specific value in case of an error.
- If the input is 0, raise a custom exception `ZeroInputException`.
- If the input is negative, raise a standard... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
class ZeroInputException(Exception):
"""Custom exception for zero input."""
pass
def M(n: int) -> int:
"""
Perform a series of mathematical operations on the input integer n.
Args:
n (int): The... |
magic_instruct_75k | 20,129 | Write a Python function to manage a parameter system where you can set a map of agent IDs to lists of floating-point values, retrieve an integer value associated with a parameter name, and add a child parameter. The function should be designed to handle these operations efficiently and correctly.
The code should start... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Union
class ConcreteParams:
def __init__(self):
"""
Initialize the ConcreteParams class with necessary data structures.
"""
self.agent_map = {} # Map of agent IDs to l... |
magic_instruct_75k | 20,147 | Write a Python function `add_features_to_function` that takes a list of feature names and a function as input. The function should return a new function with the specified features added as annotations in the format 'Feature:<feature_name>'. The annotations should be added to the function's `__annotations__` attribute.... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Callable, List
def add_features_to_function(feature_list: List[str], function: Callable) -> Callable:
"""
Adds a list of features as annotations to a given function.
Args:
feature_list (List[str]... |
magic_instruct_75k | 20,150 | Write a Python function to calculate the number of unique paths from the top-left corner to the bottom-right corner of an m x n grid, where you can only move right or down. The function should start with:
```python
from typing import List
def unique_paths(m: int, n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
from typing import List
def unique_paths(m: int, n: int) -> int:
"""
Calculate the 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 row... |
magic_instruct_75k | 20,158 | Write a Python function to parse and extract metadata information from a given Python code snippet. The metadata information is present in the comments at the beginning of the code snippet and follows the format `#key: value`. The function should return a dictionary containing the extracted metadata.
The code should s... | Here is the Python code to solve the given problem in the markdown block:
```python
def parse_metadata(code: str) -> dict:
"""
Parses and extracts metadata information from a given Python code snippet.
The metadata information is present in the comments at the beginning of the code snippet
and follows ... |
magic_instruct_75k | 20,162 | Write a Python function to find all prime numbers less than a given integer `n` using the Sieve of Eratosthenes algorithm. The function should take an integer `n` as input and return a list of all prime numbers less than `n`. The function should be efficient and handle the upper limit constraint where `2 <= n <= 10^6`.... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sieve_of_eratosthenes(n: int) -> List[int]:
"""
Find all prime numbers less than a given integer `n` using the Sieve of Eratosthenes algorithm.
Args:
n (int): The upper limit for finding... |
magic_instruct_75k | 20,165 | Write a Python function `lookup_message_type` that takes a message type value as input and returns the corresponding description from a predefined dictionary. If the input value does not exist in the dictionary, the function should return "Unknown Message Type". The dictionary mapping message type values to their descr... | Here is the Python code to solve the given problem in the markdown block:
```python
def lookup_message_type(message_type: int) -> str:
"""
Look up the description of a given BLE message type value.
Args:
message_type (int): The hexadecimal value representing the BLE message type.
Returns:
... |
magic_instruct_75k | 20,170 | Write a Python function to count the occurrences of each keyword in a given text. The function should be case-insensitive, meaning that the occurrences of keywords should be counted regardless of the case in the text. The function should return a dictionary where the keys are the keywords and the values are the counts ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def countOccurrences(text: str, keywords: List[str]) -> Dict[str, int]:
"""
Counts the occurrences of each keyword in the given text. The counting is case-insensitive.
Args:
text (str)... |
magic_instruct_75k | 20,175 | Implement a Python function to simulate the process of simulated annealing for optimizing a given function. The function should start with an initial solution and iteratively explore the search space by accepting new solutions based on a probability function, which allows it to escape local optima. The function should ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Callable, Any
import random
import math
def simulated_annealing(initial_solution: Any, objective_function: Callable[[Any], float], neighbor_function: Callable[[Any], Any], initial_temperature: float, cooling_rate: fl... |
magic_instruct_75k | 20,186 | Write a Python function to process command-line parameters for a fictional application. The function should parse the input parameters and perform the necessary actions based on the provided commands. The input parameters are represented as a string (`params`).
Your task is to implement the `process_command_line` func... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_command_line(params: str) -> bool:
"""
Process command-line parameters for a fictional application.
Args:
params (str): The command-line parameters as a single string.
Returns:
bool: True if... |
magic_instruct_75k | 20,201 | Write a Python function to determine if two given strings, `s1` and `s2`, are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. The function should return `True` if `s2` is an anagram of `s1`, an... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_anagram(s1: str, s2: str) -> bool:
"""
Determines if two given strings are anagrams of each other.
Args:
s1 (str): The first string to compare.
s2 (str): The second string to compare.
Returns:
... |
magic_instruct_75k | 20,207 | Write a Python function to construct a command string for the `ogr2ogr` command-line tool to convert a shapefile from the WGS84 Geographic coordinate system (EPSG:4326) to the UTM (Universal Transverse Mercator) coordinate system. The UTM zone for the conversion is determined by the input variable `utm_zone`.
The func... | Here is the Python code to solve the given problem in the markdown block:
```python
def construct_ogr2ogr_command(utm_zone: int) -> str:
"""
Constructs a command string for the `ogr2ogr` tool to convert a shapefile from the WGS84 Geographic coordinate system (EPSG:4326) to the UTM coordinate system.
Args:
... |
magic_instruct_75k | 20,221 | Write a Python function to convert a given positive integer into its binary representation. The function should take an integer `num` as input and return a string representing the binary equivalent of the input number. The function should handle the special case where the input number is 0.
The code should start with:... | Here is the Python code to solve the given problem in the markdown block:
```python
def decimal_to_binary(num: int) -> str:
"""
Converts a given positive integer into its binary representation.
Args:
num (int): The positive integer to be converted.
Returns:
str: The binary representati... |
magic_instruct_75k | 20,234 | Write a Python function to manipulate a given string based on a set of predefined rules. The function should take a string as input and perform the following operations:
1. Replace all occurrences of the substring "Hello" with "Hi".
2. Replace all occurrences of the substring "Alice" with "Bob".
3. Replace all occurren... | Here is the Python code to solve the given problem in the markdown block:
```python
def manipulate_string(input_string: str) -> str:
"""
Manipulates the input string based on a set of predefined rules.
The rules are:
1. Replace all occurrences of "Hello" with "Hi".
2. Replace all occurrences of "Al... |
magic_instruct_75k | 20,240 | Write a Python function to convert a given number of minutes into hours and minutes. The function should take an integer representing the total number of minutes and return a string in the format "h hours m minutes". The function should handle singular and plural forms of "hour" and "minute" correctly.
The code should... | Here is the Python code to solve the given problem in the markdown block:
```python
def convert_minutes_to_hours_and_minutes(minutes: int) -> str:
"""
Converts a given number of minutes into hours and minutes and returns a string in the format "h hours m minutes".
Args:
minutes (int): The total num... |
magic_instruct_75k | 20,249 | Write a Python function to find and return the maximum value in a given list of integers. The function should be named `findMax` and should take a single parameter, `nums`, which is a list of integers. The function should return the maximum value found in the list.
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 findMax(nums: List[int]) -> int:
"""
Find and return the maximum value in the given list of integers.
Args:
nums (List[int]): A list of integers from which to find the maximum value.
... |
magic_instruct_75k | 20,250 | Write a Python function to extract entry points from a `setup` function call and return them as a dictionary. The entry points are defined within the `entry_points` argument of the `setup` function call and follow a specific format. Each entry point consists of a section name enclosed in square brackets, followed by on... | Here is the Python code to solve the given problem in the markdown block:
```python
def extract_entry_points(entry_points: str) -> dict:
"""
Extracts entry points from a `setup` function call and returns them as a dictionary.
Args:
entry_points (str): A string containing sections and key-value pair... |
magic_instruct_75k | 20,254 | Write a Python function that takes in a dictionary representing environment variables and a string representing a user's name. The function should modify the dictionary by replacing any occurrences of the placeholder `{PF_USER_NAME}` in the values with the actual user's name provided as an argument to the function. If ... | Here is the Python code to solve the given problem in the markdown block:
```python
def replace_placeholder(env: dict, user_name: str) -> dict:
"""
Replaces any occurrences of the placeholder `{PF_USER_NAME}` in the values of the given dictionary with the provided user's name.
Args:
env (dict): A d... |
magic_instruct_75k | 20,309 | Write a Python function to implement the Metropolis algorithm for simulating the behavior of a physical system at a given temperature. The function should take the change in energy `delta_e` and the inverse temperature `beta` as inputs and return a boolean indicating whether the proposed change should be accepted based... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
import math
def metropolis(delta_e: float, beta: float) -> bool:
"""
Implements the Metropolis algorithm to decide whether to accept a change in a physical system.
Args:
delta_e (float): The change in... |
magic_instruct_75k | 20,318 | Write a Python function to count the number of book titles in a given list that start with a specific prefix. The prefix is a string of alphanumeric characters and may contain special characters. The function should return the count of titles that start with the specified prefix.
The code should start with:
```python
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def count_titles_starting_with_prefix(titles: List[str], prefix: str) -> int:
"""
Counts the number of book titles in the given list that start with the specified prefix.
Args:
titles (List[... |
magic_instruct_75k | 20,324 | Write a Python function to calculate the duration between two given timestamps. The function should take two parameters, `start` and `end`, representing the start and end timestamps, and return the duration between them in seconds. If the `end` timestamp is not provided, the current time should be used as the end times... | Here is the Python code to solve the given problem in the markdown block:
```python
from datetime import datetime
from typing import Optional
def calculate_duration(start: datetime, end: Optional[datetime]) -> int:
"""
Calculate the duration between two timestamps in seconds.
Args:
start (datetime... |
magic_instruct_75k | 20,349 | Write a Python function to validate a set of p-values used in statistical hypothesis testing. The function should perform the following checks on the input p-values:
1. Ensure that there are no NaN (Not a Number) values in the p-values.
2. Verify that all p-values are within the range of 0 to 1.
3. Check that there are... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def validate_pvalues(pvals: np.ndarray) -> bool:
"""
Validate a set of p-values used in statistical hypothesis testing.
Args:
pvals (np.ndarray): A NumPy array of p-values to be validated.
R... |
magic_instruct_75k | 20,375 | Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock at most once over a given period of N days. The input is an array of integers representing the stock prices for each day. If it is not possible to make any profit, return 0.
The function should start with:
```pyt... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def max_profit(prices: List[int]) -> int:
"""
Calculate the maximum profit that can be obtained by buying and selling a stock at most once.
Args:
prices (List[int]): A list of integers repre... |
magic_instruct_75k | 20,377 | Write a Python function to calculate the number of unique paths from the top-left corner to the bottom-right corner of an m x n grid, where you can only move right or down. The function should start with:
```python
from typing import List
def unique_paths(m: int, n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def unique_paths(m: int, n: int) -> int:
"""
Calculate the 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 ... |
magic_instruct_75k | 20,381 | Implement a Python function to simplify a given line by removing redundant points. The line is represented as a list of tuples, where each tuple contains two integers representing the x and y coordinates of a point. A point is considered redundant if it lies on the line segment between its neighboring points. The funct... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def simplify_line(line: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
"""
Simplifies a given line by removing redundant points.
A point is considered redundant if it lies on the line segme... |
magic_instruct_75k | 20,400 | Write a Python function to determine if a project portfolio includes projects of a 'new' capacity type based on the given dictionary structure. The function should check if any of the table features contain the substring "new" and return `True` if found, otherwise return `False`.
The input dictionary will have the fol... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def check_new_capacity_type(portfolio_data: Dict[str, str]) -> bool:
"""
Determines if the project portfolio includes projects of a 'new' capacity type.
Args:
portfolio_data (Dict[str, str])... |
magic_instruct_75k | 20,404 | Write a Python function to determine if a given element is present in a list. If the element is not present, return `True`; otherwise, return `False`. The function should use a more readable and conventional if-else statement format.
The code should start with:
```python
from typing import List, Any
def is_element_no... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Any
def is_element_not_in_list(element: Any, lst: List[Any]) -> bool:
"""
Determines if the given element is not present in the list.
Args:
element (Any): The element to check for presence ... |
magic_instruct_75k | 20,406 | Write a Python function to filter a list of organizations based on specific criteria. Each organization is represented as a dictionary with various attributes. The function should include only organizations of type 'Non-profit' or 'Charity' and exclude organizations located in 'Unknown' location. The function should re... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def filter_organizations(orgs: List[Dict[str, str]]) -> List[Dict[str, str]]:
"""
Filters a list of organizations based on specific criteria.
Args:
orgs (List[Dict[str, str]]): A list ... |
magic_instruct_75k | 20,413 | Write a Python function `is_punctuation` that determines whether a given character is a punctuation mark. The function should take a single parameter, `letter`, which represents the character to be checked. The function should return `True` if the `letter` is a punctuation mark, and `False` otherwise. The function shou... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_punctuation(letter: str) -> bool:
"""
Determines whether a given character is a punctuation mark.
Args:
letter (str): The character to be checked.
Returns:
bool: True if the character is a punctu... |
magic_instruct_75k | 20,424 | Write a Python function to calculate the total resistance of a circuit represented as a list of components. Each component can be either a resistance value or a sub-circuit enclosed within opening and closing characters. The resistance value of a sub-circuit is the sum of the resistance values of its components. The fu... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_total_resistance(ohms: dict, circuit: List[str]) -> int:
"""
Calculate the total resistance of a circuit represented as a list of components.
Args:
ohms (dict): A dictionary ma... |
magic_instruct_75k | 20,430 | Write a Python function to transform a given string based on specific substring replacement rules. The function should replace occurrences of certain substrings with predefined replacements. The transformation rules are as follows:
- Replace "id_" with "user_".
- Replace "tpo" with "admin".
- Replace "ski" with "root".... | Here is the Python code to solve the given problem in the markdown block:
```python
def transformString(s: str) -> str:
"""
Transforms the input string by replacing specific substrings with predefined replacements.
The transformation rules are:
- Replace "id_" with "user_".
- Replace "tpo" with "ad... |
magic_instruct_75k | 20,453 | Write a Bash script to automate the extraction and transfer of data from an Amazon S3 bucket. The script should retrieve a list of objects from a specified prefix within a bucket, process the output by removing the last character from each object's name, create a JSON file containing the original prefix and the process... | Here is the Python code to solve the given problem in the markdown block:
```bash
#!/bin/bash
# Set the bucket name and key prefix
bucket_name="your_bucket_name"
bucket_keyprefix="your_key_prefix"
# Retrieve a list of objects from the specified prefix within the S3 bucket
output=$(aws s3 ls s3://$bucket_name/$bucket_... |
magic_instruct_75k | 20,461 | Write a Python function to generate a 2D grid of coordinates using NumPy. The function should take two parameters, `nz` and `nx`, representing the number of points along the z and x axes, respectively. The function should return a grid of coordinates in the form of two NumPy arrays, `zz` and `xx`, representing the z an... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def generate_grid_coordinates(nz: int, nx: int) -> (np.ndarray, np.ndarray):
"""
Generates a 2D grid of coordinates using NumPy.
Args:
nz (int): The number of points along the z axis.
nx ... |
magic_instruct_75k | 20,468 | Write a Python function to simulate a simple migration system for a hypothetical database. The function should take a list of migration operations and apply them to the database in the order they are provided. Each migration operation is represented as a dictionary with the following structure:
```python
{
'operati... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def apply_migrations(migrations: List[Dict]) -> List[Dict]:
"""
Simulates a simple migration system for a hypothetical database.
Args:
migrations (List[Dict]): A list of migration oper... |
magic_instruct_75k | 20,473 | Write a Python function to replace all occurrences of a placeholder `{{name}}` in a configuration file content with a user-provided target name. The function should take two inputs:
- A string representing the original configuration file content.
- A string representing the user-provided target name.
The function shou... | Here is the Python code to solve the given problem in the markdown block:
```python
def replace_placeholder(config_content: str, target_name: str) -> str:
"""
Replaces all occurrences of the placeholder `{{name}}` in the configuration file content with the provided target name.
Args:
config_content... |
magic_instruct_75k | 20,504 | Write a Python function to determine if a given string `s` can be segmented into a space-separated sequence of one or more dictionary words from a provided list `wordDict`. The function should return `True` if such a segmentation is possible, and `False` otherwise. The function should allow reusing words from `wordDict... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def wordBreak(s: str, wordDict: List[str]) -> bool:
"""
Determine if the string `s` can be segmented into a space-separated sequence of one or more dictionary words from `wordDict`.
Args:
s ... |
magic_instruct_75k | 20,533 | Write a Python function to process a list of model configurations and generate a dictionary of results for each model. The function should take in the initial batch size, a list of model configurations, and a set of arguments, and then iterate through the model configurations to produce the results. The results should ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any
from collections import OrderedDict
def process_model_configurations(start_batch_size: int, model_cfgs: List[tuple], args: Dict[str, Any]) -> List[Dict[str, Any]]:
"""
Processes a list of mode... |
magic_instruct_75k | 20,534 | Create a Python class `Channel` to manage channels for a medical device used in neuromuscular electrical stimulation. Each channel should be defined by its name, channel number, anode-cathode pair, maximum amplitude, and maximum pulse width. Implement the following methods for the `Channel` class:
- `__init__(self, nam... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
class Channel:
def __init__(self, name: str, channel_number: int, anode_cathode_pair: str, max_amplitude: int, max_pulse_width: int):
"""
Constructor to initialize the attributes of the Chann... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.