response_seed stringlengths 53 5.17k | instruction_seed stringlengths 29 4.02k | response stringlengths 16 8.81k | __original_row_idx int64 0 50k |
|---|---|---|---|
Here is the Python implementation of the `modulo_add` function:
```python
def modulo_add(a, b):
return (a + b) % 1000
``` | Implement a Python function `modulo_add` that takes two integer arguments `a` and `b` and returns their sum modulo 1000.
Your code should pass the following assertion:
```python
assert modulo_add(1000, 1) == 1
``` | To implement a Python function `modulo_add` that sums two integers `a` and `b`, and then returns the result modulo 1000, we can use the following code:
```python
def modulo_add(a, b):
return (a + b) % 1000
# Testing the function with the provided assertion
assert modulo_add(1000, 1) == 1
```
In this function:
- ... | 36,700 |
To implement a function to create a unique ID for a row in a database by concatenating its primary key with a unique key and applying a hashing function, we need to address a few considerations:
1. Collisions: To prevent collisions and ensure uniqueness of the ID, we should use a hashing function that minimizes the ri... | Implement a Python function to create a unique ID for a row in a database by concatenating its primary key with a unique key and applying a hashing function. Ensure the resulting ID has a low risk of collisions and is encoded in base32. The base32 encoding should be case insensitive and omit all non-alphanumeric charac... | To create a unique ID for a row in a database based on its primary key and a unique key, you can use the following steps:
1. **Concatenate the primary key and the unique key** into a single string.
2. **Hash the concatenated string** using a cryptographic hash function (such as SHA-256).
3. **Encode the hash** in base... | 36,701 |
Here is the implementation:
```python
import xml.etree.ElementTree as ET
def xml_to_dict(xml_file_path):
tree = ET.parse(xml_file_path)
root = tree.getroot()
def convert_element_to_dict(element):
if len(element) == 0:
return element.text
return {element.tag: {
chil... | I have an XML file that I want to parse in Python and convert to a dictionary representation. Note that I only care about the first occurrence of each tag.
If the XML file looks like this:
```xml
<root>
<child1>value1</child1>
<child2>value2</child2>
<child3>value3</child3>
</root>
```
I want to convert it to ... | You can use Python's `xml.etree.ElementTree` module to parse the XML file and convert it into a dictionary representation. Below is an example of how you can do this, taking into account the requirements you've mentioned, including handling attributes, empty elements, and nested elements.
Here's a sample implementatio... | 36,702 |
Here is the implementation of the `get_student_emails` function:
```python
import sqlite3
def get_student_emails(db_file_path, student_id):
with sqlite3.connect(db_file_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT email FROM students WHERE id = ?", (student_id,))
email = cu... | Write a Python function `get_student_emails` that takes two inputs: `db_file_path` and `student_id`. The function should connect to a SQLite database at the specified `db_file_path`, retrieve the email address of the student with the given `student_id`, and return a string with the email address. | To create the function `get_student_emails` that retrieves a student's email address from a SQLite database, you'll need to follow these steps:
1. Import the necessary SQLite module.
2. Connect to the database provided in `db_file_path`.
3. Execute a SQL query that selects the email associated with the specified `stud... | 36,703 |
Here is an implementation of the `match_path()` function using the `fnmatch()` function from the `fnmatch` module:
```python
import fnmatch
def match_path(path, pattern):
return fnmatch.fnmatch(path, pattern)
```
The `match_path()` function simply calls the `fnmatch()` function with the given `path` and `pattern... | Write a Python function `match_path(path, pattern)` that checks if a given `path` string matches a regular expression `pattern`, which is interpreted as a shell-style pattern. The pattern may contain characters:
- `.` to match exactly one character
- `*` to match zero or more characters
- `?` to match any character
T... | To implement a `match_path` function that checks if a given `path` string matches a shell-style `pattern`, we can convert the shell-style pattern to a regular expression format and then use Python's `re` module to test for a match. The shell-style pattern includes:
- `.` to match exactly one character,
- `*` to match ... | 36,704 |
To escape a given string, you can iterate through its characters and check if they are any of the characters above. If they are, replace them with their corresponding escape sequences.
Here's how you can implement it:
```python
def escape_html(text):
escape_dict = {
"&": "&",
"<": "<",
... | Write a Python function named `escape_html(text)` that takes a string `text` as input, and returns the string with HTML tags and special characters replaced with the corresponding escape sequences. The function should escape the following characters:
| Original Character | Escaped Sequence |
| ------------------ | -... | You can implement the `escape_html` function in Python by using the `str.replace()` method to replace the specified characters with their HTML escape sequences. Below is the implementation of the function, along with the assertions provided in your prompt:
```python
def escape_html(text):
# Replace special charact... | 36,705 |
The function you need to write takes a string of arbitrary length and converts it to a hexadecimal representation using the standard encoding. It should handle both ASCII and UTF-8 encodings, as well as Unicode and non-Unicode strings.
Here is the implementation of the function:
```python
def string_to_hex_encoding(s... | Create a Python function that takes a string of arbitrary length and converts it to a hexadecimal representation using the standard encoding. The function should handle ASCII and UTF-8 encodings, and should work with both Unicode and non-Unicode strings. The output should be a string of hexadecimal characters.
Your co... | You can achieve the conversion of a string to its hexadecimal representation in Python by encoding the string into bytes (using UTF-8 encoding) and then converting those bytes to hexadecimal format. Below is a function that accomplishes this task:
```python
def string_to_hex_encoding(input_string):
# Encode the in... | 36,706 |
Here is an implementation of this algorithm in Python:
```python
def longest_substring_without_repeats(strings):
"""
Given a list of strings, return a list of strings with each string replaced by the longest substring that has no repeated characters.
"""
result = []
for s in strings:
window... | Given a list of strings, return a list of strings with each string replaced by the longest substring that has no repeated characters. For instance, given ['abc', 'cccc', 'a', 'abcd', 'cc'], the function should return ['abc', 'c', 'a', 'abcd', 'c'].
Your code should pass the following assertion:
```python
assert longes... | To solve the problem of finding the longest substring without repeating characters from each string in the provided list, we can implement a function that uses a sliding window technique along with a hash set to track the characters in the current window.
Here is how we can implement this:
```python
def longest_subst... | 36,707 |
To convert a Pandas Series to a dictionary, you can use the `to_dict()` method. However, this method returns a dictionary with the keys as strings and values as the corresponding values in the series. To ensure that the keys in the dictionary are strings, you can convert the keys to strings using a list comprehension.
... | Write a function that takes a Pandas Series `series` and returns a dictionary `d` with the same keys and values as in the series. The keys of `d` should be strings.
Your code should pass the following test case:
```python
import pandas as pd
series = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
dictionary = series_to_... | You can create a function named `series_to_dictionary` that converts a Pandas Series to a dictionary with string keys. Here's how you can implement it:
```python
import pandas as pd
def series_to_dictionary(series):
# Convert the series to a dictionary, ensuring keys are strings
return {str(key): value for ke... | 36,708 |
To implement this function, we can use regular expressions to search for specific characters and replace them with their corresponding HTML entities. By using the `re` module, we can easily create a regular expression pattern that matches any special characters and replace them with their corresponding HTML entities.
... | Develop a Python function to generate HTML entities from a given string. The function should perform string substitution using regular expressions to replace characters with their corresponding HTML entities, such as `&` to `&`. Additionally, any `<`, `>`, or `"` characters should be replaced with `<`, `>`, a... | You can create a function called `html_entities` that uses Python's `re` module for regular expressions to replace specific characters in a string with their corresponding HTML entities. Here’s how you can implement this function:
```python
import re
def html_entities(s):
# Define a function that replaces charact... | 36,709 |
To determine whether two file paths are equivalent, we can compare the parent directories of the two paths and whether the last components of the paths match. We can use the `os.path.relpath` function to get the relative path of a path to a given parent directory.
Here is the implementation:
```python
import os
def ... | Write a Python function to determine whether two file paths are equivalent, given that `..` can occur in the file path and resolves as a relative path.
The function should take two strings as inputs, `path1` and `path2`, and return `True` if the two paths are equivalent, and `False` otherwise. | To determine whether two file paths are equivalent while handling the `..` parts in the paths correctly, we can create a Python function that normalizes both paths. This involves resolving any `..` and `.` components and ensuring that both paths are compared in their canonical forms.
Here's a Python function that acco... | 36,710 |
Here's how you can do it in one line of Python code:
```python
def generate_bounding_box(scale, location):
half_width = scale[0] / 2
half_height = scale[1] / 2
return {
'x_min': location[0] - half_width,
'x_max': location[0] + half_width,
'y_min': location[1] - half_height,
... | Write a Python function to generate a bounding box object, given a scale and location. The input is a list of two numbers (scale and location), where the scale represents the width and height of a bounding box, and the location represents the coordinates of the center of the box. The output should be a dictionary with ... | Here's a Python function that generates a bounding box object based on the given scale and location. It takes a list with two elements (scale and location) and returns a dictionary containing the minimum and maximum x and y coordinates.
```python
def generate_bounding_box(params):
# Unpack the scale and location v... | 36,711 |
To generate a string representation of a function call in Python, we can use the `inspect` module to get the function's name and arguments, and then use string formatting to create the desired string.
Here is a Python function that takes a function `f` and returns a string representing a function call in Python code:
... | Given a function `f` with a set of arguments, create a string that represents a function call in Python code. The string should contain the function name, the arguments, and the return value.
Use the ternary operator to only include the return value if it's not None. | To create a string that represents a function call in Python with the specified characteristics, we can follow these steps:
1. Identify the function name and its arguments.
2. Format these into a Python function call string.
3. If the return value is not None, include it in the string.
Here is an example implementati... | 36,712 |
To write a Python function `is_record_type(obj)` with the specified conditions, we will need to check whether the object is a `dict` type and has a key named `"type"` with the specified value. We can use the `isinstance()` function to check the type of the object and the `in` operator to check the presence of the `"typ... | Write a Python function `is_record_type(obj)` that determines whether an object is a record type by checking the following conditions:
- The object is `dict` type
- The object has a key named `"type"`
- The value of the `"type"` key is a `str` type
- The value of the `"type"` key is either `"A"`, `"AAAA"`, or `"CNAME"... | You can define the function `is_record_type(obj)` in Python by following the specified conditions. Below is an implementation that checks if the given object is a record type:
```python
def is_record_type(obj):
# Check if the object is a dictionary
if not isinstance(obj, dict):
return False
# ... | 36,713 |
To format a datetime object with millseconds in the required format, we need to use the `datetime` module and the `datetime.datetime.strftime()` method. We'll use the `datetime.datetime.strftime()` method to format the datetime object, and the `datetime.datetime.astimezone()` method to convert the datetime to UTC.
We ... | Write a Python function that takes a datetime object and returns a string representation in the following format: "YYYY-MM-DDTHH:MM:SS.mmmmmmZ", where YYYY is the four digit year, MM is the two digit month, DD is the two digit day, HH is the two digit hour, MM is the two digit minute, SS is the two digit second, and mm... | You can use the `datetime` module in Python to format a datetime object to the specified string representation. Below is a function that takes a `datetime` object and returns the formatted string in the specified format, using the UTC timezone.
```python
from datetime import datetime, timezone
def format_datetime_to_... | 36,714 |
A valid semantic version consists of three parts: `x.x.x`, where each `x` is an integer greater than or equal to zero. You can check if the input string satisfies this format using string methods or regular expressions.
Here's a possible implementation in Python:
```python
import re
def check_valid_version(version):... | Design a Python function `check_valid_version` that checks whether the given version string is a valid semantic version. Follow this format: `x.x.x`, where `x` is an integer greater than or equal to zero. You may use the `assert` statement to check if the version is valid.
Example: `check_valid_version('0.5.0')` shoul... | You can design the `check_valid_version` function to validate semantic versioning strings by checking if they follow the format `x.x.x`, where each `x` is a non-negative integer. To achieve this, you can use regular expressions to ensure that the input string matches the expected format. Here's the implementation:
```... | 36,715 |
Here is the implementation of the function `is_all_even(numbers)`:
```python
def is_all_even(numbers):
"""
Returns `True` if all elements in `numbers` are even, and `False` otherwise.
>>> is_all_even([2, 4, 6])
True
>>> is_all_even([1, 2, 3, 4])
False
>>> is_all_even([])
True
>>> i... | Write a Python function `is_all_even(numbers)` that takes a list of integers `numbers` and returns `True` if all the elements are even. Otherwise, return `False`.
Do not use a for-loop or list comprehension. Instead, use boolean expression evaluation and boolean value return to check each element.
Write doctest-style... | Here is the `is_all_even` function implemented according to your specifications, along with doctest-style documentation:
```python
def is_all_even(numbers):
"""
Check if all elements in the list are even.
Args:
numbers (list of int): A list of integers.
Returns:
bool: True if all elem... | 36,716 |
Here's how we can implement this:
```python
class Foo:
def __init__(self, attr, bar):
self.attr = attr
self.bar = bar
def func(obj, attribute):
return getattr(obj, attribute, None)
obj = Foo(1, 2)
assert func(obj, 'attr') == 1
assert func(obj, 'bar') == 2
assert func(obj, 'baz') is None
``` | I have a Python class `Foo` with two attributes `attr` and `bar`. I want to write a function `func` that takes a `Foo` object as input and returns the value of the selected attribute. The function should accept two parameters: the object and a string that specifies the attribute to return. If the attribute is not found... | To implement your request, you'll want to define the class `Foo` with the specified attributes and then create the function `func` that retrieves the value of the specified attribute. If the attribute does not exist, it should raise an `AttributeError`. Here's how you can do that:
```python
class Foo:
def __init__... | 36,717 |
```python
def alias_context(ctx):
def decorator(func):
def wrapper(*args, **kwargs):
with ctx as cm:
return func(cm, *args, **kwargs)
return wrapper
return decorator
```
This implementation uses a decorator function to create an alias for the original context manager... | Define a Python function `alias_context` that creates an alias for a given context manager `ctx` using a decorator. This function should return a `context_manager` object that aliases the original `ctx` context manager. | To define a Python function `alias_context` that creates an alias for a given context manager, you can use a decorator. The decorator will return a context manager that behaves like the original one but allows you to refer to it with a different name. Here is how you could implement this:
```python
from contextlib imp... | 36,718 |
Here's how we can implement this in Python:
```python
import os
def encode_separator(file_path):
return os.path.join(*file_path.split(os.sep))
``` | Write a Python function that takes a file path and returns the path with the OS-specific separator encoded. Replace the backslash '\' or forward slash '/' depending on the current operating system. | You can use the built-in `os` module in Python to determine the OS-specific path separator. Here’s a function that takes a file path and replaces the separators with the appropriate one for the current operating system:
```python
import os
def encode_path_separators(file_path):
# Get the current OS-specific separ... | 36,719 |
To validate a Python keyword, we need to consider several cases:
1. The keyword is an empty string or contains only whitespace characters: In this case, the keyword is invalid.
2. The keyword is a single character: This is valid if the character is an underscore ('_') or a letter.
3. The keyword is longer than one char... | Define a Python function `validate_keyword(keyword)` that takes a string and checks whether it is a valid Python keyword. It should return a boolean indicating whether the keyword is valid.
The function should ignore the case of the keyword (convert it to lowercase) and trim any whitespace characters from both ends.
... | To create a Python function `validate_keyword(keyword)` that checks whether a given string is a valid Python keyword, you can leverage the `keyword` module, which provides a list of reserved keywords in Python. The function should process the input by trimming whitespace and converting it to lowercase, and then check i... | 36,720 |
Here is the implementation of the function:
```python
def get_url_from_endpoint(endpoint_identifier: str) -> str:
base_url = "https://api.com/"
if endpoint_identifier not in ("endpoint_1", "endpoint_2", "endpoint_3"):
raise ValueError("Invalid endpoint identifier.")
url = base_url + endpoint_iden... | Write a Python function to accept a string that identifies a specific API endpoint, and returns the associated URL by performing string interpolation with the endpoint identifier. The function should raise an exception if the provided endpoint identifier is not valid.
Use string replacement and string formatting to co... | Here's a Python function that accepts a string representing an API endpoint identifier, constructs the corresponding URL using string interpolation, and raises an exception if the endpoint identifier is invalid. I'll demonstrate both string replacement and string formatting methods.
Let's assume we are working with a ... | 36,721 |
Here's how you can implement this function:
```python
def replace_and_snake_case(text: str, old_char: str, new_char: str) -> str:
replaced_text = text.replace(old_char, new_char)
snake_case_text = '_'.join(replaced_text.split())
return snake_case_text
``` | Write a Python function to replace all the occurrences of a specific character in a given string with another character. The function should also convert the resulting string into snake case, as defined in Python PEP 8.
For example, for the given string "Hello World", if we want to replace all the spaces with undersco... | Certainly! To achieve the desired functionality of replacing specific characters in a string and converting the result to snake case, we can follow these steps:
1. Replace the specified character with another character.
2. Convert the resulting string into lowercase.
3. Replace any spaces with underscores to create th... | 36,722 |
To create a Python function that returns the next Monday date after a given datetime, we can utilize the `datetime` module. The `datetime` module provides a `timedelta` object that represents a time interval, allowing us to add or subtract a certain amount of time to a datetime object.
We can obtain the weekday of the... | Create a Python function `get_next_monday` that returns the next Monday date (weekday=0) after the given datetime. If the given datetime is already a Monday, the function should return its next Monday. You should use the `datetime` module. | You can create a function `get_next_monday` that calculates the next Monday after a given `datetime`. Here’s how you can implement this using the `datetime` module:
```python
from datetime import datetime, timedelta
def get_next_monday(dtm):
# dtm is expected to be a datetime object
# Find out how many days u... | 36,723 |
To solve this problem, we'll leverage the `collections.OrderedDict` class to track the first occurrence of each character in the string. We'll iterate through the string and keep track of the first occurrence of each character using an OrderedDict.
The OrderedDict class preserves the order of insertion, which allows u... | Write a Python function that takes a string and returns a list of non-repeated characters present in the string. The characters should be sorted in the order of their first appearance in the original string.
For example, given `string = 'hello world!'`, the function should return `['h', 'e', 'l', 'o', ' ', 'w', 'r', '... | You can create a function that extracts non-repeated characters from a given string while maintaining their order of appearance. Here's one way to implement this:
```python
def non_repeated_characters(string):
# Create a dictionary to count occurrences of each character
char_count = {}
# Count each ch... | 36,724 |
To swap the first and last characters of a string, you need to first check if the input is a string. If it's not, you can raise a TypeError to indicate an invalid input.
If the input is a string, you can use Python's built-in string slicing to obtain the first and last characters. You can then concatenate them in the ... | Write a Python function that takes a string as an input and returns a new string with the first and last characters of the input string swapped. For a string of length 1 or 0, the function should return the original string.
If the input is not a string, the function should raise a TypeError. | Here's a Python function that accomplishes the task you described. It swaps the first and last characters of the input string, handles cases where the string length is 0 or 1, and raises a TypeError for non-string inputs.
```python
def swap_first_last(input_string):
# Check if the input is a string
if not isin... | 36,725 |
Here's how you could implement the `normalize_abbreviations` function:
```python
import re
def normalize_abbreviations(text):
pattern = r'U\.S\.A\.|U\.S\.|U\.S|USA\.|USA'
def replacement(match):
if match.group(0) == 'U.S.A.':
return 'United States of America'
elif match.group(0) ==... | Write a Python function `normalize_abbreviations` that normalizes abbreviations in text. It should take a string and normalize all abbreviations in the text to their full form. Here is the list of abbreviations to be normalized:
```
U.S.A. -> United States of America
U.S.A -> United States of America
U.S. -> United St... | You can use Python's `re` module to handle the normalization of abbreviations in the provided text. Here's a function `normalize_abbreviations` that accomplishes this task:
```python
import re
def normalize_abbreviations(text):
# Define the mappings of abbreviations to their full forms
abbreviations = {
... | 36,726 |
Here's a sample implementation in Python:
```python
def get_time_interval_indices(times, intervals):
result = []
for i, interval in enumerate(intervals):
start, end = interval
for j, time in enumerate(times):
if time >= start:
break
for k, time in enumerate(t... | Write a Python function `get_time_interval_indices(times, intervals)` that returns a list of pairs of indices `(i, j)` such that the time interval `times[i:j]` is contained within the given `intervals`. If no such intervals exist, return an empty list. Ensure your solution handles nested lists within `intervals` and ac... | To solve the problem of finding all pairs of indices `(i, j)` such that the subarray `times[i:j]` is fully contained within any of the given `intervals`, we need to follow these steps:
1. Iterate over all possible pairs of indices `(i, j)` defined by the array `times`. The outer loop will define the starting index `i`... | 36,727 |
Here's how you can implement this function:
```python
import re
def detect_caller_ip() -> str:
if 'get_caller_ip' not in globals():
return '0.0.0.0'
ip_address = get_caller_ip()
pattern = re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
if not pattern.match(ip_address):
return '0.0.... | Write a Python function that detects the caller's IP address, if available. In the function body, check if the `get_caller_ip` function is available (i.e., it was not included in the request) and return `'0.0.0.0'` accordingly. Otherwise, use the `get_caller_ip` function to retrieve the caller's IP address and validate... | To create a Python function that detects the caller's IP address while checking if the `get_caller_ip` function is available, you can do the following:
1. Check if the `get_caller_ip` function is present in the calling environment.
2. If it's available, call it to retrieve the IP address.
3. Validate the retrieved IP ... | 36,728 |
To flatten the attributes of an arbitrary nested object into a single, flat dictionary, you can use a recursive approach. The function should traverse the nested object and build up the key-value pairs of the flat dictionary. The key of each item in the dictionary should be the attribute path, with a period (.) as the ... | Write a Python function to flatten the attributes of an arbitrary nested object into a single, flat dictionary. The key of each item in the dictionary should be the attribute path, with a period (.) as the delimiter. For example, given the following object:
```
{
"a": {
"b": 1,
"c": 2
},
"d... | You can achieve this by using recursion to traverse through the attributes of the nested object. Below is a Python function that flattens an arbitrary nested object into a single, flat dictionary with the desired key format.
Here is the implementation:
```python
def flatten_object(nested_obj, parent_key='', sep='.'):... | 36,729 |
Here's how you could do it:
```python
import pandas as pd
from pandas.errors import ParserError
class LendingClubDatasetParsingError(Exception):
pass
def parse_lendingclub_dataset(csv_file):
try:
df = pd.read_csv(csv_file)
except ParserError as e:
raise LendingClubDatasetParsingError("Err... | Write a Python function to parse the "lendingclub" loan dataset from its CSV file into a `DataFrame` and add some useful columns. The CSV file's name is "lendingclub_loans.csv", and the dataset can be found [here](https://www.lendingclub.com/info/download-data.action). The function should return a `DataFrame` with the ... | Certainly! Below is a Python function that reads a CSV file named "lendingclub_loans.csv", processes the data to extract the specified columns, and returns a Pandas DataFrame. It also includes error handling with custom exceptions.
Before running the code, ensure you have the required libraries installed. You can inst... | 36,730 |
Here's the implementation of the function:
```python
def construct_http_header(headers_dict):
try:
header_string = ""
for key, value in headers_dict.items():
if key and value:
header_string += f"{key}: {value}\r\n"
return header_string
except Exception as e:
... | Write a Python function that takes a dictionary of headers as an argument and returns a string containing the corresponding HTTP header. Handle errors appropriately and return `None` if an error occurs. | Certainly! Below is a Python function that takes a dictionary of HTTP headers as an argument and constructs a well-formed HTTP header string. If any error occurs during the process, the function will return `None`.
```python
def dict_to_http_header(headers):
"""
Converts a dictionary of HTTP headers to a strin... | 36,731 |
A recursive implementation of this algorithm can be written in Python as follows:
```python
def lcs(s1, s2):
def helper(i, j):
if i < 0 or j < 0:
return ""
elif s1[i] == s2[j]:
return helper(i - 1, j - 1) + s1[i]
else:
return max(helper(i - 1, j), helper(... | Write a Python function that takes two strings as input and returns the longest common subsequence between them. If there are multiple subsequences with the same length, return any one of them.
For example, the LCS between "ABCBDAB" and "BDCABA" is "BCBA" (length = 4).
Remember to use the prefix match to determine wh... | To solve the problem of finding the longest common subsequence (LCS) between two strings, we can utilize dynamic programming. We'll create a 2D table where each entry at position `(i, j)` represents the length of the LCS of the substrings that end at the `i`-th character of the first string and the `j`-th character of ... | 36,732 |
To correctly implement `get_keys_with_attribute(collection, attribute)`, you need to consider these conditions:
1. Collection is empty or attribute doesn't exist: Return an empty list if the collection is empty or if the attribute does not exist in any object in the collection.
2. Attribute exists in some objects but ... | Design a Python function `get_keys_with_attribute(collection, attribute)` that takes a collection of objects and an attribute name and returns a list of keys (i.e., object indices) with the specified attribute. The function should check if the collection is non-empty and if the attribute exists in each object of the co... | Here is a Python function `get_keys_with_attribute` that meets your requirements. The function checks each object in the provided collection to see if it has the specified attribute and returns the indices (or keys) where the attribute exists. If the collection is empty or no objects have the specified attribute, it re... | 36,733 |
To implement the `make_logger` function, we'll need to use Python's `logging` module to create a logger object and specify the log file path and message format. We'll also need to ensure that the code is compatible with Python 2 by using the `unicode_literals` and `print_function` imports.
Here's a possible implementa... | Develop a Python function `make_logger` that creates a logger with a specified file name. The function should take two arguments: `file_path`, a string representing the file path to create the logger with, and `msg_format`, a string that specifies the format of the log message. The function should use Python's `logging... | To create a logger in Python that logs messages to a specified file with a specified format, we can use the `logging` module. Here’s how we can implement the `make_logger` function, ensuring compatibility with Python 2 by using `__future__` imports for `unicode_literals` and `print_function`.
Here's the complete imple... | 36,734 |
To solve this problem, we can define a class `PositiveFloat` with a constructor that accepts a float value and initializes an instance variable for the value if the value is positive. We can also define a function `get_positive_float` that accepts a float value and returns an instance of `PositiveFloat` if the value is... | Write a class named `PositiveFloat` with a constructor that accepts a float value and initializes an instance variable for the value if the value is positive.
Write a function named `get_positive_float` that accepts a float value and returns an instance of `PositiveFloat` if the value is positive. Otherwise, raise a `... | Certainly! Below is an implementation of the `PositiveFloat` class and the `get_positive_float` function as you described.
```python
class PositiveFloat:
def __init__(self, value: float):
if value <= 0:
raise ValueError("Value must be positive.")
self.value = value
def __repr__(sel... | 36,735 |
Here is the implementation of the `add_component_name` function:
```python
import re
def add_component_name(src, dst, name, component):
src_count = src.count("<")
dst_count = dst.count("<")
if src_count == dst_count:
regex = re.compile(r"<!-- .* -->")
match = regex.search(dst)
if m... | Develop a Python function `add_component_name(src, dst, name, component)` that takes four arguments: `src`, a string representing the source HTML document; `dst`, a string representing the destination HTML document; `name`, a string representing the component name; and `component`, a string representing the component c... | Here's a Python function `add_component_name` that meets the requirements you've specified. This function identifies where to insert the component content based on the number of `<` characters in the same line of the `src` and `dst` HTML documents. It then inserts the component inside a comment block in the specified f... | 36,736 |
The `find_max_elements` function receives a list of dictionaries with elements that have `id` and `value` attributes. The function should return a sorted list of unique `value` elements. Here's how you can approach this problem:
1. Flatten the list of dictionaries into a single list of `value` elements using a list co... | Write a Python function `find_max_elements` that receives a list of dictionaries with elements that have `id` and `value` attributes. The function should return a sorted list of unique elements by `value` attribute. For example, given `[{'id': 1, 'value': 5}, {'id': 2, 'value': 1}, {'id': 3, 'value': 2}, {'id': 4, 'val... | To create the `find_max_elements` function as described, we'll follow these steps:
1. Extract the `value` attributes from the list of dictionaries.
2. Remove duplicates to ensure we have unique values.
3. Sort the unique values in descending order.
4. Return the sorted list.
Here's the implementation of the function:... | 36,737 |
Here's how you can implement the function in Python:
```python
def sort_by_length_then_position(word_list):
def key_func(word_tuple):
return (word_tuple[1], word_tuple[2])
return [word_tuple[0] for word_tuple in sorted(word_list, key=key_func)]
```
The `key_func` function returns a tuple of `(length,... | Create a Python function that takes a list of tuples of the form `(original_word, length, position)` where `original_word` is a string representing the original word, `length` is the length of the word, and `position` is the position of the word in the original sentence. The function should sort the list of tuples by `... | You can create the desired function `sort_by_length_then_position` to sort the list of tuples based on the specified criteria. Below is the implementation:
```python
def sort_by_length_then_position(word_list):
# Sort the list of tuples first by length, then by position
sorted_list = sorted(word_list, key=lamb... | 36,738 |
To calculate the rank of a tensor $X$ with shape (N, M, L), we need to compute the rank of each slice $X[:, :, l]$ for $l=1,2,...,L$. We can then find the rank of the tensor as the maximum rank of all the slices.
Here is an example Python function that computes the rank of a tensor $X$ with shape (N, M, L):
```python... | Given a tensor $X$ with shape (N, M, L), where N is the number of samples, M is the number of features, and L is the number of time steps, write a Python function to calculate the rank of the tensor $X$.
Assume that the tensor is a 3D matrix with dimensions (N, M, L) and each row is an N-dimensional vector. | To calculate the rank of a 3D tensor \( X \) with shape (N, M, L), we need to clarify the definition of "rank" in this context. The rank of a tensor is a generalization of the matrix rank to higher dimensions. In many cases, calculating the rank of a tensor is complex and may involve techniques from multilinear algebra... | 36,739 |
To transpose a list of lists using tuple comprehension, you can use the `zip()` function to create a new list of tuples that contain the corresponding elements from each sublist. Assuming that the input list is not empty and each sublist has the same length, you can create a transposed list by iterating over the first ... | Given a list of lists, write a Python function that transposes it using tuple comprehension. The function should accept a single argument, `data`, which represents the list of lists to transpose. Ensure that the input list is not empty and each sublist has the same length. Return the transposed list.
Your code should ... | To write a Python function that transposes a list of lists using tuple comprehension, we need to ensure that the input list is not empty and that all sublists have the same length. The function will handle the transposition and return the result.
Here’s how to implement this:
```python
def transpose_using_tuple_comp... | 36,740 |
To decode and parse the base64-encoded string, let's follow these steps:
1. Decode: Use the `b64decode` function from the `base64` module to decode the base64-encoded string into a `bytes` object.
2. Parse: Use the `loads` function from the `json` module to parse the JSON-formatted data into a Python object.
Here's t... | Given a base64-encoded string that represents a serialized Python object, decode the string, parse the data, and return the deserialized Python object. The object could be a string, number, list, tuple, dictionary, or any other object that can be represented in JSON. | To decode a base64-encoded string that represents a serialized Python object and return the deserialized object, you can follow these steps. Here's a Python example of how to do this:
1. Decode the base64 string.
2. Deserialize the resulting bytes back into a Python object using the `pickle` module (if the object was ... | 36,741 |
You can use regular expressions to match patterns in column names and filter the DataFrame columns accordingly.
Here's how you could implement this function in Python:
```python
import re
def filter_columns_by_pattern(df, patterns):
filtered_columns = []
for column in df.columns:
for pattern in patt... | Develop a Python function to filter Pandas DataFrame columns by regular expression pattern. The input is a DataFrame and a list of patterns. The function should return a DataFrame with columns filtered to match at least one of the patterns. | Certainly! You can use the `filter` method of a Pandas DataFrame along with the `regex` parameter to filter columns based on regular expression patterns. Here’s how you can implement the function:
```python
import pandas as pd
def filter_columns_by_pattern(df, patterns):
"""
Filters the columns of a DataFrame... | 36,742 |
To create a function that checks if a given text is a lowercase sentence, we need to iterate through the text and check for uppercase letters and punctuation marks that are not periods. If we encounter any uppercase letters or punctuation marks other than periods, we can return `False`. Otherwise, we can return `True` ... | Write a Python function `is_lowercase_sentence(text)` that returns whether the given `text` is a lowercase sentence. A sentence is considered lowercase if it has no uppercase letters and no punctuation marks other than periods. For example:
```python
assert is_lowercase_sentence("hello world.") == True
assert is_lower... | To implement the function `is_lowercase_sentence(text)` that determines if a given text is a lowercase sentence according to your specifications, we can use a simple approach with string methods. The function will check that the text contains no uppercase letters and only allows periods as punctuation. Here's a possibl... | 36,743 |
To extract the RDS tags from a given endpoint URL, we need to parse the URL and extract the tag key-value pairs. We can accomplish this by using regular expressions to match the key-value pattern and extract the tag keys and values.
Here is a Python function that implements this approach:
```python
import re
from typ... | Write a Python function named `get_tags_from_endpoint_url` that extracts AWS RDS tags from a given endpoint URL. The endpoint URL format is `https://<endpoint>.rds.<region>.amazonaws.com:<port>/`, where `<endpoint>` is an alphanumeric string that contains RDS tags, `<region>` is a specific AWS region, and `<port>` is a... | Certainly! Below is a Python function named `get_tags_from_endpoint_url` that extracts AWS RDS tags from a given endpoint URL, along with several test cases to ensure the function works correctly.
```python
def get_tags_from_endpoint_url(url):
"""
Extracts AWS RDS tags from a given endpoint URL.
Args:... | 36,744 |
To write a Python function that takes a string `s` and returns a list of case-insensitive glob patterns that match `s` exactly, you can follow these steps:
1. First, split the string `s` into individual characters using the `list()` function.
2. Next, use a `for` loop to iterate over each character in the list.
3. Wit... | Write a Python function that takes a string `s` as an argument and returns a list of case-insensitive glob patterns that match `s` exactly. The returned patterns should be in the form of a list of lists, where the inner list represents a single pattern and each element in the inner list is a single glob pattern.
Your ... | To create a Python function that generates case-insensitive glob patterns matching a given string `s`, we need to consider each character in `s` and generate the corresponding patterns. Each character can have both its lowercase and uppercase variants, as well as a wildcard character `*` to capture any other character.... | 36,745 |
Here is the implementation of the function:
```python
def strings_to_single_string(strings, delimiter=""):
return delimiter.join(strings)
``` | Write a Python function that takes a list of strings and returns a single string in the following format: `"[string1][string2]...[stringN]"`, where `string1`, `string2`, ..., `stringN` are the elements of the input list. Additionally, if the list is empty, the function should return an empty string.
Your code should p... | You can create the required function in Python as follows:
```python
def strings_to_single_string(strings):
# Join the strings from the list with square brackets
return ''.join(f"[{s}]" for s in strings)
```
This function accomplishes the task by using a generator expression to format each string in the list ... | 36,746 |
To implement the `early_return` function, we can use the `if` statement to check if `a` is greater than `b`. If it is, we return the result of the expression `(a + b) * c`, otherwise we return `0`.
```python
def early_return(a, b, c):
if a > b:
return (a + b) * c
else:
return 0
``` | Implement a Python function `early_return(a, b, c)` that accepts three integers `a`, `b`, and `c`. The function should return the result of the expression `(a + b) * c` if `a` is greater than `b`, otherwise it should return `0`. | You can implement the `early_return` function in Python as follows:
```python
def early_return(a, b, c):
if a > b:
return (a + b) * c
else:
return 0
# Example usage:
result1 = early_return(5, 3, 2) # Should return (5 + 3) * 2 = 16
result2 = early_return(2, 4, 3) # Should return 0
print(resul... | 36,747 |
Here's an example implementation of the `lookup_method()` function:
```python
def lookup_method(obj, name):
for cls in obj.__class__.__mro__:
try:
return getattr(cls, name)
except AttributeError:
continue
return None
```
This function traverses the object's class and i... | Implement a Python function `lookup_method(obj, name)` that takes an object and a method name as input and returns the first method found in the object's class or its base classes, or None if no method with the given name exists. Use the object's `__mro__` attribute to get the list of base classes in the order of metho... | You can implement the `lookup_method` function using the following steps:
1. Access the object's class using `type(obj)`.
2. Use the `__mro__` attribute to get the method resolution order, which gives you a tuple of classes starting from the most specific (the object's class) to the least specific (which is usually `o... | 36,748 |
To convert a string representation of a dictionary into an actual dictionary object, we can use the `ast.literal_eval()` function from the `ast` module. This function can evaluate a string representation of a Python object and return its actual value. For example, if we have the string `'{"key": "value"}'`, we can use ... | Write a Python function that converts a string representation of a dictionary into an actual dictionary object. The string may contain a single dictionary, or several dictionaries separated by a newline character. For example, the input string may look like this:
```python
'{"key1": "value1", "key2": "value2"}\n{"key3... | You can achieve this by using the `json` module in Python, which provides functions to parse JSON strings into Python data structures. Here's a function that does exactly what you need:
```python
import json
from typing import List, Dict, Any
def convert_string_to_dicts(input_string: str) -> List[Dict[str, Any]]:
... | 36,749 |
To write a Python function that takes a positive integer input `seconds` and returns a string that represents the total time elapsed in days, hours, minutes, and seconds, you can follow these steps:
1. Implement a helper function `format_unit` that takes a unit name and value and returns a string of the unit name and ... | Write a Python function `format_time` that takes a positive integer input `seconds` and returns a string that represents the total time elapsed in days, hours, minutes, and seconds. The returned string should follow the pattern "D days, H hours, M minutes, and S seconds". If a unit is zero, it should be omitted from th... | You can create the `format_time` function by calculating the number of days, hours, minutes, and seconds from the total seconds provided. Here's how you can implement it:
```python
def format_time(seconds):
if seconds < 0:
raise ValueError("Input must be a positive integer.")
if seconds == 0:
... | 36,750 |
Here's how we can modify the existing function:
```python
def filter_rows_by_category(df, categories=[]):
if not categories:
return df
return df[df['category'].isin(categories)]
``` | I have an existing function that I want to modify as below to take a `categories` argument that is a list of categories for which to filter results. If `categories` is empty, then the function should behave as before. If `categories` is not empty, then the function should return only rows that match any of the supplied... | To modify your existing function to handle the `categories` argument, we can use the following approach. The function will check if the `categories` list is empty or not. If it is empty, the function will return the original DataFrame. If it contains categories, it will filter the DataFrame based on the specified categ... | 36,751 |
To calculate precision, recall, and F1-score for a binary classifier, we need to consider the following cases:
1. True Positive (TP): The predicted label is 1 and the true label is 1
2. False Positive (FP): The predicted label is 1 but the true label is 0
3. False Negative (FN): The predicted label is 0 but the true l... | Write a Python function to calculate precision, recall, and F1-score for a binary classifier. The input is a `list` of `tuple` objects, where each tuple contains 3 `int`s: the first is the true label, the second is the predicted label, and the third is the weight for that example. The function should return a `dict` wi... | Here's a Python function that calculates precision, recall, and F1-score for a binary classifier from a list of tuples containing true labels, predicted labels, and weights. The function will handle cases where division by zero might occur by using conditional checks.
```python
from typing import List, Tuple, Dict
de... | 36,752 |
To satisfy the functional requirements, the following steps are needed:
1. Handle invalid input: check if the input is a 1D NumPy array. If not, raise an exception.
2. Create an empty boolean array of the same length as the input array.
3. Define the quality criteria: NaN values should be False, values within the spec... | Write a Python function that takes a single input argument: a 1D NumPy array containing the data to be assessed for data quality. The function should return a boolean array of the same length, where each element indicates whether the corresponding data value meets the quality criteria. The criteria are as follows:
- I... | To create a function that assesses the quality of data in a 1D NumPy array based on the specified criteria, you can follow the implementation below:
```python
import numpy as np
def assess_data_quality(data, min_value=-np.inf, max_value=np.inf):
"""
Assess data quality for a given 1D NumPy array.
Par... | 36,753 |
Here is the implementation of the `format_floating_point_number` function:
```python
def format_floating_point_number(value: float) -> str:
formatted_value = f'{value:.3f}'
return f'${formatted_value}'
``` | Write a Python function to format a floating-point number with up to three decimal places and add a '$' sign in front of the number.
Your code should pass the following assertions:
```python
assert format_floating_point_number(40.12345) == '$40.123'
assert format_floating_point_number(50.123456) == '$50.123'
assert fo... | You can create a function called `format_floating_point_number` that formats a floating-point number with up to three decimal places and adds a '$' sign in front of it. Below is the implementation of the function along with the assertions provided:
```python
def format_floating_point_number(number):
# Format the n... | 36,754 |
Here's a possible implementation:
```python
def menu_to_dict(items):
menu_dict = {}
for item in items:
menu_dict[item['id']] = item['title']
return menu_dict
``` | Given a list of dictionaries that represent a menu, write a Python function `menu_to_dict(items)` that converts the list into a dictionary with the key as the `id` and the value as the `title`.
Example list:
```
menu_items = [
{
"id": 10,
"title": "Burger",
"price": 2.5
},
{
... | You can accomplish this task by iterating through the list of dictionaries and constructing a new dictionary where each `id` from the items becomes a key and its corresponding `title` becomes the value. Below is the implementation of the `menu_to_dict` function:
```python
def menu_to_dict(items):
result = {item['i... | 36,755 |
Here is how you could implement the function:
```python
from random import randint
def rand_int_from_zero_to_n_minus_one(n: int) -> int:
"""Generate a random integer between 0 and n-1 (inclusive).
Args:
n (int): The upper bound of the range.
Returns:
int: A random integer between 0 and n... | Write a Python function that takes a single argument `n` (an integer) and returns a random integer between `0` and `n-1` (inclusive). The function should use the `random` module's `randint` function to generate the random number. Type hint the function's argument and return types. Include a docstring with the function'... | Here’s a Python function that meets your requirements:
```python
import random
def get_random_integer(n: int) -> int:
"""Returns a random integer between 0 and n-1 (inclusive).
Args:
n: An integer specifying the range for the random number generation.
Returns:
A random integer be... | 36,756 |
To create a random bounding box within the given dimensions, we can use the random module to generate random coordinates within the image's boundaries. We can also calculate the maximum possible area of the bounding box based on the image's width and height if `max_area` is not provided.
We can validate the input para... | Write a Python function `create_random_bounding_box(width, height, min_area=0, max_area=None)` that takes in the `width` and `height` of an image. Additionally, it has two optional parameters: `min_area` and `max_area`. The function should generate a random bounding box within the given dimensions, ensuring its area is... | Here's a Python function that meets your requirements. The function `create_random_bounding_box` generates a random bounding box within specified dimensions while ensuring its area adheres to the provided constraints. It also includes validation for the input parameters.
```python
import random
def create_random_boun... | 36,757 |
You can use string formatting to achieve the desired output for any number of strings. The string formatting method `format` allows you to insert values into a string at specified placeholder points using curly braces `{<n>}` with an integer `n` representing the argument index.
Here's the Python function `format_strin... | Write a Python function to format a list of `n` strings into a string with each value enclosed in brackets, separated by commas and spaces. The function should take in a single parameter `n`, and generate code for any value of `n`. | Certainly! You can create a Python function that takes a list of strings, formats each string by enclosing it in brackets, and then joins them into a single string with commas and spaces in between. Here's a function that accomplishes that:
```python
def format_strings(string_list):
# Enclose each string in bracke... | 36,758 |
Here's how you could achieve this in Python:
```python
def create_search_function(pattern):
def search_function(text, case_sensitive=False):
if case_sensitive:
return pattern in text
else:
return pattern.lower() in text.lower()
return search_function
``` | Construct a Python function `create_search_function(pattern)` that returns a function that searches for a given pattern within a text string. The function should accept an optional flag to control whether the match should be case-sensitive. You should utilize a functional approach by defining the inner function and ret... | You can achieve this in Python using closures, where the outer function `create_search_function` defines an inner function that performs the search. The inner function should take a string input and check if the pattern exists in that string, respecting the case sensitivity flag.
Here is how you can implement the `cre... | 36,759 |
You can achieve this functionality by first iterating through the list and checking for the target number. If it's found, simply return the index. Otherwise, you can use a `for` loop to iterate through the list again and compare numbers. If the target number is less than the current number, it's the right place to inse... | Design a Python function that takes a list of numbers and a target number as input. If the target number exists in the list, return its index. Otherwise, return the index where the target number would be inserted in the list if it was sorted in ascending order.
Your code should pass the following assertions:
```python... | You can create a function called `search_insert` that achieves this by iterating through the list. If the target number is found, the function returns its index. If the target number is not found, it returns the index where the number would be inserted while keeping the list sorted.
Here's a possible implementation:
... | 36,760 |
To create a Python function decorator that converts the input type to a specific type, let's follow these steps:
1. Define the decorator function: Create a function named `convert_input_type` to take the target function and expected input type as arguments.
2. Define the wrapper function: Inside the decorator function... | Create a Python function decorator named `convert_input_type` that converts the input type to a specific type before calling the function. For example, if the input type is `str`, the decorator should convert the input to a string. | Certainly! Below is an implementation of a Python function decorator named `convert_input_type`. This decorator converts the argument of the decorated function to a specified type before calling the function.
Here's how you can implement it:
```python
def convert_input_type(arg_type):
"""
Decorator to convert... | 36,761 |
To generate all possible index pairs for an `n x n` matrix, we can use nested for loops to iterate over each row and column index and create a tuple of the current indices.
Here's the Python function that accomplishes this task:
```python
def get_index_pairs(n):
"""
Generates all possible index pairs for an n... | Define a Python function `get_index_pairs(n)` that generates all possible index pairs for an `n x n` matrix. The function should return a list of tuples, where each tuple represents an index pair `(i, j)` corresponding to the row and column indices of a matrix element.
For example, `get_index_pairs(3)` should return t... | Certainly! Below is the implementation of the `get_index_pairs` function with a docstring explaining its behavior, input, and output.
```python
def get_index_pairs(n):
"""
Generate all possible index pairs for an n x n matrix.
Args:
n (int): The size of the matrix (n x n).
Returns:
list of tu... | 36,762 |
Here's an example implementation of the function:
```python
import re
def extract_structured_text(document, keys, values):
data = {}
for key, value in zip(keys, values):
matches = re.findall(key, document)
data[value] = matches
return data
``` | Write a Python function to extract structured text from a document and return a dictionary with a list of key-value pairs. The function should take a string input that represents a document, a list of keys to extract, and a list of values that the keys should be mapped to. The function should return a dictionary with t... | Certainly! Below is a Python function that extracts structured text from a document based on specified keys and their corresponding values. Here, we assume the document is made up of lines of text, and each key-value pair can be extracted from these lines.
```python
def extract_structured_text(document: str, keys: lis... | 36,763 |
To implement the desired compression and serialization, I will use two helper functions: `compress_string(s)` and `serialize_and_encode(s)`. The former compresses a string by replacing repeated characters with the format `<count><character>`, while the latter serializes the compressed string into a JSON string and then... | Implement a Python function that compresses a string by replacing each sequence of repeated characters with the format: `<count><character>`, where `count` is the number of repeated occurrences of `character`. For example, the string `'aaaabbccc'` can be compressed as `'4a2b3c'`. Additionally, the function should take ... | To achieve the task of compressing a string and encoding it as specified, we can break down the implementation into a few steps:
1. Compress the string by replacing sequences of repeated characters with the format `<count><character>`.
2. Serialize the compressed string into JSON format.
3. Encode the serialized JSON ... | 36,764 |
To solve this problem, we can use a list comprehension to extract the values from the list. First, we can filter all the values that are not operators. Then, we can extract the values from the remaining nodes.
Here's the Python code for the `extract_node_values` function:
```python
def extract_node_values(nodes):
... | Write a Python function `extract_node_values` that takes a list of operators and operands and returns a list of all the values stored in the nodes. For example, the list `[0, '+', 1, '/', 1]` should return `[0, 1, 1]`. | You can achieve this by creating a function that traverses the provided list and collects all the values that are not operators. Below is the implementation of the `extract_node_values` function:
```python
def extract_node_values(operators_and_operands):
# Define a set of operators for easy checking
operators ... | 36,765 |
Here's an example implementation of the `find_longest_words` function:
```python
def find_longest_words(filename):
with open(filename, 'r') as f:
content = f.read()
words = content.split()
word_lengths = {}
for word in words:
word_lengths[word] = len(word)
longest_words = []
... | Write a Python function `find_longest_words(filename)` that reads the contents of a file, splits the content into individual words, and returns the longest words in the file along with their lengths. The function should take a filename as input and return a list of tuples, where each tuple contains a word and its lengt... | Here's a Python function `find_longest_words(filename)` that accomplishes the task you described:
```python
def find_longest_words(filename):
longest_words = []
max_length = 0
# Open the file and read its contents
with open(filename, 'r') as file:
content = file.read()
# Split... | 36,766 |
Here is the implementation of the function:
```python
def delete_attr(obj, key):
if hasattr(obj, key):
del obj.__dict__[key]
else:
return None
```
In this implementation:
- We first check if the object has the attribute with the given key using the `hasattr` function.
- If the attribute exists... | Create a Python function that takes an object `obj` and a string `key`. The function should delete the attribute of the object with the given key if the attribute is present. If the attribute is not present, the function should return `None`. | You can create a function named `delete_attribute` that takes an object `obj` and a string `key`. The function will check if the attribute represented by `key` exists in `obj`, and if it does, it will delete it. If it does not exist, the function will return `None`. Here is how you can implement this:
```python
def de... | 36,767 |
Here's how you can implement the function:
```python
import random
def random_digits(n):
digits = list(range(0, 10)) # Create a set of all possible digits
sequence = []
for _ in range(n):
digit = random.choice(digits)
sequence.append(digit)
sequence_str = "".join(map(str, sequence))
... | Design a Python function `random_digits` that generates a random sequence of digits of a given length `n`. The sequence must be a string of exactly `n` digits, and each digit can be any value between 0 and 9. The function should generate the sequence randomly, ensuring that each digit has an equal chance of appearing i... | You can create the function `random_digits` using Python's built-in `random` module. The function will generate a string of random digits based on the specified length `n`. Here's how you can implement this:
```python
import random
def random_digits(n):
# Generate a random sequence of n digits
return ''.join(... | 36,768 |
To create a Python function that takes a CLI input string as an argument and returns a Python data structure based on the type of input, you can use the `type()` function to determine the input type and the `ast.literal_eval()` function to convert the input string to a Python data structure. The function should return ... | Create a Python function that takes a command line interface (CLI) input string as an argument and returns a Python data structure based on the type of input. The function should infer the input type based on the provided string and convert it to the appropriate data type. The function's return value should be annotate... | To create a function that parses and converts a Command Line Interface (CLI) input string into the appropriate Python data structure, we can use Python's `ast.literal_eval()` which safely evaluates an expression node or a string containing a Python literal structure. This function will infer the data type based on the ... | 36,769 |
Here's how you can implement this:
```python
import re
def replace_and(text):
pattern = r"\bAND\b"
return re.sub(pattern, "&", text, flags=re.IGNORECASE)
``` | Write a Python function that takes a string and replaces all instances of "AND" with "&". The function should build a regular expression that matches "AND" in any combination of upper and lower case, followed by a space. The function should return the modified string with the replacements made.
Your code should pass t... | You can achieve this by using the `re` module in Python, which allows for regular expression searching and replacing. The following function uses a regular expression to match the string "AND" in a case-insensitive manner, followed by a space, and replaces it with "&".
Here is the implementation of the `replace_and` f... | 36,770 |
Here's a Python implementation of the `are_anagrams` function using the sliding window algorithm:
```python
def are_anagrams(s1, s2):
def normalize(s):
return ''.join(char.lower() for char in s if char.isalnum())
s1 = normalize(s1)
s2 = normalize(s2)
if len(s1) < len(s2):
return False... | Write a Python function `are_anagrams` to check whether two strings are anagrams. A string is an anagram of another if they have the same characters, possibly in a different order. Define a sliding window algorithm that scans through the first string and compares the current window to the second string. If there is a m... | An anagram is a rearrangement of the characters of a string to form another string. Given this, we can implement the sliding window approach to check for anagrams between two strings `s1` and `s2`.
First, we need to ensure that the first string `s1` is longer than or equal to the second string `s2`. If `s1` is shorte... | 36,771 |
Here's how you can implement a `make_hash` function in Python:
```python
import os
import hashlib
def make_hash(file_path):
assert isinstance(file_path, str), "Input must be a string"
key = os.urandom(32)
hasher = hashlib.sha256()
hasher.update(file_path.encode())
return hasher.hexdigest()
```
Th... | Write a Python function `make_hash` that takes a single string argument `file_path` and returns a cryptographic hash string. Your function should be deterministic and have no external dependencies.
The hash string should be encoded with a Unicode encoding, and it should be compatible with the file system encoding, whi... | You can create a cryptographic hash in Python using the built-in `hashlib` module, which provides a way to hash strings using various algorithms like SHA-256. The resulting hash can be encoded to a hexadecimal string representation. Here's a function called `make_hash` that meets your requirements:
```python
import ha... | 36,772 |
To solve this problem, we need to first understand the concept of intervals and how they are represented in Python. An interval, as described in the problem, is a tuple of two numbers in the form of `(start, end)`. For example, the interval `(1, 5)` represents the numbers 1, 2, 3, 4, 5.
Once we have a good understandi... | Write a Python function that takes a list of intervals and converts them into a sequence of numbers in ascending order. An interval is a tuple of two numbers in the form of `(start, end)`. For example, the interval `(1, 5)` represents the numbers 1, 2, 3, 4, 5. The function should preserve the order of intervals as wel... | You can achieve this by defining a function that processes each interval and adds the numbers it covers to a set (to avoid duplicates), and then converts that set to a sorted list. Here's how you could implement such a function:
```python
def merge_intervals(intervals):
if not intervals:
return []
# U... | 36,773 |
You can write a Python function that takes a person's name as an argument and prints a greeting based on their name. The function checks if the name is "John" or "Jane".
If it is either of these, the function prints "Hello, John or Jane!". Otherwise, the function prints "Hi, NAME!", where NAME is the name of the perso... | Develop a Python function `print_greeting` that takes a person's name as a string and prints a greeting based on their name. Include a precondition check to ensure the name is valid (not an empty string).
The function checks if the name is "John" or "Jane".
If it is either of these, print "Hello, John or Jane!".
Oth... | Here's a Python function called `print_greeting` that meets your requirements. It checks if the name is valid (not an empty string), and if the name is "John" or "Jane", it prints a special greeting. For any other name, it prints a general greeting using the `format()` method.
```python
def print_greeting(name: str):
... | 36,774 |
To compute the sum of squared differences between two images, we can use a nested for loop to iterate through each pixel in the images and calculate the difference between the corresponding pixel values. We can then square the difference and add it to a running total to obtain the sum of squared differences.
```python... | Given two images, `img1` and `img2`, which have the same size, write a function `ssd` that returns the sum of squared differences between these two images, where the sum is computed for each pixel. The return value should be an integer.
Use the function signature `ssd(img1, img2)`, where both `img1` and `img2` are two... | To compute the sum of squared differences (SSD) between two images represented as two-dimensional lists, we can create a function `ssd` that iterates through each pixel in the images, calculates the squared difference for each corresponding pixel, and accumulates those values to get the final result.
Here's how you c... | 36,775 |
To write a Python function to calculate the average time per user for a set of user activities, you can follow these steps:
1. Group the user activities by `user_id` using the `groupby()` method.
2. Calculate the average time for each user by taking the sum of the duration of each activity for a given user and dividin... | Write a Python function to calculate the average time per user for a set of user activities. The input is a Pandas DataFrame with columns `user_id` and `duration`. The function should return a DataFrame with columns `user_id` and `avg_duration`. | To calculate the average time per user based on a DataFrame with user activities, you can use the Pandas library in Python. Here is a function that accomplishes this task:
```python
import pandas as pd
def calculate_avg_time_per_user(activity_data):
"""
Calculate the average duration per user from a DataFrame... | 36,776 |
Here's how you can implement this in Python:
```python
def sort_tuples(tuples):
def key_function(t):
return (-t[0], t[1], t[2])
return sorted(tuples, key=key_function)
```
In the custom key function, we return a tuple with the first element being the negative value of `x`, which will be sorted in dec... | Write a Python function that takes as input a list of tuples, each tuple of the form `(x, y, z)`, and returns a sorted list of tuples in lexicographic order based on the values of `x`, `y`, and `z`. The sorting should be done in decreasing order of `x`, followed by increasing order of `y`, and finally by increasing ord... | You can achieve the desired sorting behavior by using the `sorted()` function in Python and providing a custom sorting key. The key will sort the tuples based on the values of `x` (in decreasing order), and then by `y` and `z` (both in increasing order).
Here is the implementation of the function:
```python
def sort_... | 36,777 |
Here's how you can implement this function:
```python
def numbers_in_one_list_but_not_both(list_a, list_b):
set_a = set(list_a)
set_b = set(list_b)
intersection = set_a.intersection(set_b)
only_in_a = set_a.difference(intersection)
only_in_b = set_b.difference(intersection)
result = list(only_i... | Create a Python function that takes two lists of integers and returns a list of integers that exists in only one list, but not in both. For example, given `list_a = [1, 2, 3, 4]` and `list_b = [3, 4, 5, 6]`, the function should return `[1, 2, 5, 6]`. | You can achieve this by using Python's built-in set operations, which allow you to easily find elements that are unique to each list. Here's a function that implements this:
```python
def unique_elements(list_a, list_b):
# Convert lists to sets
set_a = set(list_a)
set_b = set(list_b)
# Find elemen... | 36,778 |
To find all sublists of length `depth` in a given list `lst`, you can iterate through the list, extract sublists of length `depth`, and add them to a list of sublists. To extract sublists of length `depth`, you can use a nested for loop that iterates through the list, starting at each index, extracting the sublist, and... | Write a Python function `find_sublists_from(lst, depth)` that takes a list `lst` and an integer `depth` as inputs, and returns a list of all sublists with a length of `depth` that appear in `lst`. If a sublist is repeated, it should be included multiple times in the result.
Your code should pass the following test cas... | You can create the function `find_sublists_from` in Python to achieve the desired outcome. The function will iterate through the list `lst` and collect all sublists of the specified `depth`. Here's the implementation:
```python
def find_sublists_from(lst, depth):
# Initialize an empty list to store our sublists
... | 36,779 |
Here's the implementation of the function using regular expressions to extract the content of an HTML `<a>` tag and any named groups specified in the `href` attribute:
```python
import re
from urllib.parse import urlparse
def extract_a_tag_content(html_string: str) -> dict:
a_tag_match = re.search(r'<a\s+[^>]*?hr... | Write a Python function to extract the content of an HTML `<a>` tag, including the contents of any named groups specified in the `href` attribute. If no href is specified, return `None`. For example, given `<a href="https://www.example.com/test?query=123">test</a>`, the function should return `{'path': 'https://www.exa... | To extract the contents of an HTML `<a>` tag, including processing the `href` attribute to separate the path and query parameters, we can use Python's `BeautifulSoup` library to handle the HTML parsing and the `urllib.parse` module to extract the query parameters.
Here's the function that accomplishes this:
```python... | 36,780 |
To modify the case of the first letter of each word in a string, we need to iterate through the words in the string and apply the desired case transformation to the first letter of each word.
Here is the implementation of the `change_case_of_first_letter` function:
```python
def change_case_of_first_letter(string: st... | Write a Python function to modify the case of the first letter of each word in a string. The first letter of each word should be capitalized while the rest of the letters should be in lowercase.
Your code should pass the following assertions:
```python
assert change_case_of_first_letter("i am a student") == "I Am A St... | You can achieve the desired functionality by defining a function that processes each word in the input string, capitalizes the first letter, and turns the rest to lowercase. Here's the function you need:
```python
def change_case_of_first_letter(input_string):
# Split the input string into words
words = input_... | 36,781 |
```python
import json
import importlib.resources
def load_dict_from_json(pkg_name, file_name):
try:
with importlib.resources.open_text(pkg_name, file_name) as f:
return json.load(f)
except FileNotFoundError:
raise Exception(f"File not found: {file_name}")
``` | Write a Python function that loads a dictionary from a JSON file and returns it. You must use `importlib.resources` to load the file from the given package. The function should take two arguments: the package name and the file name. If the file cannot be opened, the function should raise an exception. Use a `with` stat... | You can use the `importlib.resources` module to load a JSON file from a specified package and return its contents as a dictionary. Below is an example function that implements this:
```python
import json
import importlib.resources
def load_dict_from_json(package_name, file_name):
"""
Load a dictionary from a ... | 36,782 |
The problem can be solved using recursion and the `os` module. You can follow these steps:
1. Check if the given path is a directory using the `os.path.isdir` function.
2. If it is, loop through all the files and directories inside it using `os.listdir` and call the `remove_empty_directories` function for each entry, ... | Write a Python function `remove_empty_directories` that takes a directory path as an argument and removes all empty directories under that path. The function should recursively check subdirectories, following symlinks if they are present and traversing into them as well. | You can create a function called `remove_empty_directories` that uses the `os` and `os.path` modules to recursively traverse through directories, removing empty ones. To handle symlinks and ensure that we are following them, we can use `os.walk` with the `followlinks=True` option.
Here’s how you can implement this fun... | 36,783 |
To generate the HTML page from the given lists of RGB triples and integers, we need to iterate over both lists simultaneously, and for each RGB triple, we need to generate a colored box with the corresponding width and height. To achieve this, we can use a combination of HTML and CSS to generate the desired output.
We... | Create a Python function that takes a list of RGB triples and a list of integers and generates an HTML page displaying the corresponding colored boxes. The output should follow the following format:
```html
<html>
<head>
<style>
.box {
width: 100px;
height: 100px;
display: inline-bl... | You can create a Python function that generates an HTML page displaying colored boxes based on a list of RGB triples and a list of integers. Below is the implementation of such a function:
```python
def generate_html(rgb_list, box_counts):
html_content = """
<html>
<head>
<style>
.box {
width: ... | 36,784 |
To solve this problem, you can use recursion, a loop, or a combination of both. The idea is to subtract the divisor from the dividend until it becomes smaller than the divisor, and then divide the remaining dividend by the divisor using integer division. If the remainder is not zero, you can concatenate it to the resul... | Write a Python function to divide two non-negative integers without using the division operator. If the divisor is zero, the function should return an error message stating "Invalid divisor: 0". If the divisor is not zero, the function should divide the dividend by the divisor using integer division and return the resu... | Below is a Python function that divides two non-negative integers without using the division operator. It handles the cases where the divisor is zero and correctly formats the output based on whether there is a remainder.
```python
def divide_without_dividing(dividend, divisor):
if divisor == 0:
return "In... | 36,785 |
Here's the Python implementation of the `get_object()` function:
```python
import ast
def get_object(module_path):
with open(module_path) as f:
source = f.read()
tree = ast.parse(source)
data_node = None
for node in ast.walk(tree):
if isinstance(node, ast.Assign) and len(node.targets) ... | I have a user-provided Python module (`.py` file) with a `data` dictionary that I need to extract from. I don't know what the module will be called, but I know that the module name is always the first string in the file. For example, if I have the following file:
```
my_module
data = {...}
```
I want to extract the `... | You can achieve this by reading the contents of the provided Python module file and executing it safely in a controlled environment. You'll want to extract the first line to determine the module name, then use `exec` to evaluate the content of the file and access the `data` dictionary. Below is the implementation of th... | 36,786 |
You can create a Python function to negate a boolean value. This can be achieved by using the `not` operator and checking if the input is a boolean value.
Here's how you could do it:
```python
def negate_boolean(b):
if not isinstance(b, bool):
raise ValueError("The input must be a boolean value!")
ret... | Write a Python function to negate a boolean value. The function should take a single argument `b` and return `not b` when `b` is a boolean value. Otherwise, if `b` is not a boolean value, the function should raise a `ValueError` with the message "The input must be a boolean value!".
Your code should pass the following... | You can implement the function `negate_boolean` as described in your request. Here’s a Python function that checks if the input is a boolean value and returns its negation. If the input is not a boolean, it raises a `ValueError`.
Here's the implementation:
```python
def negate_boolean(b):
if isinstance(b, bool): ... | 36,787 |
To retrieve the name and version of the current operating system and return them as a dictionary, we can leverage the `platform` module from the standard library. The `platform` module provides access to underlying platform information, such as the operating system name, version, and architecture.
In addition to the o... | Design a Python function that retrieves the name and version of the current operating system and returns them as a dictionary. Additionally, if the OS is Linux, the function should also return the distribution name and version. If the OS is Windows, the function should return the release and version. If the OS is macOS... | You can achieve this by using the built-in `platform` module in Python, which provides a way to access various properties of the OS. Below is a function called `get_os_info` that retrieves the name and version of the current operating system, along with additional details based on the specific OS type.
```python
impor... | 36,788 |
To extract the first paragraph from a text, you can use the `split` method with `'\n\n'` as the separator. Then, you can access the first element of the resulting list and return it.
Here's how you can implement this in Python:
```python
def get_first_paragraph(text):
paragraphs = text.split('\n\n')
return pa... | I have a Python program that uses the [GitHub API](https://docs.github.com/en/rest) to access a repository's README file and extract the text. I need to extract only the first paragraph, which is separated by two consecutive line breaks within the text. Can you write a function to help me out?
Your code should pass th... | Certainly! To extract the first paragraph from a given text based on the presence of two consecutive line breaks, you can define a function called `get_first_paragraph`. This function will split the text by the double newline character (`\n\n`) and return the first part. Here’s how you can implement it:
```python
def ... | 36,789 |
To create a function that takes a list of paths to text files and returns a list of dictionaries containing each file's name, number of lines, and number of words, you can follow these steps:
1. Loop over the given list of paths to text files.
2. Open each file and read it line by line to count the number of lines and... | Create a Python function that takes a list of paths to text files and returns a list of dictionaries containing each file's name, number of lines, and number of words. The function should open each file and read it line by line to count the number of lines and words. The resulting dictionary should contain the followin... | Certainly! Below is a Python function that takes a list of paths to text files and returns a list of dictionaries, each containing the file's name, the number of lines, and the number of words:
```python
import os
def analyze_text_files(file_paths):
results = []
for file_path in file_paths:
if os... | 36,790 |
To extract the "keywords" from a JSON file, we can use the `json` module to load the JSON data into a Python dictionary. The "keywords" field is a list of strings, so we can use list comprehension to extract the keywords from the dictionary and return them as a list.
Here's how we can implement this:
```python
import... | Create a Python function to extract the "keywords" from a JSON file. The function should take the file path as input and return a list of keywords.
The "keywords" are a list of strings nested within the "keywords" field in the JSON file. | Certainly! You can create a Python function that reads a JSON file, extracts the "keywords" field, and returns it as a list of strings. Below is a sample implementation:
```python
import json
def extract_keywords_from_json(file_path):
"""
Extracts keywords from a JSON file.
Parameters:
file_path (str... | 36,791 |
To create a Python function `randomize_list_copy` that takes a list and returns a randomly shuffled copy of the list without side effects, you can follow these steps:
1. Copy the list by using a slice method or the `copy` module.
2. Use the `random` module's `shuffle` method to shuffle the copied list in place.
3. Ret... | Create a Python function `randomize_list_copy` that takes a list and returns a randomly shuffled copy of the list. No side effects should occur when calling the function.
Your code should pass the following test case:
```python
lst = [1, 2, 3, 4, 5]
randomized_lst = randomize_list_copy(lst)
assert randomized_lst != ls... | You can achieve this by using the `random.sample` function to create a shuffled copy of the list. The `random.sample` function returns a new shuffled list without modifying the original list. Here's how you can implement the `randomize_list_copy` function:
```python
import random
def randomize_list_copy(lst):
ret... | 36,792 |
To write a Python function that selects certain frames from a list of dicts, we need to iterate through the list and check if the `timestamp` value in each dict is present in the given list of `timestamps`. We can use a list comprehension to create a new list with the selected frames.
To check if the `timestamp` value... | Write a Python function to select certain frames from a list of dicts representing frame-based data, where each dict has `timestamp` and `sensor_data` keys, and the `timestamp` key is an integer. The function should take a list of `timestamps` and return a list of dicts containing only the frames whose timestamps are i... | Certainly! Below is a Python function called `select_frames_by_timestamps` that selects frames from a list of dictionaries based on given timestamps. Each dictionary contains a `timestamp` key and a `sensor_data` key.
```python
def select_frames_by_timestamps(frames, timestamps):
# Convert timestamps to a set for ... | 36,793 |
Here is a Python function that implements this approach:
```python
def get_key_count(dictionary, search_key):
"""
Returns the number of keys in a dictionary that match the specified `search_key`.
"""
count = 0
for key in dictionary:
if key == search_key:
count += 1
return co... | Implement a Python function `get_key_count(dictionary, search_key)` that returns the number of keys with the specified `search_key` in a dictionary. | The task requires implementing a Python function that counts how many times a specified key appears in a given dictionary. However, it's important to note that standard dictionaries in Python do not allow duplicate keys; therefore, a key can either exist once or not at all. This means that the function could only retur... | 36,794 |
Here is the implementation of the `create_anchor_grid` function:
```python
import numpy as np
def create_anchor_grid(image_size, anchor_size):
num_rows = image_size // anchor_size
num_cols = image_size // anchor_size
grid = np.zeros((num_rows, num_cols, 4), dtype=np.float32)
for row in range(num_rows)... | Construct a Python function `create_anchor_grid(image_size, anchor_size)` that creates a grid of anchor boxes given an image size and an anchor size. The anchor boxes should be generated in a 2D grid with the same size as the image, where each anchor box is represented as a tuple of 4 elements: `(x0, y0, x1, y1)`. `(x0... | You can create the function `create_anchor_grid` as follows. This function will generate anchor boxes on a grid with the specified image size and anchor size:
```python
def create_anchor_grid(image_size, anchor_size):
"""
Create a grid of anchor boxes given an image size and anchor size.
Parameters:
i... | 36,795 |
To solve this problem, we can write a function that takes the length and unit as input, and returns the converted length in centimeters. We can first parse the docstring to extract the unit, and then use a dictionary of unit conversions to convert the length to centimeters.
Here is a Python function that implements th... | Write a Python function `convert_length_to_centimeters` that converts the length unit given in the docstring's first line to centimeters. The docstring should be in the format:
```
'''
Length in <unit>.
'''
```
For example, given the docstring:
```
'''
Length in m.
'''
```
The function should return the length conv... | To create the function `convert_length_to_centimeters`, we will define a function that reads the length unit from its docstring and converts the provided length value based on the unit. We will handle common length units such as meters (m), kilometers (km), centimeters (cm), millimeters (mm), inches (in), and feet (ft)... | 36,796 |
To implement a Python function that takes a single argument that is a list of objects with a `type` attribute and returns a new list of objects that are of the same type as the input, you can follow these steps:
1. Check if the input is a list.
2. Iterate through the input list and get the type of each object in the l... | Implement a Python function that takes a single argument that is a list of objects with a "type" attribute. The function should return a new list of objects that are of the same type as the input.
For example, given a list of `['a', 'b', 'c']`, the function should return a new list of `[<class 'str'>, <class 'str'>, <... | You can implement a Python function that takes a list of objects, extracts their types, and returns a new list containing the type of each object. Here is how you can do it:
```python
def extract_types(objects):
return [type(obj) for obj in objects]
# Example usage:
input_list = ['a', 'b', 'c']
output_list = extr... | 36,797 |
```python
def is_power_of_two(n):
if n == 0:
return False
return (n & (n - 1)) == 0
def power_of_two(n):
if not is_power_of_two(n):
return -1
power = 0
while n != 1:
n >>= 1
power += 1
return power
```
The `is_power_of_two` function uses the bitwise AND operator... | Write a fast Python function to check whether a given positive integer is a power of two. If it is, calculate the power (i.e., the number of times the integer must be divided by 2 before reaching 1). If it is not a power of two, return -1. | You can check if a positive integer is a power of two and calculate the associated exponent efficiently using bit manipulation. Here is a Python function that accomplishes this:
```python
def is_power_of_two(n):
if n <= 0:
return -1 # not a positive integer
# Check if n is a power of two using bi... | 36,798 |
Here is the code:
```python
def pixel_to_color(pixel):
red, green, blue = pixel
if red == 255 and green == 0 and blue == 0:
return "Red"
elif green == 255 and red == 0 and blue == 0:
return "Green"
elif blue == 255 and red == 0 and green == 0:
return "Blue"
elif red == 255 ... | Write a Python function that takes an RGB pixel and returns a color name. Use the following table to determine the color name based on the pixel's saturation.
| Color name | Saturation range |
| ---------- | ---------------- |
| Red | (255, 0, 0) to (255, 255, 255) |
| Green | (0, 255, 0) to (255, 255, 255) |
| Blue |... | To create a Python function `pixel_to_color` that returns the name of a color based on the RGB pixel value, we need to check which color the pixel falls into according to the saturation ranges defined in your table.
Here's the function:
```python
def pixel_to_color(pixel):
r, g, b = pixel
if r == 255 and g ... | 36,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.