response_seed stringlengths 53 5.17k | instruction_seed stringlengths 29 4.02k | response stringlengths 16 8.81k | __original_row_idx int64 0 50k |
|---|---|---|---|
To sort the values of the `OrderedDict` based on their keys' indices in an input `order`, we need to first understand how `OrderedDict` works and what it guarantees about its behavior. An `OrderedDict` is a subclass of `dict` that preserves the order of insertion of its keys. This means that when iterating over the key... | Write a Python function `sort_within_values()` that takes a `mapping` argument and sorts the values of the dictionary based on their keys' indices in an input list `order`. The function should return a new `OrderedDict` whose values are sorted based on the order of keys in `order`. The `mapping` argument should be an `... | Certainly! Below is the Python function `sort_within_values()` that takes an `OrderedDict` as `mapping` and a list of strings as `order`, and returns a new `OrderedDict` containing the values sorted according to the indices of their keys in the `order` list.
You'll need to ensure you have `collections.OrderedDict` imp... | 45,500 |
To calculate the convolution of an image with a kernel, you can use a sliding window approach. The kernel slides over the image and calculates the dot product of the kernel and the image region under it. The result is stored in a new array.
Here's an example implementation of the `convolve` function in Python:
```pyt... | Implement a Python function `convolve(image, kernel)` to calculate the convolution of an image with a kernel. The image and kernel are both represented as 2D numpy arrays. The convolution is a linear operation that combines two arrays into a third array.
The function should handle different padding modes, such as 'CON... | To implement the convolution function `convolve(image, kernel)` with different padding modes, we can utilize NumPy for efficient array manipulation. Below is the complete implementation that adheres to the specifications provided, including the handling of different padding modes: 'CONSTANT', 'REFLECT', and 'WRAP'.
``... | 45,501 |
Here's one implementation:
```python
from datetime import datetime, timezone
def parse_iso_datetime(iso_datetime_str):
dt = datetime.strptime(iso_datetime_str, "%Y-%m-%dT%H:%M:%SZ")
return dt.replace(tzinfo=timezone.utc)
``` | Write a Python function that takes a string representing a date in a specific format and returns a corresponding Python `datetime` object. The input string will have the following format: `YYYY-MM-DDThh:mm:ssZ`, which represents a date in the ISO 8601 standard. The `datetime` object should be returned with a `tzinfo` a... | You can create a Python function to convert a string in the specified ISO 8601 format into a `datetime` object with the UTC timezone using the `datetime` module and the `pytz` library, which is commonly used for timezone handling.
Here's an example of how you can implement this function:
```python
from datetime impor... | 45,502 |
To extract data and parity numbers from a given object type, you can use string manipulation techniques to split the string into its constituent parts, validate the input string format, and extract the data and parity numbers.
Here's one possible solution:
```python
def extract_data_parity_numbers(object_type):
t... | Write a Python function to extract data and parity numbers from a given object (class) type. The function should accept a string representing the object type, and return a list of data and parity numbers.
Here is the format of the string:
```
<object_type> = <object_name>([<data_number> <parity_number>])
```
For exa... | Here's a Python function that extracts data and parity numbers from a given input string representing an object type. The function uses regular expressions to parse the input and extracts the necessary values while also incorporating error handling for invalid input formats.
```python
import re
def extract_data_and_p... | 45,503 |
The Heap's algorithm is a recursive algorithm to generate all possible permutations of a list of elements. It works by generating permutations for a list with one element, then recursively generating permutations for a list with one additional element by swapping the new element with each of the existing permutations.
... | Create a Python function that implements the Heap's algorithm to generate all permutations of a given list of elements. Use recursive function calls to generate the permutations. | Certainly! Heap's algorithm is an efficient way to generate all permutations of a list. Here's a Python function that implements Heap's algorithm using recursion:
```python
def heaps_algorithm(n, array, result):
# If there's only one element, there's only one permutation
if n == 1:
result.append(array[... | 45,504 |
Here's an example implementation of the `format_stat` function:
```python
def format_stat(stat, name, precision=4):
return f"{name}: {stat:.{precision}f}"
```
The `format_stat` function accepts a floating-point statistic `stat`, a `name` for that statistic, and an optional `precision` parameter to specify the num... | Implement a Python function `format_stat(stat, name, precision=4)` that formats a floating-point statistic `stat` with the given `name` and `precision`. If the `precision` parameter is not specified, set the default precision to 4.
The function should return a string in the following format:
```python
f"{name}: {stat... | You can implement the `format_stat` function as described. It uses formatted string literals (also known as f-strings) to create the desired output. Here's the implementation:
```python
def format_stat(stat, name, precision=4):
return f"{name}: {stat:.{precision}f}"
# Assertions to test the function
assert format... | 45,505 |
Here's how you could implement the function:
```python
import cmath
import math
def complex_to_polar_form(complex_str):
complex_num = complex(complex_str)
modulus = abs(complex_num)
arg = cmath.phase(complex_num)
polar_form = f'{modulus:.1f}·(cos({arg:.2f}) + i·sin({arg:.2f}))'
return polar_form
... | Implement a Python function to convert a complex number to polar form, i.e. convert a complex number from rectangular form (real and imaginary components) to polar form (modulus and argument). The input is a complex number as a string in rectangular form, such as '1+2j' or '3-4j', and the output is the polar form as a ... | To convert a complex number from its rectangular form to polar form, we need to calculate its modulus and argument. The modulus \( r \) can be found using the formula:
\[
r = \sqrt{x^2 + y^2}
\]
where \( x \) is the real part and \( y \) is the imaginary part of the complex number. The argument \( \theta \) can be ca... | 45,506 |
Here is the implementation of the `replace_dollar_signs()` function:
```python
import re
def replace_dollar_signs(text, replacement):
return re.sub("\$", replacement, text)
```
The `replace_dollar_signs()` function takes two arguments: `text` and `replacement`. The function uses the `re.sub()` function to replac... | Write a Python function `replace_dollar_signs(text, replacement)` that takes in two arguments, `text` and `replacement`, and returns a new string where all occurrences of the dollar sign `$` in `text` have been replaced by the `replacement` string. The function should implement the following logic:
1. Split the `text`... | Certainly! You can achieve this using Python's built-in regular expression (`re`) module to replace occurrences of the dollar sign `$` with the specified replacement string. Here’s how you can implement the `replace_dollar_signs` function according to your description:
```python
import re
def replace_dollar_signs(tex... | 45,507 |
Use sets to store unique points and list comprehension to filter them from the input list:
```python
def unique_points(points):
seen = set()
unique_points = [p for p in points if tuple(p) not in seen and not seen.add(tuple(p))]
return unique_points
print(unique_points([[1, 0], [1, 0], [2, 1], [3, 2], [3, ... | Consider a set of 2D points, where each point is represented as a list `[x, y]`. Write a Python function `unique_points(points)` that removes all duplicates from the list of points.
```python
def unique_points(points):
# TODO: Implement this function
print(unique_points([[1, 0], [1, 0], [2, 1], [3, 2], [3, 2], [3... | To remove duplicates from a list of 2D points represented as lists, we can utilize a combination of a set to track unique points and a list to maintain the order of appearance. Here's how you can implement the `unique_points` function:
```python
def unique_points(points):
seen = set()
unique = []
for ... | 45,508 |
Here's how you could implement the function:
```python
def parse_dto(dto_str):
vehicles = []
for line in dto_str.splitlines():
vehicle_id, make, model, year, color, mileage = line.split(',')
vehicle = Vehicle(
vehicle_id=vehicle_id,
make=make,
model=model,
... | Write a Python function that takes a string representing the data transfer object (DTO) of a vehicle and returns a list of vehicle objects. The vehicle DTO string is formatted as follows:
```
vehicle_id,make,model,year,color,mileage
1,Toyota,Camry,2018,Red,10000
2,Honda,Accord,2015,Blue,20000
```
Each line in the str... | To achieve this, we will first define a `Vehicle` class that represents a vehicle object. Then we'll create a function to parse the DTO string, split it into individual lines, extract the attributes from each line, and create `Vehicle` objects accordingly. Finally, we'll return a list of these vehicle objects.
Here's ... | 45,509 |
Here's how you could implement this function decorator:
```python
import time
def measure_runtime(func):
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
result = func(*args, **kwargs)
end_time = time.perf_counter()
runtime = round(end_time - start_time, 2)
pr... | Write a Python function decorator that measures the runtime of the function it decorates. The decorator should print the runtime in seconds, rounded to two decimal places. Use accurate timing to obtain the most precise measurement. | You can create a Python function decorator that measures the runtime of a function using the `time` module, specifically the `time.perf_counter()` function, which is suitable for measuring short durations with high accuracy. Here's how you can implement the decorator:
```python
import time
from functools import wraps
... | 45,510 |
Here is an example implementation using Python's built-in `logging` module:
```python
import logging
def inspect_nested_dictionary(dictionary, path, logger=logging.getLogger(__name__)):
try:
for key, value in dictionary.items():
full_path = '.'.join([path, key]) if path else key
if... | Write a Python function that inspects a nested dictionary object and recursively log all keys and values along with their path through the dictionary using the `logging` module. For example, given the input dictionary `{'a': 1, 'b': {'c': 2}}`, the function should log:
```
b.c 2
a 1
```
Handle any errors that may occ... | You can achieve this by creating a recursive function that inspects a nested dictionary and logs each key-value pair along with its path. We'll use the `logging` module for logging, and ensure that we handle any potential errors gracefully. Here's how you can implement this function:
```python
import logging
# Set up... | 45,511 |
To implement the `ends_with_any` function, we can use the `any` function from the `builtin` module. This function takes an iterable (such as a list or a tuple) as an argument and returns `True` if any of the elements in the iterable evaluate to `True`, and `False` otherwise.
```python
def ends_with_any(string, suffixe... | Write a Python function to determine if a string ends with one of the suffixes in a list. The function takes two parameters, a string and a list of suffixes. The function should return `True` if the string ends with any of the suffixes in the list, and `False` otherwise. Here is the function signature:
```
def ends_wi... | You can implement the `ends_with_any` function easily by iterating through the list of suffixes and checking if the given string ends with any of them using the `str.endswith()` method. Here's how the implementation looks:
```python
from typing import List
def ends_with_any(string: str, suffixes: List[str]) -> bool:
... | 45,512 |
```python
import hashlib
class User:
def __init__(self, username, password):
self.username = username
self.password = hashlib.sha256(password.encode()).hexdigest()
self.session_token = None
def authenticate(self, password):
hashed_password = hashlib.sha256(password.encode()).he... | Create a Python function `create_user(username, password)` that takes a username and password as input and returns a `User` object with the given username and password. The `User` object should include methods to authenticate the user using the stored password, validate the user's session token using a secret key, and ... | To create the `User` class and the associated methods, we can use Python's built-in libraries to handle password hashing and token generation. Below is an implementation of the `create_user` function, along with the necessary `User` class and its methods for authentication and session token management.
```python
impor... | 45,513 |
Here's how we can implement this:
```python
def format_course_run_name(course_number, course_run_slug, course_run_number):
course_run_name = f"{course_number} {course_run_slug} ({course_run_number})"
return course_run_name
```
In this implementation, we use the `f-string` to format the course run name. The `f... | Write a function to format a course's run name.
Course run names are formatted in the following way:
```
<course_number>
<course_run_slug> (<course_run_number>)
```
The course run's slug is an alphanumeric string, such as "summer-21". The slug is followed by the course run's number in parentheses (e.g., "(2)"). ... | You can create a function called `format_course_run_name` that takes three parameters: `course_number`, `course_run_slug`, and `course_run_number`. The function will format these parameters according to the specified structure and return the formatted course run name.
Here's the implementation:
```python
def format_c... | 45,514 |
To load, format, and validate the data from a file, we can use the `csv` module in the standard library. We can read the file line by line and split each line into its three columns, using the `split()` method. Then, we can check if the date is in the correct format using a regular expression. The temperature and humid... | Write a Python function to load data from a file, format it, and validate it. The function should take a file path as an argument and return a list of formatted and validated data.
The data in the file is arranged in rows, with each row representing a single record. There are three columns in each row:
- Column 1: A s... | Certainly! Below is a Python function that meets your requirements. The function reads data from a given file path, validates the data as specified, and returns a list of tuples if everything is correct. If there are any validation issues, it prints an appropriate error message and returns `None`.
```python
from datet... | 45,515 |
Here's how you can implement this:
```python
def find_first(sequence, predicate):
for index, value in enumerate(sequence):
if predicate(value):
return index
return None
def find_last(sequence, predicate):
last_index = None
for index, value in enumerate(sequence):
if predica... | Given a sequence of values, write a Python function `find_first` that returns the index of the first element in the sequence that matches a given predicate. If no element matches the predicate, return `None`.
Now, write a Python function `find_last` that returns the index of the last element in the sequence that match... | Certainly! Below you'll find the Python implementations for the functions `find_first` and `find_last`. Both functions take a sequence and a predicate (a function that returns a boolean) as arguments.
```python
def find_first(sequence, predicate):
"""
Returns the index of the first element in the sequence that... | 45,516 |
To parse the text into a list of dictionaries, we need to split the text into lines, then split each line into a list of values, and then use these values to create the dictionaries.
Here is the implementation:
```python
import csv
def parse_text_into_dict_list(text):
lines = text.split("\n")
header = lines[... | Given the following text-based format:
```
id,name,price,category
1,Apple,0.5,Fruit
2,Banana,0.3,Fruit
3,Mango,0.8,Fruit
4,Grape,1.0,Fruit
5,Carrot,0.4,Vegetable
6,Beetroot,0.6,Vegetable
7,Cabbage,0.7,Vegetable
```
Develop a Python function to parse the text into a list of dictionaries, where each dictionary has four... | You can achieve this by creating a Python function that reads the text, splits it into lines, and then processes each line to convert it into a dictionary. Below is an example implementation of such a function:
```python
def parse_text_to_dicts(text):
# Split the text by new lines to get individual lines
lines... | 45,517 |
Here is an implementation of the `find_byte` function that meets the described requirements:
```python
import io
def find_byte(binary_stream, byte):
chunk_size = 4096
stream = io.BytesIO(binary_stream)
byte_index = -1
position = 0
while True:
chunk = stream.read(chunk_size)
if not... | Create a Python function to find the index of the first occurrence of a specified byte in a binary data stream. The function should take two arguments: a binary stream and a byte value to search for. The function should return -1 if the byte is not found.
Ensure efficient byte searching by processing the binary data i... | You can create a function that searches for the first occurrence of a specified byte in a binary data stream by reading the stream in chunks. Here's how you could implement this in Python:
```python
def find_first_occurrence(stream, byte_value):
"""
Find the index of the first occurrence of a specified byte in... | 45,518 |
The implementation of the binary search algorithm is divided into three main steps:
1. Initialize the left and right pointers to the start and end of the list.
2. While the left pointer is less than or equal to the right pointer, do the following:
a. Calculate the midpoint using the formula `mid = (left + right) ... | Write a Python function `binary_search` that performs a binary search on a list of numbers. The function takes a list of sorted numbers, a target number, and an optional key parameter. The key parameter is a function that takes an element of the list and returns a number. If no key function is provided, the default beh... | You can implement the `binary_search` function as follows. This implementation performs a binary search on a sorted list of numbers and uses an optional `key` function to determine the value to compare against the target.
Here is the complete function:
```python
def binary_search(lst, target, key=None):
if key is... | 45,519 |
Here's an example implementation of the `get_env_for_subprocess` function:
```python
def get_env_for_subprocess(key_value_pairs):
env_dict = {}
for key, value in key_value_pairs:
env_dict[key] = value
return env_dict
```
The function `get_env_for_subprocess` takes a list of key-value pairs as inpu... | Create a Python function that generates a dictionary of environment variables to be passed to a subprocess. The function should be named `get_env_for_subprocess` and should accept a list of key-value pairs as input. Here is an example of the function usage:
```python
get_env_for_subprocess([("FOO", "bar"), ("BAZ", "qu... | Certainly! Below is the implementation of the `get_env_for_subprocess` function in Python. This function takes a list of key-value pairs as input and generates a dictionary that can be used for environment variables in a subprocess.
```python
def get_env_for_subprocess(vars_list):
"""
Generate a dictionary fro... | 45,520 |
You can create a Python function to return the final digit of the product of two positive integers by following these steps:
1. Extract the digits from the given lists `a` and `b`.
2. Multiply the extracted digits and store the result.
3. Extract the last digit of the resulting product.
4. Return the extracted last dig... | Create a Python function `d` that returns the final digit of the product of two positive integers whose digits are given as two lists. The function should have the following docstring:
```python
def d(a: List[int], b: List[int]) -> int:
"""
Returns the final digit of the product of two positive integers whose ... | Certainly! Below is the implementation of the function `d` as per your requirements.
```python
from typing import List
def d(a: List[int], b: List[int]) -> int:
"""
Returns the final digit of the product of two positive integers whose digits are given as two lists.
Args:
a: A list of integers... | 45,521 |
Here's how you could do it:
```python
def format_object_name(object_type, object_name, depth):
if object_type == 'feature':
formatted_name = f'{object_name}_f{depth}'
elif object_type == 'target':
formatted_name = f'{object_name}_t{depth}'
elif object_type == 'artifact':
formatted_n... | Write a Python function `format_object_name(object_type, object_name, depth)` that returns a formatted string based on the given object type and name. The function should return the object name with the correct depth-based naming, where the depth represents the number of levels of nesting. For example, if `object_type`... | Here is a Python function named `format_object_name` that formats an object name based on the given `object_type`, `object_name`, and `depth`. The function constructs the formatted name according to the specified rules.
```python
def format_object_name(object_type, object_name, depth):
# Create a suffix based on t... | 45,522 |
To filter out anagrams, we can use a list comprehension and the `is_anagram` function that we created in the previous example. The `is_anagram` function checks if two strings are anagrams by sorting their characters and comparing the sorted strings. The list comprehension creates a new list with only those strings that... | Given a list of strings, create a function that filters out strings that are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once. For example, `"cinema"` and `"iceman"` are anagrams, but `"cinma"` and `"icena... | To filter out strings that are anagrams of each other, we can use a combination of sorting each string and using a set to keep track of unique sorted representations. Here’s how you can implement this in Python:
```python
def filter_anagrams(strings):
# Dictionary to hold unique anagram groups
anagram_dict = {... | 45,523 |
Here is one way to implement the function:
```python
def str_compose(d, s):
for key, value in d.items():
s = s.replace(key, value)
return s
```
The function iterates through each key/value pair in the dictionary and applies the `replace` method to the input string `s` using the key to search and the v... | Develop a Python function `str_compose` that takes two arguments: a dictionary `d` and a string `s`. The function should return a new string that is the result of applying each key/value pair in the dictionary to the input string in sequence, where each key represents a string to search for in the string and the corres... | Here's a Python function `str_compose` that meets your requirements. The function takes a dictionary `d` and a string `s` and applies the replacements defined in the dictionary to the string in the order the key-value pairs appear in the dictionary.
```python
def str_compose(d, s):
# Iterate over the dictionary an... | 45,524 |
Here's how we can implement this:
```python
import math
class EmptyPointsError(Exception):
pass
def neighborhoods(points, radius):
if radius <= 0:
raise ValueError("Radius must be positive")
if not isinstance(radius, (int, float)):
raise TypeError("Radius must be numeric")
if not poin... | Design a Python function `neighborhoods` that returns a dictionary where each key is a coordinate tuple and the value is a list of other coordinate tuples that are within a given radius. The function should have the following signature:
```python
def neighborhoods(points, radius):
# ...
```
The function should ha... | Certainly! Below is a Python function `neighborhoods` that fulfills the specified requirements. This function takes a list of coordinate tuples (`points`) and a numeric value representing a radius, and it returns a dictionary where each coordinate tuple is mapped to a list of other coordinates that fall within the spec... | 45,525 |
To determine if a given string is an acronym, we need to analyze the characters in the string and check if they meet the following criteria:
1. The first character should be an uppercase letter.
2. The subsequent characters should either be uppercase letters or punctuation.
3. There should be no lowercase letters or sp... | Write a Python function to determine if the given string is an acronym or not. An acronym is a word or name formed by taking the initial letters of the words in a phrase and combining them into a new word or name. The following are all examples of acronyms: "NATO", "NASA", "FIFA", "LOL", "CDC".
Your code should pass t... | To determine if a given string is an acronym or not, we can create a function called `is_acronym`. The function will check if the string is composed of uppercase letters only and if it is a single word. If there are spaces or lowercase characters in the string, we can consider that it is not an acronym. Here’s how the ... | 45,526 |
Here's a Python implementation of the `assign_tensor_values` function:
```python
from typing import List
import torch
def assign_tensor_values(tensor: torch.Tensor) -> torch.Tensor:
"""
Creates a new tensor of the same shape as `tensor` and assigns values to it based on the
conditions in the question.
... | Develop a Python function `assign_tensor_values` that creates a tensor `t` of shape `(H, W)` and assigns values to it conditionally based on the input `tensor`, a tensor of shape `(H, W)`. The function should calculate the values `t[i, j]` as follows:
```python
if tensor[i, j] > 0:
t[i, j] = 1.0
elif tensor[i, j] ... | To create a Python function `assign_tensor_values` that assigns values to a tensor based on the conditions specified, you can use NumPy, a powerful library for numerical computing in Python. The function will iterate over each element of the input tensor and apply the conditional logic to fill the new tensor `t`.
Here... | 45,527 |
To validate whether the input is a valid dict object, we can use Python's `isinstance()` function to check if the keys and values are of the correct type. Additionally, we can use a recursive function to check if the dict object has any nested dicts. If any of these checks fail, we can return an error message. If the v... | Write a function `dict_to_json_wrapper` that takes a dict object as input and returns a wrapped JSON string. The function should validate whether the input is a valid dict object (keys are strings or integers, values are of any type, and the dict object does not have any nested dicts). If the validation fails, an error... | To implement the `dict_to_json_wrapper` function, we need to carry out the following steps:
1. Check if the input is a dictionary.
2. Validate that all keys are either strings or integers.
3. Ensure that all values are of any type but that there are no nested dictionaries in the values.
If any of these validations fa... | 45,528 |
Here is how you could implement a `read_pmt_log` function:
```python
def read_pmt_log(file_path):
pmt_values = []
with open(file_path, 'r') as file:
for line in file:
timestamp, pmt_value = line.split(',')
pmt_value = float(pmt_value)
pmt_values.append(pmt_value)
... | Write a Python function named `read_pmt_log` that reads a PMT log file (a PMT log file is a file with a list of PMT measurements) and returns a list of floating-point numbers.
The PMT log file only contains one measurement per line. Each line contains a timestamp, followed by a comma, followed by a PMT value. For exam... | Here's a Python function called `read_pmt_log` that reads a PMT log file and returns a list of floating-point numbers representing the PMT measurements. The function will open the specified file, read each line, extract the PMT value after the comma, and convert it to a float before appending it to the list.
Here's th... | 45,529 |
Here's a Python function that generates region proposals based on anchors and the corresponding coordinates of an image:
```python
import numpy as np
def generate_region_proposals(anchors, image_coordinates):
region_proposals = []
for anchor in anchors:
anchor_x, anchor_y, anchor_w, anchor_h = anchor
... | Create a Python function to generate region proposals for an object detector based on anchors with the main objective of reducing the number of bounding box proposals needed to find the object. The function should take in the anchor boxes and the corresponding coordinates of the image, and return a list of the region p... | To generate region proposals for an object detector using anchor boxes, we can implement a function that refines and selects the most relevant anchor boxes based on their overlap with the true object locations. The function will filter anchor boxes based on their intersection-over-union (IoU) with ground truth boxes.
... | 45,530 |
You can create a Python function that calculates the projection of a 2D point onto a line by using the dot product of the vector from the point to the line and the line itself.
Here's how you could do it:
```python
def project_point_on_line(p, l):
p1, p2 = l
vector_to_line = (p2[0] - p1[0], p2[1] - p1[1])
... | Given a 2D point `p` and a line `L` represented as a pair of points, write a Python function to find the projection of `p` onto `L`. If the point is not on the line, return a tuple with the projection point and a `False` flag indicating the point is not on the line. If the point is on the line, return the projection po... | To find the projection of a point `p` onto a line `L` represented by two points, we can follow these steps:
1. Define the line using two points `A` and `B`.
2. Use vector projections to calculate the projection of the point `p` onto the line.
3. Check if the projected point lies on the segment defined by `A` and `B`.
... | 45,531 |
The following function, `validate_nested_types`, takes two parameters: `data` and `type_map`, and returns `True` if all items match their specified types, or `False` otherwise. It uses a recursive implementation to handle nested dictionaries.
```python
def validate_nested_types(data, type_map):
for key, value in d... | Create a Python function to validate the types of all items in a nested dictionary. If any items do not match the specified type, raise a ValueError with a message indicating the keys of the incorrectly typed items.
For example, given the following data:
- `data = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}}`
- `type_map ... | Here is a Python function that validates the types of all items in a nested dictionary according to a specified type map. The function raises a `ValueError` if any type does not match the expected type, providing a detailed message with the key and expected/actual types.
```python
def validate_types(data, type_map):
... | 45,532 |
Here's how you could implement this function in Python:
```python
from typing import Dict
import pandas as pd
def get_dtypes(df: pd.DataFrame) -> Dict[str, str]:
dtypes = {col: df[col].dtype for col in df.columns}
return dtypes
``` | Create a Python function that takes a pandas or modin dataframe and returns a dictionary containing the schema and names of the data types. Since the implementation may vary between different frameworks, use a data type abstraction layer to handle the differences. For example, pandas has `DataFrame.dtypes` while modin ... | To create a function that returns the schema of a pandas or modin DataFrame in a consistent manner, we'll abstract the differences in how each library handles data types. Here’s an example implementation:
```python
import pandas as pd
import modin.pandas as mpd
def get_dataframe_schema(df):
"""
Returns the sc... | 45,533 |
To write a Python function that takes two file names as input and returns a list of unique lines from both files, with duplicates removed, you can follow these steps:
1. Open the files and read their contents into two separate lists.
2. Iterate over the lines from file1 and compare them to each line in file2.
3. Add a... | Write a Python function `get_non_duplicates(file1, file2)` that takes two file names as input and returns a list of unique lines from both files, with duplicates removed. Your function should compare each line from file1 with every line from file2 and exclude duplicates. | Certainly! Below is a Python function named `get_non_duplicates` that reads lines from two specified files, compares them, and returns a list of unique lines from both files while excluding duplicates.
```python
def get_non_duplicates(file1, file2):
# Use sets to store unique lines
lines_file1 = set()
line... | 45,534 |
To solve this problem, we can use a sliding window approach. We can iterate over the numbers list, keeping track of the distinct elements in the current window. If the current window has more than `k` distinct elements, we can remove the first element to maintain the window size. After each iteration, we can update the... | Write a Python function `max_distinct` that takes two arguments: `numbers` (a list of integers) and `k` (an integer). The function should return the maximum number of distinct elements among all the subsequences of `numbers` of length `k`. | To solve the problem of finding the maximum number of distinct elements among all subsequences of a given length `k` from a list of integers, we can utilize the following approach:
1. **Understand Subsequences**: A subsequence is created by deleting some elements from a sequence without changing the order of the remai... | 45,535 |
Here's how you can implement this:
```python
from typing import Union
import re
def get_int_or_float(text: str) -> Union[int, float]:
match = re.search(r"^\s*(?P<number>[+-]?(?:\d+\.?\d*|\d*\.?\d+))\s*$", text, re.MULTILINE)
if match is not None:
value = float(match.group("number"))
if value.i... | Write a Python function `get_int_or_float` to extract an integer or a float value from a string, accounting for the possibility of multiple lines of text. The function should return an integer or float value, as appropriate, and ignore any non-numeric characters. Here is an example of a valid input string:
```
"""
Thi... | To create a function that extracts an integer or float from a multi-line string, we need to process the input string to filter out numeric values, convert them appropriately, and then return them. Here’s how you can implement the `get_int_or_float` function:
```python
import re
from typing import Union
def get_int_or... | 45,536 |
```python
def is_match(text, pattern):
def match_pattern(text_idx, pattern_idx):
if text_idx == len(text) and pattern_idx == len(pattern):
return True
if text_idx < len(text) and pattern_idx < len(pattern):
curr_char = pattern[pattern_idx]
if curr_char == '.':
... | Write a Python function that takes a string pattern and a string text as input, and determines if the text matches the pattern. The pattern may contain the following special characters:
- `.`: Matches any single character.
- `*`: Matches zero or more of the preceding character.
The function should return a boolean va... | To solve the problem of matching a string `text` against a `pattern` that may contain the special characters `.` and `*`, we can use a recursive approach or dynamic programming. Below is a Python implementation of a recursive function that handles these special characters:
```python
def is_match(pattern: str, text: st... | 45,537 |
Here's how you can do it in Python:
```python
def move_zeroes_to_end(arr):
n = len(arr)
next_nonzero = 0
for i in range(n):
if arr[i] != 0:
arr[i], arr[next_nonzero] = arr[next_nonzero], arr[i]
next_nonzero += 1
return arr
```
The `next_nonzero` variable keeps track of ... | Given an array of integers, write a function to move all zeroes to the end of the array while maintaining the relative order of the non-zero integers.
For example, given `[0, 1, 0, 3, 12]`, the function should modify the array to `[1, 3, 12, 0, 0]`. | You can achieve this by using a two-pointer technique where you maintain a pointer for the position of the last non-zero element found. Here's a function in Python that implements this approach:
```python
def move_zeroes(nums):
"""
Move all zeroes in the array to the end while maintaining the order of non-zero... | 45,538 |
You can achieve this functionality by first ensuring the input is a list of integers using a `type_check` decorator. Then, use a comprehension to return a list of unique elements that appear in both lists.
Here's how you can do it in two lines of Python code:
```python
from typing import List
def type_check(func):
... | Write a Python function that takes two lists as input and returns a list of unique elements that appear in both lists. The function should be type-annotated and return a list of integers. For example, given `list_1 = [1, 2, 3, 4]` and `list_2 = [3, 4, 5, 6]`, the function should return `[3, 4]`. | Certainly! Below is a Python function that meets your requirements. It takes two lists of integers as input and returns a list of unique integers that appear in both lists. The function is type-annotated as requested.
```python
from typing import List
def unique_elements_in_both(list_1: List[int], list_2: List[int]) ... | 45,539 |
To check if any of the dictionaries in a list satisfy a given condition, you can use a list comprehension along with the `any` function. The list comprehension will iterate through the dictionaries, and for each dictionary, it will check if the condition is satisfied for any key-value pairs using the `any` function. Th... | Given a list of dictionaries, return a boolean indicating whether all dictionaries contain (key, value) pairs that satisfy a given condition.
The condition is defined as a lambda function `predicate` that takes a dictionary `d`, a key `k`, and a value `v`, and returns a boolean indicating whether `d[k]` is equal to `v... | You can implement the function `any_key_value_pairs` to check whether all dictionaries in the list contain the specified key-value pairs that satisfy the given condition. Below is the implementation:
```python
def any_key_value_pairs(dicts, predicate, key, value):
return all(predicate(d, key, value) for d in dicts... | 45,540 |
```python
import numpy as np # import numpy
def conjugate_complex(z):
return np.conjugate(z)
``` | Given a complex number `z = a + bi`, write a Python function to conjugate it. Conjugation is the process of changing the sign of the imaginary part (b) of a complex number. For example, the conjugate of 3 + 4i is 3 - 4i. In addition, your code should create a matrix representation of the given complex number `z` and tr... | To conjugate a complex number `z = a + bi`, the conjugate is given by `a - bi`. Additionally, we can represent this complex number as a 2D matrix, where the real part `a` is stored in one cell, and the imaginary part `b` is stored in another cell.
Here's the Python code that defines a function to conjugate the comple... | 45,541 |
To efficiently convert a byte-string to a bit-string, you must use bitwise operations to manipulate the bits of the integer representation of the byte-string. Bitwise operations allow you to perform binary operations on the individual bits of an integer, such as AND (&), OR (|), and XOR (^) operations.
Here's how you ... | Write a Python function named `byte_string_to_bit_string` that accepts a byte-string and returns a bit-string. You must first convert the byte-string to an integer by using bitwise operations. Then, use bitwise operations to generate a bit-string representation of the integer.
Your code should pass the following asser... | To achieve the conversion of a byte string to a bit string using bitwise operations, we can follow these steps:
1. Convert the byte string to an integer.
2. Use bitwise operations to extract each bit from the integer and construct the bit string.
Here's the Python function `byte_string_to_bit_string` that implements ... | 45,542 |
To generate a list of values following a transition from 0 to 1 over a specified number of steps, you can use a lambda function to control the easing function's behavior. The lambda function can be passed to a function that generates the list of values.
The list comprehension will make use of the `range` function to g... | Develop a Python function that generates a list of values to smoothly transition from 0 to 1 over a specified number of steps. The transition should follow an easing function, with an optional lambda function as a parameter to control the easing function's behavior. Use list comprehension to generate the list of values... | Certainly! To create a Python function that generates a list of values transitioning from 0 to 1 over a specified number of steps, using an optional easing function, you can follow this approach. The easing function can be a lambda function that takes a value from the range [0, 1] and outputs a value based on the easin... | 45,543 |
Here is a Python function that implements this approach:
```python
from typing import Dict, List
def group_records(records: List[Dict]) -> Dict[int, List[str]]:
"""
Groups records by their `id` field and returns a dictionary that maps `ids` to a list of `names` belonging to that `id`.
"""
grouped_reco... | Write a Python function to read a JSON file that contains a list of dictionaries, where each dictionary represents a record. Each record has two fields: a numerical `id` and a string `name`. The function should group the records by their `id` field and return a dictionary that maps `ids` to a list of `names` belonging ... | Certainly! You can create a Python function that reads a JSON file containing a list of dictionaries and groups the records by their `id` field as specified. Below is a sample implementation of such a function:
```python
import json
from collections import defaultdict
def group_records_by_id(json_file_path):
"""
... | 45,544 |
The confusion matrix is a table representing the performance of a classification model. The four elements in the confusion matrix are:
- True Positive (TP): the number of positive instances correctly predicted as positive.
- False Positive (FP): the number of negative instances incorrectly predicted as positive.
- Fals... | Write a Python function that takes 4 arguments: `tp`, `fp`, `fn`, and `tn`, corresponding to the four elements in the confusion matrix. The function should compute the precision, recall, and specificity, then return the F-score as a float value. Each argument should be a non-negative integer. Return `None` if any of th... | You can define the function as follows. This function computes precision, recall, specificity, and then calculates the F-score. The F-score is commonly referred to as the F1 score, which is the harmonic mean of precision and recall.
Here’s the implementation:
```python
def compute_f_score(tp, fp, fn, tn):
# Valid... | 45,545 |
Here is the implementation in Python:
```python
def process_sequence(sequence):
output = []
for num in sequence:
output.append(~num)
return output
```
In this implementation, we loop through each integer `num` in the input sequence and flip the most significant bit using the bitwise operator `~`. ... | Write a Python function to process a sequence of non-negative integers, where each integer represents a group of bits. Return a list of integers, where each integer represents the group of bits with the most significant bit flipped. The input sequence and the output sequence may have different lengths. | To solve this problem, we will write a Python function that takes a list of non-negative integers as input. Each integer in the list represents a group of bits. The function will flip the most significant bit (MSB) of each integer and return a new list containing the modified integers.
Here's how we can approach this:... | 45,546 |
Since you've given a formula for `x + 2` and a formula for `x - 1`, it's a good idea to define two functions, `f_int(x)` and `f_float(x)`, that calculate `x + 2` and `x - 1`, respectively. Then, you can use a conditional statement to determine which function to call based on the type of `x`.
Here is the implementation... | Write a Python function `f(x)` that returns `x + 2` if `x` is an integer and `x - 1` if `x` is a float.
Your code should pass the following assertion:
```python
assert f(3.0) == 2.0
``` | You can create the function `f(x)` as specified. Here's how you can do it:
```python
def f(x):
if isinstance(x, int):
return x + 2
elif isinstance(x, float):
return x - 1
else:
raise TypeError("Input must be either an integer or a float.")
# Testing the function with the provided a... | 45,547 |
To merge two configuration dictionaries, we can use the `update` method of the `dict` class to add keys from the first dictionary if they don't exist in the second dictionary. For the keys that exist in both dictionaries, we can check whether the values are equal. If they are, we can skip the key. Otherwise, we can rem... | Write a Python function named `merge_config_files` that merges two configuration dictionaries. The function should check whether each key in the first dictionary also exists in the second dictionary. If a key exists in both dictionaries, the function should skip it. If a key exists only in the first dictionary, the fun... | Certainly! Below is the Python function `merge_config_files` that merges two configuration dictionaries according to your specifications:
```python
def merge_config_files(dict1, dict2):
# Create a set of keys from dict1 for quick lookup
keys_in_dict1 = set(dict1.keys())
# Loop through keys in dict2
... | 45,548 |
Here's the code for the function:
```python
import argparse
def apply_command_to_words(words, command):
command = command.replace('"', '')
command = command.strip()
command = command.replace('by', ' ')
parser = argparse.ArgumentParser()
parser.add_argument('verb', help='The verb to apply to the wo... | Write a Python function that takes in a list of words and a command string, and returns a list of words with the command applied to each.
The command consists of a verb and a noun. For example, `"sort by name"` is a command that can be applied to a list of words.
The function should use the command line parser built ... | To implement the functionality you described using Python's `argparse` library, we first need to preprocess the command string to remove double quotes and leading/trailing whitespace. Then, we will define a function that applies the specified command (in this case, sorting by the name of the words). Below is a sample P... | 45,549 |
We can use regular expressions to extract the items from the input string and infer their types based on the value and quotation marks. The process can be broken down into the following steps:
- Split the input string on the comma character to get a list of items.
- Iterate over the items and infer their types.
- If t... | Design a Python function `parse_list_str(s)` to parse a string of comma-separated items into a list of items. The items can be of different types: string, integer, or floating point. The function should convert each item to its corresponding type. If the item is an integer or floating point, the function should infer i... | You can achieve the task of parsing a comma-separated string and converting it into a list of appropriate types by implementing the `parse_list_str` function as follows:
```python
def parse_list_str(s):
if not s:
return []
items = []
current_item = ""
in_quotes = False
quote_char = Non... | 45,550 |
The `add` function is designed to handle the case where the magnitude of `x` is much larger than that of `y` by leveraging the `add_precise` function, which is a numerical stability optimization technique. If the `fast` argument is set to `True` (default), the `add` function calls the `add_precise` function to compute ... | Write a Python function `add(x, y)` that accurately computes the sum of two floating-point numbers `x` and `y`. The function should handle the case when the magnitude of `x` is much larger than that of `y` (i.e., `abs(x) >> abs(y)`). Your solution should be based on the `add_precise` function provided below, which is a... | Certainly! To implement the `add` function that utilizes the `add_precise` function for improved numerical stability when adding two floating-point numbers, here's how you can structure the code:
The `add_precise` function is typically used to manage cases where the magnitude of one number overwhelms the other, which ... | 45,551 |
You can create a Python function that uses the `.split()` method to split the input string at the specified character and then return the result as a list of strings. If the character does not exist in the input string, the `.split()` method will return a list with the entire string as the only element.
Here's how you... | Write a Python function that takes a string and a character as arguments and returns a list of strings, where each string is a substring of the input string created by splitting the input string at the specified character. If the character does not exist in the input string, the function should return an empty list. | You can accomplish this by using the built-in `split()` method in Python, which splits a string at the specified character. Here’s a function that implements your requirements:
```python
def split_string(input_string, delimiter):
# Split the input_string using the specified delimiter
substrings = input_string.... | 45,552 |
To create such a function, we can utilize the `hasattr` function to check if the given attribute exists on the object. If it does, we can use `getattr` to retrieve its value. Otherwise, we'll set the attribute to the default value using `setattr` and return it. If the attribute is already set to the default value, we'l... | Create a function `get_attribute_with_default` that takes three arguments: `obj`, an object; `attr`, a string representing the attribute name; and an optional `default` value. If the attribute exists on `obj`, return its value. If the attribute does not exist, set the attribute to `default` and return it. If the attrib... | Certainly! Here's how you can implement the `get_attribute_with_default` function as per your requirements:
```python
def get_attribute_with_default(obj, attr, default=None):
# Define a nested function to return the value of the attribute
def attribute_handler(attr_value):
return attr_value
# Chec... | 45,553 |
Here's how you can implement this:
```python
def reformat_summary(summary):
sorted_summary = sorted(summary, key=lambda d: d['id'])
reformatted_summary = []
for person in sorted_summary:
id = person['id']
name = person['name']
age = person['age']
address = person['address']... | I have a summary that is a list of dictionaries like this:
```python
summary = [
{
'id': 1,
'name': 'John',
'age': 20,
'address': 'New York',
'has_car': True,
'children': '0',
},
{
'id': 2,
'name': 'Mary',
'age': 25,
'address':... | Sure! You can achieve this by first sorting the list of dictionaries by the `id` key and then formatting each dictionary into the desired string format. Here's how you can do that:
```python
# Given summary
summary = [
{
'id': 1,
'name': 'John',
'age': 20,
'address': 'New York',
... | 45,554 |
To solve this problem, we need to iterate through each character in the input string and check if it is a letter or a number. If it is, we append it to the result string, otherwise we append a space. We also need to remove any leading or trailing spaces in the result.
Here's one way to do it:
```python
import re
def... | Write a Python function that takes a string as input and returns a new string in which all characters that are not letters or numbers are replaced with spaces. The function should also remove any leading or trailing spaces in the result.
Your code should pass the following test case:
```python
input_string = 'a1b!2c@3... | You can implement the function `remove_non_alphanumeric_chars` as described. Here’s a simple way to achieve that using Python’s built-in string methods and list comprehensions.
Here's the implementation:
```python
def remove_non_alphanumeric_chars(input_string):
# Replace non-alphanumeric characters with spaces
... | 45,555 |
To generate the function template, we can use the string provided as input and split it into individual tokens. The first token will be the function name, and the rest will be the parameter names and types. We can use the `split()` method to split the string based on spaces and parentheses, and use the `strip()` method... | Write a Python function called `function_template` that takes a string representing a function signature and returns the function template in Python. For example, `function_template('my_function(param1: int, param2: int)')` should return `"def my_function(param1: int, param2: int):\n pass"`, meaning the function def... | Certainly! Below is a Python function called `function_template` that takes a function signature as a string and returns a formatted function template in Python.
```python
def function_template(signature: str) -> str:
# Split the signature to extract the function name and parameters
name_end_index = signature.... | 45,556 |
Here's how we can implement this:
```python
def common_chars(word1, word2):
return set(word1).intersection(set(word2))
def find_word_pair(words1, words2):
results = []
for word1 in words1:
for word2 in words2:
if len(common_chars(word1, word2)) > 0:
results.append((wor... | Develop a Python function `find_word_pairs` that takes two dictionaries as arguments, `words1` and `words2`. It should find all pairs of words that share a common character and return them in the form of a list of tuples. Each tuple should contain two words from the two dictionaries, and the words should be in the same... | To achieve the goal of finding all pairs of words that share a common character from two dictionaries, we can follow these steps in the function `find_word_pairs`:
1. Extract the words from both dictionaries.
2. Iterate over each word from the first dictionary and compare it with each word from the second dictionary.
... | 45,557 |
Here's how you can implement the function in Python:
```python
def energy(mass, speed_of_light):
"""
Calculates the energy of a particle with given mass and speed of light.
Args:
mass (float): The mass of the particle.
speed_of_light (float): The speed of light.
Returns:
float... | Implement the following formula and return the result as a float. Make sure to write a docstring for this function that explains what the function does and how to use it.

Your code should pass the following assertion:
```python
assert energy(1, 299792458) ==... | Here is the implementation of the formula \( E = mc^2 \), which calculates the energy equivalent of mass given the speed of light. The function includes a docstring that explains its purpose and usage.
```python
def energy(mass: float, speed_of_light: float) -> float:
"""
Calculate the energy equivalent of a g... | 45,558 |
Here is the implementation:
```python
def compose_unique_combinations(*arrays):
def combine_two_arrays(first, second):
combinations = []
for item1 in first:
for item2 in second:
combinations.append([item1, item2])
return combinations
def combine_three_arrays... | Write a Python function `compose_unique_combinations` that takes multiple input arrays and returns a combined list of unique array combinations. For example, given `[[1, 2, 3], [4, 5], [6, 7]]`, the function should return `[[1, 4, 6], [1, 4, 7], [1, 5, 6], [1, 5, 7], [2, 4, 6], [2, 4, 7], [2, 5, 6], [2, 5, 7], [3, 4, 6... | You can achieve this by composing functions that generate unique combinations of the given arrays. Below is a Python implementation of the `compose_unique_combinations` function that uses function composition to handle combinations of any number of arrays. For simplicity, I'll create two helper functions: one for combi... | 45,559 |
Here is a Python function that calculates the phase factor of a complex tensor:
```python
import numpy as np
def complex_phase(z):
z_arr = np.array(z)
mag = np.abs(z_arr)
phase_factor = z_arr / mag
return phase_factor
``` | Implement a Python function to calculate the phase factor of a complex tensor. The function should accept a complex tensor as input. It should then calculate the phase factor by dividing each element in the complex tensor by its magnitude, and then return the result. The function should handle broadcasting of operation... | To implement a Python function that calculates the phase factor of a complex tensor, we can use NumPy which provides powerful capabilities for handling complex numbers and broadcasting. The phase factor for each element in a complex tensor is calculated by dividing the element by its magnitude.
Here is a function that... | 45,560 |
You can create a Python function that splits the input list into two sublists based on its length, and place the middle element in the first sublist. The function should handle lists of even and odd lengths, empty lists, and non-list inputs by raising a `TypeError`.
Here's how you could implement this function:
```py... | Design a Python function that takes a list, splits it into two sublists, and returns a tuple of the two sublists, with the middle element placed in the first sublist. If the list has an even number of elements, it should be split equally. If the list has an odd number of elements, the middle element should be in the fi... | Certainly! Below is a Python function that meets the specified requirements. The function takes a list as an argument, splits it into two sublists according to the rules you've provided, and returns a tuple of the two sublists. It also handles the case where the input is not a list by raising a `TypeError`.
Here's the... | 45,561 |
Here is the implementation of the function:
```python
def check_callable(func):
if callable(func):
if hasattr(func, "__call__") and callable(getattr(func, "__call__")):
return True
else:
return False
else:
raise TypeError("The given function is not callable.")
``... | Write a Python function to check if a given function is callable or not. In addition, if the given function has the `__call__` method, use `callable` to determine if `__call__` is callable. Otherwise, use `getattr` to find the `__call__` attribute and check if it is callable. If neither of these conditions is met, rais... | Certainly! In Python, you can define a function to check if a given object is callable. To follow your instructions, we will create a function that checks for the `__call__` attribute and verifies its callability. Here's how you can implement this:
```python
def is_callable(obj):
# First, check if the object is di... | 45,562 |
Here's an implementation of the `subset_count` function in Python:
```python
def subset_count(set_of_distinct_integers):
return 2 ** len(set_of_distinct_integers)
``` | Write a Python function `subset_count` to compute the number of non-empty subsets of a given set (without repetition) using the [inclusion-exclusion principle](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle). The function should take as input a set of distinct integers and return the number of subs... | To compute the number of non-empty subsets of a given set using the inclusion-exclusion principle, we can follow a straightforward combinatorial method. The total number of subsets of a set with `n` elements is `2^n`, including the empty subset. To find the number of non-empty subsets, we simply subtract the empty subs... | 45,563 |
To create a Python function that takes a list of objects and a batch size and returns a generator that yields batches of the list, you can follow these steps:
1. Check that the input arguments are valid. The function should raise an exception if `data` is not a list or `batch_size` is not an integer greater than 0.
2.... | Create a Python function named `batch_output` which takes two arguments, `data` and `batch_size`. The `data` argument is a list of objects and `batch_size` is an integer representing the number of objects to be returned per batch. The function should return a generator that yields batches of the `data` list. If the num... | Certainly! Below is the implementation of the `batch_output` function that meets the specified requirements:
```python
def batch_output(data, batch_size):
"""Yield batches of the data list.
Args:
data (list): A list of objects to be batched.
batch_size (int): The number of objects to return pe... | 45,564 |
The task is to generate a random 12-digit number and store it in a file called `secret.txt`, and then write a function to check if the secret matches the content of the file.
Here is the Python code to achieve this:
```python
import random
def generate_secret():
secret = random.randint(10**11, 10**12 - 1) # Gen... | Generate a random 12-digit number to be used as a privacy secret and store it in a file called `secret.txt`. Then write a function to check if the secret matches the content of the file.
Your code should pass the following test case:
```python
secret = generate_secret()
assert check_secret(secret)
``` | Here's a Python implementation that generates a random 12-digit number as a privacy secret, stores it in a file called `secret.txt`, and provides a function to check if the secret matches the content of the file.
```python
import random
def generate_secret():
# Generate a random 12-digit number
secret = ''.j... | 45,565 |
Here's how you could implement the `join_csv_files_by_key` function:
```python
import pandas as pd
def join_csv_files_by_key(paths, key):
dataframes = [pd.read_csv(path) for path in paths]
joined_df = pd.concat(dataframes, axis=0, join='inner', ignore_index=True)
return joined_df
``` | Write a Python function `join_csv_files_by_key` that takes a list of paths to CSV files and a column name. The function should read each file into a DataFrame and join them based on the specified column. The function should return a single DataFrame that contains all the joined data. | You can use the `pandas` library in Python to achieve this. The function `join_csv_files_by_key` will read each CSV file into a DataFrame and then perform a join operation based on the specified column. Here is how you could implement this function:
```python
import pandas as pd
def join_csv_files_by_key(file_paths, ... | 45,566 |
Here's how you can implement the function in Python:
```python
def split_pairs(string):
pairs = string.split(",")
result = []
for pair in pairs:
key, value = pair.split("=")
result.append((key, value))
return result
``` | Write a Python function that takes a string as input and splits it into key-value pairs using an equals sign. Each key-value pair should be stored as a tuple in a list. The function should return the resulting list.
Your code should pass the following test case:
```python
pairs = split_pairs("a=1,b=2,c=3")
assert pair... | You can create the function `split_pairs` that takes a string as input, splits it by commas to get individual key-value pairs, and then splits each pair by the equals sign. The resulting tuples can then be added to a list, which is returned at the end. Here's how you can implement this:
```python
def split_pairs(input... | 45,567 |
To manipulate a NumPy array in the way described, you can use the `np.stack` function to stack the original array `x` with itself along the first axis, then use the `np.swapaxes` function to swap the first and last axes. This will produce a new array `x_new` that has the desired shape and order of axes.
Here is an exa... | Create a Python function `numpy_stack_shape_manipulation` that takes an array `x` and returns a new array `x_new` in the following way:
1. Stack `x` with itself (along the first axis) so it becomes a 3-dimensional array.
2. Swap the axes of the resulting array so that the first axis is the last axis (the one that cont... | Certainly! You can achieve the required functionality using NumPy's built-in functions for stacking and swapping axes. Here's the implementation of the `numpy_stack_shape_manipulation` function:
```python
import numpy as np
def numpy_stack_shape_manipulation(x):
# Stack x with itself along the first axis
stac... | 45,568 |
To accomplish the given intent, we can follow these steps:
1. Ensure that the input is a string: Use `isinstance` to check if the input is a string. If not, raise a TypeError.
2. Check the length of the string: If the length is less than 3, return the original string unchanged.
3. Remove the third character: Extract t... | Create a Python function that takes a string input and returns a new string that is a modified version of the original. The modification is defined by the following intent:
> If the length of the original string is less than 3, the function should return the original string unchanged. Otherwise, the function should re... | You can achieve the required behavior by implementing a function called `remove_third_character`. Below is the code that fulfills all the specified requirements:
```python
def remove_third_character(input_string):
if not isinstance(input_string, str):
raise TypeError("Input must be a string")
if l... | 45,569 |
Here is a Python function that implements this approach:
```python
def weighted_avg(nums, weights):
def helper(nums, weights, left, right):
if left == right:
return nums[left] * weights[left]
mid = (left + right) // 2
return helper(nums, weights, left, mid) + helper(nums, weight... | Calculate the weighted average of a list of numbers (with weights) using an efficient algorithm in Python. You can assume that the weights are non-negative and that the list has at least one element. | You can calculate the weighted average of a list of numbers using Python efficiently by using a combination of the `sum()` function to calculate both the weighted sum and the total weight. Here's one way to implement this:
```python
def weighted_average(values, weights):
"""
Calculate the weighted average of a... | 45,570 |
Implementing the `is_uppercase` function involves several key steps:
1. The function should check if the input is a string and raise an `AssertionError` if it is not.
2. The function should iterate over each character in the string and check if it is uppercase. It can use a built-in `isupper` method or a custom check.... | Given a string that may contain a lowercase letter, write a function `is_uppercase` that returns `True` if all letters in the string are uppercase, `False` otherwise. The function should raise an `AssertionError` if the input is not a string.
Additionally, add a docstring to the function explaining its arguments and r... | Certainly! Below is a Python function `is_uppercase` that meets the specified requirements. The function checks if all alphabetic characters in the given string are uppercase, raises an `AssertionError` if the input is not a string, and includes a docstring to explain its arguments and return value.
```python
def is_u... | 45,571 |
In Python, a class attribute is a piece of data that is associated with the class itself. It is shared by all instances of that class. You can access a class attribute using the class name, followed by a dot (.) and the attribute name. You can also assign a new value to a class attribute, which will change the value fo... | In Python, a class attribute is a piece of data that is associated with the class itself. It is shared by all instances of that class. You can access a class attribute using the class name, followed by a dot (.) and the attribute name. You can also assign a new value to a class attribute, which will change the value fo... | Certainly! Below is a Python function `convert_attributes_to_camel_case` that takes an object as input and converts each of its attribute names from snake_case (lowercase words separated by underscores) to camelCase. This function uses the `setattr` and `getattr` functions to modify the object's attributes dynamically.... | 45,572 |
Here's an example implementation of the `square_root_list` function:
```python
def square_root(num):
return num ** 0.5
def square_root_list(input_list):
if not isinstance(input_list, (list, tuple)):
raise TypeError("Input must be a list or tuple.")
return list(map(square_root, input_list))
``` | I want to write a function that takes a list or tuple and returns a new list, where the elements are the square roots of the original numbers. The function should handle the case when the input is not a list or tuple by throwing an exception. | You can create a function that checks the type of the input and then computes the square roots of the elements if the input is either a list or a tuple. If the input type is incorrect, an exception can be raised. You can use Python's built-in `math.sqrt` function to compute the square roots. Here is a sample implementa... | 45,573 |
To convert a 4D tensor of RGB images into a 4D tensor of single-channel images, we need to apply a transformation to each image in the input tensor. One approach is to use NumPy's `reshape` and `squeeze` methods to perform the required manipulation.
Here's how you can implement this function using NumPy:
```python
im... | Implement a Python function that takes a 4D tensor of shape `(batch_size, 64, 64, 3)` as input and outputs a 4D tensor of shape `(batch_size, 64, 64, 1)`. The input tensor represents a batch of RGB images of size 64x64 pixels, and the output tensor should contain the same images but in a single channel format. | To convert a 4D tensor of shape `(batch_size, 64, 64, 3)` representing RGB images into a tensor of shape `(batch_size, 64, 64, 1)`, we can use various methods in Python, including NumPy or TensorFlow/PyTorch for handling tensors. I will provide an implementation using NumPy and also using TensorFlow.
### Implementatio... | 45,574 |
Here is the implementation of the `format_time` function using a function called `convert_to_hms` to convert seconds to hours, minutes, and seconds:
```python
def format_time(seconds):
h, m, s = convert_to_hms(seconds)
return f'{h}:{m}:{s}'
def convert_to_hms(seconds):
hours = seconds // 3600
minutes ... | Write a Python function called `format_time` that takes a second value as an integer and returns a string representing the time in the format: hour:minute:second. For example, `format_time(60)` should return `'0:1:0'`, and `format_time(3700)` should return `'1:1:40'`. | You can create the `format_time` function in Python by performing the following steps:
1. Divide the total seconds by 3600 to calculate the hours.
2. Use the modulus operator to determine the remaining seconds after calculating hours, and divide that by 60 to get the minutes.
3. Again, use the modulus operator to find... | 45,575 |
To implement the `find_min_distance` function, I'll utilize the dot product formula to calculate the distance between two points. The dot product is the product of the magnitudes of the two vectors and the cosine of the angle between them; this can be used to compute the distance between the point and every point in th... | Implement a Python function `find_min_distance(points, x, y)` that returns the minimum distance from a given point (x,y) to any point in a list of points. The function should traverse the list of points and compute the distance using the frame transformation algorithm. Utilize the dot product (the vector dot product) t... | To implement the function `find_min_distance(points, x, y)`, we need to calculate the Euclidean distance from the point `(x, y)` to each point in the list of `points`. The distance can be calculated using the formula:
\[
\text{distance} = \sqrt{(x2 - x1)^2 + (y2 - y1)^2}
\]
where `(x1, y1)` is the point we are compar... | 45,576 |
To compute the union and intersection of two ordered sets, we can use the `union()` and `intersection()` methods on sets. These methods are available in the Python `set` data type.
Here is the implementation:
```python
def union_and_intersection(A, B):
union = set(A).union(set(B))
intersection = set(A).inters... | Write a Python function to compute the union and intersection of two ordered sets. For example, given sets A = [1, 2, 3, 4, 5] and B = [1, 3, 5, 7, 9], the function should return the union as [1, 2, 3, 4, 5, 7, 9] and the intersection as [1, 3, 5]. Additionally, write a test function to validate this behavior using exa... | To compute the union and intersection of two ordered sets in Python, we can use a function called `union_and_intersection` that takes two lists as input. Since the problem specifies that the inputs are ordered sets, we can assume the lists contain unique elements without duplicates.
Here’s how you can implement the fu... | 45,577 |
Here is a Python function that implements this approach:
```python
def convert_query_params(query_params_string: str) -> dict:
"""
Converts a string of comma-separated key-value pairs of URL query parameters into a dictionary.
The function should split each pair by a '=' character, and convert the value to... | Write a Python function that takes a string of comma-separated key-value pairs of URL query parameters as input, and returns a dictionary mapping keys to values. The function should split each pair by a '=' character, and the function should convert the value to an integer if all of the characters in the value are digi... | Certainly! Below is the Python function that takes a string of comma-separated key-value pairs, processes it, and returns a dictionary with the desired behavior:
```python
def parse_query_params(query_string):
# Initialize an empty dictionary to hold the parameters
params = {}
# Split the query string... | 45,578 |
Here's how you can implement this function:
```python
def is_set_subset(set1: set, set2: set) -> bool:
return set1.issubset(set2)
``` | Write a Python function to check if a given set is a subset of another set. The function should return True if the first set is a subset of the second, and False otherwise.
Your code should pass the following assertion:
```python
assert is_set_subset(set([1, 2, 3]), set([1, 2])) is False
``` | You can create a Python function called `is_set_subset` that checks if one set is a subset of another. In Python, there is a built-in method `issubset()` for sets, which you can leverage. However, you can also manually implement the subset check.
Here’s how you can write this function:
```python
def is_set_subset(set... | 45,579 |
Here's a Python function that takes a list of images and a function that takes an image as input and returns a mask, and returns a new list of images with only the object pixels:
```python
def select_object_pixels(images, get_object_mask):
new_images = []
for image in images:
object_mask = get_object_m... | I have a large set of images and I want to select objects of interest, like a person, and select only those pixels for each image.
Suppose I have a function that takes an image as input and returns a mask where the pixels that are part of the object are True, while the background is False.
Given a set of images, I wa... | To achieve the goal of extracting the object of interest from each image using a mask, we can write a function that processes each image in the set, applies the mask, and returns a new set of images containing only the pixels of the object. Below is a Python function that accomplishes this using NumPy and the PIL (Pill... | 45,580 |
Here's how you could do it:
```python
import string
def extract_words_unicode(input_string):
if not isinstance(input_string, str):
raise TypeError('Input must be a string.')
words = input_string.split()
words_nopunct = []
for word in words:
words_nopunct.append(word.strip(string.punctu... | Create a Python function that takes a Unicode string and returns a list of Unicode strings (i.e., words) without punctuation. The function should treat any Unicode character that is not included in the `string.punctuation` list as a word separator. For example, given the input string `"Hello, world! What's your name?"`... | You can create a function that processes a Unicode string, removes punctuation using `string.punctuation`, and splits the string into words based on that punctuation. Here's how you can implement it:
```python
import string
import re
def split_unicode_string(input_string):
# Check if the input is a string
if ... | 45,581 |
To implement a recursive function that counts the number of occurrences of a character in a string, we can utilize the power of recursion. Recursion is a powerful technique that allows us to break down complex problems into smaller, simpler steps.
In the provided instruction, we want to count the occurrences of a char... | Implement a Python function `recursive_count` that takes a string and a character as input arguments and returns the number of times the character appears in the string. The string is a non-empty string of lowercase letters. The character is a lowercase letter.
Use recursion and include appropriate validation for empt... | Certainly! Below is a Python function named `recursive_count` that takes a string and a character as input arguments and returns the count of occurrences of the specified character in the string using recursion. It includes validation for non-empty strings and checks that the character is a lowercase letter.
```python... | 45,582 |
Here's how you can implement the Python function to calculate the curve of $f(z)$:
```python
import cmath
def evaluate_function(z):
return (z**2 + 1) / (z + 1)
def calculate_curve(z):
results = []
for i in range(8):
start_value = cmath.exp(2j * cmath.pi * i / 8) * z
end_value = cmath.exp(... | There is a function defined as:
$$
f(z)=\frac{z^2+1}{z+1}
$$
The goal is to write a Python function to accept an input parameter `z` (complex number) and output a list of values along the curve. The curve can be simply split into 8 equal parts, and the function should return a list of 8 complex numbers that are $f(z)... | To achieve the task, we need to create a Python function that accepts a complex number `z` and computes the function \( f(z) \) along the curve. The curve can be conveniently represented by varying the angle in the polar form, effectively allowing us to compute points on the circle corresponding to \( z \).
Here’s how... | 45,583 |
To encode a byte string into a base64url string, let's follow these steps:
1. Encode the byte string using the `base64` module. This module allows us to encode a byte string into a base64 string using the `base64.b64encode()` function.
2. Convert the base64 string to a byte string using the `encode()` function. This i... | Write a Python function `b64u_encode(payload)` that encodes the given payload into a base64url string, where the given payload is a byte string. Return a byte string instead of a regular string, as this preserves the payload type. Test your function using the assertion:
```python
assert b64u_encode(b'payload') == b'cG... | To create a function `b64u_encode(payload)` that encodes a byte string into a base64url encoded string, you can utilize the `base64` library in Python. Base64url encoding is similar to standard base64, but it replaces the `+` and `/` characters with `-` and `_`, respectively, and it does not use any padding characters.... | 45,584 |
To implement this function, we need to convert the integer to a string, remove leading zeros, and return the result.
Here is the implementation:
```python
def neg_int_to_str(num: int) -> str:
if num >= 0:
raise TypeError("Input must be a negative integer.")
if num == 0:
return "0"
return s... | Write a Python function `neg_int_to_str(num: int) -> str` that takes a negative integer as input and returns its string representation without leading zeros.
Input validation:
- If the input is not a negative integer, raise a `TypeError` exception.
- If the input is a zero, return `'0'`.
Type hinting:
- Use functio... | Here is a Python function that meets your requirements. The function takes a negative integer as input and returns its string representation without leading zeros. It includes input validation as specified.
```python
def neg_int_to_str(num: int) -> str:
# Input validation: Check if num is a negative integer
if... | 45,585 |
To validate that a string contains only alphanumeric characters, let's follow these steps:
1. Use a regular expression to match alphanumeric characters: Define a regular expression pattern that matches alphanumeric characters using the `re` module from the standard library.
2. Validate the user input: Use the `re.full... | Write a Python function that prompts the user to enter a string and validates that the input contains only alphanumeric characters. The function should return a boolean result indicating whether the input is valid or not.
Include function documentation using the standard docstring format.
Your code should pass the fo... | Certainly! Below is a Python function named `validate_alphanumeric_input` that prompts the user to enter a string and checks if it contains only alphanumeric characters. The function includes proper documentation and passes the specified assertions.
```python
def validate_alphanumeric_input():
"""
Prompts the ... | 45,586 |
To compose two functions, `f` and `g`, such that the return value of the composed function is the one that satisfies the condition `g(f(x)) > 10`, we need to first define the two functions `f` and `g` and then create a third function that combines them.
Here is the implementation:
```python
def f(x):
return x**2 ... | Write a Python function to compose two functions, `f` and `g`, such that the return value of the composed function is the one that satisfies the condition `g(f(x)) > 10`. Both functions take a single argument and return a single value.
Your code should pass the following assertion:
```python
assert compose(f, g, 2) > ... | To achieve the task of composing two functions, `f` and `g`, such that the result of `g(f(x))` is greater than 10 when `x` is 2, we can define `f` and `g` according to specific behavior that meets the requirement.
Here’s a Python function `compose` that will take two functions `f` and `g`, as well as an argument `x`, ... | 45,587 |
The problem requires applying the square operation to each integer in a given list and returning the resulting list in the same order. To achieve this, we can utilize multithreading to create multiple threads to process the input list concurrently. To ensure the output is in the correct order, we can maintain an order-... | Develop a Python function that takes a list of integers as input and returns a new list of their squares in the same order. Use multithreading to process the input with multiple threads, and ensure that the output is in the correct order.
Your code should pass the following assertion:
```python
assert square_list([-1,... | To achieve the goal of squaring a list of integers using multithreading while preserving the order of the original list, we can use the `concurrent.futures` module available in Python. The `ThreadPoolExecutor` will help us to manage multiple threads efficiently.
Here's how you can implement a function that processes t... | 45,588 |
The task is to reshape a 3D tensor representing a batch of images into a 2D matrix. The batch size, height, and width are the three dimensions of the input tensor. The output should be a (batch_size, height * width) matrix. To accomplish this task, we need to perform the following steps:
1. Validate the input shape, wh... | Write a Python function `batch_and_reshape` that takes a 3D tensor representing a batch of images and reshapes it into a 2D matrix. The input tensor dimensions are (batch_size, height, width), and the output should be a (batch_size, height * width) matrix. The function should also support a batch_first argument, which ... | Here's a Python function `batch_and_reshape` that implements the specified functionality:
```python
import numpy as np
def batch_and_reshape(tensor, batch_first=True):
"""
Reshape a 3D tensor from (batch_size, height, width)
to (batch_size, height * width) or (height * width, batch_size) based on the `ba... | 45,589 |
To shuffle a deck of cards represented as a dictionary, you can use the following steps:
1. Create an empty dictionary to store the shuffled deck.
2. Loop through the keys of the deck dictionary.
3. For each key, get the corresponding value (card rank) and add it to a list of possible values.
4. Randomly select one of... | Write a Python function `shuffle_cards(deck)` that shuffles a deck of cards represented as a dictionary. The function should shuffle the order of the cards in the deck by randomly picking one card from the deck and adding it to a new deck. The function should return the shuffled deck as a dictionary.
Example:
```pyth... | To create a function `shuffle_cards(deck)` that shuffles a given deck of cards, we can use the `random` module in Python. The function will randomly pick cards from the original deck and create a new shuffled deck. Below is the implementation of the function:
```python
import random
def shuffle_cards(deck):
# Cre... | 45,590 |
Here is a possible implementation of the `extract_payload` function using regular expressions and the `json` module:
```python
import re
import json
def extract_payload(message):
pattern = r"\[([^\[\]]+)\]\(([^\[\]]+)\)"
match = re.match(pattern, message)
if match:
header, payload = match.groups()... | Write a Python function `extract_payload(message)` that takes a message string as input and returns the payload as a dictionary if the message format follows the standard format. The standard format is:
```
[HEADER]([PAYLOAD])
```
The header and payload are each surrounded by square brackets and can contain any chara... | Certainly! Below is a Python function `extract_payload` that parses a message string according to the specified format:
```python
import json
import re
def extract_payload(message):
# Define regex pattern to match the standard format [HEADER]([PAYLOAD])
pattern = r'^\[([^[\]()]+)\]\(\s*({.*?})\s*\)$'
... | 45,591 |
You can create a Python function named `calculate_average_and_std` that takes a list of tuples as input and returns a tuple with the average and standard deviation. The function should first check that the input is a non-empty list of tuples. If it is not valid, it should raise an appropriate error. Otherwise, it shoul... | Write a Python function named `calculate_average_and_std` that calculates the average and standard deviation of a list of tuples. The function should take the list of tuples as input and return a tuple with the average and standard deviation. Import the `statistics` module to calculate the standard deviation. Use preco... | Certainly! Below is a Python function that calculates the average and standard deviation of a list of tuples. I've implemented input validation to ensure the function receives a non-empty list of tuples. Additionally, I used the `statistics` module to compute the standard deviation.
```python
import statistics
def ca... | 45,592 |
Here's an example implementation of such a function:
```python
import re
def find_patterns(regex, input_string):
matches = []
for match in re.finditer(regex, input_string):
matches.append({
'start_index': match.start(),
'length': match.end() - match.start(),
'matche... | Write a Python function that takes a string and returns a list of all the matched patterns, where the patterns are defined by a regular expression and the input string is any string. The function should return a list of matching patterns, where each matching pattern is a dictionary containing the following information:... | You can use the `re` module in Python to accomplish this task. Below is a Python function that takes a string and a regular expression pattern as inputs, and returns a list of dictionaries containing the start index, the length, and the matched string for each match found in the input string.
Here's the function:
```... | 45,593 |
To extract subtensors from a tensor with shape `[batch_size, seq_length, hidden_size]`, you can use a combination of slicing and indexing operations. The `batch_indices` parameter specifies the indices of the batches from which to extract subtensors. The function should use assertions to validate the `batch_indices` pa... | Implement a Python function to extract a subtensor from a tensor with shape `[batch_size, seq_length, hidden_size]`, where `batch_size` is the number of input sequences, `seq_length` is the length of each input sequence, and `hidden_size` is the size of the hidden states. The function should take the following paramete... | Certainly! Below is a Python function that implements the requested functionality. This function extracts a subtensor from a given tensor according to the specified batch indices and includes validation as requested:
```python
import numpy as np
def extract_subtensor(tensor: np.ndarray, batch_indices: list) -> np.nda... | 45,594 |
Given a string, to reverse its characters we can approach it in multiple ways.
1. One approach is to use a for-loop to iterate through the string in reverse and append each character to a new string. This approach involves iterating through the string from the end to the beginning, collecting each character in the new... | Create a Python function that takes a string and returns a new string with the characters in reverse order. For example, given `"Hello World"`, the function should return `"dlroW olleH"`. | You can create a function in Python to reverse a string by utilizing Python's slicing capabilities. Here's a simple implementation of such a function:
```python
def reverse_string(s):
return s[::-1]
# Example usage:
input_string = "Hello World"
reversed_string = reverse_string(input_string)
print(reversed_string)... | 45,595 |
To detect duplicate keys and modify them, you can perform a depth-first traversal of the dictionary using recursion. When you encounter a key that has already been seen, you can modify its value to include the original and new values separated by a pipe character.
Here is a Python function that performs the depth-firs... | Given a nested dictionary representing a data structure, write a Python function to detect and modify duplicate keys. If the keys are identical, the value should be a list of the original and new values, separated by a '\|' (pipe) character.
For example, given the input:
```
{
'a': 1,
'b': 2,
'c': 3,
... | To achieve the goal of detecting duplicate keys in a nested dictionary, we can implement a function that traverses the dictionary structure recursively. If it encounters a duplicate key, it can concatenate the values in a list format as specified, using a pipe (`|`) to separate them.
However, in Python dictionaries, k... | 45,596 |
Here's the implementation of my solution using Python's built-in `all()` function:
```python
def filter_objects_by_attributes(items, attributes):
filtered_items = []
for item in items:
if all(attr in item for attr in attributes):
filtered_items.append({attr: item[attr] for attr in attribute... | Design a Python function that takes two arguments, `items` and `attributes`. `items` is a list of objects, and each object has attributes. The function should return a list of objects that have the specified attributes.
For example, if the input is `items = [{'name': 'John', 'age': 25}, {'name': 'Mike', 'age': 30}, {'... | You can achieve this by defining a function that takes the `items` list and the list of `attributes` you want to filter by. The function will iterate over each item and create a new dictionary that only includes the specified attributes. Here's how you can implement this:
```python
def filter_attributes(items, attribu... | 45,597 |
To read a configuration file and lookup a property name in it, we can use the Python library `json` and the built-in function `open` to open and read the configuration file. We can then parse the JSON-formatted data using the `json.load` function, which returns a dictionary representing the configuration file. Finally,... | Write a Python function to read a configuration file and lookup a property name in it to return a value. The configuration file is a JSON file with key-value pairs, and the property name is a string. If the property name is found, return the corresponding value. If the property name is not found, return None. | You can create a Python function to read a JSON configuration file and look up a property name as follows:
```python
import json
import os
def lookup_property(config_file_path, property_name):
"""
Reads a JSON configuration file and looks up a property name to return its value.
:param config_file_path: P... | 45,598 |
Here's how you can do it in one line of Python code:
```python
import os
def safe_path_concat(path1, path2):
return os.path.join(path1, path2)
``` | Write a Python function, preferably one or two lines of code with no helper functions, that safely concatenates paths on Windows and Linux/Unix systems. The function should support both forward slash `/` and backslash `\\` as path separators.
Your code should pass the following assertions:
```python
assert safe_path_c... | You can achieve safe concatenation of paths in a single line by using the `os.path.join` function from the `os` module, which handles path separators appropriately for the operating system. Additionally, you can normalize the separators to ensure they are consistent.
Here's the one-liner function to do this:
```pytho... | 45,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.