source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
magic_instruct_75k | 64,437 | Write a Python function to automate the installation and caching of a software library. The function should take a single argument, which is the installation directory for the library. The function should then check if the specified installation directory exists and if it contains certain files with a specific extensio... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
from typing import List
def install_and_cache_library(install_dir: str, required_files: List[str]) -> None:
"""
Automates the installation and caching of a software library.
Args:
install_dir (str): The i... |
magic_instruct_75k | 64,471 | Write a Python function to generate Pascal's Triangle up to a given number of rows. Pascal's Triangle is a triangular array of binomial coefficients, where each number is the sum of the two numbers directly above it. The function should take an integer `num_rows` as input and return a list of lists, where each inner li... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_pascals_triangle(num_rows: int) -> List[List[int]]:
"""
Generate Pascal's Triangle up to a given number of rows.
Args:
num_rows (int): The number of rows to generate in Pascal's... |
magic_instruct_75k | 64,504 | Write a Python function to calculate the sum of all integers from 1 to a given number `n`. The function should correctly handle the calculation and return the sum. The code should start with:
```python
def sum_of_integers(n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def sum_of_integers(n: int) -> int:
"""
Calculate the sum of all integers from 1 to a given number `n`.
Args:
n (int): The upper limit of the range of integers to sum.
Returns:
int: The sum of all integ... |
magic_instruct_75k | 64,507 | Write a Python function to simulate a simple file system operation. The function should take a list of commands and execute them to manipulate a file system. Each command in the list represents a file system operation. The commands can be one of the following types:
1. `mkdir <directory_name>`: Create a new directory w... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def simulate_file_system(commands: List[str]) -> List[str]:
"""
Simulates a simple file system operation based on a list of commands.
Args:
commands (List[str]): A list of commands to execut... |
magic_instruct_75k | 64,508 | Write a Python function to calculate the sum of all even Fibonacci numbers up to a given limit. The Fibonacci sequence is defined as follows: F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2) for n > 1. For example, the first few terms of the Fibonacci sequence are 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.
The function sho... | 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 | 64,514 | Write a Python function to generate a sequence of events based on a given frequency and batch size. The function should take two parameters: `every_nth` (the frequency of events) and `n` (the batch size). The function should return a 2D NumPy array representing the events, where each row corresponds to a batch and each... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def generate_events(every_nth: int, n: int) -> np.ndarray:
"""
Generates a sequence of events based on a given frequency and batch size.
Args:
every_nth (int): The frequency of events, meaning ev... |
magic_instruct_75k | 64,524 | Write a Python function to perform a specific analysis on data from three different detector collections: HBHE, HF, and HO. The function should take the detector data as input and return a string representing the result of the analysis. The function should be named `perform_analysis` and should have the following signa... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def perform_analysis(hbhe_data: List[Tuple[int, int]], hf_data: List[Tuple[int, int]], ho_data: List[Tuple[int, int]]) -> str:
"""
Perform a specific analysis on the data from three different dete... |
magic_instruct_75k | 64,525 | Write a Python function to generate a skymap for a given astronomical observation and update its metadata attributes. The function `ts_skymap` should take in five parameters: `time` (time of observation), `data` (observed data), `energy` (energy level of observation), `phi` (azimuthal angle), and `theta` (polar angle).... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Any
def generate_skymap(time: float, data: Any, energy: float, phi: float, theta: float) -> Any:
"""
Helper function to generate a skymap based on the provided parameters.
Args:
time (float... |
magic_instruct_75k | 64,541 | Write a Python function `process_billing_profiles` that processes a list of `BillingProfile` objects and returns a dictionary containing the count of active and inactive billing profiles, grouped by the domain of the email addresses. The function should adhere to the following specifications:
1. **Input**: A list of `... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Tuple
from collections import defaultdict
class BillingProfile:
def __init__(self, user: str, email: str, active: bool):
self.user = user
self.email = email
self.active = activ... |
magic_instruct_75k | 64,585 | Write a Python function to calculate the total number of parameters in a neural network flow model. The flow model consists of multiple flow steps, each of which may have a different number of parameters. The function should take the batch size and the shapes of the tensors involved in the flow model as input and retur... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def calculate_total_parameters(batch_size: int, tensor_shapes: List[Tuple[int, int]]) -> int:
"""
Calculate the total number of parameters in a neural network flow model.
Args:
batch_... |
magic_instruct_75k | 64,587 | Write a Python function to filter a list of dictionaries representing books based on specified criteria. Each dictionary contains the keys "title", "author", "year", and "genre". The function should return a list of book titles that meet all the specified filtering criteria. If a key is not present in the criteria dict... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def filter_books(books: List[Dict[str, any]], criteria: Dict[str, any]) -> List[str]:
"""
Filters a list of books based on specified criteria and returns a list of book titles that meet all the cri... |
magic_instruct_75k | 64,609 | Write a Python function to calculate the sum of all even numbers in a given list of integers. The function should handle an empty list and return 0 in such cases. The code should start with:
```python
from typing import List
def sum_of_even_numbers(nums: 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_even_numbers(nums: List[int]) -> int:
"""
Calculate the sum of all even numbers in the input list.
Args:
nums: A list of integers.
Returns:
int: The sum of all even n... |
magic_instruct_75k | 64,617 | Create a Python function to determine the segment path for a given node in a hierarchical tree-like structure. The function should return the path from the root node to the given node as a string, where each segment is separated by a delimiter (e.g., '/'). The tree structure is represented using nested dictionaries, wh... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Any
def get_segment_path(tree: Dict[str, Any], target_node: str, delimiter: str = '/') -> str:
"""
Determine the segment path for a given node in a hierarchical tree-like structure.
Args:
t... |
magic_instruct_75k | 64,621 | Write a Python function to map a string representing a DirectX presentation interval to its corresponding numerical value. The function should handle both valid and invalid input strings. If the input string is not a valid presentation interval, the function should return -1.
The code should start with:
```python
def ... | Here is the Python code to solve the given problem in the markdown block:
```python
def get_presentation_interval_value(presentation_interval: str) -> int:
"""
Maps a DirectX presentation interval string to its corresponding numerical value.
Args:
presentation_interval (str): The string representin... |
magic_instruct_75k | 64,623 | Write a Python function to perform k-fold cross-validation on a dataset. The function should partition the dataset into k equal-sized subsamples and return the indices of the data points for each fold. The function should handle cases where the dataset size is not perfectly divisible by k by distributing the remainder ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def k_fold_cross_validation(dataset: List, k: int) -> List[List[int]]:
"""
Perform k-fold cross-validation on a dataset and return the indices of the data points for each fold.
Args:
dataset... |
magic_instruct_75k | 64,652 | Write a Python function to calculate the sum of the first two elements of each tuple in a given list of tuples. Each tuple contains exactly three integers. The function should return a new list containing these sums.
The code should start with:
```python
from typing import List, Tuple
def sum_of_pairs(testdata: List[... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def sum_of_pairs(testdata: List[Tuple[int, int, int]]) -> List[int]:
"""
Calculate the sum of the first two elements of each tuple in the given list of tuples.
Args:
testdata (List[Tu... |
magic_instruct_75k | 64,657 | Write a Python function to retrieve the color of the light in an aquarium based on its ID. The aquarium has a set of predefined light colors, and the function should return the color associated with the given ID. If the ID is invalid or does not correspond to any known color, the function should return "Unknown".
The ... | Here is the Python code to solve the given problem in the markdown block:
```python
def get_aquarium_light_color(aquarium_id: int) -> str:
"""
Retrieve the color of the light in an aquarium based on its ID.
Args:
aquarium_id (int): The ID of the aquarium.
Returns:
str: The color of the... |
magic_instruct_75k | 64,665 | Write a Python function `apply_transform` that processes a user's selected transform and applies it to a list of instance files. The function should handle case-insensitive transform selection and apply the corresponding transformation to each file name. The available transformations are defined in the `TRANSFORM_LIBRA... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
TRANSFORM_LIBRARY = {
"uppercase": lambda x: x.upper(),
"lowercase": lambda x: x.lower(),
"capitalize": lambda x: x.capitalize()
}
def apply_transform(selected_transform: str, instance_files: List[s... |
magic_instruct_75k | 64,696 | Write a Python function to automate the installation of a specific command-line tool, Argo CD, on a Linux system. The function should check if the tool is already installed, and if not, download and install it. The function should handle the installation process and provide appropriate feedback to the user.
The code s... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
import subprocess
import requests
def install_argocd() -> None:
"""
Automates the installation of Argo CD on a Linux system.
This function checks if the `argocd` command is available. If not, it downloads
the... |
magic_instruct_75k | 64,726 | Write a Python function to calculate the sum of all even numbers in a given list of integers. If the input list is empty or does not contain any even numbers, the function should return 0. The function should be named `sum_even_numbers` and should accept a list of integers as its parameter.
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 sum_even_numbers(numbers: List[int]) -> int:
"""
Calculate the sum of all even numbers in the given list of integers.
Args:
numbers (List[int]): A list of integers.
Returns:
... |
magic_instruct_75k | 64,729 | Write a Python function `simulateRace` that simulates a race with runners using multithreading. The function should take two parameters:
1. `numRunners`: an integer representing the number of runners participating in the race.
2. `numThreads`: an integer representing the number of threads available for the race.
The f... | Here is the Python code to solve the given problem in the markdown block:
```python
import threading
import sys
def simulateRace(numRunners: int, numThreads: int) -> None:
"""
Simulates a race with runners using multithreading.
Args:
numRunners (int): The number of runners participating in the rac... |
magic_instruct_75k | 64,746 | Write a Python function to calculate the intersection of two sets represented as dictionaries. The keys of the dictionaries represent elements of the sets, and the values indicate whether the element is present in the set. If the value is "Yes", the element is present in the set; otherwise, it is not. The function shou... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def calculate_intersection(set1: Dict[str, str], set2: Dict[str, str]) -> Dict[str, str]:
"""
Calculate the intersection of two sets represented as dictionaries.
Args:
set1 (Dict[str, str]):... |
magic_instruct_75k | 64,754 | Write a Python script that automates the process of building and releasing an Android application on both MacOS and Windows operating systems. The script should:
1. Determine the operating system and execute the appropriate build command.
2. Set the project path and package path.
3. Execute the build command with the s... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
import subprocess
def build_android_app(project_path: str, platform: str, configuration: str) -> None:
"""
Automates the process of building and releasing an Android application on both MacOS and Windows.
Args:
... |
magic_instruct_75k | 64,762 | Write a Python function to generate a specified amount of random numbers within a given range based on different simulation modes. The function should take three parameters:
- `mode` (integer): Simulation mode, where 0 represents local simulation, 1 represents IBM server simulation, and 2 represents IBM server real exp... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
def generate_random_numbers(mode: int, number_amount: int, bits: int) -> list:
"""
Generate a specified amount of random numbers within a given range based on different simulation modes.
Args:
mode (i... |
magic_instruct_75k | 64,770 | Write a Python function `generate_integer_division_code` that takes two integer inputs `dividend` and `divisor`, and generates LLVM IR code to perform integer division and remainder operations. The function should return the LLVM IR code as a string.
The LLVM IR code should include the following operations:
1. Fetch t... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_integer_division_code(dividend: int, divisor: int) -> str:
"""
Generates LLVM IR code to perform integer division and remainder operations.
Args:
dividend (int): The dividend in the division operation.
... |
magic_instruct_75k | 64,800 | Write a Python function `uniq_kmers` that takes a list of DNA k-mers as input and returns a list of tuples where each tuple contains a unique k-mer and its reverse complement. The function should ensure that each k-mer and its reverse complement are considered unique pairs. The reverse complement of a DNA sequence is f... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def find_reverse(kmer: str) -> str:
"""
Find the reverse complement of a given DNA k-mer.
Args:
kmer (str): The DNA k-mer to find the reverse complement for.
Returns:
str... |
magic_instruct_75k | 64,801 | Write a Python function to parse a list of classifiers and return a dictionary containing the count of each unique audience category. The audience categories are represented in the classifiers list as strings following the format 'Intended Audience :: <category>'. The function should ignore any leading or trailing whit... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_audience_categories(classifiers: List[str]) -> Dict[str, int]:
"""
Parses a list of classifiers and returns a dictionary containing the count of each unique audience category.
Args:
... |
magic_instruct_75k | 64,830 | Write a Python function to combine two distinct pipelines, `data_engineering_pipeline` and `data_science_pipeline`, into a unified pipeline configuration. The combined pipeline should be stored under the key `"__default__"` in a dictionary. The function should take two dictionaries as input, each representing an indivi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def combine_pipelines(data_engineering_pipeline: Dict[str, str], data_science_pipeline: Dict[str, str]) -> Dict[str, Dict[str, str]]:
"""
Combines two distinct pipelines, data_engineering_pipeline and da... |
magic_instruct_75k | 64,866 | Write a Python function to extract unique tags from a list of blog entries. Each blog entry is represented as a dictionary with a "title" and a "tags" field. The "tags" field is a list of strings. The function should return a set of unique tags present in all the entries.
The code should start with:
```python
from typ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Union, Set
def extract_unique_tags(entries: List[Dict[str, Union[str, List[str]]]]) -> Set[str]:
"""
Extracts unique tags from a list of blog entries.
Args:
entries (List[Dict[str, Un... |
magic_instruct_75k | 64,868 | Write a Python function to add a label "FirstBar" at the first bar of each group in a bar chart. The bar chart is represented as a list of integers, where each integer represents the height of a bar. A group is defined as a sequence of consecutive bars with the same height.
The function should start with:
```python
fr... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def addLabelToFirstBar(bars: List[int]) -> List[str]:
"""
Adds a label "FirstBar" at the first bar of each group in a bar chart.
Args:
bars (List[int]): A list of integers representing the h... |
magic_instruct_75k | 64,882 | Write a Python function to determine the maximum number of trains that can run simultaneously without conflicting schedules. Each train schedule is represented as a tuple containing the start time and end time of the train's journey, both in seconds from the beginning of the day. The function should take a list of such... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def max_simultaneous_trains(train_schedules: List[Tuple[int, int]]) -> int:
"""
Calculate the maximum number of trains that can run simultaneously without conflicting schedules.
Args:
... |
magic_instruct_75k | 64,892 | Write a Python function to configure the input shapes for a deep learning model. The function should define the input shapes for the 'input' tensor, ensuring it meets the minimum shape requirement of [1, 3, 320, 320]. The function should return the complete model inputs configuration as a list of dictionaries.
The cod... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def configure_model_inputs() -> List[Dict]:
"""
Configures the input shapes for a deep learning model.
This function defines the input shapes for the 'input' tensor, ensuring it meets the mini... |
magic_instruct_75k | 64,913 | Create a Python function to convert a number from one base to another base, where the bases can be any of the following: binary, octal, decimal, or hexadecimal. The function should handle conversion between these bases and return the converted number as a string. The function should also handle invalid inputs gracefull... | Here is the Python code to solve the given problem in the markdown block:
```python
def convert_number_base(number: str, from_base: str, to_base: str) -> str:
"""
Converts a number from one base to another base.
Args:
number (str): The number to be converted.
from_base (str): The base of th... |
magic_instruct_75k | 64,934 | Write a Python function to encode a given wallet ID and a code into a hexadecimal string using a specific encoding process. The encoding process involves concatenating the "open wallet" string with the wallet ID and the code, and then converting the concatenated string into a hexadecimal representation.
The function s... | Here is the Python code to solve the given problem in the markdown block:
```python
def encode_wallet(wallet: str, code: str) -> str:
"""
Encodes a given wallet ID and a code into a hexadecimal string using a specific encoding process.
The encoding process involves concatenating the string "open wallet" wi... |
magic_instruct_75k | 64,956 | Write a Python function to check if a given Markdown document contains one or more valid emphasis sequences. An emphasis sequence in Markdown is denoted by either asterisks (`*`) or underscores (`_`) surrounding a word or phrase. For example, `*emphasis*` or `_emphasis_` are valid emphasis sequences. The function shoul... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def has_valid_emphasis(document: str) -> bool:
"""
Check if a given Markdown document contains one or more valid emphasis sequences.
An emphasis sequence in Markdown is denoted by either asterisks (*) or undersco... |
magic_instruct_75k | 64,958 | Write a Python function to process a list of strings representing programming language classifiers and extract specific information from them. Each string in the list follows the format 'Category :: Subcategory :: Sub-subcategory', where each part is separated by ' :: '. Your program should extract the unique subcatego... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def extract_subcategories(classifiers: List[str]) -> Dict[str, int]:
"""
Extracts unique subcategories from a list of programming language classifiers and counts their occurrences.
Args:
... |
magic_instruct_75k | 64,965 | Write a Python function to reverse the vowels in a given string while keeping the consonants in their original positions. The vowels are 'a', 'e', 'i', 'o', and 'u'. The function should return the modified string with the reversed vowels.
The code should start with:
```python
def reverse_vowels(name: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def reverse_vowels(name: str) -> str:
"""
Reverses the vowels in the given string while keeping the consonants in their original positions.
Args:
name (str): The input string containing a lowercase word.
Return... |
magic_instruct_75k | 64,983 | Write a Python function to extract usernames from a given HTML snippet and store them in a list. The usernames are prefixed with specific labels such as "Line" and "IG" followed by a colon and a space. The usernames are always preceded by the "@" symbol and may contain alphanumeric characters and underscores.
The func... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def extract_usernames(html: str) -> List[str]:
"""
Extracts usernames from a given HTML snippet and returns them as a list.
The usernames are prefixed with specific labels such as "Line" a... |
magic_instruct_75k | 65,005 | Write a Python function to implement a key derivation function (KDF) using the HMAC-based Extract-and-Expand Key Derivation Function (HKDF) algorithm. The function should take the shared secret, context information, and other parameters as input and generate the derived keys using the HKDF algorithm. The function shoul... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
import hmac
import hashlib
def derive_keys(shared_secret: bytes, psk: bytes, suite_id: bytes, key_schedule_context: bytes, cipher_key_length: int) -> Tuple[bytes, bytes]:
"""
Derive cryptographic ... |
magic_instruct_75k | 65,031 | Write a Python function to process a given text string according to a set of rules. The function should perform the following operations on the input text:
1. Remove the substring `'{% -program None %} ==> []'` from the text.
2. Replace any occurrences of `'{%\s*load.*?%}'` with an empty string.
3. Prepend the modified... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def process_text(txt: str) -> str:
"""
Processes the input text string according to a set of rules.
Args:
txt (str): The input text string to be processed.
Returns:
str: The processed text st... |
magic_instruct_75k | 65,047 | Write a Python function to convert a given time in seconds into a formatted string representing the time in minutes and seconds. The function should take an integer representing the total number of seconds and return a string in the format "Total time: X min and Y seconds", where X is the number of minutes and Y is the... | Here is the Python code to solve the given problem in the markdown block:
```python
def format_time(total_secs: int) -> str:
"""
Converts a given time in seconds into a formatted string representing the time in minutes and seconds.
Args:
total_secs (int): The total number of seconds to be converted... |
magic_instruct_75k | 65,055 | Write a Python function to extract the brand and model information from a given string representing the name of a computer graphics card. The string consists of alphanumeric characters and underscores. The function should return a dictionary containing the extracted information.
The code should start with:
```python
d... | Here is the Python code to solve the given problem in the markdown block:
```python
def extract_graphics_card_info(nume2: str) -> dict:
"""
Extracts the brand and model information from a given string representing the name of a computer graphics card.
Args:
nume2 (str): The string representing the ... |
magic_instruct_75k | 65,059 | Write a Python function to calculate the sum of all positive integers less than a given integer `n` that are multiples of 3 or 5. The function should be efficient and handle large values of `n` up to \(10^6\).
The code should start with:
```python
def solution(n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def solution(n: int) -> int:
"""
Calculate the sum of all positive integers less than `n` that are multiples of 3 or 5.
Args:
n (int): The upper limit (exclusive) for the range of integers to consider.
Returns:... |
magic_instruct_75k | 65,072 | Write a Python function to extract model names referenced in the imports from a list of view lines. Each view line is a string containing information about a view in a Python web application. The information includes comments, imports, and model references. The function should parse these view lines and extract the mod... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def extract_model_names(views_lines: List[str]) -> List[str]:
"""
Extracts model names referenced in the imports from a list of view lines.
Args:
views_lines (List[str]): A list of strings w... |
magic_instruct_75k | 65,073 | Write a Python function to perform a bitwise XOR operation on two binary strings of equal length, ensuring that the operation is performed correctly without causing an Index Out of Bounds error. The function should handle binary strings of any length and return the resulting binary string after the XOR operation.
The ... | Here is the Python code to solve the given problem in the markdown block:
```python
def bitwise_xor(bin_str1: str, bin_str2: str) -> str:
"""
Perform a bitwise XOR operation on two binary strings of equal length.
Args:
bin_str1 (str): The first binary string.
bin_str2 (str): The second bina... |
magic_instruct_75k | 65,075 | Write a Python function `process_data` that processes a list of elements and their corresponding counts in three different groups. The function should return a formatted string that includes the counts for each element and a final region string.
The function should start with:
```python
from typing import List
def pr... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_data(lis: List[str], g2: List[str], g3: List[str], g4: List[str]) -> str:
"""
Processes a list of elements and their corresponding counts in three different groups,
and returns a formatte... |
magic_instruct_75k | 65,081 | Implement a simple network protocol for data transmission using the Vegas congestion control algorithm. The protocol consists of two components: a sender and a receiver. The sender is responsible for transmitting data packets to the receiver, while the receiver handles incoming packets and sends acknowledgments back to... | Here is the Python code to solve the given problem in the markdown block:
```python
import sys
import socket
import time
class VegasSender:
def __init__(self, port):
"""
Initialize the sender with the given port.
Args:
port (int): The port number on which the sender will transm... |
magic_instruct_75k | 65,085 | Write a Python function to calculate the output size of a tensor after a concatenation operation. The function should take three inputs:
- `node`: a node object representing the concatenation operation, which has an attribute `input` that is a list of input tensor names.
- `diction`: a dictionary containing the input t... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_output_size(node, diction, axis):
"""
Calculate the output size of a tensor after a concatenation operation.
Args:
node: A node object representing the concatenation operation, with an attribute `input... |
magic_instruct_75k | 65,092 | Write a Python function to generate a random order of presentation for a list of participants in a competition. The function should take a list of participant names as input and return a randomly shuffled order of presentation. The function should use the `random` module to shuffle the list of participant names and the... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def generate_presentation_order(participants: List[str]) -> List[str]:
"""
Generates a random order of presentation for a list of participants.
Args:
participants (List[str]): ... |
magic_instruct_75k | 65,098 | Write a Python function to generate a migration script for a hypothetical database migration tool. The migration script should handle the creation of new tables and the addition of new fields to existing tables. The function should take a list of migration operations, where each operation is represented as a dictionary... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def generate_migration_script(operations: List[Dict]) -> str:
"""
Generates a migration script for a hypothetical database migration tool.
Args:
operations (List[Dict]): A list of dict... |
magic_instruct_75k | 65,102 | Write a Python function to apply renaming operations on a list of tuples. Each tuple in the list represents a renaming operation, with the first element being the old variable name and the second element being the new variable name. The function should return a new list of tuples with the renaming operations applied, e... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def apply_renaming_operations(renaming_operations: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
"""
Applies renaming operations on a list of tuples, ensuring no duplicate renaming operations a... |
magic_instruct_75k | 65,127 | Write a Python function to calculate the new centroids for a k-means clustering algorithm based on the current centroids and the data points. The function should take in the current centroids and the data points, and return the new centroids. Each centroid and data point is represented as a dictionary with keys `'clust... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def find_new_centroids(centroids: List[Dict[str, float]], data: List[Dict[str, float]]) -> List[Dict[str, float]]:
"""
Calculate the new centroids for a k-means clustering algorithm based on the cu... |
magic_instruct_75k | 65,130 | Write a Python function to calculate the sum of squares of the first n natural numbers. The function should take an integer `n` as input and return the sum of the squares of the first `n` natural numbers. The code should start with:
```python
def sum_of_squares(n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def sum_of_squares(n: int) -> int:
"""
Calculate the sum of squares of the first n natural numbers.
Args:
n (int): The number of natural numbers to consider.
Returns:
int: The sum of squares of the firs... |
magic_instruct_75k | 65,160 | Write a Python function to generate a list of excluded paths for a file system traversal based on specified file system types and paths to be pruned. The function should handle multiple values separated by spaces in the input variables. The code should start with:
```python
def generate_excluded_paths(filesystems: str,... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_excluded_paths(filesystems: str, prunepaths: str) -> str:
"""
Generate a list of excluded paths for a file system traversal based on specified file system types and paths to be pruned.
Args:
filesystems... |
magic_instruct_75k | 65,183 | Write a Python function to simulate a simplified version of a remote procedure call (RPC) framework server. The server will expose a set of functions that the client can call remotely. The server will use a thread pool to handle incoming RPC requests.
The task involves implementing the following functions:
1. `initial... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Callable, Dict
import threading
import queue
# Global variables to manage the thread pool and registered functions
thread_pool = []
function_registry = {}
task_queue = queue.Queue()
def initialize_rpc_threadpo... |
magic_instruct_75k | 65,210 | Write a Python function to extend a given guest list with additional guests. The function should take two lists as input: one representing the current guest list and the other representing the new guests to be added. The function should return the updated guest list after including the new guests.
The code should star... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def extend_guest_list(current_guests: List[str], new_guests: List[str]) -> List[str]:
"""
Extends the current guest list with additional guests.
Args:
current_guests (List[str]): The list of... |
magic_instruct_75k | 65,212 | Write a Python function to analyze a reference table and create a replacement table based on certain criteria. The reference table contains field names and data types, and the replacement table will exclude key fields and modify certain data types. The data types are represented using an enum called `DataType`, which i... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Any
from enum import Enum
class DataType(Enum):
iter = "iter"
string = "string"
integer = "integer"
float = "float"
def analyze_reference_table(table_obj: Dict[str, Any]) -> Dict[str, Any... |
magic_instruct_75k | 65,220 | Write a Python function to implement the Rectified Linear Unit (ReLU) activation function using NumPy. The ReLU function is defined as ReLU(x) = max(0, x), where x is the input value. The function should take an input array `x` and optional keyword arguments `out` and `ind`. If the `out` argument is provided, the resul... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def ReLU(x, **kwds):
"""
Applies the Rectified Linear Unit (ReLU) activation function to the input array `x`.
Args:
x (numpy.ndarray): The input array to which the ReLU function is applied.
... |
magic_instruct_75k | 65,221 | Write a Python function to count the frequency of each integer in a given list of integers. The function should return a dictionary where the keys are the integers from the list and the values are their respective frequencies.
The code should start with:
```python
from typing import List, Dict
def count_frequency(num... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_frequency(nums: List[int]) -> Dict[int, int]:
"""
Counts the frequency of each integer in the given list and returns a dictionary with the integers as keys and their frequencies as values... |
magic_instruct_75k | 65,226 | Write a Python function to simulate the behavior of the `assertContains` method used in unit testing. The function should check whether a given value is present in an array. The function should take an array and a value as input and return `true` if the value is present in the array, and `false` otherwise. The function... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def custom_assert_contains(arr: List[str], value: str) -> bool:
"""
Simulates the behavior of the `assertContains` method used in unit testing.
Checks whether a given value is present in an array.
... |
magic_instruct_75k | 65,241 | Write a Python function to calculate the total width of a Vernier mask for a microfabrication process. The mask consists of a series of fingers on the top and bottom layers, and the total width is determined by the design parameters.
The design parameters are:
- `layerNumber`: The number of layers for the mask design.... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_mask_width(layerNumber: int, numFingers: int, fingerWidth: int) -> int:
"""
Calculate the total width of a Vernier mask based on the design parameters.
Args:
layerNumber (int): The number of layers in ... |
magic_instruct_75k | 65,263 | Write a Python function to check for duplicate file names in a package manifest. The package manifest is represented as a dictionary called `packageManifest`, where the "Loose" key contains a dictionary of file names. The function should take two parameters: `packageManifest` (the package manifest dictionary) and `rela... | Here is the Python code to solve the given problem in the markdown block:
```python
def check_for_duplicate_file(packageManifest: dict, relativeSourceFilePath: str) -> bool:
"""
Checks for duplicate file names in a package manifest.
Args:
packageManifest (dict): The package manifest dictionary cont... |
magic_instruct_75k | 65,269 | Write a Python function `perform_transformation(array, axis)` that takes a multi-dimensional array `array` and an integer `axis` as input. The function should reshape the array and insert a new axis at the specified position. If the input array is not multi-dimensional or the specified axis is out of bounds, the functi... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def perform_transformation(array, axis):
"""
Reshape the given multi-dimensional array and insert a new axis at the specified position.
Args:
array (list): A multi-dimensional list representing t... |
magic_instruct_75k | 65,276 | Write a Python function to automate the setup process for different environments based on the value of the `ENV` variable. The function should execute specific setup tasks for the production and staging environments, and handle any unknown environment by performing common tasks. The function should also handle cases wh... | Here is the Python code to solve the given problem in the markdown block:
```python
def setup_environment(env: str = None) -> None:
"""
Automates the setup process for different environments based on the value of the `env` variable.
Args:
env (str, optional): The environment to set up. Defaults to ... |
magic_instruct_75k | 65,291 | Write a Python function to process a dictionary of unique keys and their corresponding values. The function should iterate through the dictionary, print each key-value pair in the format "key;value", and then concatenate the key-value pairs into a single string with semicolons as delimiters and ending each pair with a ... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_unique(unique: dict) -> str:
"""
Processes a dictionary of unique keys and their corresponding values.
Prints each key-value pair in the format "key;value" and concatenates
them into a single string with semi... |
magic_instruct_75k | 65,296 | Implement a method `calculate_duration` in a Python class that calculates the duration of timeseries data based on the number of frames and the sampling frequency. The duration should be returned in seconds. The class already has methods to retrieve the number of frames and the sampling frequency.
The starter code is ... | Here is the Python code to solve the given problem in the markdown block:
```python
class TimeseriesData:
def __init__(self, timeseries_model):
self._timeseries_model = timeseries_model
def get_num_frames(self) -> int:
return self._timeseries_model.numTimepoints()
def get_sampling_frequenc... |
magic_instruct_75k | 65,298 | Write a Python function to reconstruct the itinerary from a list of airline tickets represented as pairs of departure and arrival airports. The itinerary should start from the departure airport "JFK". It is guaranteed that the input list of tickets forms a valid itinerary.
The function signature is as follows:
```pyth... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
from collections import defaultdict
def findItinerary(tickets: List[List[str]]) -> List[str]:
"""
Reconstructs the itinerary from a list of airline tickets.
Args:
tickets (List[List[str]]): ... |
magic_instruct_75k | 65,309 | Write a Python function to calculate the factorial of a given non-negative integer efficiently. The function should handle edge cases such as negative input and optimize the calculation to avoid potential issues with recursion depth.
The code should start with:
```python
def factorial(n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def factorial(n: int) -> int:
"""
Calculate the factorial of a given non-negative integer.
Args:
n (int): The non-negative integer for which to calculate the factorial.
Returns:
int: The factorial of th... |
magic_instruct_75k | 65,366 | Write a Python function to calculate the average monthly revenue for a given year and month from a list of revenue data objects and a list of monthly statistics objects. Each revenue data object contains information about the revenue for a specific date, and each monthly statistics object contains information about the... | Here is the Python code to solve the given problem in the markdown block:
```python
from datetime import datetime
from typing import List, Dict
class Revenue:
def __init__(self, date: str, amount: float):
self.date = date
self.amount = amount
class MonthlyStats:
def __init__(self, year: int, m... |
magic_instruct_75k | 65,369 | Write a Python function to count the number of file paths that start with a valid drive letter followed by a colon and a backslash (e.g., "C:\", "D:\", etc.), ensuring that the count does not exceed a specified range limit. The function should efficiently process the list of paths and return the count of valid paths.
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
DRIVE_LETTER_REGEX = re.compile(r'^[a-zA-Z]:\\')
RANGE_LIMIT = 10000
def count_valid_drive_paths(paths: List[str]) -> int:
"""
Counts the number of file paths that start with a valid drive let... |
magic_instruct_75k | 65,379 | Write a Python function to validate a set of firewall rules based on their allowed protocols. Each rule is represented as a dictionary with an 'allowed' key containing a list of allowed protocols. The function should return `True` if all rules have at least one specified protocol, and `False` otherwise.
The code shoul... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Union
def validate_firewall_rules(rules: List[Dict[str, Union[str, List[str]]]]) -> bool:
"""
Validates a set of firewall rules based on their allowed protocols.
Args:
rules (List[Dic... |
magic_instruct_75k | 65,394 | Write a Python function to process user information and return it in a specific format. The function should take in three parameters: `userNumber` (an integer representing the user's unique identifier), `year` (an integer representing the user's graduation year), and `school` (a string representing the user's school na... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_user_information(userNumber: int, year: int, school: str) -> List[int | str]:
"""
Processes user information and returns it in a specific format.
Args:
userNumber (int): The user... |
magic_instruct_75k | 65,398 | Implement a `TestParameters` class that manages parameters for a testing framework. The class should support the following functionalities:
1. Setting a parameter with a given key and value.
2. Retrieving a parameter's value by key, with an option to provide a default value if the key is not found.
3. Checking if a par... | Here is the Python code to solve the given problem in the markdown block:
```python
class TestParameters:
def __init__(self):
"""
Initialize the TestParameters object with an empty dictionary to store parameters.
"""
self.parameters = {}
def set_parameter(self, key: str, value: ... |
magic_instruct_75k | 65,426 | Write a Python function to simulate the behavior of retrieving the latest version of cluster images for versions 4.3, 4.4, 4.5, and 4.6, combining them into a single space-separated string, and then randomly shuffling the output. The function should mimic the behavior of using the `oc` command-line tool to interact wit... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def get_and_shuffle_cluster_versions() -> str:
"""
Simulates retrieving the latest version of cluster images for versions 4.3, 4.4, 4.5, and 4.6,
combines them into a single space-separ... |
magic_instruct_75k | 65,427 | Write a Python function to distribute a given number of files evenly across a specified number of jobs. Each job should receive an equal or nearly equal number of files, and any remaining files should be distributed among the jobs in a fair manner. The function should return a list of integers, where each element repre... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def distribute_files(total_files: int, total_jobs: int) -> List[int]:
"""
Distributes a given number of files evenly across a specified number of jobs.
Args:
total_files (int): The total num... |
magic_instruct_75k | 65,431 | Write a Python function to parse and extract indices and texture IDs from a given input string. The input string contains a series of integers representing indices and texture IDs, separated by spaces. The goal is to extract these values and store them in separate lists.
The input string contains a series of integers ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def parse_indices_and_tex_ids(input_str: str) -> Tuple[List[int], List[int]]:
"""
Parses the input string to extract indices and texture IDs, and returns them as two separate lists.
Args:
... |
magic_instruct_75k | 65,433 | Write a Python function to compare two version numbers represented as tuples of integers. The function should return:
- `1` if `version1` is greater than `version2`
- `0` if `version1` is equal to `version2`
- `-1` if `version1` is less than `version2`
The version numbers are represented as tuples of integers, where e... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
def compare_versions(version1: Tuple[int], version2: Tuple[int]) -> int:
"""
Compare two version numbers represented as tuples of integers.
Args:
version1 (Tuple[int]): The first version nu... |
magic_instruct_75k | 65,437 | Write a Python function to construct a dictionary that maps each day to its corresponding organized text data. The function should take three parameters: `days` (a list of days), `day_titles` (a list of titles for each day), and `new_descrip` (a list of organized text data based on the day titles). The function should ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def dict_builder(days: List[str], day_titles: List[str], new_descrip: List[str]) -> Dict[str, str]:
"""
Constructs a dictionary that maps each day to its corresponding organized text data.
Arg... |
magic_instruct_75k | 65,444 | Write a Python function to map human body parts to their corresponding identifiers. The identifiers are structured in a hierarchical manner, with each body part having a unique identifier. The identifiers follow a naming convention where the body part name is followed by a number indicating the level of detail.
Your t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def map_body_parts(identifiers: List[str]) -> Dict[str, List[str]]:
"""
Maps body parts to their corresponding identifiers.
Args:
identifiers (List[str]): A list of body part identifie... |
magic_instruct_75k | 65,449 | Implement the `SimpleSelfMsgHandler` class in Python to manage self messages for a simple bot in a simulation environment. The class should have the following attributes and methods:
1. **Constructor**: Initializes the `node` attribute with the owner node casted as a `SimpleBot` and creates a new self message object na... | Here is the Python code to solve the given problem in the markdown block:
```python
class BasicSelfMsg:
def __init__(self, interval):
self.interval = interval
class SimpleBot:
pass # Placeholder for the SimpleBot class
class SimpleSelfMsgHandler:
def __init__(self, owner_node, interval):
... |
magic_instruct_75k | 65,450 | Write a Python function to process a list of transactions and calculate the total amount of money spent by each user. Each transaction is represented by a tuple containing the user ID, transaction type, and transaction amount. The function should output the total amount spent by each user, regardless of the transaction... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Dict
def calculate_total_spent_by_user(transactions: List[Tuple[str, str, float]]) -> Dict[str, float]:
"""
Calculate the total amount of money spent by each user from a list of transactions.
... |
magic_instruct_75k | 65,472 | Write a Python function to construct a color command string from given RGB values and another function to send this command to a simulated robotic arm interface. The robotic arm interface should handle errors and log them using a custom logging function. The `set_color` function should return a string representing the ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Optional, Tuple
def set_color(red: int, green: int, blue: int) -> str:
"""
Construct a color command string from the given RGB values.
Args:
red (int): The red component of the color (0-255).
... |
magic_instruct_75k | 65,474 | Write a Python function to parse a series of code snippets and extract specific information from them. Each code snippet follows the format `<reponame><gh_stars>`, where `<reponame>` is the name of a GitHub repository and `<gh_stars>` is the number of stars the repository has received. The function should take a string... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
def parse_code_snippet(code_snippet: str) -> Tuple[str, int]:
"""
Parses a code snippet formatted as `<reponame><gh_stars>` and extracts the repository name and the number of stars.
Args:
c... |
magic_instruct_75k | 65,490 | Write a Python function that takes a list of integers as input and returns two separate lists: one containing all the even numbers that are divisible by 2, and the other containing all the odd numbers that are divisible by 3. The function should be named `find_divisible_numbers` and should have the following signature:... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def find_divisible_numbers(input_list: List[int]) -> Tuple[List[int], List[int]]:
"""
Separates the input list into two lists: one containing all even numbers divisible by 2,
and the other con... |
magic_instruct_75k | 65,491 | Write a Python function `parse_log_entry(log_entry: str) -> dict` that takes a single log entry as input and returns a dictionary containing the extracted information. The keys of the dictionary should be "timestamp", "class", "method", and "description", and the values should correspond to the extracted components fro... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def parse_log_entry(log_entry: str) -> dict:
"""
Parses a single log entry and returns a dictionary containing the extracted information.
Args:
log_entry (str): A single log entry in the for... |
magic_instruct_75k | 65,505 | Write a Python function to check whether a given string is a palindrome or not. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). For example, "racecar" and "A man a plan a canal Panama" are palindromes.
... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_palindrome(s: str) -> bool:
"""
Check if the given string is a palindrome.
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward,
ignoring spaces, punctu... |
magic_instruct_75k | 65,514 | Write a Python function to extract function prototypes from a given C/C++ header file content. The function should parse the content and return a list of function prototypes. A function prototype is defined as a line of code that starts with a return type, followed by the function name, parameters, and ending with a se... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def extractFunctionPrototypes(headerContent: str) -> List[str]:
"""
Extracts function prototypes from a given C/C++ header file content.
Args:
headerContent (str): The content of a... |
magic_instruct_75k | 65,518 | Write a Python function to monitor the CPU usage of Docker containers and identify which containers are experiencing high CPU usage. The function should take a list of tuples as input, where each tuple contains the container name and its CPU usage percentage. A container is considered to be experiencing high CPU usage ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def check_container_stats(containers: List[Tuple[str, int]]) -> List[str]:
"""
Monitors the CPU usage of Docker containers and returns a list of containers
that are experiencing high CPU usage... |
magic_instruct_75k | 65,520 | Write a Python function to analyze a list of integers and return the maximum value, minimum value, and average of the integers in the list. The function should handle edge cases such as an empty list and a list with a single element. The code should start with:
```python
from typing import List, Tuple
def analyze_list... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def analyze_list(list1: List[int]) -> Tuple[int, int, float]:
"""
Analyzes a list of integers and returns the maximum value, minimum value, and average of the integers in the list.
Args:
... |
magic_instruct_75k | 65,551 | Write a Python function to create a node-community hash map from a given graph represented as an adjacency list and a list of communities. Each community is a list of nodes that belong to the same community. The function should return a dictionary where the keys are the nodes and the values are the community indices to... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def create_node_community_map(graph: Dict[int, List[int]], communities: List[List[int]]) -> Dict[int, int]:
"""
Creates a node-community hash map from a given graph and list of communities.
Ar... |
magic_instruct_75k | 65,553 | Create a Python function `add_to_cart` that handles the addition of items to a shopping cart and returns the distributor ID based on the user's provided ZIP code. The function should perform the following:
1. Check if the provided ZIP code exists in the database. If not found, return an empty dictionary and the HTTP st... | Here is the Python code to solve the given problem in the markdown block:
```python
def add_to_cart(zipcode: str, item: dict) -> (dict, int):
"""
Adds an item to the shopping cart and returns the distributor ID based on the provided ZIP code.
Args:
zipcode (str): The ZIP code provided by the user.
... |
magic_instruct_75k | 65,562 | Write a Python function to find the maximum score from a given list of scores representing the scores of candidates in a coding competition. The function should efficiently determine the highest score in the list.
The code should start with:
```python
from typing import List
def findMaxScore(scores: List[int]) -> int... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def findMaxScore(scores: List[int]) -> int:
"""
Find the maximum score from a list of scores.
Args:
scores (List[int]): A list of integers representing the scores of candidates.
Returns... |
magic_instruct_75k | 65,564 | Write a Python function that generates a blueprint dictionary for a dataframe based on a given JSON database, its schema, and an index property. The function should ensure that the specified index property is correctly marked in the blueprint dictionary.
The function should start with:
```python
def notion_db_blueprin... | Here is the Python code to solve the given problem in the markdown block:
```python
def notion_db_blueprint_df(db_json: dict, db_schema: dict, index_prop: str) -> dict:
"""
Generates a blueprint dictionary for a dataframe based on the given JSON database, its schema, and an index property.
Args:
db... |
magic_instruct_75k | 65,571 | Write a Python function to count the frequency of each unique integer in a given list of 10 random integers between 0 and 10 (inclusive). The function should return a dictionary where the keys are the unique integers in the input list and the values are the frequency of each integer in the input list.
The code should ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_frequency(nums: List[int]) -> Dict[int, int]:
"""
Counts the frequency of each unique integer in a given list of 10 random integers between 0 and 10 (inclusive).
Args:
nums (... |
magic_instruct_75k | 65,584 | Write a Python function to process a given NumPy array based on specific conditions. The function should take a NumPy array as input and perform the following operations:
1. Replace any negative values in the array with zero.
2. Round up any positive values in the array to the nearest integer.
3. Round any non-integer ... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def process_array(data: np.ndarray) -> np.ndarray:
"""
Process a given NumPy array based on specific conditions.
Args:
data (np.ndarray): The input NumPy array to be processed.
Returns:
... |
magic_instruct_75k | 65,586 | Write a Python function to find the smallest positive integer `g` that is a factor of both integers in a given list `zcw_g`. The function should return the correct value of `g` based on the given list.
The code should start with:
```python
from typing import List
def find_correct_g(zcw_g: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_correct_g(zcw_g: List[int]) -> int:
"""
Find the smallest positive integer `g` that is a factor of both integers in the given list `zcw_g`.
Args:
zcw_g (List[int]): A list of 2 inte... |
magic_instruct_75k | 65,621 | Write a Python function to manage dotfiles in a user's home directory. The function should:
1. Identify all dotfiles in a specified directory.
2. Check if each dotfile already exists in the user's home directory.
3. If a dotfile exists, move it to a temporary backup directory.
4. Copy the dotfiles from the specified di... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
import shutil
import platform
import tempfile
from typing import List
def manage_dotfiles(dotfiles_dir: str, home_dir: str) -> None:
"""
Manages dotfiles in a user's home directory.
Args:
dotfiles_dir (st... |
magic_instruct_75k | 65,624 | Write a Python function to calculate the total distance of a transportation network based on its configuration. The network configuration is represented as a list of link configurations, where each link configuration is a dictionary with the following keys:
- "endpoint1": the name of the first endpoint
- "endpoint2": t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def calculate_total_distance(network_config: List[Dict[str, str]]) -> float:
"""
Calculate the total distance of a transportation network based on its configuration.
Args:
network_conf... |
magic_instruct_75k | 65,648 | Write a Python function to unpack a dictionary and return a list of tuples containing the key-value pairs. The function should handle dictionaries of any size and ensure that the key-value pairs are correctly unpacked and stored in the list.
The code should start with:
```python
from typing import Dict, List, Tuple
d... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Tuple
def unpack_dictionary(value: Dict[str, int]) -> List[Tuple[str, int]]:
"""
Unpacks a dictionary and returns a list of tuples containing the key-value pairs.
Args:
value (Dict[st... |
magic_instruct_75k | 65,654 | Write a Python function `generate_action_summary` that processes a list of actions and returns a summary report in the form of a dictionary. Each action in the list is represented as a dictionary with an "id" and a "status" key. The status can be one of the following: "pending", "in-progress", "completed", or "failed".... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def generate_action_summary(actions: List[Dict[str, str]]) -> Dict[str, int]:
"""
Generates a summary report of actions based on their status.
Args:
actions (List[Dict[str, str]]): A l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.