source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
magic_instruct_75k | 13,925 | Write a Python function to count the number of occurrences of a target value within a given sequence (which can be a list or tuple). The function should be efficient and handle different types of sequences.
The code should start with:
```python
from typing import Union, Sequence
def my_count(arr: Union[Sequence[int],... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Union, Sequence
def my_count(arr: Union[Sequence[int], Sequence[float]], target: Union[int, float]) -> int:
"""
Counts the number of occurrences of a target value within a given sequence.
Args:
a... |
magic_instruct_75k | 13,931 | Write a Python function to parse and validate an argument list for a specific command. The argument list is represented as a string, where each argument is enclosed within parentheses and separated by a comma. Each argument can be either a literal string or a variable name followed by a colon and a data type. The funct... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def parse_argument_list(argument_list: str) -> List[str]:
"""
Parses and validates an argument list for a specific command.
Args:
argument_list (str): A string representing the argument list... |
magic_instruct_75k | 13,934 | Write a Python function to process a list of letters and perform a specific operation on each letter. The function should take a list of letters as input and append each letter to a new list called `appended_letters`. The function should return the `appended_letters` list.
The code should start with:
```python
from ty... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_letters(letters: List[str]) -> List[str]:
"""
Processes a list of letters by appending each letter to a new list.
Args:
letters (List[str]): A list of letters to be processed.
... |
magic_instruct_75k | 13,939 | Write a Python function to simulate a simple priority scheduling algorithm. The function should take a list of processes, where each process is represented by a dictionary containing the process ID and its priority level. The function should return the IDs of the processes in the order they would be executed, based on ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def priority_scheduling(processes: List[Dict[str, int]]) -> List[str]:
"""
Simulates a simple priority scheduling algorithm.
Args:
processes (List[Dict[str, int]]): A list of dictionar... |
magic_instruct_75k | 13,945 | Write a Python function to generate a header table from a given dataset. The header table should contain unique items from the dataset along with their frequency counts. The dataset is represented as a list of transactions, where each transaction is a set of items.
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, Set, Dict
def generate_header_table(dataSet: List[Set[str]]) -> Dict[str, int]:
"""
Generates a header table from a given dataset. The header table contains unique items
from the dataset along with ... |
magic_instruct_75k | 13,948 | 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 | 13,954 | Write a Python function to process a dictionary containing customization and environment information. The function should extract specific data from the dictionary and concatenate the values of the 'customize' and 'env' keys into a single string. If either key does not exist in the dictionary, the function should ignor... | Here is the Python code to solve the given problem in the markdown block:
```python
def setup(i: dict) -> str:
"""
Processes a dictionary containing customization and environment information,
and returns a concatenated string of the values of the 'customize' and 'env' keys.
Args:
i (dict): A di... |
magic_instruct_75k | 13,977 | Write a Python function to find the highest score from a list of game scores. If the list is empty, the function should return 0. The function should be efficient and handle edge cases appropriately.
The code should start with:
```python
from typing import List
def highest_score(scores: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def highest_score(scores: List[int]) -> int:
"""
Returns the highest score from a list of game scores.
Args:
scores (List[int]): A list of integers representing the scores of a game.
Re... |
magic_instruct_75k | 13,988 | Write a Python function to perform a case-insensitive comparison of two strings and return a corresponding enum value based on the comparison. The function should be able to match a given test keyword to the corresponding `TraceKeywords` enum value. If a match is found, the function should return the corresponding enum... | Here is the Python code to solve the given problem in the markdown block:
```python
from enum import Enum
from typing import Union
class TraceKeywords(Enum):
Test1 = "test1"
Test2 = "test2"
Test3 = "test3"
Unknown = "unknown"
def are_equal_case_insensitive(str1: str, str2: str) -> bool:
"""
Co... |
magic_instruct_75k | 13,995 | Write a Python function to perform elementwise addition on two input arrays. The function should take two arrays of the same shape as input and return a new array containing the elementwise sum of the input arrays. The function should raise a `ValueError` if the input arrays do not have the same length.
The code shoul... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def elementwise_add(arr1: List[int], arr2: List[int]) -> List[int]:
"""
Perform elementwise addition on two input arrays.
Args:
arr1 (List[int]): The first array of integers.
arr2 (L... |
magic_instruct_75k | 14,008 | Write a Python function to process a list of files and directories and perform specific actions based on their types. The function should iterate through the list and execute the following actions:
- For each regular file (not a directory or special file), calculate the file size and print a message indicating the file... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import os
def process_files_and_directories(files: List[str]) -> None:
"""
Processes a list of files and directories and performs specific actions based on their types.
Args:
files (List[str... |
magic_instruct_75k | 14,014 | Write a Python function to process command-line arguments and perform specific actions based on the provided options. The function should handle the following command-line options:
1. `-h` or `--help`: Display a help message explaining how to use the script.
The function should be able to parse the command-line argume... | Here is the Python code to solve the given problem in the markdown block:
```python
import sys
def process_command_line_args():
"""
Process command-line arguments and perform specific actions based on the provided options.
The function handles the following command-line options:
- `-h` or `--help`: Di... |
magic_instruct_75k | 14,016 | Write a Python function to find the index of the first occurrence of a space character in a given string. If the space character is not found, the function should return -1. The function should be efficient and handle edge cases such as empty strings and strings without spaces.
The code should start with:
```python
de... | Here is the Python code to solve the given problem in the markdown block:
```python
def find_first_space_index(inputString: str) -> int:
"""
Find the index of the first occurrence of a space character in the given string.
Args:
inputString (str): The input string to search for the space character.
... |
magic_instruct_75k | 14,021 | Write a Python function `process_date_time(string)` that takes a string in the format "YYYY-MM-DD HH:MM" as input and returns a tuple containing the date and time components as integers in the order (year, month, day, hour, minute). The function should use a more efficient approach compared to the given code snippet.
... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_date_time(string: str) -> tuple:
"""
Processes a date and time string in the format "YYYY-MM-DD HH:MM" and returns a tuple of integers representing the date and time components.
Args:
string (str): A str... |
magic_instruct_75k | 14,022 | Write a Python function to process a response data structure according to the following specifications:
- Remove a specific key from the dictionary.
- Concatenate the values of another key into a single string, separated by commas.
- Add a new key-value pair to the dictionary with the key "error" and the value being th... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_response(response: dict, key_to_remove: str, key_to_concat: str) -> dict:
"""
Processes a response data structure by removing a specific key, concatenating the values of another key into a single string,
and addi... |
magic_instruct_75k | 14,026 | Write a Python function to verify the validity of transactions in a simple blockchain simulation. Each transaction is represented as a dictionary with keys "sender", "recipient", "amount", and "signature". The function should check if the sender has sufficient balance to cover the transaction amount and verify the sign... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def verify_transactions(transactions: List[Dict], public_key: str, balances: Dict[str, int]) -> List[Dict]:
"""
Verify the validity of transactions in a simple blockchain simulation.
Args:
... |
magic_instruct_75k | 14,028 | Write a Python function to calculate the total amount spent by each consumer from a list of consumer data. The consumer data is represented as a list of tuples, where each tuple contains the consumer's name and a list of their purchases. The function should return a dictionary mapping each consumer's name to their tota... | 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(consumer_data: List[Tuple[str, List[float]]]) -> Dict[str, float]:
"""
Calculate the total amount spent by each consumer from a list of consumer data.
Args:
... |
magic_instruct_75k | 14,037 | Write a Python function `detect_anomalies(logs)` that processes a list of log dictionaries and identifies any anomalies in the data. Each log dictionary contains temperature and pressure readings. An anomaly is defined as a temperature outside the range of 35 to 38 degrees Celsius or a pressure outside the range of 2.5... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def detect_anomalies(logs: List[Dict[str, float]]) -> List[int]:
"""
Detects anomalies in a list of environmental monitoring logs.
An anomaly is defined as a temperature outside the range of 3... |
magic_instruct_75k | 14,055 | Write a Python function to parse a list of package dependencies and return a dictionary containing the package names as keys and their respective versions as values. Each package dependency is represented as a string in the format "package_name>=version". The function should handle dependencies with version constraints... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def parse_dependencies(dependencies: List[str]) -> Dict[str, str]:
"""
Parses a list of package dependencies and returns a dictionary with package names as keys and their versions as values.
A... |
magic_instruct_75k | 14,060 | Write a Python function to determine whether a Django application is using version 2.1 or below and is configured to use SQLite as its database. The function should take in the Django version and the database configuration as input and return a boolean value indicating whether the conditions are met.
The function sign... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_django_2_1_and_sqlite(django_version: str, db_config: str) -> bool:
"""
Determines whether a Django application is using version 2.1 or below and is configured to use SQLite as its database.
Args:
django_vers... |
magic_instruct_75k | 14,077 | Write a Python function to resolve a URL redirect chain given a dictionary of redirect mappings and a source URL. The function should follow the redirect chain until it reaches the final destination URL. The function should start with:
```python
def resolve_redirects(redirects: dict, source_url: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def resolve_redirects(redirects: dict, source_url: str) -> str:
"""
Resolves the final destination URL after following a chain of URL redirects.
Args:
redirects (dict): A dictionary where keys are source URLs and va... |
magic_instruct_75k | 14,091 | Write a Python function to automate the setup and initialization of a distributed file system using Weed-FS. The function should perform the following steps:
1. Extract the contents of the file `weed-fs-latest-linux-386.tar.gz` using the `tar` command.
2. Print the message "starting servers" to the console.
3. Create t... | Here is the Python code to solve the given problem in the markdown block:
```python
import subprocess
import os
def setup_weed_fs():
"""
Automates the setup and initialization of a distributed file system using Weed-FS.
Steps:
1. Extracts the contents of the file `weed-fs-latest-linux-386.tar.gz` usin... |
magic_instruct_75k | 14,093 | Write a Python function to manage an inventory using dictionary methods. The function should perform the following tasks:
1. Create an initial inventory dictionary with the following items and quantities: `{'croissant': 19, 'bagel': 4, 'muffin': 8, 'cake': 1}`.
2. Print the initial inventory using the `print` function ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def manage_inventory() -> Dict[str, int]:
"""
Manages an inventory by performing several operations on a dictionary.
Steps:
1. Create an initial inventory dictionary.
2. Print the initial in... |
magic_instruct_75k | 14,103 | Write a Python function to extract subscription and device statuses from a JSON response received from a remote server. The response is a dictionary containing lists of subscriptions and devices, each with an `id` and a `status`. The function should parse the response and return a new dictionary with the extracted stat... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def extract_statuses(response: Dict) -> Dict[str, List[str]]:
"""
Extracts subscription and device statuses from the response.
Args:
response (dict): A dictionary representing the resp... |
magic_instruct_75k | 14,113 | Write a Python function `generate_native_app_command` that constructs a command to generate a native desktop application for a given website. The function should take the following parameters:
- `website_url` (string): The URL of the website for which the native application will be generated.
- `icon_path` (string): Th... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_native_app_command(website_url: str, icon_path: str, app_name: str, maximize: bool, single_instance: bool, wildvine: bool, inject_css: str) -> str:
"""
Generates a command to create a native desktop application for ... |
magic_instruct_75k | 14,114 | Write a Python function to calculate the sum of all elements in a nested list of integers. The nested list can contain integers or other nested lists, and the depth of nesting is not limited. Your task is to write a function `nested_list_sum` that takes a nested list as input and returns the sum of all the integers in ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def nested_list_sum(nested_list: Union[List[Union[int, List]], int]) -> int:
"""
Calculate the sum of all integers in a nested list.
Args:
nested_list: A nested list of integers, wher... |
magic_instruct_75k | 14,137 | Write a Python function to find the shortest path in a maze represented by a dictionary. Each room in the maze is represented by a key in the dictionary, and the value associated with each key is another dictionary containing the possible movements from that room and the corresponding room number to which each movement... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_shortest_path(maze: dict, start: str, end: str) -> List[str]:
"""
Find the shortest path from the starting room to the ending room in a maze represented by a dictionary.
Args:
maze ... |
magic_instruct_75k | 14,138 | Write a Python function to determine the installation order of packages based on their dependencies. The dependencies are represented as a list of tuples, where each tuple contains two package names. The first package in the tuple depends on the second package. The function should return the installation order of the p... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
import heapq
def install_order(packages: List[str], dependencies: List[Tuple[str, str]]) -> List[str]:
"""
Determine the installation order of packages based on their dependencies.
Args:
... |
magic_instruct_75k | 14,139 | Write a Python function to generate a list of opam commands based on a given set of switches. The function should follow these guidelines:
- The function should take a list of switches as input, where each switch is a string representing the name of an opam switch.
- For each switch in the input list, the function shou... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_opam_commands(switches: List[str]) -> List[str]:
"""
Generates a list of opam commands based on a given set of switches.
Args:
switches (List[str]): A list of strings representi... |
magic_instruct_75k | 14,140 | Write a Python function `to_datetime` that converts a dictionary representing a date and time into a string formatted as "YYYY-MM-DD HH:MM:SS". The input dictionary will have the following keys: "year", "month", "day", "hour", "minute", and "second", each corresponding to the respective components of the date and time.... | Here is the Python code to solve the given problem in the markdown block:
```python
def to_datetime(dict_date: dict) -> str:
"""
Converts a dictionary representing a date and time into a string formatted as "YYYY-MM-DD HH:MM:SS".
Args:
dict_date (dict): A dictionary with keys "year", "month", "day"... |
magic_instruct_75k | 14,154 | Write a Python function to analyze a given software license text and count the occurrences of specific phrases provided as input. The function should be case-insensitive when matching the phrases in the license text. The function should return a dictionary where the keys are the phrases and the values are the counts of... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
import re
def count_phrase_occurrences(license_text: str, phrases: List[str]) -> Dict[str, int]:
"""
Counts the occurrences of specific phrases in a given software license text.
Args:
... |
magic_instruct_75k | 14,160 | Write a Python function to generate SQL statements for a simplified database migration system. The function should take a list of migration operations and return a list of SQL statements that apply those migrations to a database. Each migration operation is represented as a tuple containing the operation type and the r... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def generate_sql_statements(migrations: List[Tuple]) -> List[str]:
"""
Generates SQL statements for a list of database migration operations.
Args:
migrations (List[Tuple]): A list of ... |
magic_instruct_75k | 14,173 | Write a Python function to parse a string of setup arguments into a dictionary. The setup arguments are provided in the format "key1=value1, key2=value2, key3=value3, ...". The function should handle various data types for the values, including integers, floats, and strings. If a key-value pair is not in the correct fo... | Here is the Python code to solve the given problem in the markdown block:
```python
def parse_setup_args(setup_args: str) -> dict:
"""
Parses a string of setup arguments into a dictionary.
Args:
setup_args (str): A string containing the setup arguments in the format "key1=value1, key2=value2, key3=... |
magic_instruct_75k | 14,179 | Write a Python function to apply a dropout layer in a neural network. The dropout layer randomly sets a fraction of input units to 0 at each update during training, which helps prevent overfitting. The dropout rate, denoted as a decimal value between 0 and 1, determines the fraction of the input units to drop. The func... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def apply_dropout(input_values: List[float], dropout_rate: float) -> List[float]:
"""
Applies a dropout layer to the input values.
Args:
input_values (List[float]): The list of... |
magic_instruct_75k | 14,180 | Write a Python function to find the nth prime number using the Sieve of Eratosthenes algorithm. The function should take an integer `n` as input and return the nth prime number. The Sieve of Eratosthenes is an efficient algorithm for finding all prime numbers up to a specified integer. It works by iteratively marking t... | Here is the Python code to solve the given problem in the markdown block:
```python
def nth_prime(n: int) -> int:
"""
Find the nth prime number using the Sieve of Eratosthenes algorithm.
Args:
n (int): The position of the prime number to find.
Returns:
int: The nth prime number.
""... |
magic_instruct_75k | 14,181 | Write a Python function to calculate the total number of frames in a cycle, given the number of frames in one cycle and the number of times all the other frames of a cycle repeat. The function should handle an optional parameter for the repetition count with a default value of 1.
The code should start with:
```python
... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_total_frames(frames_in_cycle: int, other: int = 1) -> int:
"""
Calculate the total number of frames in a cycle, considering the repetition of all the other frames.
Args:
frames_in_cycle (int): The numb... |
magic_instruct_75k | 14,191 | Write a Python function to filter out valid Python identifiers from a given list of strings. A valid Python identifier is a non-empty string consisting of only letters, digits, or underscores, and not starting with a digit. The function should handle the case where the input list is empty.
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 valid_identifiers(input_list: List[str]) -> List[str]:
"""
Filters out valid Python identifiers from a given list of strings.
Args:
input_list (List[str]): A list of strings to be filter... |
magic_instruct_75k | 14,223 | Write a Python function `paginate_notices` that takes a list of notices and a page number as input and returns the notices to be displayed on that page. The function should also return the total number of pages required to display all the notices. Each page should display a maximum of 15 notices. The list of notices is... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any, Tuple
def paginate_notices(notices: List[Dict[str, Any]], page_number: int) -> Tuple[List[Dict[str, Any]], int]:
"""
Paginate a list of notices and return the notices for a specified page alo... |
magic_instruct_75k | 14,261 | Write a Python function `sum_of_largest` that takes three integer inputs and returns the sum of the two largest numbers. Additionally, write a function `find_minimum_in_random_list` that generates a list of 100 randomly generated integers between 1 and 100 (inclusive) and returns the minimum value in that list.
The co... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
from typing import List
def sum_of_largest(a: int, b: int, c: int) -> int:
"""
Calculate the sum of the two largest numbers from three given integers.
Args:
a (int): The first integer.
b (int)... |
magic_instruct_75k | 14,276 | Write a Python function to determine if a given string is a palindrome. A palindrome is a sequence of characters that reads the same forward and backward, ignoring spaces, punctuation, and capitalization. The function should return `True` if the input string is a palindrome, and `False` otherwise.
The code should star... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_palindrome(s: str) -> bool:
"""
Determine if a given string is a palindrome, ignoring spaces, punctuation, and capitalization.
Args:
s (str): The input string to check.
Returns:
bool: True if the... |
magic_instruct_75k | 14,283 | Write a Python function to manage game server information. The function should store details such as the server name, IP address, port number, account ID, session ID, and server status. Your goal is to implement a function that encapsulates this information and provides methods to manipulate and access the server detai... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Union
def game_server_manager(server_name: str, ip_address: str, port: int, account_id: int, session_id: str, status: str) -> Dict[str, Union[str, int]]:
"""
Manages game server information and provides... |
magic_instruct_75k | 14,288 | Write a Python function to parse a given code snippet and extract the range of GitHub stars for a repository and the comment associated with the pylint disable directive. The code snippet will be provided as a string input to your function.
The code snippet will consist of the following components:
- `<gh_stars>1-10`:... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def parse_code_snippet(code: str) -> (str, str):
"""
Parses a given code snippet and extracts the range of GitHub stars and the comment associated with the pylint disable directive.
Args:
code (str): The ... |
magic_instruct_75k | 14,289 | Write a Python function to count the number of vowels and consonants in a given string. The function should return a tuple containing the count of vowels and consonants in that order. For the purpose of this problem, consider the following as vowels: 'a', 'e', 'i', 'o', and 'u'. The input string will only contain lower... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_vowels_consonants(name: str) -> tuple:
"""
Count the number of vowels and consonants in the given string.
Args:
name (str): The input string containing only lowercase letters.
Returns:
tuple: ... |
magic_instruct_75k | 14,300 | Write a Python function to initialize the input-to-hidden weight matrix `ix` for a recurrent neural network (RNN) using a truncated normal distribution with a specified standard deviation. The function should take the size of the vocabulary and the number of nodes in the RNN's hidden layer as inputs and return the init... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def initialize_ix(vocabulary_size: int, num_nodes: int) -> np.ndarray:
"""
Initialize the input-to-hidden weight matrix `ix` for a recurrent neural network (RNN) using a truncated normal distribution.
Ar... |
magic_instruct_75k | 14,323 | Write a Python function to generate synthetic data for significant wave height and spectral peak using the Weibull distribution. The function should generate samples for both significant wave height and spectral peak, calculate their means and standard deviations, and return these statistics in a dictionary. The functi... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def generate_wave_data(shape_wave_height: float, scale_wave_height: float, shape_spectral_peak: float, scale_spectral_peak: float, size: int) -> dict:
"""
Generate synthetic data for significant wave height a... |
magic_instruct_75k | 14,337 | Write a Python function to filter event registrations based on a given event name and return a list of attendee names for that event. Each registration is represented as a dictionary containing the event name, attendee name, and registration status. If the event name is not found in the registrations, return an empty l... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def get_attendees(registrations: List[Dict[str, str]], event_name: str) -> List[str]:
"""
Filters event registrations based on a given event name and returns a list of attendee names for that event... |
magic_instruct_75k | 14,359 | Create a Python program that simulates a scenario involving manipulating a list of objects and measuring the time taken for the operations. The program should perform the following steps:
1. Define a class `TestClass` with a public integer member variable `integer`.
2. Create a list of instances of `TestClass`.
3. Popu... | Here is the Python code to solve the given problem in the markdown block:
```python
import time
class TestClass:
def __init__(self):
self.integer = 0
def measure_time(num_objects: int) -> None:
"""
Measures the time taken to iterate through a list of `TestClass` objects and increment their `intege... |
magic_instruct_75k | 14,368 | Write a Python function to simulate the movement of a ball in a 2D space. The ball has a position and velocity, and it can be affected by forces. The ball should also handle collisions with the boundaries of the screen.
The code should start with:
```python
from typing import Tuple
class Ball:
def __init__(self, ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
class Ball:
def __init__(self, initial_position: Tuple[float, float], initial_velocity: Tuple[float, float]):
"""
Initialize the ball with an initial position and velocity.
Args:
... |
magic_instruct_75k | 14,389 | Write a Python function to process image annotations and add them to a JSON object. The function should assign unique IDs to each annotation and image, and ensure that the JSON object is correctly formatted. Additionally, complete the conditional check at the end of the script to handle cases where no annotations are f... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def process_annotations(annotations: List[Dict[str, any]], categories: List[Dict[str, any]]) -> Dict[str, any]:
"""
Processes image annotations and adds them to a JSON object.
Args:
an... |
magic_instruct_75k | 14,390 | Create a Python function to simulate a media recording and event handling system. The function should encapsulate the functionality of a media recorder and provide methods for starting, stopping, and handling events related to media recording.
The function should have the following methods:
1. `start_recording(stream:... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Optional, Callable, Any
class MediaRecorderManager:
def __init__(self):
"""
Initialize the MediaRecorderManager with an empty dictionary for event listeners
and a flag to indic... |
magic_instruct_75k | 14,396 | Write a Python function to simulate rolling a six-sided die a specified number of times and return a dictionary containing the frequency of each possible outcome (1 through 6). The function should start with:
```python
import random
def roll_dice_frequencies(num_rolls: int) -> dict:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
import random
def roll_dice_frequencies(num_rolls: int) -> dict:
"""
Simulate rolling a six-sided die a specified number of times and return the frequency of each outcome.
Args:
num_rolls (int): The number of times... |
magic_instruct_75k | 14,401 | Write a Python function to check if a given model exists in a collection of models. The models are represented as strings, and the function should return `True` if the model exists in the collection, and `False` otherwise. The collection of models is represented as a list of strings, and the function should take the mo... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def model_exists(models: List[str], model_to_check: str) -> bool:
"""
Check if a given model exists in a collection of models.
Args:
models (List[str]): A list of strings representing the co... |
magic_instruct_75k | 14,434 | Write a Python function to extract all unique keys from a given JSON object, including keys from nested objects and arrays, and return them in lexicographical order. The JSON object is provided as a dictionary. The function should handle nested structures and ensure that keys are not duplicated in the output list.
The... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def extract_json_keys(json_obj: dict) -> List[str]:
"""
Extracts all unique keys from a given JSON object, including keys from nested objects and arrays,
and returns them in lexicographical order.
... |
magic_instruct_75k | 14,457 | Write a Python function to calculate the frequency of each unique word in a given list of strings, ignoring case sensitivity. The function should return a dictionary where the keys are the unique words (in lowercase) and the values are their respective frequencies. If the input list is empty, the function should return... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def word_frequency(words: List[str]) -> Dict[str, int]:
"""
Calculate the frequency of each unique word in a given list of strings, ignoring case sensitivity.
Args:
words (List[str]): ... |
magic_instruct_75k | 14,468 | Write a Python function to fix the bug in the given code snippet that is part of a unit test function. The function is designed to compare the expected output with the actual output of a program and produce an error message if they do not match. The bug causes incorrect error messages to be produced. Your task is to id... | Here is the Python code to solve the given problem in the markdown block:
```python
def fix_unit_test_error_message(output: str, attach: list, numbers: list) -> str:
"""
Fixes the bug in the unit test error message formatting.
Args:
output (str): The string template for the error message.
a... |
magic_instruct_75k | 14,472 | Write a Python function to automate the build process for a microservices-based application. The function should handle different build types and set appropriate options based on the build type. The function should handle the following services:
- `powermanager-service`
- `procmanager-service`
- `settings-service`
- `t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def build_microservices(services: List[str], build_type: str) -> Dict[str, Dict[str, str]]:
"""
Automates the build process for a microservices-based application.
Args:
services (List[... |
magic_instruct_75k | 14,478 | Write a Python function to detect if a loop exists in a directed graph starting from a given vertex `u`. The graph is represented by an adjacency list, and the function should use two boolean arrays, `visited` and `checkedLoop`, to keep track of visited vertices and vertices that have been checked for forming a loop, r... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Any
def detectLoop(graph: Dict[Any, List[Any]], visited: List[bool], checkedLoop: List[bool], u: Any) -> bool:
"""
Detects if a loop exists in a directed graph starting from a given vertex `u`.
... |
magic_instruct_75k | 14,494 | Write a Python class `EventSystem` that simulates a simple event-driven system. The class should allow users to register event handlers for specific events, trigger those events with optional data, and unregister event handlers. The class should have the following methods:
1. `register_event_handler(event_type, handler... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Callable, Any, Dict, List
class EventSystem:
def __init__(self):
"""
Initialize the EventSystem with an empty dictionary to store event handlers.
"""
self.event_handlers: Dict[str,... |
magic_instruct_75k | 14,495 | Write a Python function to convert a given semantic segmentation map into a discrete representation based on a specified discretization method. The function should take into account the chosen discretization method and apply the corresponding sampling technique to obtain the discrete representation of the semantic segm... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Any
def to_discrete(fake_seg: Dict[str, Any], discretization: str, gumbel_sampler, max_sampler) -> Any:
"""
Converts a given semantic segmentation map into a discrete representation based on a specified... |
magic_instruct_75k | 14,508 | Write a Python function `concat_multiples` that takes a number and a multiplier as input and returns the concatenation of the number and its multiples up to the specified multiplier. Additionally, write a program to find all unique 9-digit concatenations of multiples for the given ranges of numbers and store them in a ... | Here is the Python code to solve the given problem in the markdown block:
```python
def concat_multiples(num: int, multiplier: int) -> str:
"""
Returns the concatenation of a number and its multiples up to the specified multiplier.
Args:
num (int): The base number.
multiplier (int): The num... |
magic_instruct_75k | 14,513 | Write a Python function to calculate the sub-hourly energy delivered from providing upward reserves based on the given parameters and any relevant data within the optimization model. The function should take three parameters: `mod` (the optimization model object), `prj` (the project identifier), and `tmp` (the timepoin... | Here is the Python code to solve the given problem in the markdown block:
```python
def subtimepoint_delivered_energy_expression_rule(mod, prj, tmp):
"""
Calculate the sub-hourly energy delivered from providing upward reserves.
Args:
mod: The optimization model object.
prj: The project iden... |
magic_instruct_75k | 14,531 | Write a Python function to extract and return the unique parameters from a given list of strings, while preserving their original order. The function should take a list of strings representing various parameters used in a machine learning model and return a new list containing only the unique parameters in the same ord... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def extract_unique_parameters(parameter_list: List[str]) -> List[str]:
"""
Extracts and returns the unique parameters from a given list of strings, preserving their original order.
Args:
par... |
magic_instruct_75k | 14,565 | Write a Python function to analyze a stack frame and extract specific information from it. The function should take two parameters: `frame` and `newer_frame`. The `frame` parameter represents the current stack frame, while the `newer_frame` parameter represents a newer stack frame.
Your task is to implement a function... | Here is the Python code to solve the given problem in the markdown block:
```python
def analyze_stack_frame(frame, newer_frame):
"""
Analyzes the stack frames to extract specific information.
Args:
frame: The current stack frame.
newer_frame: The newer stack frame.
Returns:
dic... |
magic_instruct_75k | 14,571 | Write a Python function to convert a given flat index to its corresponding row and column indices in a 2D grid. The flat index starts from 1 and increases row by row. The function should take the flat index and the grid dimensions (number of rows and columns) as input and return the row and column indices as a tuple.
... | Here is the Python code to solve the given problem in the markdown block:
```python
def flat_index_to_grid_indices(flat_index: int, num_rows: int, num_cols: int) -> (int, int):
"""
Convert a given flat index to its corresponding row and column indices in a 2D grid.
Args:
flat_index (int): The flat ... |
magic_instruct_75k | 14,572 | Write a Python function to calculate the bitwise XOR of two byte arrays and return the resulting byte array. The function should take two byte arrays of equal length as input and perform the XOR operation element-wise. The function should handle cases where the input arrays are of different lengths by raising a `ValueE... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_xor(arr1: bytes, arr2: bytes) -> bytes:
"""
Calculate the bitwise XOR of two byte arrays and return the resulting byte array.
Args:
arr1 (bytes): The first byte array.
arr2 (bytes): The second ... |
magic_instruct_75k | 14,589 | Write a Python function to process a list of router prefixes and return a dictionary containing the count of unique prefixes for each router. The router prefixes are provided in the format `app.include_router(router, prefix="/vector")`, where `router` is the name of the router and `prefix` is the prefix associated with... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
import re
def count_router_prefixes(prefix_list: List[str]) -> Dict[str, int]:
"""
Processes a list of router prefixes and returns a dictionary containing the count of unique prefixes for each rout... |
magic_instruct_75k | 14,595 | Write a Python function to generate a unique revision ID for a database record. The revision ID should be a combination of the create date and a unique key. The create date should be in the format "YYYY-MM-DD" and the unique key should be a randomly generated alphanumeric string of length 12.
The function should start... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
import string
def generate_revision_id(create_date: str, unique_key: str = None) -> str:
"""
Generates a unique revision ID for a database record.
Args:
create_date (str): The create date in the forma... |
magic_instruct_75k | 14,609 | Write a Python function to manage the weakening of a system's security levels. The function should take in a list of security levels and a threshold value. The weakening process involves reducing each security level by the threshold value, but ensuring that the resulting level does not fall below zero. If the weakening... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def weaken_security(security_levels: List[int], threshold: int) -> bool:
"""
Manages the weakening of a system's security levels by reducing each level by a given threshold.
Ensures that no security ... |
magic_instruct_75k | 14,642 | Create a Python class `Resource` that represents a resource with various attributes. The class should be able to handle different types of resources and provide methods for setting and getting the resource type. The `Resource` class should have the following attributes and methods:
- `resource_type`: A string represent... | Here is the Python code to solve the given problem in the markdown block:
```python
class Resource:
"""
A class representing a resource with a type attribute.
Attributes:
resource_type (str): A string representing the type of the resource.
"""
def __init__(self):
"""
Initia... |
magic_instruct_75k | 14,663 | Write a Python function to automate the process of finishing a feature branch in a version control system. The function should handle the following functionalities:
1. Check if the previous command was successful. If successful, call the `finish` function passing the current branch name as an argument. If unsuccessful,... | Here is the Python code to solve the given problem in the markdown block:
```python
def finish_feature_branch(previous_command_success: bool, branch_name: str, pr_url: str) -> None:
"""
Automates the process of finishing a feature branch in a version control system.
Args:
previous_command_success (... |
magic_instruct_75k | 14,680 | Implement a Python function to compute the inverse parallel transport of a vector on a manifold. The function should take a vector `u`, a source point `src`, a destination point `dst`, and a radius `radius` as inputs, and return the vector `u` transported from the destination point back to the source point. The functio... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def inverse_parallel_transport(u: np.ndarray, src: np.ndarray, dst: np.ndarray, radius: float) -> np.ndarray:
"""
Compute the inverse parallel transport of a vector u from the destination point back to the so... |
magic_instruct_75k | 14,700 | Write a Python function to assign a unique random number to each participant in a given list of participants. The function should return a dictionary where the keys are the participants' names and the values are the randomly assigned numbers. The numbers should be unique and within the range of 1 to the number of parti... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
import random
def assign_random_numbers(participants: List[str]) -> Dict[str, int]:
"""
Assigns a unique random number to each participant in the given list.
Args:
participants (List[s... |
magic_instruct_75k | 14,707 | Write a Python function to extract image sources from a given HTML string that represents a carousel component. The HTML string will contain multiple carousel items, each with an image tag. The function should return a list of image sources for each carousel item. The HTML structure will always be well-formed and follo... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def extract_carousel_images(html: str) -> List[str]:
"""
Extracts image sources from a given HTML string representing a carousel component.
Args:
html (str): The HTML string contai... |
magic_instruct_75k | 14,726 | Write a Python function `parse_migration_info` that takes a string representing the content of a Django migration file as input and returns a dictionary containing the extracted Django version and generation date. The dictionary should have the keys "django_version" and "generation_date" with their respective values. T... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def parse_migration_info(migration_content: str) -> dict:
"""
Parses the content of a Django migration file and extracts the Django version and generation date.
Args:
migration_content (str): The content ... |
magic_instruct_75k | 14,736 | Write a Python function to find the floor value of the square root of a given non-negative integer `num` using a binary search algorithm. The function should return the integer part of the square root, truncating any decimal part.
The code should start with:
```python
def sqrt(num: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def sqrt(num: int) -> int:
"""
Calculate the floor value of the square root of a given non-negative integer `num` using binary search.
Args:
num (int): The non-negative integer for which to find the square root.
... |
magic_instruct_75k | 14,783 | Write a Python function to convert a list of image resolutions from pixels to kilopixels. Each resolution in the input list is an integer representing the number of pixels. The function should return a new list where each resolution is converted to kilopixels (kpx), where 1 kilopixel is equal to 1000 pixels.
The code ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def convert_to_kpx(resolutions: List[int]) -> List[float]:
"""
Converts a list of image resolutions from pixels to kilopixels.
Args:
resolutions (List[int]): A list of integers representing ... |
magic_instruct_75k | 14,793 | Write a Python script to automate the build process for a software project. The script should perform the following steps:
1. Download the source code from a given URL using the `wget` command.
2. Extract the downloaded archive using the `tar` command.
3. Navigate into the extracted directory.
4. Copy a specific file n... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
import subprocess
import shutil
def automate_build_process(url: str, archive_name: str, extracted_dir: str, makefile_src: str, makefile_dest: str) -> None:
"""
Automates the build process for a software project by per... |
magic_instruct_75k | 14,809 | Write a Python function to simulate the uninstallation of a specific package on various Linux distributions using the `apt-get` package manager. The function should handle potential errors and provide informative messages to the user. The function should perform the following steps:
1. Display a message indicating the ... | Here is the Python code to solve the given problem in the markdown block:
```python
def simulate_package_uninstallation(distribution: str) -> None:
"""
Simulate the uninstallation of the package 'apache2.2-common' using `apt-get` on specified Linux distributions.
Args:
distribution (str): The Linux... |
magic_instruct_75k | 14,838 | Write a Python function to determine if a given string `s` consisting of lowercase English letters and curly braces is properly nested. Properly nested means that for every opening curly brace `{` there is a corresponding closing curly brace `}`, and they are properly nested within each other. The function should retur... | Here is the Python code to solve the given problem in the markdown block:
```python
def isProperlyNested(s: str) -> bool:
"""
Determine if the given string `s` consisting of lowercase English letters and curly braces is properly nested.
Args:
s (str): The string to check for proper nesting of curly... |
magic_instruct_75k | 14,853 | Write a Python function to determine if each object in a list can fit inside a box based on its dimensions. The function should take the width and height of the box and a list of integers representing the lengths of various objects. It should return a list of strings indicating whether each object can fit inside the bo... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
from math import hypot
def fits_in_box(w: int, h: int, nums: List[int]) -> List[str]:
"""
Determines if each object in a list can fit inside a box based on its dimensions.
Args:
w (int): The... |
magic_instruct_75k | 14,861 | Write a Python function to compare two database objects and determine if there are any differences between them. The function should take in two database objects as input and return a boolean value indicating whether there are any differences between the two databases.
The database objects are represented as dictionar... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def db_diff(db1: Dict[str, List[Dict[str, any]]], db2: Dict[str, List[Dict[str, any]]]) -> bool:
"""
Compare two database objects and determine if there are any differences between them.
Args:... |
magic_instruct_75k | 14,881 | Write a Python function to return a new list containing only the unique elements from the input list, preserving their original order. The function should start with:
```python
from typing import List
def unique_elements(input_list: List[int]) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def unique_elements(input_list: List[int]) -> List[int]:
"""
Returns a new list containing only the unique elements from the input list, preserving their original order.
Args:
input_list (Li... |
magic_instruct_75k | 14,890 | Write a Python function to calculate the total quantity of a specific item ordered by a given customer from a list of historical orders. Each order is represented as a tuple containing the customer ID, item ID, and quantity ordered. The function should take the list of historical orders, the customer ID, and the item I... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def total_quantity_ordered(orders: List[Tuple[int, int, int]], customer_id: int, item_id: int) -> int:
"""
Calculate the total quantity of a specific item ordered by a given customer from a list o... |
magic_instruct_75k | 14,915 | Write a Python function to process point cloud data. The function takes in a list of point cloud data and performs a series of operations on it. The point cloud data is represented as a list of points, and each point is represented by its coordinates in 3D space. Additionally, the function maintains a buffer of transfo... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def process_point_cloud(data: List[Tuple[float, float, float]], matrix_buffer: List[List[List[float]]]) -> List[Tuple[float, float, float]]:
"""
Process point cloud data by printing the number of ... |
magic_instruct_75k | 14,929 | Write a Python function to calculate the total cost of all employee benefits provided by a company. The function should take a dictionary representing the benefits scheme, where the keys are the names of the benefits and the values are their respective costs. The function should return the total cost of all benefits.
... | Here is the Python code to solve the given problem in the markdown block:
```python
def total_benefit_cost(scheme: dict) -> float:
"""
Calculate the total cost of all employee benefits provided by a company.
Args:
scheme (dict): A dictionary where keys are the names of the benefits and values are t... |
magic_instruct_75k | 14,938 | Write a Python function to determine if there are any open challenges in a ladder for a given user. The function should take the user and ladder as input and return `True` if there are open challenges for the user in the provided ladder; otherwise, it should return `False`.
The `user` parameter represents the user for... | Here is the Python code to solve the given problem in the markdown block:
```python
def open_challenges_exist(user, ladder):
"""
Determine if there are any open challenges in a ladder for a given user.
Args:
user (User): The user for whom to check for open challenges.
ladder (Ladder): The l... |
magic_instruct_75k | 14,947 | Write a Python function to manage the provisioning of virtual machines using Vagrant. The function should perform the following tasks:
1. Retrieve a list of virtual machines managed by Vagrant that are using the VMware provider.
2. Start up all the identified virtual machines using the `vagrant up` command, without tri... | Here is the Python code to solve the given problem in the markdown block:
```python
import subprocess
from typing import List, Dict
def manage_vagrant_vms() -> Dict[str, int]:
"""
Manages the provisioning of virtual machines using Vagrant.
This function retrieves a list of virtual machines managed by Vagr... |
magic_instruct_75k | 14,948 | Write a Python function `extract_author_info(metadata)` that takes a dictionary `metadata` as input. The `metadata` dictionary contains key-value pairs representing the package metadata. The keys include "version", "author", "author_email", "description", and "license". The function should extract the author's name and... | Here is the Python code to solve the given problem in the markdown block:
```python
def extract_author_info(metadata: dict) -> str:
"""
Extracts the author's name and email from the given metadata dictionary and returns them in a formatted string.
Args:
metadata (dict): A dictionary containing pack... |
magic_instruct_75k | 14,965 | Write a Python function to decode a given decimal number representing the sum of permissions into a list of strings representing the individual permissions granted. The permissions are represented as powers of 2 and are predefined in a dictionary. The function should return a list of permission names that correspond to... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def decodePermissions(permissionSum: int) -> List[str]:
"""
Decodes a decimal number representing the sum of permissions into a list of strings representing the individual permissions granted.
Args:... |
magic_instruct_75k | 15,015 | Write a Python function to generate all possible combinations of a given list of unique elements. The function should take a list of elements as input and return a list of lists, where each inner list represents a unique combination of the elements. The order of selection does not matter, and the input list will not co... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
from itertools import combinations
def generate_combinations(elements: List[int]) -> List[List[int]]:
"""
Generate all possible combinations of a given list of unique elements.
Args:
element... |
magic_instruct_75k | 15,034 | Write a Python function to simulate the process of updating and synchronizing git submodules with retry logic. The function should:
1. Simulate the synchronization of submodules.
2. Simulate the recursive update of submodules.
3. Retry the synchronization and update process if it fails, up to a specified maximum number... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
def simulate_synchronize_submodules() -> bool:
"""
Simulates the synchronization of git submodules.
Returns:
bool: True if the synchronization succeeds, False otherwise.
"""
# Randomly dec... |
magic_instruct_75k | 15,044 | Write a Python function to generate a URI for a wallet icon based on the wallet type and the current theme. The function should take the wallet type as input and return the corresponding URI for the wallet icon based on the current theme. The URI format is "avares://WalletWasabi.Fluent/Assets/WalletIcons/{currentTheme}... | Here is the Python code to solve the given problem in the markdown block:
```python
from enum import Enum
class WalletType(Enum):
Ledger = "ledger"
Normal = "normal"
Unknown = "unknown"
class ThemeHelper:
CurrentTheme = "dark" # This is a placeholder for the actual theme. In a real application, this ... |
magic_instruct_75k | 15,053 | Write a Python function to automate the deployment process for a web application using Docker and Magento. The deployment process involves executing a series of commands within a Docker container running the web application. The commands to be executed are as follows:
```
su www-data
bin/magento indexer:reindex
bin/mag... | Here is the Python code to solve the given problem in the markdown block:
```python
import subprocess
def deploy_magento_app() -> None:
"""
Automates the deployment process for a web application using Docker and Magento.
This function switches the user to `www-data` and then executes a series of Magento c... |
magic_instruct_75k | 15,090 | Write a Python function to process a list of theme icons and their properties. Each theme icon is represented as a dictionary containing the icon details. The function should extract and return the unique combinations of icon variants and their corresponding gradient colors.
The theme icon dictionary has the following... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any
def extract_icon_variants(icons: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
"""
Extracts unique combinations of icon variants and their corresponding gradient colors from a list... |
magic_instruct_75k | 15,092 | Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock on different days. You are given a list of integers representing the daily stock prices of a company. You can only make one transaction (i.e., buy one and sell one share of the stock), and you must buy before you ... | 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 on different days.
Args:
prices (List[int]): A list of integers ... |
magic_instruct_75k | 15,133 | Write a Python function to test the validity of a given UTF-8 query. The function should take a list of integers representing bytes and determine if it forms a valid UTF-8 encoding. The function should return `True` if the given list of integers forms a valid UTF-8 encoding, and `False` otherwise. The input list repres... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def test_utf8_query(data: List[int]) -> bool:
"""
Determines if the given list of integers forms a valid UTF-8 encoding.
Args:
data (List[int]): A list of integers representing the bytes of ... |
magic_instruct_75k | 15,159 | Write a Python function to calculate the transformation matrix for a specific type of joint in a robotic arm. The transformation matrix is used to represent the position and orientation of the end effector of the robotic arm relative to the base frame. The joint type can be either 'revolute' or 'prismatic'.
For a revo... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def calculate_transformation_matrix(joint_type: str, q: float) -> np.ndarray:
"""
Calculate the transformation matrix for a specific type of joint in a robotic arm.
Args:
joint_type (str): The ty... |
magic_instruct_75k | 15,162 | Write a Python function to generate the full path for a given image file based on the `LOCATION` variable and the image's filename. The function should take in the `LOCATION` variable (string) and the `filename` (string) and return the full path for the image file. The full path should be in the format: `"/<LOCATION>/i... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_image_path(LOCATION: str, filename: str) -> str:
"""
Generates the full path for an image file based on the `LOCATION` variable and the image's filename.
Args:
LOCATION (str): The name of the repository... |
magic_instruct_75k | 15,169 | Write a Python function `process_text_data(minerallist, lemmas, ners)` that processes text data to extract specific information. The function should take three input parameters:
- `minerallist`: A list of minerals.
- `lemmas`: A list of lemmas.
- `ners`: A list of named entities recognized in the text.
The function sh... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def process_text_data(minerallist: List[str], lemmas: List[str], ners: List[str]) -> Tuple[List[str], List[str], List[str]]:
"""
Processes text data to extract specific information from a list of ... |
magic_instruct_75k | 15,171 | Write a Python function `simulate_training_scope` that emulates the behavior of a training scope in a deep learning framework. The function should take an `is_training` parameter, which indicates whether the scope is for training or not. When `is_training` is set to `True`, the training scope should include the key `'i... | Here is the Python code to solve the given problem in the markdown block:
```python
def simulate_training_scope(is_training: bool = False) -> dict:
"""
Simulates the behavior of a training scope in a deep learning framework.
Args:
is_training (bool, optional): Indicates whether the scope is for tra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.