response_seed stringlengths 53 5.17k | instruction_seed stringlengths 29 4.02k | response stringlengths 121 11.9k | __original_row_idx int64 0 50k | conversations listlengths 2 2 |
|---|---|---|---|---|
Here is a Python function that uses a try-except block to handle the error scenario:
```python
import json
def request_api_data(url: str) -> dict:
"""
Makes an API request to the provided URL and returns the response as a Python
dictionary. If there is any error, an empty dictionary is returned.
"""
... | Write a Python function to request data from an API endpoint and return the response as a Python dictionary. If there is any error in the response, the function should return an empty dictionary. | Certainly! Below is a Python function that requests data from a specified API endpoint. It handles potential errors during the request and will return the response as a Python dictionary if successful; otherwise, it will return an empty dictionary.
We will use the `requests` library, so make sure you have it installed... | 37,000 | [
{
"from": "human",
"value": "Write a Python function to request data from an API endpoint and return the response as a Python dictionary. If there is any error in the response, the function should return an empty dictionary."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function th... |
```python
def prefix_dict(d, prefix):
return dict(map(lambda item: (f"{prefix}{item[0]}", item[1]), d.items()))
``` | Write a function in Python that takes a dictionary as input and returns a new dictionary with keys constructed by concatenating a prefix to each existing key in the input dictionary. The function should also support custom data models for the input dictionary and the returned dictionary. The function should also suppor... | Certainly! Below is a Python function that meets your requirements. The function takes a dictionary, a prefix, a function to convert the input data model (if needed), and a function to convert the output data model (if needed). Here's how you can structure it:
```python
def transform_dict(input_dict, prefix, input_con... | 37,001 | [
{
"from": "human",
"value": "Write a function in Python that takes a dictionary as input and returns a new dictionary with keys constructed by concatenating a prefix to each existing key in the input dictionary. The function should also support custom data models for the input dictionary and the returned di... |
Here is the Python function:
```python
def run_save(items):
saved_items = []
for item in items:
if item.save():
saved_items.append(item)
return saved_items
``` | Write a Python function to run a method `save()` on all items in a list of objects `items`. The `items` list is actually a list of `Data` objects, each of which has a `save()` method. The function should return a list of all the objects that were successfully saved. | You can create a function that iterates through a list of `Data` objects and calls their `save()` method. You'll want to keep track of the objects that were saved successfully. Typically, to determine success, you might have the `save()` method return a boolean indicating whether the save was successful or raise an exc... | 37,002 | [
{
"from": "human",
"value": "Write a Python function to run a method `save()` on all items in a list of objects `items`. The `items` list is actually a list of `Data` objects, each of which has a `save()` method. The function should return a list of all the objects that were successfully saved."
},
{
... |
To extract the function number from a given text using regular expressions, we can use the following steps:
1. Define a regular expression to match the function number pattern: `r'function\s*\((\d+)\)'`. This expression looks for the word "function" followed by zero or more whitespace characters, then an opening paren... | Design a Python function `extract_function_number(text)` that takes a string `text` and extracts the function number defined in the text using regular expressions. The function number is defined as a number that appears within parentheses after the word "function" in the text. The function should return the extracted n... | You can achieve this by using the `re` module in Python, which provides support for regular expressions. Below is a Python function `extract_function_number(text)` that implements the desired functionality:
```python
import re
def extract_function_number(text):
# Define the regular expression pattern to match the... | 37,003 | [
{
"from": "human",
"value": "Design a Python function `extract_function_number(text)` that takes a string `text` and extracts the function number defined in the text using regular expressions. The function number is defined as a number that appears within parentheses after the word \"function\" in the text.... |
To extract the IDs from a URL path, you need to identify the part of the path that contains the IDs. You can use a regular expression to identify the ID pattern, "id=xxxx" in the URL. The regular expression can be defined as "id=[0-9]+" to match the ID pattern followed by one or more digits.
Here is how you can extrac... | Write a Python function named `extract_ids_from_url` that extracts the IDs from a URL path and returns them as a list.
Input: A URL string, and the expected ID format is "id=xxxx", where "xxxx" is the ID value.
Output: A list of ID values.
Example:
Input URL: "https://example.com/page/id=123/id=456"
Output: ['123'... | You can extract IDs from a URL path by using regular expressions in Python. Below is a function named `extract_ids_from_url` that accomplishes this task:
```python
import re
def extract_ids_from_url(url):
# Use a regular expression to find all occurrences of "id=xxxx"
pattern = r'id=(\d+)'
# Find all matc... | 37,004 | [
{
"from": "human",
"value": "Write a Python function named `extract_ids_from_url` that extracts the IDs from a URL path and returns them as a list.\n\nInput: A URL string, and the expected ID format is \"id=xxxx\", where \"xxxx\" is the ID value.\n\nOutput: A list of ID values.\n\nExample:\n\nInput URL: \"h... |
```python
def letter_frequencies(string):
"""Return a dictionary containing the frequency of each letter in the string.
Args:
string (str): The input string.
Returns:
dict: A dictionary containing the frequency of each letter in the string.
"""
frequencies = {}
for letter in st... | Write a Python function that takes a Unicode string and returns a dictionary containing the frequency of each letter in the string. The keys of the dictionary should be the letters themselves, and the values should be the corresponding frequencies.
Here is an example input/output:
Input: 'hello'
Output: { 'h': 1, 'e'... | Here is a Python function that calculates the frequency of each letter in a given Unicode string. The function meets your requirements and passes the provided assertions:
```python
def letter_frequencies(s):
"""
Calculate the frequency of each letter in a given Unicode string.
Args:
s (str): The i... | 37,005 | [
{
"from": "human",
"value": "Write a Python function that takes a Unicode string and returns a dictionary containing the frequency of each letter in the string. The keys of the dictionary should be the letters themselves, and the values should be the corresponding frequencies.\n\nHere is an example input/ou... |
Here is the implementation of the function:
```python
def csv_to_string(csv_list):
return ' '.join([val.replace(',', ' ') for csv in csv_list for val in csv.split(',')])
``` | Develop a Python function that takes a list of comma-separated values (CSV) strings and returns a string containing the same values in a different format. The function should first separate values in each CSV string by removing the comma and then concatenate them with a space.
For instance, given the list `['a,b,c', '... | You can create a Python function called `csv_to_string` that processes a list of CSV strings, removes the commas, and concatenates the resulting values with spaces. Below is a sample implementation of that function, along with the passing assertions you provided:
```python
def csv_to_string(csv_list):
# Initialize... | 37,006 | [
{
"from": "human",
"value": "Develop a Python function that takes a list of comma-separated values (CSV) strings and returns a string containing the same values in a different format. The function should first separate values in each CSV string by removing the comma and then concatenate them with a space.\n... |
Here is the implementation of the Python function using the `glob` module:
```python
import glob
def list_files_matching_pattern(directory_path, pattern):
return glob.glob(f"{directory_path}/{pattern}")
``` | Write a Python function to list all files under a directory that match a given wildcard pattern, such as `*.txt`. The function should return a list of matched file names. | To list all files under a directory that match a given wildcard pattern such as `*.txt`, you can use the `fnmatch` module along with the `os` or `pathlib` module in Python. Here's a Python function that does just that:
```python
import os
import fnmatch
def list_files_with_pattern(directory, pattern):
matched_fil... | 37,007 | [
{
"from": "human",
"value": "Write a Python function to list all files under a directory that match a given wildcard pattern, such as `*.txt`. The function should return a list of matched file names."
},
{
"from": "gpt",
"value": "To list all files under a directory that match a given wildcard p... |
Here is a Python function that implements this approach:
```python
def get_string_lengths(strings):
if len(strings) == 0:
return []
else:
return [len(string) for string in strings]
```
This implementation uses a list comprehension to iterate over each string in the input list and append its le... | Given a list of strings, return a list of integers representing the length of each string. If the input list is empty, return an empty list.
Your code should pass the following assertions:
```python
assert get_string_lengths([]) == []
assert get_string_lengths(["a", "bb", "ccc"]) == [1, 2, 3]
``` | You can achieve this by defining a function `get_string_lengths` that takes a list of strings as input and returns a list of their lengths. You can use a list comprehension to iterate through the strings and apply the `len()` function to each one. Below is the implementation of the function:
```python
def get_string_l... | 37,008 | [
{
"from": "human",
"value": "Given a list of strings, return a list of integers representing the length of each string. If the input list is empty, return an empty list.\n\nYour code should pass the following assertions:\n```python\nassert get_string_lengths([]) == []\nassert get_string_lengths([\"a\", \"bb... |
To implement the `get_timezone_from_user_input` function, we will need to use the `pytz` library, which provides a collection of timezones and their corresponding identifiers. We will check if the user-provided timezone string matches any of the valid identifiers in the `pytz` library, and if it does, we will return th... | Write a Python function `get_timezone_from_user_input` that parses a user-provided timezone string and returns the corresponding timezone object. The function should accept a string as input and return a `pytz.timezone` object if the input matches a valid timezone identifier. If the input is invalid, the function shoul... | To create the function `get_timezone_from_user_input`, we need to use the `pytz` library, which provides access to the time zone database and allows for time zone conversions. Below is the implementation of the function that checks if the user-provided string corresponds to a valid timezone identifier and returns the c... | 37,009 | [
{
"from": "human",
"value": "Write a Python function `get_timezone_from_user_input` that parses a user-provided timezone string and returns the corresponding timezone object. The function should accept a string as input and return a `pytz.timezone` object if the input matches a valid timezone identifier. If... |
You can achieve this functionality by first splitting the input string using the `split()` method, converting each element to an integer using `int()`, and filtering out invalid inputs by using the `all()` function. Then, you can use a list comprehension to return a comma-separated string of the odd numbers within the ... | Write a Python function that takes a string of comma-separated integers, and returns a comma-separated string of the odd numbers within the range specified by the integers. The string should be sorted in ascending order. Ensure the function handles invalid data and filters out invalid inputs. For example, given `"1,2,3... | Certainly! Below is a Python function that accomplishes what you need. It takes a string of comma-separated integers, filters out invalid inputs, identifies the odd numbers, and returns them as a sorted comma-separated string:
```python
def filter_odd_numbers(input_string):
try:
# Split the input string by... | 37,010 | [
{
"from": "human",
"value": "Write a Python function that takes a string of comma-separated integers, and returns a comma-separated string of the odd numbers within the range specified by the integers. The string should be sorted in ascending order. Ensure the function handles invalid data and filters out i... |
Here is a Python function that implements this approach:
```python
def humanize_duration(duration):
seconds = duration % 60
minutes = (duration // 60) % 60
hours = (duration // 3600) % 24
days = (duration // 86400)
return f'{days} days, {hours} hours, {minutes} minutes, {seconds} seconds'
``` | Create a Python function `humanize_duration(duration)` that takes an integer argument `duration` representing the number of seconds, and returns a human-readable string representation of the duration. The string should follow the format "{#d} days, {#h} hours, {#m} minutes, {#s} seconds", where {#d}, {#h}, {#m}, and {#... | You can create a function `humanize_duration` to convert a duration in seconds into a human-readable string format. Below is an implementation that meets the specified requirements:
```python
def humanize_duration(duration):
# Calculate the number of days, hours, minutes, and seconds
days = duration // (24 * 3... | 37,011 | [
{
"from": "human",
"value": "Create a Python function `humanize_duration(duration)` that takes an integer argument `duration` representing the number of seconds, and returns a human-readable string representation of the duration. The string should follow the format \"{#d} days, {#h} hours, {#m} minutes, {#s... |
Here is a Python implementation of the solution:
```python
def sum_in_array(numbers, target):
complements = set()
for number in numbers:
if number in complements:
return True
complements.add(target - number)
return False
``` | Determine whether a given array/list of integers contains two elements that sum to a given number. Return a boolean value indicating the presence of such a pair.
Optimize your solution by avoiding unnecessary comparisons and by utilizing appropriate data structures to store and search for the complementary values. | To determine whether a given array of integers contains two distinct elements that sum to a specified target value, we can utilize a set to store the numbers we've seen so far as we iterate through the array. This allows us to check for the existence of the complementary value (i.e., `target - current_number`) in const... | 37,012 | [
{
"from": "human",
"value": "Determine whether a given array/list of integers contains two elements that sum to a given number. Return a boolean value indicating the presence of such a pair.\n\nOptimize your solution by avoiding unnecessary comparisons and by utilizing appropriate data structures to store a... |
To compare two range objects `range1` and `range2`, you can:
1. Get the start and end values of each range using the `start` and `stop` attributes of the range objects.
2. Compare the start and end values of each range to determine if they overlap, are entirely before, or are entirely after.
Here's an example impleme... | Write a Python function `compare_ranges` that takes two arguments: `range1` and `range2`. Both arguments are range objects, which are Python objects used to define and iterate over a range of integers. Your function should return -1 if `range1` is entirely before `range2`, 0 if they overlap, and 1 if `range1` is entire... | You can create the `compare_ranges` function in Python to compare two range objects. Here's how you can implement it:
```python
def compare_ranges(range1, range2):
"""
Compare two range objects.
Args:
- range1: A range object
- range2: A range object
Returns:
- -1 if range1 is entirel... | 37,013 | [
{
"from": "human",
"value": "Write a Python function `compare_ranges` that takes two arguments: `range1` and `range2`. Both arguments are range objects, which are Python objects used to define and iterate over a range of integers. Your function should return -1 if `range1` is entirely before `range2`, 0 if ... |
Here's how you can implement this:
```python
import re
def extract_ip_and_port(url):
pattern = r'^(?:http|https)://([0-9\.]+):([0-9]+)$'
match = re.findall(pattern, url)
if match:
return match[0]
return None
``` | Write a Python function to extract the IP address and port from a URL string, assuming the URL is of the format `http://<IP_address>:<port>` or `https://<IP_address>:<port>`. Use regular expressions to extract the IP address and port from the URL and return them as a tuple. If the URL does not match the expected format... | You can achieve this using Python's `re` module for regular expressions. The function will check the format of the URL and extract the IP address and port if the format is correct. Here's the implementation:
```python
import re
def extract_ip_and_port(url):
# Regular expression pattern to match the URL format
... | 37,014 | [
{
"from": "human",
"value": "Write a Python function to extract the IP address and port from a URL string, assuming the URL is of the format `http://<IP_address>:<port>` or `https://<IP_address>:<port>`. Use regular expressions to extract the IP address and port from the URL and return them as a tuple. If t... |
Here is a possible solution in Python:
```python
from typing import List, Optional
def max_product_of_three(numbers: List[int]) -> Optional[int]:
if len(numbers) < 3:
return None
largest_three = [-float('inf'), -float('inf'), -float('inf')]
for number in numbers:
if number > largest_three... | Create a Python function `max_product_of_three` that accepts a list of integers and returns the maximum product of any three elements. The function should accept a typed `List[int]` as its argument and return a `int`. If the input list has fewer than three elements, return `None`.
```python
assert max_product_of_three... | To create the function `max_product_of_three` that calculates the maximum product of any three elements in a list of integers, we will follow these steps:
1. Check if the input list has fewer than three elements. If so, return `None`.
2. Sort the list of integers to efficiently find the candidates for the maximum prod... | 37,015 | [
{
"from": "human",
"value": "Create a Python function `max_product_of_three` that accepts a list of integers and returns the maximum product of any three elements. The function should accept a typed `List[int]` as its argument and return a `int`. If the input list has fewer than three elements, return `None... |
Here is a Python function that takes a classification number as input and returns the corresponding classification description:
```python
classifications = {
"K.1.0": "Digital libraries",
"K.2.0": "Digital libraries",
"K.3.0": "Digital libraries",
"K.4.0": "Digital libraries",
"K.5.0": "Digital lib... | In the ACM classification system, the first digit denotes the general field, the second digit denotes the specific field, and the third digit denotes the topic. The fourth digit indicates the level of detail. Given an ACM classification number, can you write a Python function that takes a string representing the classi... | To implement the function `get_classification_description`, we need a predefined dictionary that maps the ACM classification numbers to their corresponding descriptions. Based on the examples you've provided, it looks like we need to return just the description related to the classification number without the classific... | 37,016 | [
{
"from": "human",
"value": "In the ACM classification system, the first digit denotes the general field, the second digit denotes the specific field, and the third digit denotes the topic. The fourth digit indicates the level of detail. Given an ACM classification number, can you write a Python function th... |
Here's an implementation of a Python function that takes in a POST request object and returns a corresponding form object:
```python
from typing import Optional
class HTMLForm():
def __init__(self, html_content):
self.html_content = html_content
class EmptyForm():
def __init__(self):
self.htm... | Write a Python function that takes in a POST request object and returns a corresponding form object. If the POST request contains a "form" parameter that contains the form's HTML content, the function should return an HTMLForm object. If the POST request is empty, the function should return an EmptyForm object. | To achieve this functionality in Python, we can create a function that checks the contents of a POST request object to determine if it contains a "form" parameter with HTML content. The function will return an instance of an `HTMLForm` class if the form content is present, or an `EmptyForm` object if the request does n... | 37,017 | [
{
"from": "human",
"value": "Write a Python function that takes in a POST request object and returns a corresponding form object. If the POST request contains a \"form\" parameter that contains the form's HTML content, the function should return an HTMLForm object. If the POST request is empty, the function... |
To calculate the probability of a given number of coin flips resulting in k heads, we need to use the binomial coefficient formula `nCk` to find the number of ways to choose k heads from n flips (without replacement), and then multiply the result by the probability of getting a head on each flip, which is 1/2.
Here's ... | Write a Python function to calculate the probability of a given number (n) of coin flips resulting in k heads, where n and k are integer numbers and n >= k. The probability is calculated using the following formula:
```
P(n, k) = nCk * (1/2)^n
```
This formula combines the binomial coefficient `nCk` (the number of wa... | You can calculate the probability of getting `k` heads in `n` coin flips using the formula provided. The binomial coefficient `nCk` can be calculated using the `math` module in Python which provides a convenient function called `comb`. Here's how you can implement the `probability_n_k` function:
```python
import math
... | 37,018 | [
{
"from": "human",
"value": "Write a Python function to calculate the probability of a given number (n) of coin flips resulting in k heads, where n and k are integer numbers and n >= k. The probability is calculated using the following formula:\n\n```\nP(n, k) = nCk * (1/2)^n\n```\n\nThis formula combines t... |
Here's how you can implement this function:
```python
def count_item_occurrences(lst):
counts = {}
for item in lst:
if item in counts:
counts[item] += 1
else:
counts[item] = 1
return counts
```
The function `count_item_occurrences` takes a list as an argument and re... | Implement a function to count the number of times each item appears in a list and return a dictionary mapping the item to its count. For example, given list `[1, 1, 2, 3, 3, 3]`, the function should return `{1: 2, 2: 1, 3: 3}`. If an element appears more than once, add the count to the existing item in the dictionary. ... | You can implement the function to count the occurrences of each item in a list using a dictionary. Below is a Python function that accomplishes this:
```python
def count_items(lst):
counts = {}
for item in lst:
if item in counts:
counts[item] += 1
else:
counts[item] = 1
... | 37,019 | [
{
"from": "human",
"value": "Implement a function to count the number of times each item appears in a list and return a dictionary mapping the item to its count. For example, given list `[1, 1, 2, 3, 3, 3]`, the function should return `{1: 2, 2: 1, 3: 3}`. If an element appears more than once, add the count... |
Here is the implementation of the function:
```python
from typing import List
import numpy as np
def encode_spike_timings(spike_timings: List[List[float]], bin_size: float) -> np.ndarray:
"""
Encode a list of spike timings in a 2D tensor fashion.
Args:
spike_timings (List[List[float]]): A list o... | Write a Python function to encode a list of spike timings in a 2D tensor fashion. The function takes two arguments: `spike_timings`, a list of lists, where each list contains the spike timings for a single neuron; and `bin_size`, a float indicating the size of each time bin, in milliseconds. The function should return ... | Here's a Python function that encodes a list of spike timings into a 2D tensor format. The function accepts the spike timings and a bin size as inputs and returns a 2D array (using NumPy for efficient numerical operations). Each row corresponds to a neuron, and each column corresponds to a time bin, with the values ind... | 37,020 | [
{
"from": "human",
"value": "Write a Python function to encode a list of spike timings in a 2D tensor fashion. The function takes two arguments: `spike_timings`, a list of lists, where each list contains the spike timings for a single neuron; and `bin_size`, a float indicating the size of each time bin, in ... |
Here is the implementation of the `fibonacci_while_loop` function with a while loop and variable swap:
```python
def fibonacci_while_loop(n):
if n < 1:
return -1
a = 0
b = 1
while n > 1:
a, b = b, a + b
n -= 1
return b
``` | Write a Python function `fibonacci_while_loop` that returns the nth Fibonacci number using a while loop. The function should have a single parameter `n` that represents the index of the desired Fibonacci number. The function should check for valid input and return -1 if the input is not a positive integer. The function... | Certainly! Below is the implementation of the `fibonacci_while_loop` function in Python that adheres to your specifications. It checks for valid input, uses a while loop to calculate the Fibonacci number iteratively, and utilizes variable swapping for efficiency.
```python
def fibonacci_while_loop(n):
# Check if t... | 37,021 | [
{
"from": "human",
"value": "Write a Python function `fibonacci_while_loop` that returns the nth Fibonacci number using a while loop. The function should have a single parameter `n` that represents the index of the desired Fibonacci number. The function should check for valid input and return -1 if the inpu... |
Here's how you can implement this:
```python
def parse_paragraph(paragraph):
words = paragraph.split()
sentences = []
current_sentence = []
for word in words:
current_sentence.append(word)
if word.endswith('.') and (word[-2].isalpha() or word[-2].isdigit() or word[-2].isspace()):
... | Write a Python function to parse a paragraph of text into a list of sentences, where each sentence is a list of words. The function should support the following cases:
- Periods followed by a letter (e.g., "Mr. X" or "Dr. Y")
- Periods followed by a digit (e.g., "12.34" or "56.78")
- Periods followed by a white space ... | To achieve the parsing of a paragraph into a list of sentences, we can utilize regular expressions to carefully split sentences while accounting for periods in various contexts. Here's a Python function that handles the specified requirements:
```python
import re
def parse_paragraph(paragraph):
# Regular expressi... | 37,022 | [
{
"from": "human",
"value": "Write a Python function to parse a paragraph of text into a list of sentences, where each sentence is a list of words. The function should support the following cases:\n\n- Periods followed by a letter (e.g., \"Mr. X\" or \"Dr. Y\")\n- Periods followed by a digit (e.g., \"12.34\... |
In order to find the first occurrence of a substring `sub` in a string `s` using a linear search algorithm, the following steps are required:
1. The function `linear_search_substring` should accept two arguments: `s` and `sub`.
2. The function should iterate over the characters in `s` using a for loop.
3. For each cha... | Write a Python function to find the first occurrence of a substring in a string using a linear search algorithm. The function should take two arguments: `s` for the string, and `sub` for the substring to find. It should return the index of the first occurrence of `sub` in `s` if found, otherwise return -1. | Certainly! Here's a Python function that implements a linear search algorithm to find the first occurrence of a substring in a string:
```python
def find_substring(s, sub):
# Get lengths of the main string and the substring
len_s = len(s)
len_sub = len(sub)
# If the substring is longer than the string... | 37,023 | [
{
"from": "human",
"value": "Write a Python function to find the first occurrence of a substring in a string using a linear search algorithm. The function should take two arguments: `s` for the string, and `sub` for the substring to find. It should return the index of the first occurrence of `sub` in `s` if... |
To remove control characters from a Unicode string, you can use the `str.maketrans` method to create a character translation table that maps control characters to `None`. The `str.translate` method can then be used to perform the translation on the original string. Here's how you can do it:
```python
def remove_contro... | Write a Python function to remove control characters from a Unicode string. Use the `str.maketrans` method to create a character translation table that maps control characters to `None`.
Your code should pass the following assertions:
```python
assert remove_control_chars("\x00\x01\x02\x03\x04\x05\x06\x07") == ""
asse... | To remove control characters from a Unicode string using the `str.maketrans` method, you can create a translation table that maps all control characters to `None`. Control characters in Unicode are those with Unicode code points less than 32 (and also 127, which is the "delete" control character).
Here’s how to write ... | 37,024 | [
{
"from": "human",
"value": "Write a Python function to remove control characters from a Unicode string. Use the `str.maketrans` method to create a character translation table that maps control characters to `None`.\n\nYour code should pass the following assertions:\n```python\nassert remove_control_chars(\... |
You can use the `zipfile` module to create an archive from a directory using the `ZipFile.write` method. This method takes a directory and recursively adds all files and directories inside it.
Here's how you could implement the `create_archive_from_dir` function:
```python
import os
import zipfile
def create_archive... | Write a Python function `create_archive_from_dir` that takes two arguments: `directory`, a directory path, and `archive_name`, the name of the resulting archive file. The function should create an archive (e.g., zip or tar.gz) from all files and directories in the specified directory. | Certainly! Below is a Python function `create_archive_from_dir` that creates an archive from the contents of the specified directory. It accepts two parameters: `directory` (the path of the directory to archive) and `archive_name` (the name of the resulting archive file). The function will create a zip file, but you ca... | 37,025 | [
{
"from": "human",
"value": "Write a Python function `create_archive_from_dir` that takes two arguments: `directory`, a directory path, and `archive_name`, the name of the resulting archive file. The function should create an archive (e.g., zip or tar.gz) from all files and directories in the specified dire... |
Here is an example of how you could implement a Python function that takes a JSON file path and returns a list of products with a price lower than or equal to a specific maximum price:
```python
import json
def get_products_with_price_less_than_or_equal_to(json_file_path, max_price):
with open(json_file_path, 'r'... | I have a JSON file containing information about products sold on an online store. The JSON file is organized as a list of dictionaries, where each dictionary represents a product. Here is an example of a product dictionary:
```json
{
"id": 72,
"name": "",
"price": 43.23,
"stock": 100,
"description": "A produc... | You can achieve this by creating a Python function that reads the JSON file, parses the data, and filters the products based on the specified maximum price. Here's a sample implementation of that function:
```python
import json
def filter_products_by_price(json_file_path, max_price):
"""
Filters products from... | 37,026 | [
{
"from": "human",
"value": "I have a JSON file containing information about products sold on an online store. The JSON file is organized as a list of dictionaries, where each dictionary represents a product. Here is an example of a product dictionary:\n```json\n{\n \"id\": 72,\n \"name\": \"\",\n \"pric... |
To accomplish this task, we can count the occurrences of a given number in the array and calculate the percentage of the occurrences. However, we need to ensure that we are handling floating-point numbers correctly and do not use built-in functions like `sum()` or `len()`.
Here's how we can implement this:
```python
... | I want to write a Python function that returns the percentage (with one decimal point) of a number in an array of numbers, where the number is found in the array of numbers. If the number is not found in the array, the function should return 0.
Here is the function signature:
```python
def percentage_of_array(array, ... | Sure! Below is a Python function `percentage_of_array` that calculates the percentage of a specified number in an array of numbers, following your requirements. It avoids using built-in functions like `sum()` and `len()`.
Here's how the function works:
1. It iterates through the array to count the occurrences of the s... | 37,027 | [
{
"from": "human",
"value": "I want to write a Python function that returns the percentage (with one decimal point) of a number in an array of numbers, where the number is found in the array of numbers. If the number is not found in the array, the function should return 0.\n\nHere is the function signature:... |
Here is the implementation of the `abs_val` function:
```python
import math
def abs_val(x):
if isinstance(x, complex):
real_abs = abs(x.real)
imag_abs = abs(x.imag)
abs_val = math.sqrt(real_abs**2 + imag_abs**2)
elif isinstance(x, (int, float)):
abs_val = abs(x)
else:
... | Implement a Python function `abs_val` to calculate the absolute value of an input `x` of arbitrary type (including negative and positive integers, floats, and complex numbers). Use the following algorithm to compute the absolute value:
1. If `x` is negative, multiply it by -1 to get its positive value.
2. `abs_val` sh... | To implement the `abs_val` function according to the specified algorithm, we need to handle several types of inputs: integers, floats, complex numbers, and any non-numeric types. The absolute value for floating-point numbers and integers can be straightforwardly obtained, while complex numbers require calculating their... | 37,028 | [
{
"from": "human",
"value": "Implement a Python function `abs_val` to calculate the absolute value of an input `x` of arbitrary type (including negative and positive integers, floats, and complex numbers). Use the following algorithm to compute the absolute value:\n\n1. If `x` is negative, multiply it by -1... |
Here is how you could implement such a function:
```python
def parse_complex(complex_str: str) -> complex or None:
real_imag_parts = complex_str.split("+")
if len(real_imag_parts) != 2 or not real_imag_parts[1].endswith("i"):
return None
real_part = real_imag_parts[0]
imaginary_part = real_imag... | Implement a Python function `parse_complex` that takes a string as input and returns a complex number, given the convention that a complex number is represented as `real + imaginary`, where the `real` and `imaginary` parts are both integers or floats. For example, `parse_complex('3+4i')` should return `3 + 4j`, and `pa... | To implement the `parse_complex` function that extracts real and imaginary parts from a given string and returns a complex number in Python, we will:
1. Use regular expressions to identify valid complex number formats.
2. Convert the extracted real and imaginary parts into floats or integers as appropriate.
3. Return ... | 37,029 | [
{
"from": "human",
"value": "Implement a Python function `parse_complex` that takes a string as input and returns a complex number, given the convention that a complex number is represented as `real + imaginary`, where the `real` and `imaginary` parts are both integers or floats. For example, `parse_complex... |
Here is how you could implement a function to summarize a text file:
```python
def summarize_text_file(text_file):
with open(text_file, 'r') as file:
summaries = []
order = 1
line = file.readline()
while line:
if line.startswith('S'):
summaries.append((or... | I'm writing a function to summarize a text file.
The text file contains sentences, each on a new line, with the first character of each sentence indicating whether the sentence is a summary `S`, a non-summary `N`, or neither `E`.
I want to return the sentences that are summaries and their order in the original text f... | You can write a Python function to process the text file and return the summary sentences along with their original order. Here's a sample implementation of such a function:
```python
def summarize_text_file(file_path):
# List to hold summary sentences
summary_sentences = []
# Open and read the text f... | 37,030 | [
{
"from": "human",
"value": "I'm writing a function to summarize a text file.\n\nThe text file contains sentences, each on a new line, with the first character of each sentence indicating whether the sentence is a summary `S`, a non-summary `N`, or neither `E`.\n\nI want to return the sentences that are sum... |
We can use the bitwise `AND` operator (`&`) to check if a bit mask is present in a byte. To do this, we first convert the `byte` and `bit_mask` to integer values using the `int` function, which assumes the input is in binary format and converts it to a decimal integer. Then, we compare the result of the bitwise `AND` o... | Write a Python function `has_bit(byte_data, bit_mask)` to check whether a `byte` object contains a particular bit mask. The `byte` object is a binary string representing an 8-bit integer. The `bit_mask` is also a binary string representing a bit mask to check. The function should return a boolean value indicating if th... | To check whether a given bit mask is present in a byte object in Python, we can use bitwise operations. We'll convert the `byte_data` and `bit_mask` into integers and then apply the bitwise AND operation to see if the specific bits from the bit mask are set in the byte data.
Here's a Python function `has_bit` that per... | 37,031 | [
{
"from": "human",
"value": "Write a Python function `has_bit(byte_data, bit_mask)` to check whether a `byte` object contains a particular bit mask. The `byte` object is a binary string representing an 8-bit integer. The `bit_mask` is also a binary string representing a bit mask to check. The function shoul... |
To find the mutual friends between two users in a social network graph, you can follow these steps:
1. Validate inputs: Check whether the graph, user1, and user2 are valid inputs. If any of them is not found, return an empty list.
2. Collect friends of user1 and user2: Retrieve the friends of user1 and user2 from the ... | Construct a Python function `get_mutual_friends(graph, user1, user2)` to return a list of friends that are both friends with the given two users in a social network graph. The function should utilize the `set` intersection operator for efficiency. If either user is not a part of the graph, the function should return an... | To construct the `get_mutual_friends` function, we'll assume that the graph is represented as a dictionary where the keys are user identifiers (like usernames or user IDs) and the values are sets of friends. Using sets will allow efficient calculation of the intersection when finding mutual friends.
Here’s how the fun... | 37,032 | [
{
"from": "human",
"value": "Construct a Python function `get_mutual_friends(graph, user1, user2)` to return a list of friends that are both friends with the given two users in a social network graph. The function should utilize the `set` intersection operator for efficiency. If either user is not a part of... |
Here's a possible implementation of this function:
```python
import re
def parse_parameter_documentation(documentation: str) -> dict:
parameter_re = re.compile(r"^- (\w+):.*$")
required_re = re.compile(r"(Required parameters|Optional parameters)")
parameter_list = []
required = True
for line in do... | Consider the following documentation for an API endpoint:
```
POST /api/v1/user
Add a new user.
Required parameters:
- name: Name of the user.
Optional parameters:
- age: Age of the user, if known.
- country: Country of residence.
```
Write a Python function to parse the above documentation into a dictionary, wher... | You can create a Python function that parses the provided API documentation string and converts it into the desired dictionary format. Here’s one way to implement such a function:
```python
def parse_api_documentation(doc_string):
# Initialize the result dictionary.
params = {}
# Split the documentati... | 37,033 | [
{
"from": "human",
"value": "Consider the following documentation for an API endpoint:\n\n```\nPOST /api/v1/user\n\nAdd a new user.\n\nRequired parameters:\n- name: Name of the user.\n\nOptional parameters:\n- age: Age of the user, if known.\n- country: Country of residence.\n```\n\nWrite a Python function ... |
To write a Python function that validates four velocities in the correct order, you can follow these steps:
1. Validate that all four velocities are positive numbers.
2. Verify that `v1` is the smallest and `v4` is the largest velocity.
3. Check if `v4` > `v3` > `v2` > `v1`.
4. Return `True` if all checks pass, `False... | Write a Python function called `validate_velocities` that takes four parameters: `v1`, `v2`, `v3`, and `v4`. The function should validate whether the four velocities are in the correct order and return `True` or `False`.
The velocities should be in order from highest to lowest: `v4` > `v3` > `v2` > `v1`. All four velo... | You can solve the problem as follows with the three lines of code you specified:
```python
def validate_velocities(v1, v2, v3, v4):
return all(v > 0 for v in [v1, v2, v3, v4]) and v4 > v3 > v2 > v1
```
This function checks for two conditions: first, using a generator expression, it verifies that all values are po... | 37,034 | [
{
"from": "human",
"value": "Write a Python function called `validate_velocities` that takes four parameters: `v1`, `v2`, `v3`, and `v4`. The function should validate whether the four velocities are in the correct order and return `True` or `False`.\n\nThe velocities should be in order from highest to lowes... |
To achieve the desired output, we can use the `stack` function from PyTorch to stack the image tensors horizontally. We can also use the `zip` function to unzip the batch into image tensors and labels, then stack the image tensors using `torch.stack`. This ensures that the resulting batch is identical to the original b... | Write a Python function `identity_collate_fn(batch)` that takes a batch of data as an input, which is a list of tuples consisting of an image tensor and a label. The function should return the same batch but with the image tensors stacked horizontally along the first dimension. | Certainly! To create a function called `identity_collate_fn` that takes a batch of data (consisting of image tensors and labels) and returns a tensor with the image tensors stacked horizontally (along the first dimension), you can utilize the `torch` library. Here's how you can implement this function:
```python
impor... | 37,035 | [
{
"from": "human",
"value": "Write a Python function `identity_collate_fn(batch)` that takes a batch of data as an input, which is a list of tuples consisting of an image tensor and a label. The function should return the same batch but with the image tensors stacked horizontally along the first dimension."... |
To count the occurrences of a specific string pattern in a given string using the `re.findall` function, you can provide a regular expression that matches one or more consecutive occurrences of either the strings `A` or `B`. The pattern is given as an argument to the `re.findall` function, and the string in which to se... | In Python, use `re.findall` to count the occurrences of a specific string pattern in a given string. The pattern is a regular expression that matches one or more consecutive occurrences of either the strings `A` or `B`, where `A` and `B` are arbitrary strings. For example, the pattern `A+B+` will match the following st... | Certainly! You can use Python's `re` module to accomplish this task. The `re.findall` function can be used to find all occurrences of a specified pattern in a string. Here's a function that takes the pattern and the string, finds the occurrences, and returns the count of matches:
```python
import re
def count_pattern... | 37,036 | [
{
"from": "human",
"value": "In Python, use `re.findall` to count the occurrences of a specific string pattern in a given string. The pattern is a regular expression that matches one or more consecutive occurrences of either the strings `A` or `B`, where `A` and `B` are arbitrary strings. For example, the p... |
Here's how you can implement the function in Python:
```python
def time_to_next_bus(arrival_times, start_time):
if not arrival_times:
return "No more buses today"
for time in arrival_times:
if time > start_time:
break
if time == start_time:
return "Bus is here!"
elif... | Write a Python function `time_to_next_bus` that takes in a list of integers representing arrival times of buses and an integer `start_time` representing the current time. The function should return a string formatted as "Bus arrives in X minutes", where X is the number of minutes until the next bus arrives. If the next... | To create the function `time_to_next_bus`, we will iterate through the provided list of bus arrival times, check their relationship with `start_time`, and calculate how long until the next bus arrives. The function will account for the three possible outcomes based on the described conditions.
Here's how we can implem... | 37,037 | [
{
"from": "human",
"value": "Write a Python function `time_to_next_bus` that takes in a list of integers representing arrival times of buses and an integer `start_time` representing the current time. The function should return a string formatted as \"Bus arrives in X minutes\", where X is the number of minu... |
Here is a Python function that implements this approach:
```python
import importlib
def deserialize_dict(data):
"""
Accepts a dictionary `data` and returns a new object with the same structure and attributes as `data`.
"""
if not isinstance(data, dict):
return data
new_dict = {}
for ke... | Write a Python function `deserialize_dict(data)` that accepts a dictionary `data` and returns a new object with the same structure and attributes as the input dictionary. The function should recursively traverse the dictionary and dynamically create modules, classes, and objects using the built-in `importlib` module. | To create a function that can deserialize a dictionary into a corresponding object structure with classes and instances, we can use the `importlib` module to dynamically create classes and instantiate them based on the keys and value types in the dictionary.
Here's how you can implement the `deserialize_dict` function... | 37,038 | [
{
"from": "human",
"value": "Write a Python function `deserialize_dict(data)` that accepts a dictionary `data` and returns a new object with the same structure and attributes as the input dictionary. The function should recursively traverse the dictionary and dynamically create modules, classes, and objects... |
For this problem, you have to:
1. Develop a function that parses a structured string and returns a dictionary containing the key-value pairs extracted from the string.
2. Develop the function with an optional argument `args` to pass a list of key names as a string to extract only the specified keys and their correspon... | Develop a Python function that parses a structured string and returns a dictionary containing the key-value pairs extracted from the string. The string format is as follows:
```
<key1>:<value1> <key2>:<value2> ... <keyN>:<valueN>
```
where each key-value pair is separated by a space and the value for a key may contai... | Below is a Python function that meets your requirements for parsing a structured string into a dictionary. It includes optional parameters for filtering keys and formatting output for command line use, along with error handling and thorough documentation.
```python
def parse_key_value_string(s: str, args: str = None, ... | 37,039 | [
{
"from": "human",
"value": "Develop a Python function that parses a structured string and returns a dictionary containing the key-value pairs extracted from the string. The string format is as follows:\n\n```\n<key1>:<value1> <key2>:<value2> ... <keyN>:<valueN>\n```\n\nwhere each key-value pair is separate... |
Here is the implementation of the function:
```python
def list_of_objects_to_list_of_dicts(objects):
dicts = []
for obj in objects:
vars_dict = obj.__dict__ # Get the object's instance variables
dicts.append(vars_dict)
return dicts
```
In this implementation:
- `objects` is a list of obje... | Design a Python function that takes a list of objects and returns a list of dictionaries, each containing only the object's instance variables.
For example, given the following list of objects:
```python
class Person:
def __init__(self, name, age, height):
self.name = name
self.age = age
s... | You can achieve this by defining a Python function that uses the built-in `vars()` function, which returns the `__dict__` attribute of the given object. The `__dict__` attribute holds all of the instance variables of an object in a dictionary format.
Here's how you can implement the function you described:
```python... | 37,040 | [
{
"from": "human",
"value": "Design a Python function that takes a list of objects and returns a list of dictionaries, each containing only the object's instance variables.\n\nFor example, given the following list of objects:\n\n```python\nclass Person:\n def __init__(self, name, age, height):\n s... |
Here's an example code snippet that demonstrates how to accomplish this:
```python
from typing import List
class Event:
def __init__(self, event1: float, event2: float, event3: float):
self.event1 = event1
self.event2 = event2
self.event3 = event3
def load_data(file_path: str) -> List[Even... | I have a text file `log.txt` that contains some data in a particular format:
```
0.15 0.20 0.20
0.10 0.20 0.30
```
Each line contains three real numbers (each between 0 and 1) representing probabilities for the occurrence of three events. I want to load the data into a Python list of `Event` objects, with the three n... | To load the data from your `log.txt` file into a list of `Event` objects in Python, you need to follow these steps:
1. Define the `Event` class.
2. Read the contents of the file.
3. Parse each line to extract the three probabilities.
4. Create an `Event` object for each line and store them in a list.
Here's how you c... | 37,041 | [
{
"from": "human",
"value": "I have a text file `log.txt` that contains some data in a particular format:\n\n```\n0.15 0.20 0.20\n0.10 0.20 0.30\n```\n\nEach line contains three real numbers (each between 0 and 1) representing probabilities for the occurrence of three events. I want to load the data into a ... |
To write a Python function that concatenates a directory path with a list of file names, we can use string concatenation or Python's template path formatting. String concatenation involves adding the directory path and file name together using the `+` operator, while template path formatting uses a format string with p... | Write a Python function that takes a list of file objects and a directory path, and returns a list of file paths by concatenating the directory path with the file name. Use string concatenation or the Python template path formatting to achieve this task. | Certainly! Below is a Python function that takes a list of file objects and a directory path, and returns a list of full file paths by concatenating the directory path with the file name. We'll use the `os.path.join` method, which is generally preferred for building file paths as it takes care of different operating sy... | 37,042 | [
{
"from": "human",
"value": "Write a Python function that takes a list of file objects and a directory path, and returns a list of file paths by concatenating the directory path with the file name. Use string concatenation or the Python template path formatting to achieve this task."
},
{
"from": "g... |
To solve this problem, we'll use a recursive algorithm to explore the labyrinth and search for a path between the given start and end points. The algorithm will start at the start point and recursively explore adjacent cells until it finds the end point or reaches a cell that is marked as visited.
To efficiently explo... | Given a 2-dimensional array representing a labyrinth, where 0 represents a wall and 1 represents a path, write a Python function `find_path(labyrinth, start, end)` to check if there is a path between the start and end points. The start point is guaranteed to be on an outer wall of the labyrinth, while the end point is ... | To solve the problem of finding a path in a labyrinth represented by a 2D array, we can use a graph traversal algorithm like Depth-First Search (DFS) or Breadth-First Search (BFS). In this case, we will implement BFS, which is particularly useful for finding the shortest path in an unweighted grid like our labyrinth.
... | 37,043 | [
{
"from": "human",
"value": "Given a 2-dimensional array representing a labyrinth, where 0 represents a wall and 1 represents a path, write a Python function `find_path(labyrinth, start, end)` to check if there is a path between the start and end points. The start point is guaranteed to be on an outer wall ... |
In Python, you can use the `json` module to parse a JSON string and access its properties. Here's how you can implement the function:
```python
import json
def get_article_url_from_json(json_str):
try:
json_obj = json.loads(json_str)
url = json_obj.get('url')
if url and isinstance(url, str... | Develop a Python function `get_article_url_from_json` that extracts the `url` value from a JSON object (if present) and returns the value as a string. Handle potential errors and invalid inputs gracefully by returning `None`.
The input JSON object has the following structure:
```json
{
"title": "Article Title",
"... | Certainly! Below is a Python function `get_article_url_from_json` that extracts the `url` value from a JSON object, handling potential errors and invalid inputs gracefully by returning `None`.
```python
import json
def get_article_url_from_json(json_object):
"""
Extracts the 'url' value from a provided JSON o... | 37,044 | [
{
"from": "human",
"value": "Develop a Python function `get_article_url_from_json` that extracts the `url` value from a JSON object (if present) and returns the value as a string. Handle potential errors and invalid inputs gracefully by returning `None`.\n\nThe input JSON object has the following structure:... |
Here's how you can implement this:
```python
def convert_fraction_to_dec(fraction):
fraction_parts = fraction.split('/')
if len(fraction_parts) != 2 or fraction_parts[1] == '0':
raise ValueError('Invalid fraction format')
numerator = int(fraction_parts[0])
denominator = int(fraction_parts[1])... | Create a Python function `convert_fraction_to_dec` that takes a fraction as a string in the format `numerator/denominator` and returns its decimal equivalent as a string. For example:
```python
convert_fraction_to_dec('1/2') == '0.5'
convert_fraction_to_dec('1/3') == '0.3333333333333333'
convert_fraction_to_dec('2/7')... | Here's a Python function named `convert_fraction_to_dec` that takes a fraction represented as a string in the format `numerator/denominator`, processes it, and returns its decimal equivalent as a string:
```python
def convert_fraction_to_dec(fraction: str) -> str:
# Split the fraction by the '/' character
nume... | 37,045 | [
{
"from": "human",
"value": "Create a Python function `convert_fraction_to_dec` that takes a fraction as a string in the format `numerator/denominator` and returns its decimal equivalent as a string. For example:\n\n```python\nconvert_fraction_to_dec('1/2') == '0.5'\nconvert_fraction_to_dec('1/3') == '0.333... |
To accomplish this task, we need to loop through each character in the string. To check whether a character is a vowel, we can define a set of vowels and check whether the character is in the set. If the character is a vowel, then we return its index. If none of the characters are vowels, we return `-1`.
Here's how we... | Write a Python function named `get_first_vowel` that takes a string as an input and returns the index of the first vowel character in it. If no vowels are present, return `-1`.
Your code should pass the following assertions:
```python
assert get_first_vowel("Hello world") == 1
assert get_first_vowel("xyz") == -1
asser... | You can create the `get_first_vowel` function to find the index of the first vowel in a given string. Here's how you can implement it:
```python
def get_first_vowel(s):
vowels = "aeiouAEIOU" # Include both lowercase and uppercase vowels
for index, char in enumerate(s):
if char in vowels:
r... | 37,046 | [
{
"from": "human",
"value": "Write a Python function named `get_first_vowel` that takes a string as an input and returns the index of the first vowel character in it. If no vowels are present, return `-1`.\n\nYour code should pass the following assertions:\n```python\nassert get_first_vowel(\"Hello world\")... |
You can create a Python function that reads the text file, splits the file into lines, and then uses a set to remove duplicates. The resulting list will contain the unique URLs in the same order as they appear in the file.
Here's how you could do it:
```python
def read_and_deduplicate(file_path):
with open(file_p... | Write a Python function `read_and_deduplicate(file_path)` that reads a text file containing a list of URLs (one per line) and removes any duplicates. The function should return a list of unique URLs in the same order as they appear in the file. | You can achieve this by creating a function that reads the contents of a specified text file, splits the content into lines (representing URLs), and then deduplicates the URLs while maintaining their original order. Here’s a possible implementation of the function `read_and_deduplicate(file_path)`:
```python
def read_... | 37,047 | [
{
"from": "human",
"value": "Write a Python function `read_and_deduplicate(file_path)` that reads a text file containing a list of URLs (one per line) and removes any duplicates. The function should return a list of unique URLs in the same order as they appear in the file."
},
{
"from": "gpt",
"... |
Here's the implementation of the `timeit` function:
```python
import time
def timeit(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
elapsed_time = end_time - start_time
print(f"Function {func.__name__}() t... | Write a Python function `timeit` that measures the time taken to execute a given function, taking the function name and a list of arguments as parameters. The function should return the measured time in seconds.
The function should also handle cases where the arguments are passed as a dictionary instead of a list.
He... | You can achieve this behavior by creating a decorator `timeit` that wraps the target function and measures the execution time. Here's how you can implement it:
```python
import time
from functools import wraps
def timeit(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time() # Sta... | 37,048 | [
{
"from": "human",
"value": "Write a Python function `timeit` that measures the time taken to execute a given function, taking the function name and a list of arguments as parameters. The function should return the measured time in seconds.\n\nThe function should also handle cases where the arguments are pa... |
To calculate the rate for the given period compared to the previous period, we need to first determine the change in the value from the current period to the previous period. This can be achieved by subtracting the `previous_period` from the `current_period`.
Once we have the change in the value, we can calculate the ... | Implement a Python function named `period_rate` that calculates the rate (percentage) for the given period compared to the previous period. The function takes two arguments, `current_period` and `previous_period`, representing the current value and the previous value, respectively. It returns the period rate as a perce... | To calculate the period rate as a percentage for the given `current_period` compared to `previous_period`, you can use the formula:
\[ \text{rate} = \frac{\text{current\_period} - \text{previous\_period}}{\text{previous\_period}} \times 100 \]
This formula gives the percentage change from the `previous_period` to the... | 37,049 | [
{
"from": "human",
"value": "Implement a Python function named `period_rate` that calculates the rate (percentage) for the given period compared to the previous period. The function takes two arguments, `current_period` and `previous_period`, representing the current value and the previous value, respective... |
To check if a path is valid and contains a certain file name, you can use the `os.path.abspath` function to normalize the given path and ensure it is valid, then use the `os.path.basename` function to extract the file name from the path. Finally, you can use the `fnmatch` module to match the file name against the given... | Write a Python function that checks if a given path is valid and contains a certain file name. The function should be able to handle both absolute and relative paths and work cross-platform. The function should also be able to handle recursive directories and support regular expression patterns in the file name.
Your ... | To check if a given path is valid and contains at least one file that matches a specified filename pattern (supporting both absolute and relative paths, recursive searches, and regular expressions), we can use the `os` module for path manipulation and the `fnmatch` module to match filenames against patterns.
Here's a ... | 37,050 | [
{
"from": "human",
"value": "Write a Python function that checks if a given path is valid and contains a certain file name. The function should be able to handle both absolute and relative paths and work cross-platform. The function should also be able to handle recursive directories and support regular exp... |
Here's how you can write such a function in Python:
```python
import copy
def clone_objects(objects):
if not isinstance(objects, list):
raise TypeError("Input must be a list")
for obj in objects:
if not isinstance(obj, dict):
raise TypeError("Each object must be a dictionary")
... | Write a function that takes a list of objects, where each object has an `id`, `data`, and `tags` property. The function should create a new list of objects, where each object's `data` property is cloned from the original object. The function should also create a new `tags` object for each object with the same `id` as t... | To accomplish the task you've described, we can write a function in JavaScript that iterates through the input array of objects, validates the required properties, and then creates a new array of objects with deep-cloned structures for `data` and `tags`. Here's how the code might look:
```javascript
function cloneObje... | 37,051 | [
{
"from": "human",
"value": "Write a function that takes a list of objects, where each object has an `id`, `data`, and `tags` property. The function should create a new list of objects, where each object's `data` property is cloned from the original object. The function should also create a new `tags` objec... |
To implement this function, we need to define the security levels and their corresponding ranges. We can use a `dict` or a list of tuples to store these mappings. Then, we can use a `for` loop to iterate over the ranges and check if the input falls into a specific range. If the input falls within a range, we can return... | Implement a Python function `get_security_level` that accepts a numeric input and returns a security level based on predefined ranges. Here are the security levels and their corresponding ranges:
```
Security Levels:
Security Level 1: 0 to 25
Security Level 2: 26 to 50
Security Level 3: 51 to 75
Security Level 4: 76 ... | Here's the implementation of the function `get_security_level` that meets your requirements:
```python
def get_security_level(value):
# Check if the input is too low
if value <= 0:
return 'Input is too low'
# Check if the input is too high
elif value >= 101:
return 'Input is too high'
... | 37,052 | [
{
"from": "human",
"value": "Implement a Python function `get_security_level` that accepts a numeric input and returns a security level based on predefined ranges. Here are the security levels and their corresponding ranges:\n\n```\nSecurity Levels:\n\nSecurity Level 1: 0 to 25\nSecurity Level 2: 26 to 50\n... |
To create a list of the specified length, with each element being of the same specified data type, and with each element having a unique value, you can follow these steps:
1. Handle invalid inputs: Check that the data type is one of the supported types (`int`, `float`, and `str`) and that the length is positive.
2. Cr... | Write a Python function to create a list of the specified length, with all elements being of the same specified data type, and with each element having a unique value. Your function should support the following data types: `int`, `float`, and `str`. The input should be two parameters: the data type and the length of th... | Here is a Python function that fulfills the requirements you specified. This function, `create_list_with_unique_values`, takes a data type and a length as inputs, and returns a list of that length with unique values in the specified data type.
```python
def create_list_with_unique_values(data_type: str, length: int):
... | 37,053 | [
{
"from": "human",
"value": "Write a Python function to create a list of the specified length, with all elements being of the same specified data type, and with each element having a unique value. Your function should support the following data types: `int`, `float`, and `str`. The input should be two param... |
To solve this problem, we can use a stack to store the pushed elements and a pointer to keep track of the popped elements. We iterate through the pushed array and push the elements to the stack. Then, we iterate through the popped array and compare each element with the top element of the stack. If they are equal, we p... | Write a Python function called `is_valid_stack_order` that takes in two arrays of integers: `pushes` and `pops`. `pushes` is a list of integers that are pushed to a stack in order, and `pops` is the sequence of integers that should be popped from the stack in the same order. Return a boolean value of `True` if and only... | To determine if the `pops` sequence is a valid sequence for the given `pushes` sequence, we can simulate the behavior of a stack using a list. We'll push elements from `pushes` onto the stack and try to pop them according to the order specified in `pops`. If we are able to pop all elements in `pops` in the specified or... | 37,054 | [
{
"from": "human",
"value": "Write a Python function called `is_valid_stack_order` that takes in two arrays of integers: `pushes` and `pops`. `pushes` is a list of integers that are pushed to a stack in order, and `pops` is the sequence of integers that should be popped from the stack in the same order. Ret... |
You can achieve this functionality in two steps. First, you can use a `validate_dimensions` function to check whether the given vectors have the same dimensions. If they do, perform the element-wise addition. Otherwise, raise an `Exception` with an appropriate error message.
Here's how you can do it in two lines of Py... | Design a Python function that adds two vectors element-wise and returns the result. The function should accept two lists representing vectors as input, and return a new list containing the sum of corresponding elements. For example, `add_vectors([1, 2, 3], [2, 3, 4])` should return `[3, 5, 7]`.
Additionally, write a `... | Certainly! Below are the implementations for the `add_vectors` function, which adds two vectors element-wise, and a `validate_dimensions` function that checks if the dimensions of the vectors are compatible for addition. If the dimensions are not compatible, it raises an Exception with a suitable error message.
```pyt... | 37,055 | [
{
"from": "human",
"value": "Design a Python function that adds two vectors element-wise and returns the result. The function should accept two lists representing vectors as input, and return a new list containing the sum of corresponding elements. For example, `add_vectors([1, 2, 3], [2, 3, 4])` should ret... |
To parse a postal address and format it correctly, we can use a regular expression. The regular expression should capture the components of the address and store them in groups. We can then use string formatting to format the address in the desired format.
Here is a Python function that implements this approach:
```p... | Write a Python function `parse_address` that takes a string representing a postal address and parses it into its components (street address, city, state, and zip code). The input string may be in any format, but it should always be able to extract the street address, city, state, and zip code. If the state or zip code ... | To implement the `parse_address` function, we will use regular expressions to identify and extract the components of the address: street address, city, state, and zip code. The function will then format these components into the required output format.
Here’s a potential implementation of the function:
```python
impo... | 37,056 | [
{
"from": "human",
"value": "Write a Python function `parse_address` that takes a string representing a postal address and parses it into its components (street address, city, state, and zip code). The input string may be in any format, but it should always be able to extract the street address, city, state... |
To format a list of `Repo` objects into a single string containing a tabular representation, you can utilize the `str.format()` method and the `'\t'` separator to align each repository's attributes in columns.
Here's an example function that formats a list of `Repo` objects into a single string:
```python
class Repo:... | Write a Python function to format a list of `Repo` objects into a single string containing a tabular representation of the repositories, where each row is represented as a single line and columns are separated by tabs.
Each repository object has the following attributes: `name`, `description`, `html_url`, `private`, `... | To create a function that formats a list of `Repo` objects into a tabular representation, we will design a function named `format_repos_to_string`. This function will iterate through the list of `Repo` objects and create a string where each row corresponds to a repository, and columns are separated by tabs.
Here's a ... | 37,057 | [
{
"from": "human",
"value": "Write a Python function to format a list of `Repo` objects into a single string containing a tabular representation of the repositories, where each row is represented as a single line and columns are separated by tabs.\n\nEach repository object has the following attributes: `nam... |
Here is a Python implementation of the bit packing and unpacking functions:
```python
def bit_pack(values):
"""
Packs a sequence of 8-bit values into a bit-packing representation.
"""
packed = []
for value in values:
bit_packed = 0
bit_packed += value & 0x1F
bit_packed = bit... | I have some data as a sequence of 8-bit binary values. I want to be able to store them in a compact form, which I'll call a "bit packing" system. The bit packing system stores a number (without sign; 0 to 255) in 5 bits, with the highest bit indicating "continuation" (0 for the last byte in the number, 1 for "next byte... | Certainly! The concept you've described involves encoding each 8-bit byte into a sequence of bytes where each byte is split into a continuation bit and the remaining bits represent the value.
Here's how you can implement both the `bit_pack` and `bit_unpack` functions in Python:
```python
def bit_pack(values):
pac... | 37,058 | [
{
"from": "human",
"value": "I have some data as a sequence of 8-bit binary values. I want to be able to store them in a compact form, which I'll call a \"bit packing\" system. The bit packing system stores a number (without sign; 0 to 255) in 5 bits, with the highest bit indicating \"continuation\" (0 for ... |
To build a string representation of an arbitrary object in Python, you can utilize the built-in `inspect` module. This module provides a suite of functions for introspecting live objects, and it is particularly useful for inspecting the attributes of an object.
Here's a Python function that takes an arbitrary object a... | Write a Python function to take an arbitrary object and build a string representation of it. The string should contain the class name, all attributes (including private attributes), and the object's representation in the form of a dictionary. The dictionary representation should include the attribute name as the key, a... | To create a Python function that constructs a string representation of an arbitrary object, we can utilize reflection methods such as `vars()` or `__dict__()`, along with type checking to ensure that attributes are formatted correctly. Below is a function called `object_representation` that does just that:
```python
d... | 37,059 | [
{
"from": "human",
"value": "Write a Python function to take an arbitrary object and build a string representation of it. The string should contain the class name, all attributes (including private attributes), and the object's representation in the form of a dictionary. The dictionary representation should... |
Here's an example implementation of the Python function using regular expressions:
```python
import re
def extract_user_ids(url):
pattern = r'/users/(\d+)/'
matches = re.findall(pattern, url)
return matches
```
This implementation uses a regular expression to match the user IDs in the URL. The `re.findal... | Write a Python function to extract all user IDs from a string containing a URL using regular expressions. For example, if the input string is "https://stackoverflow.com/users/123456/username", the function should return "123456". | You can use the `re` module in Python to accomplish this task with a regular expression. Here’s a function that extracts user IDs from a URL string:
```python
import re
def extract_user_id(url):
# Define the regex pattern to match user IDs in the URL
pattern = r'/users/(\d+)/'
# Search for the patter... | 37,060 | [
{
"from": "human",
"value": "Write a Python function to extract all user IDs from a string containing a URL using regular expressions. For example, if the input string is \"https://stackoverflow.com/users/123456/username\", the function should return \"123456\"."
},
{
"from": "gpt",
"value": "Yo... |
To check if a string is a valid UTF-8 encoding, we can follow these steps:
1. Iterate through each character in the string.
2. For each character, check if it's a one-byte character or a multi-byte character.
3. If it's a one-byte character, check if the first bit is a 0 and the remaining bits represent a valid unicod... | Write a Python function to check if a string is a valid UTF-8 encoding.
A character in UTF-8 can be from 1 to 4 bytes long, subjected to the following rules:
- For 1-byte character, the first bit is a 0, followed by its unicode code.
- For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed ... | To check if a string is a valid UTF-8 encoding in Python, we need to implement a function that analyzes the byte sequences in the string according to the UTF-8 encoding rules. Here’s how we can do that:
1. Each character in a string will be encoded in bytes using UTF-8. To transform string characters into their UTF-8 ... | 37,061 | [
{
"from": "human",
"value": "Write a Python function to check if a string is a valid UTF-8 encoding.\n\nA character in UTF-8 can be from 1 to 4 bytes long, subjected to the following rules:\n\n- For 1-byte character, the first bit is a 0, followed by its unicode code.\n- For n-bytes character, the first n-b... |
Here's how you could do it:
```python
def convert_str_to_bool(input_str):
if input_str == 'True':
return True
elif input_str == 'False':
return False
else:
return None
``` | Write a Python function that converts a string of the form 'True' or 'False' to the corresponding boolean value. For example, 'True' should return True, while 'False' should return False. You may not use built-in string-to-bool conversion functions.
Ensure that your function handles invalid input as well, returning `N... | You can create a function that checks the input string and returns the corresponding boolean value or `None` for invalid input. Here's how you can implement this:
```python
def string_to_bool(s):
"""
Convert the string 'True' or 'False' to the corresponding boolean value.
Parameters:
s (str): The inpu... | 37,062 | [
{
"from": "human",
"value": "Write a Python function that converts a string of the form 'True' or 'False' to the corresponding boolean value. For example, 'True' should return True, while 'False' should return False. You may not use built-in string-to-bool conversion functions.\n\nEnsure that your function ... |
Here's an example implementation of the function using a lambda function:
```python
def find_words_starting_with_prefix(words, prefix):
return len(list(filter(lambda word: word.startswith(prefix), words)))
```
This function takes two arguments, `words` and `prefix`. It uses the `filter` function to filter out the... | Given a list of strings `words` and a string `prefix`, find all the words in `words` that start with `prefix`. Return the number of such words. You should implement the function using a lambda function.
For instance, given [`apple`, `banana`, `coconut`]. If the prefix is `co`, the function should return 1.
Your code ... | You can achieve this by utilizing Python's built-in functions along with a lambda function for filtering the list of words. Here’s how you can implement the `find_words_starting_with_prefix` function:
```python
def find_words_starting_with_prefix(words, prefix):
# Use filter with a lambda function to find words st... | 37,063 | [
{
"from": "human",
"value": "Given a list of strings `words` and a string `prefix`, find all the words in `words` that start with `prefix`. Return the number of such words. You should implement the function using a lambda function.\n\nFor instance, given [`apple`, `banana`, `coconut`]. If the prefix is `co`... |
```python
import re
def match_ip_addresses(input_string):
pattern = r'\[(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\]'
compiled_pattern = re.compile(pattern)
matches = []
try:
match = compile... | Write a Python function to match IP addresses in a string. The input string may contain any amount of text, but the IP addresses will be surrounded by square brackets ([]). IP addresses should be validated, i.e. each number should be between 0 and 255. Return the list of matching IP addresses.
Use the `re` module with... | You can achieve this by using the `re` module in Python to define a regex pattern that matches the valid IP addresses surrounded by square brackets. Then, you can use the `findall` method to extract those matches. Here's the implementation of the `match_ip_addresses` function:
```python
import re
def match_ip_address... | 37,064 | [
{
"from": "human",
"value": "Write a Python function to match IP addresses in a string. The input string may contain any amount of text, but the IP addresses will be surrounded by square brackets ([]). IP addresses should be validated, i.e. each number should be between 0 and 255. Return the list of matchin... |
Here's how you can do it:
```python
import struct
def read_binary(file_bytes):
offset = 0 # Initial offset to start reading from the binary file
first_string = file_bytes[offset:offset+4].decode('utf-8')
offset += 4 # Move the offset ahead by 4 bytes
second_string = file_bytes[offset:offset+4].decod... | I have a binary file with an unknown format that I want to read in Python. I want to extract a 4-byte string and another 4-byte string from it, and then combine them to create a new string, which I will then split into a list of bytes and return. The input file is stored in a variable `file_bytes`.
Can you write a Pyt... | Sure! To read 4-byte strings from a binary file represented as `file_bytes`, you can use the `struct` module in Python, which allows you to unpack binary data into Python objects. In this case, you'll want to read two 4-byte strings, combine them, and then convert that combined string into a list of bytes.
Here's a Py... | 37,065 | [
{
"from": "human",
"value": "I have a binary file with an unknown format that I want to read in Python. I want to extract a 4-byte string and another 4-byte string from it, and then combine them to create a new string, which I will then split into a list of bytes and return. The input file is stored in a va... |
Here is an efficient implementation of the `is_prime_factor` function:
```python
import math
def is_prime_factor(num, factor):
if num <= 0 or factor <= 0:
raise ValueError("Both num and factor must be positive integers.")
if num % factor != 0:
return False
sqrt_factor = math.sqrt(factor)
... | Write a Python function `is_prime_factor(num, factor)` that checks whether `factor` is a prime factor of the number `num`. The function should verify that `num` and `factor` are positive integers, and return `True` if `factor` is a prime factor of `num`, and `False` otherwise. Additionally, the function should be effic... | To determine if a `factor` is a prime factor of `num`, we need to check two main conditions:
1. The `factor` must divide `num` evenly (i.e., `num % factor == 0`).
2. The `factor` must be a prime number.
We'll also ensure that both `num` and `factor` are positive integers before performing any checks.
Here's the Pyth... | 37,066 | [
{
"from": "human",
"value": "Write a Python function `is_prime_factor(num, factor)` that checks whether `factor` is a prime factor of the number `num`. The function should verify that `num` and `factor` are positive integers, and return `True` if `factor` is a prime factor of `num`, and `False` otherwise. A... |
Here's an example implementation of the `get_db_url` function that meets the requirements:
```python
import os
def get_db_url():
db_host = os.environ.get('DB_HOST')
db_port = os.environ.get('DB_PORT')
db_name = os.environ.get('DB_NAME')
db_user = os.environ.get('DB_USER')
db_pass = os.environ.get(... | Create a Python function `get_db_url` that returns a PostgreSQL database URL based on the environment variables `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER`, and `DB_PASS`. The database URL should follow the format:
```
postgresql://{DB_USER}:{DB_PASS}@{DB_HOST}:{DB_PORT}/{DB_NAME}
```
Use `os.environ` to retrieve envi... | You can create the `get_db_url` function to retrieve the necessary environment variables and format them into a PostgreSQL database URL. Below is the implementation of the function:
```python
import os
def get_db_url():
# Retrieve environment variables
db_user = os.environ.get('DB_USER')
db_pass = os.envi... | 37,067 | [
{
"from": "human",
"value": "Create a Python function `get_db_url` that returns a PostgreSQL database URL based on the environment variables `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER`, and `DB_PASS`. The database URL should follow the format:\n\n```\npostgresql://{DB_USER}:{DB_PASS}@{DB_HOST}:{DB_PORT}/{DB_... |
Here is the implementation of `my_filter`:
```python
def my_filter(xs, f):
return [x for x in xs if f(x)]
``` | Write a Python function `my_filter(xs, f)` that takes a list `xs` and a function `f` as inputs, and returns a list of elements in `xs` that satisfy `f` using list comprehension and functional programming.
Your code should pass the following assertions:
```python
assert my_filter([0, 1, 2, 3, 4], lambda x: x > 2) == [3... | You can implement the `my_filter` function using list comprehension in Python. The function will iterate through each element in the input list `xs`, apply the filter function `f`, and collect elements that satisfy the condition specified by `f`. Here's how you can do it:
```python
def my_filter(xs, f):
return [x ... | 37,068 | [
{
"from": "human",
"value": "Write a Python function `my_filter(xs, f)` that takes a list `xs` and a function `f` as inputs, and returns a list of elements in `xs` that satisfy `f` using list comprehension and functional programming.\n\nYour code should pass the following assertions:\n```python\nassert my_f... |
The instruction is to write a Python function that accepts a list of dictionaries and a column name as a string, and returns the maximum value of that column.
Here is the implementation:
```python
def max_column_value(data, column):
return max(row[column] for row in data)
``` | Write a Python function that accepts a list of dictionaries (each dictionary represents a row) and a column name (as a string) and returns the maximum value of that column.
For example, given the following list of dictionaries:
```
data = [
{'id': 1, 'name': 'John', 'age': 23},
{'id': 2, 'name': 'Jane', 'age'... | You can implement the function `max_column_value` as follows:
```python
def max_column_value(data, column):
# Check if data is not empty and the column exists in the first dictionary
if not data or column not in data[0]:
return None
# Use a generator expression to get the values for the specif... | 37,069 | [
{
"from": "human",
"value": "Write a Python function that accepts a list of dictionaries (each dictionary represents a row) and a column name (as a string) and returns the maximum value of that column.\n\nFor example, given the following list of dictionaries:\n\n```\ndata = [\n {'id': 1, 'name': 'John', ... |
To rebalance the data frame, you can first find the most frequent and least frequent classes in the data frame. Then, you can randomly sample from the most frequent class until the least frequent class reaches a given minimum frequency. This creates a balanced data frame.
Here's how you could do it:
```python
import ... | I have a data frame where some classes are much more frequent than others. I want to create a model that can predict the class for a given input. Can you write a Python function that takes in a data frame, a class label column name, and a minimum frequency (e.g., 100) and rebalances the data frame by randomly sampling ... | You can achieve the desired data rebalancing in Python using the following `rebalance_data` function. This function will identify the most frequent and least frequent classes and randomly sample the most frequent class such that the counts of both classes equal the specified minimum frequency. Here's the implementation... | 37,070 | [
{
"from": "human",
"value": "I have a data frame where some classes are much more frequent than others. I want to create a model that can predict the class for a given input. Can you write a Python function that takes in a data frame, a class label column name, and a minimum frequency (e.g., 100) and rebala... |
```python
def escape_invalid_chars(path, escape_char):
invalid_chars = {' ', '?', '*'}
escaped_path = ''
for char in path:
if char in invalid_chars:
escaped_path += escape_char
else:
escaped_path += char
return escaped_path
``` | Write a Python function to escape invalid characters from a file path, such as spaces, question marks, and asterisks. You can use the string `escape_char` to represent a single character that will be inserted in place of these invalid characters. You need to return the new path with all invalid characters replaced. | You can create a Python function that replaces invalid characters in a given file path with a specified escape character. Below is a sample implementation:
```python
def escape_invalid_characters(file_path: str, escape_char: str) -> str:
# Define the set of invalid characters to be replaced
invalid_characters ... | 37,071 | [
{
"from": "human",
"value": "Write a Python function to escape invalid characters from a file path, such as spaces, question marks, and asterisks. You can use the string `escape_char` to represent a single character that will be inserted in place of these invalid characters. You need to return the new path ... |
To generate the SQL statement, we'll need to create a trigger that monitors the insertion of a new row into the table. The trigger should be named `idx_trigger` and it should create a full-text index based on the contents of the specific column `title` if a new row has the `title` column.
Here's how we can implement t... | Develop a Python function `create_index_trigger` to generate a SQL statement that creates an index trigger for a given table. The trigger should be named `idx_trigger`, and it should monitor the insertion of a new row into the table. If a new row has a specific column `title`, the trigger should create a full-text inde... | To create a Python function that generates a SQL statement for an index trigger, we need to focus on creating a trigger that will respond to the insertion of rows into a specified table. This trigger will examine the `title` column of the inserted row and create a full-text index if the `title` column meets certain con... | 37,072 | [
{
"from": "human",
"value": "Develop a Python function `create_index_trigger` to generate a SQL statement that creates an index trigger for a given table. The trigger should be named `idx_trigger`, and it should monitor the insertion of a new row into the table. If a new row has a specific column `title`, t... |
```python
def find_first_module(nested_list, module_id):
for item in nested_list:
if isinstance(item, list):
first_module = find_first_module(item, module_id)
if first_module:
return first_module
elif isinstance(item, dict) and item.get("id") == module_id:
... | Write a Python function that traverses a list of items in a nested list structure and returns the first module found in the list. The module is identified by a unique id. Your function should recursively traverse through the nested list and return the first matching module it encounters. Handle the case where no module... | To implement the function that traverses a nested list structure and finds the first module with a specified unique ID, we can define a recursive function. Here’s an example of how you could structure your code.
For this example, we will assume that a module is represented by a dictionary that contains at least an `i... | 37,073 | [
{
"from": "human",
"value": "Write a Python function that traverses a list of items in a nested list structure and returns the first module found in the list. The module is identified by a unique id. Your function should recursively traverse through the nested list and return the first matching module it en... |
Here's the implementation of the `fix_url` function:
```python
def fix_url(url):
if not url.startswith("https://"):
url = "https://" + url
url = url.split("?")[0]
return url
```
In this implementation, we first check if the URL starts with "https://" using the `startswith` method. If not, then we ... | I have a function that accepts a URL as a parameter, and I want to make some changes. If the URL does not start with "https://", then I want to add that to the beginning. I also want to remove any additional parameters from the URL. Can you write a Python code snippet for this?
Your code should pass the following asse... | Certainly! You can achieve this by defining a function `fix_url` that checks if the given URL starts with `"https://"`, adds it if necessary, and then removes any query parameters by splitting the URL at the first occurrence of `?`. Here’s a code snippet that accomplishes that:
```python
def fix_url(url):
# Check ... | 37,074 | [
{
"from": "human",
"value": "I have a function that accepts a URL as a parameter, and I want to make some changes. If the URL does not start with \"https://\", then I want to add that to the beginning. I also want to remove any additional parameters from the URL. Can you write a Python code snippet for this... |
Here's an example code to implement the function:
```python
import json
def serialize_age_gender(age, gender):
person_info = {
'age': age,
'gender': gender,
'child': age < 18,
'adult': age >= 18,
'senior': age >= 55,
'child_senior': age < 18 and age >= 55
}
... | Implement a Python function that returns a JSON-serialized dictionary given data about a person's age and gender. If the person is a child (age < 18), the function should return the dictionary with the key 'child' set to true and the value of the 'age' key should be the person's age in months. If the person is an adult... | To implement a Python function that meets the specified requirements, we can follow these steps:
1. Define the function `serialize_age_gender` which takes two parameters: `age` and `gender`.
2. Create a dictionary to store the result with the initial keys for `age`, `gender`, `child`, `adult`, `senior`, and `child_sen... | 37,075 | [
{
"from": "human",
"value": "Implement a Python function that returns a JSON-serialized dictionary given data about a person's age and gender. If the person is a child (age < 18), the function should return the dictionary with the key 'child' set to true and the value of the 'age' key should be the person's... |
To create a factory function, we need to define a function within a function, with the outer function accepting parameters `input_type` and `output_type` and returning the inner function. To handle type conversion, we can use the `input_type` and `output_type` parameters in the inner function to convert the input value... | Write a Python factory function that takes two parameters: `input_type` and `output_type`. The function should return a function that accepts a single input of `input_type` and returns a value of type `output_type`, without changing the input value. Use type hints to ensure type safety. | Certainly! Below is a Python factory function that creates a conversion function based on the provided `input_type` and `output_type`. The returned function accepts an input of `input_type` and returns a value of `output_type`, while preserving the input value as is.
```python
from typing import TypeVar, Callable
# D... | 37,076 | [
{
"from": "human",
"value": "Write a Python factory function that takes two parameters: `input_type` and `output_type`. The function should return a function that accepts a single input of `input_type` and returns a value of type `output_type`, without changing the input value. Use type hints to ensure type... |
Here is the implementation of the function:
```python
import numpy as np
def online_average_and_std(samples, interval):
n = len(samples) # Number of samples seen so far
mean = np.sum(samples) / n
diff_sq_sum = 0
for x in samples:
diff_sq_sum += (x - mean)**2
std = np.sqrt(diff_sq_sum / n)... | Define a Python function to calculate an online average and standard deviation based on multiple samples. The function should take two arguments:
- `samples`: a list of samples
- `interval`: an integer representing the time interval in seconds between two consecutive samples
The function should return a tuple consist... | To calculate the online average (mean) and standard deviation in Python, we can use algorithms that allow us to update these statistics incrementally as new samples arrive. This is especially useful when working with streaming data or when we do not want to store all past samples.
Here’s how we can implement a functio... | 37,077 | [
{
"from": "human",
"value": "Define a Python function to calculate an online average and standard deviation based on multiple samples. The function should take two arguments:\n\n- `samples`: a list of samples\n- `interval`: an integer representing the time interval in seconds between two consecutive samples... |
Here's how you could implement such a function:
```python
def filter_adults(people_dict):
adults_dict = {}
for name, age in people_dict.items():
if age >= 18:
adults_dict[name] = age
return adults_dict
```
The function `filter_adults` takes a single argument, `people_dict`, which is th... | Write a Python function that takes a dictionary as an input, where each key-value pair represents a person's name and their age. The function should return a new dictionary where the keys are the names of people who are at least 18 years old. | Certainly! Below is the Python function that takes a dictionary of names and ages as input, and returns a new dictionary including only those individuals who are at least 18 years old.
```python
def filter_adults(age_dict):
"""
Takes a dictionary of names and ages, and returns a new dictionary
with names o... | 37,078 | [
{
"from": "human",
"value": "Write a Python function that takes a dictionary as an input, where each key-value pair represents a person's name and their age. The function should return a new dictionary where the keys are the names of people who are at least 18 years old."
},
{
"from": "gpt",
"va... |
To solve this problem, we can use a recursive approach. We can define a helper function `combinations(iterable, r, index)` that takes an additional argument `index` to keep track of the current index in the iterable.
In the base case, if `r` is 0, we return a list containing an empty tuple. If `r` is larger than the l... | Write a Python function `combinations(iterable, r)` that returns a list of all possible combinations of r length from the elements of iterable. The combinations are returned as a list of tuples, sorted in lexicographical order. Duplicate elements in the iterable are treated as the same element, and the returned combina... | You can achieve this by using a recursive approach to generate combinations, or by using the `itertools` module. Below, I will implement the `combinations` function as specified, and handle all the corner cases mentioned.
Here's the implementation:
```python
def combinations(iterable, r):
# Convert iterable to a ... | 37,079 | [
{
"from": "human",
"value": "Write a Python function `combinations(iterable, r)` that returns a list of all possible combinations of r length from the elements of iterable. The combinations are returned as a list of tuples, sorted in lexicographical order. Duplicate elements in the iterable are treated as t... |
To check whether a function accepts a given dictionary of arguments, we can use the built-in `signature` function from the `inspect` module. This function returns a `Signature` object that contains information about the function's parameters, including their names. We can compare the names in the `Signature` object to ... | Write a Python function `signature_test` that takes two arguments: `func`, a function object, and `data`, a dictionary of arguments to pass to `func`. If `func` is a method (i.e., it has `self` as its first argument), `data` should include a `self` entry. The function should return a tuple of two elements: the first el... | To implement the `signature_test` function, we will leverage the `inspect` module in Python, which provides useful functions to retrieve information about live objects, including functions and their signatures. Here's how we can achieve this:
1. We will retrieve the signature of the given function using `inspect.signa... | 37,080 | [
{
"from": "human",
"value": "Write a Python function `signature_test` that takes two arguments: `func`, a function object, and `data`, a dictionary of arguments to pass to `func`. If `func` is a method (i.e., it has `self` as its first argument), `data` should include a `self` entry. The function should ret... |
To write a Python function that takes a list of tuple elements, each containing a string and an integer, and returns a list of the tuples where the integer value is greater than 200 in an ascending order:
1. The input parameter of the function has a type annotation of `List[Tuple[str, int]]`, which indicates the funct... | Write a Python function that takes a list of tuple elements, each containing a string and an integer, and returns a list of the tuples where the integer value is greater than 200 in an ascending order.
The function must return a list of named tuples, where each tuple is named `Grade`, and has attributes `student_name`... | To implement the required function in Python, we can use the `collections.namedtuple` to create a `Grade` named tuple that has the specified attributes. We will filter the list of tuples based on the integer value and sort them in ascending order by the integer value before returning the results.
Here's the implementa... | 37,081 | [
{
"from": "human",
"value": "Write a Python function that takes a list of tuple elements, each containing a string and an integer, and returns a list of the tuples where the integer value is greater than 200 in an ascending order.\n\nThe function must return a list of named tuples, where each tuple is named... |
To write a Python function that returns a new dictionary with the same keys as a given dictionary, but with the corresponding values replaced by their average across all values in the dictionary, you can follow these steps:
1. Iterate through the given dictionary and store the keys and values separately.
2. Check the ... | Write a Python function `average_dict_values()` that returns a new dictionary with the same keys as a given dictionary, but with the corresponding values replaced by their average across all values in the dictionary. If the value of a key is a list, the average should be computed for the flattened list. If the value is... | You can accomplish this task by defining a function called `average_dict_values()` that processes each key-value pair in the provided dictionary. The function will check the type of each value: if it's a list, it will flatten it and calculate the average; if it's a numeric type (integer or float), it will use that valu... | 37,082 | [
{
"from": "human",
"value": "Write a Python function `average_dict_values()` that returns a new dictionary with the same keys as a given dictionary, but with the corresponding values replaced by their average across all values in the dictionary. If the value of a key is a list, the average should be compute... |
```python
def process_data_file(file_path):
records = {}
with open(file_path, 'r') as file:
for line in file:
fields = line.strip().split(":")
if len(fields) != 2:
raise ValueError("Invalid line in data file")
record_id, fields = fields[0], fields[1].s... | Write a Python function that takes a file path to a data file containing records of the following format:
```
id1:field1,field2
id2:field1,field2
id3:field1,field2
...
```
The function should open the file and use a loop to process each line, extract the fields, and construct a dictionary where the key is `id` and th... | Certainly! Below is a Python function that accomplishes the task you described. The function checks if the file exists and verifies the format of each line before constructing a dictionary. It uses assertions for these checks.
```python
import os
def read_data_file(file_path):
# Assert that the file exists
as... | 37,083 | [
{
"from": "human",
"value": "Write a Python function that takes a file path to a data file containing records of the following format:\n\n```\nid1:field1,field2\nid2:field1,field2\nid3:field1,field2\n...\n```\n\nThe function should open the file and use a loop to process each line, extract the fields, and c... |
```python
import torch
def numpy_to_pytorch_tensor(array):
return torch.from_numpy(array)
``` | Write a Python function that takes a NumPy array as an argument and converts it to a PyTorch tensor. The function should handle both CPU and GPU inputs and convert the input array to a PyTorch tensor. | To convert a NumPy array to a PyTorch tensor while supporting both CPU and GPU inputs, you can use the following function. This function checks if a CUDA-enabled GPU is available and converts the NumPy array accordingly. Here’s how you can implement it:
```python
import numpy as np
import torch
def numpy_to_tensor(nu... | 37,084 | [
{
"from": "human",
"value": "Write a Python function that takes a NumPy array as an argument and converts it to a PyTorch tensor. The function should handle both CPU and GPU inputs and convert the input array to a PyTorch tensor."
},
{
"from": "gpt",
"value": "To convert a NumPy array to a PyTor... |
Here is the code to count the number of "male" entries in the JSON file:
```python
import json
def count_males(filename):
count = 0
with open(filename, 'r') as file:
for line in file:
try:
json_obj = json.loads(line)
if json_obj['gender'] == 'male':
... | I want to read a large JSON file (500MB) that contains multiple JSON objects with the following structure:
```json
{
"name": "",
"age": 18,
"gender": "male"
}
```
Write a function to load the JSON file and count the number of "male" entries in the file. You may assume the file is large enough that you can... | To efficiently count the number of "male" entries in a large JSON file that contains multiple JSON objects separated by newlines, we can read and process the file line by line. This approach prevents loading the entire file into memory, accommodating the file's large size.
Here is a Python function that accomplishes t... | 37,085 | [
{
"from": "human",
"value": "I want to read a large JSON file (500MB) that contains multiple JSON objects with the following structure:\n\n```json\n{\n \"name\": \"\",\n \"age\": 18,\n \"gender\": \"male\"\n}\n```\n\nWrite a function to load the JSON file and count the number of \"male\" entries in... |
Here is the implementation:
```python
def flatten_and_normalize(lists_of_strings):
flattened_and_normalized = []
for inner_list in lists_of_strings:
concatenated_string = ' '.join(
[word.lower().replace(' ', '') for word in inner_list if word.isalpha()]
)
flattened_and_norm... | Write a Python function that takes a list of lists of strings as an argument. The function should concatenate each inner list of strings with a space separator and return a list of the concatenated strings. The function should also convert the strings to lowercase and replace all non-alphabetic characters with spaces. | Certainly! Below is a Python function that accomplishes what you described:
```python
import re
def process_strings(lists_of_strings):
result = []
for inner_list in lists_of_strings:
# Concatenate the inner list into a single string with spaces
concatenated = ' '.join(inner_list)
... | 37,086 | [
{
"from": "human",
"value": "Write a Python function that takes a list of lists of strings as an argument. The function should concatenate each inner list of strings with a space separator and return a list of the concatenated strings. The function should also convert the strings to lowercase and replace al... |
Here is a Python function that always returns zero, regardless of the arguments:
```python
def always_zero(x, y):
"""
Returns zero regardless of the arguments.
"""
return 0
```
This function always returns zero, regardless of the arguments. It can handle different types and mutable arguments, and it d... | I want to write a Python function that takes two arguments (x and y) and always returns zero. Write a documentation string that explains what the function does. | Certainly! Here is a Python function that meets your requirements along with a documentation string that explains its behavior:
```python
def always_zero(x, y):
"""
Returns zero regardless of the input values.
This function takes two arguments, x and y, but does not use them in any
calculations. No m... | 37,087 | [
{
"from": "human",
"value": "I want to write a Python function that takes two arguments (x and y) and always returns zero. Write a documentation string that explains what the function does."
},
{
"from": "gpt",
"value": "Certainly! Here is a Python function that meets your requirements along wit... |
Here's how you could do it:
```python
def non_empty_strings(strings):
try:
for string in strings:
if string.strip():
yield string
except Exception as e:
print(f'Error: {e}')
```
This function takes a list of strings as input and iterates through each string. It stri... | Write a Python function that takes a list of strings as input and returns a generator object of strings that are not empty. The function should handle any exceptions that may occur during the iteration process. Any empty strings should be ignored. | Certainly! Here is a Python function that takes a list of strings as input and returns a generator object that yields only the non-empty strings. It also includes error handling to catch any exceptions that may occur during the iteration process.
```python
def non_empty_strings(string_list):
"""Generator function ... | 37,088 | [
{
"from": "human",
"value": "Write a Python function that takes a list of strings as input and returns a generator object of strings that are not empty. The function should handle any exceptions that may occur during the iteration process. Any empty strings should be ignored."
},
{
"from": "gpt",
... |
You can calculate the DPS of a string by iterating through all of its substrings and adding their lengths to a variable. Then, check whether the sum is even or odd and return the appropriate message.
Here's how you can do it in Python:
```python
def dps_check(string):
dps = 0
for i in range(len(string)):
... | Determine the degree of protection (DPS) of a given string by calculating the sum of the lengths of its substrings. If the sum is even, return "DPS is divisible by 2" (or "DPS è divisibile per 2" in Italian), otherwise return "DPS is not divisible by 2" (or "DPS non è divisibile per 2").
Your code should pass the foll... | To determine the degree of protection (DPS) of a given string by calculating the sum of the lengths of its substrings, we can follow these steps:
1. **Calculate the number of substrings:** For a string of length `n`, there are a total of \( \frac{n(n + 1)}{2} \) substrings. Each substring can be formed by choosing a s... | 37,089 | [
{
"from": "human",
"value": "Determine the degree of protection (DPS) of a given string by calculating the sum of the lengths of its substrings. If the sum is even, return \"DPS is divisible by 2\" (or \"DPS è divisibile per 2\" in Italian), otherwise return \"DPS is not divisible by 2\" (or \"DPS non è div... |
Here's how you could do it:
```python
def swap_a_b(string):
swapped_string = ''
for char in string:
if char == 'a':
swapped_string += 'b'
elif char == 'b':
swapped_string += 'a'
else:
swapped_string += char
return swapped_string
``` | Write a Python function that replaces all occurrences of the letter 'a' in a given string with the letter 'b', and vice versa.
Your code should pass the following test case:
```python
test_string = 'aba'
swapped_string = swap_a_b(test_string)
assert swapped_string == 'bab'
``` | Here's a Python function that swaps all occurrences of the letter 'a' with 'b' and vice versa in a given string:
```python
def swap_a_b(input_string):
# Create a translation table that maps 'a' to 'b' and 'b' to 'a'
translation_table = str.maketrans('ab', 'ba')
# Use the translate method to apply the trans... | 37,090 | [
{
"from": "human",
"value": "Write a Python function that replaces all occurrences of the letter 'a' in a given string with the letter 'b', and vice versa.\n\nYour code should pass the following test case:\n```python\ntest_string = 'aba'\nswapped_string = swap_a_b(test_string)\nassert swapped_string == 'bab... |
Here's the implementation of the `filter_list_without_loops` function:
```python
def filter_list_without_loops(num_list):
return [num for num in num_list if num % 2 != 0]
``` | Write a Python function `filter_list_without_loops` that takes a list of integers and returns a filtered list without using loops. The function should apply a lambda expression to filter out even numbers and return the filtered list. | You can achieve this in Python using the `filter()` function along with a lambda expression. The `filter()` function applies the lambda to each element in the list and returns an iterator with elements that satisfy a specified condition. You can then convert that iterator back into a list.
Here's how you can write the... | 37,091 | [
{
"from": "human",
"value": "Write a Python function `filter_list_without_loops` that takes a list of integers and returns a filtered list without using loops. The function should apply a lambda expression to filter out even numbers and return the filtered list."
},
{
"from": "gpt",
"value": "Yo... |
Here's how you could do it:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
def create_linked_list(int_list):
head = None
current = None
for i, value in enumerate(int_list):
if value != -1:
node = Node(value)
if not head... | Write a Python function that takes a list of integers representing the block of a linked list, and return the linked list itself. The input list is provided as a list of integers in the following format: `[data, next_index, next_index, next_index, ...]`, where `data` represents the data stored in the node, and `next_in... | You can represent a linked list in Python using a class for the nodes. Below is a Python function that takes a list of integers in the format you described and constructs a linked list from it. Each node has an associated value and a reference to the next node.
Here's a sample implementation:
```python
class ListNode... | 37,092 | [
{
"from": "human",
"value": "Write a Python function that takes a list of integers representing the block of a linked list, and return the linked list itself. The input list is provided as a list of integers in the following format: `[data, next_index, next_index, next_index, ...]`, where `data` represents ... |
To create a dictionary that maps each version to a list of all versions that it is compatible with, you can use a defaultdict to group the version strings based on their major.minor numbers. Then, you can iterate through the list of version strings and check if their major.minor numbers match the input major.minor vers... | I have a list of strings that are all Windows version names. I want to make a dictionary that maps each version to a list of all versions that it is compatible with. The Windows version names are in the format `major.minor.build.hotfix`. I want to create a dictionary where I can look up any `major.minor` version number... | To solve the problem of mapping Windows version strings to their compatible versions based on the `major.minor` format, we can write a function `get_compatible_versions` that constructs and returns a dictionary for the compatible versions.
Here’s how we can implement this:
1. Create an empty dictionary.
2. Loop throu... | 37,093 | [
{
"from": "human",
"value": "I have a list of strings that are all Windows version names. I want to make a dictionary that maps each version to a list of all versions that it is compatible with. The Windows version names are in the format `major.minor.build.hotfix`. I want to create a dictionary where I can... |
Here is an example implementation of the `matrix_multiply` function in Python:
```python
def matrix_multiply(A, B):
"""Multiplies two matrices A and B."""
m, n = len(A), len(A[0])
n, p = len(B), len(B[0])
C = [[0 for _ in range(p)] for _ in range(m)]
def row_multiply(row_A, col_B):
return ... | You are given two matrices `A` and `B` of dimensions `m x n` and `n x p`, respectively. Write a Python function `matrix_multiply` that multiplies `A` and `B` together and returns the resulting matrix of dimensions `m x p`. Implement a for loop for multiplying the matrices. Ensure the loop contains at least 10 lines of ... | Certainly! Below is the implementation of the `matrix_multiply` function that multiplies two matrices using nested for loops. The function handles the multiplication and returns the resulting matrix.
```python
def matrix_multiply(A, B):
# Get the dimensions of A and B
m = len(A) # Number of rows in A
... | 37,094 | [
{
"from": "human",
"value": "You are given two matrices `A` and `B` of dimensions `m x n` and `n x p`, respectively. Write a Python function `matrix_multiply` that multiplies `A` and `B` together and returns the resulting matrix of dimensions `m x p`. Implement a for loop for multiplying the matrices. Ensur... |
Here is how you could implement such a function using the `csv` module:
```python
import csv
def average_second_column(filename):
try:
with open(filename, 'r') as f:
reader = csv.reader(f, delimiter=' ')
values = [int(row[1]) for row in reader if len(row) == 2]
if value... | Write a Python function that takes a filename as input and returns the average value of the second column from the input file. The input file contains one line per data point, where the first column is a string and the second column is an integer. For example, the following is a valid input file:
```
foo 4
bar 10
baz ... | To achieve the functionality described, we can define a Python function that reads the input file line by line, extracts the integer values from the second column, and calculates the average. If the file is empty or cannot be read correctly, the function will return `None`. Here's how the implementation looks:
```pyth... | 37,095 | [
{
"from": "human",
"value": "Write a Python function that takes a filename as input and returns the average value of the second column from the input file. The input file contains one line per data point, where the first column is a string and the second column is an integer. For example, the following is a... |
To create a Python function that converts Celsius to Fahrenheit and vice versa, you need to implement the formula $F = C \times \frac{9}{5} + 32$.
Here's how you can write the function in Python:
```python
def celcius_to_fahrenheit(celcius):
fahrenheit = celcius * 9 / 5 + 32
return fahrenheit
```
This functi... | Create a Python function that converts Celsius to Fahrenheit and vice versa.
The formula to convert from Celsius to Fahrenheit is $F = C \times \frac{9}{5} + 32$, where $F$ is the temperature in Fahrenheit and $C$ is the temperature in Celsius.
For example, if the input is 30, the function should return 86. | You can create a Python function that converts temperatures between Celsius and Fahrenheit. The function can take two parameters: the temperature value and the scale of the input temperature ("C" for Celsius and "F" for Fahrenheit). Based on the scale, the function will perform the appropriate conversion.
Here's an ex... | 37,096 | [
{
"from": "human",
"value": "Create a Python function that converts Celsius to Fahrenheit and vice versa.\n\nThe formula to convert from Celsius to Fahrenheit is $F = C \\times \\frac{9}{5} + 32$, where $F$ is the temperature in Fahrenheit and $C$ is the temperature in Celsius.\n\nFor example, if the input ... |
To solve this problem, you can use a list comprehension to filter the integers based on the `key` function, and then reverse the resulting list.
Here's how you could implement the `filter_and_reverse` function:
```python
def filter_and_reverse(nums, key=lambda x: True):
return [x for x in reversed(nums) if key(x)... | Write a Python function `filter_and_reverse` that takes two arguments: `nums`, a list of integers, and `key`, a function that determines if an integer in `nums` should be included in the filtered and reversed list. The function should return the reversed list of filtered integers. Here are the details for the `key` fun... | You can implement the `filter_and_reverse` function as described by using list comprehension to filter the integers in `nums` based on the provided `key` function, and then reversing the resulting list. Below is the Python code for the function:
```python
def filter_and_reverse(nums, key=lambda x: True):
# Filter ... | 37,097 | [
{
"from": "human",
"value": "Write a Python function `filter_and_reverse` that takes two arguments: `nums`, a list of integers, and `key`, a function that determines if an integer in `nums` should be included in the filtered and reversed list. The function should return the reversed list of filtered integer... |
To solve this problem in constant time and space complexity, we can use a prefix and suffix product array. The prefix product array contains the product of all elements up to the current index, and the suffix product array contains the product of all elements after the current index.
Here is an example implementation ... | Write a Python function that takes a list of integers `lst` and returns a list of strings `output` where `output[i]` is the product of all elements in `lst` except `lst[i]`. Do this in constant time and space complexity. For instance, given `lst = [1, 2, 3, 4]`, the function should return `['24', '12', '8', '6']`. | To solve the problem of finding the product of all elements in a list except the element at the current index, we can use the concept of prefix and suffix products. However, achieving this in constant time and space complexity isn't strictly feasible if we don't allow for the use of additional space for outputs or requ... | 37,098 | [
{
"from": "human",
"value": "Write a Python function that takes a list of integers `lst` and returns a list of strings `output` where `output[i]` is the product of all elements in `lst` except `lst[i]`. Do this in constant time and space complexity. For instance, given `lst = [1, 2, 3, 4]`, the function sho... |
The `@` operator in Python refers to matrix multiplication, and `X.T` refers to the transpose of matrix `X`. To compute the result of `X @ X.T`, we can use the `matmul` method from the `torch` library. This method can accept both dense and sparse tensors and perform efficient matrix multiplication operations.
However,... | I have a large matrix `X` and want to compute the product `X @ X.T`. However, `X` may be a sparse tensor, so I want to avoid allocating another matrix just for the intermediate result. Can you write a Python function that takes a sparse tensor `X` as input and returns the result of `X @ X.T` without allocating any new ... | Certainly! To compute the product `X @ X.T` without allocating additional memory for intermediate results, particularly when `X` is a sparse tensor, you can utilize the properties of sparse matrices and the efficient operations provided in libraries like `scipy`.
Here’s a function that takes a sparse tensor and comput... | 37,099 | [
{
"from": "human",
"value": "I have a large matrix `X` and want to compute the product `X @ X.T`. However, `X` may be a sparse tensor, so I want to avoid allocating another matrix just for the intermediate result. Can you write a Python function that takes a sparse tensor `X` as input and returns the result... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.