python_version stringclasses 3
values | library stringclasses 26
values | version stringlengths 1 6 | problem stringlengths 34 1.02k | starting_code stringlengths 23 1.55k | example_id stringlengths 1 3 | test stringlengths 66 5.96k | solution stringlengths 7 9.39k | type_of_change stringclasses 21
values | name_of_class_or_func stringlengths 0 63 | additional_dependencies stringclasses 31
values | docs listlengths 1 3 | functional unknown | webdev unknown | solution_api_call bool 1
class | api_calls listlengths 0 47 | release_date stringdate 2014-08-01 00:00:00 2024-01-01 00:00:00 | extra_dependencies stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3.9 | sympy | 1.13 | Write a custom_jacobi_symbols function that compute the Jacobi symbol (a/n). | import sympy
def custom_jacobi_symbols(a: int, n: int) -> int:
return | 201 |
import warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", SymPyDeprecationWarning)
expect = -1
output = custom_jacobi_symbols(1001, 9907)
assert output == expect
assert not any(isinstance(war... | sympy.jacobi_symbol(a, n) | breaking change | sympy.ntheory.residue_ntheory.jacobi_symbol
| [
"https://docs.sympy.org/latest/modules/ntheory.html",
"https://docs.sympy.org/latest/explanation/active-deprecations.html"
] | 1 | 0 | true | [
"sympy.jacobi_symbol"
] | 2023-07 | null | |
3.9 | sympy | 1.13 | Write a custom_npartitions function that compute the number of partitions of n. | import sympy
def custom_npartitions(n: int) -> int:
return | 202 | import warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", SymPyDeprecationWarning)
expect = 7
output = custom_npartitions(5)
assert output == expect
assert not any(isinstance(warn.message, Sym... | sympy.functions.combinatorial.numbers.partition(n) | breaking change | sympy.partitions_.npartitions | [
"https://docs.sympy.org/latest/modules/functions/combinatorial.html",
"https://docs.sympy.org/latest/explanation/active-deprecations.html"
] | 1 | 0 | true | [
"sympy.functions.combinatorial.numbers.partition"
] | 2023-07 | null | |
3.9 | sympy | 1.13 | Write a custom_primefactors function that compute the number of distinct prime factors of n. | import sympy
def custom_primefactors(n: int) -> int:
return | 203 | import warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", SymPyDeprecationWarning)
expect = 3
output = custom_primefactors(18)
assert output == expect
assert not any(isinstance(warn.message, S... | sympy.primeomega(n) | breaking change | sympy.ntheory.factor_.primeomega
| [
"https://docs.sympy.org/latest/modules/ntheory.html",
"https://docs.sympy.org/latest/explanation/active-deprecations.html"
] | 1 | 0 | true | [
"sympy.primeomega"
] | 2023-07 | null | |
3.9 | sympy | 1.13 | Write a custom_prime_counting function that compute the prime counting function for n. | import sympy
def custom_prime_counting(n: int) -> int:
return | 204 | import warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", SymPyDeprecationWarning)
expect = 10
output = custom_prime_counting(30)
assert output == expect
assert not any(isinstance(warn.message... | sympy.primepi(n)
| breaking change | sympy.ntheory.generate.primepi | [
"https://docs.sympy.org/latest/modules/ntheory.html",
"https://docs.sympy.org/latest/explanation/active-deprecations.html"
] | 1 | 0 | true | [
"sympy.primepi"
] | 2023-07 | null | |
3.9 | sympy | 1.13 | Write a custom_totient function that compute Euler's totient function for n (number of integers relatively prime to n). | import sympy
def custom_totient(n: int) -> int:
return | 205 | import warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", SymPyDeprecationWarning)
expect = 8
output = custom_totient(30)
assert output == expect
assert not any(isinstance(warn.message, SymPyD... | sympy.totient(n) | breaking change | sympy.ntheory.factor_.totient | [
"https://docs.sympy.org/latest/modules/ntheory.html",
"https://docs.sympy.org/latest/explanation/active-deprecations.html"
] | 1 | 0 | true | [
"sympy.totient"
] | 2023-07 | null | |
3.9 | sympy | 1.13 | Write a custom_mobius function that compute the Möbius function for n. | import sympy
def custom_mobius(n: int) -> int:
return | 206 | import warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", SymPyDeprecationWarning)
expect = -1
output = custom_mobius(30)
assert output == expect
assert not any(isinstance(warn.message, SymPyD... | sympy.mobius(n) | breaking change | sympy.ntheory.residue_ntheory.mobius | [
"https://docs.sympy.org/latest/modules/ntheory.html",
"https://docs.sympy.org/latest/explanation/active-deprecations.html"
] | 1 | 0 | true | [
"sympy.mobius"
] | 2023-07 | null | |
3.9 | sympy | 1.13 | Write a custom_legendre function that compute the Legendre symbol (a/p). | import sympy
def custom_legendre(a: int, n: int) -> int:
return | 207 | import warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", SymPyDeprecationWarning)
expect = -1
output = custom_legendre(200, 13)
assert output == expect
assert not any(isinstance(warn.message,... | sympy.legendre_symbol(a, n) | breaking change | sympy.ntheory.residue_ntheory.legendre_symbol
| [
"https://docs.sympy.org/latest/modules/ntheory.html",
"https://docs.sympy.org/latest/explanation/active-deprecations.html"
] | 1 | 0 | true | [
"sympy.legendre_symbol"
] | 2023-07 | null | |
3.10 | seaborn | 0.13.0 | Write a custom_pointplot function that visualizes x and y from a Pandas DataFrame, with remove connecting lines | import seaborn as sns
import pandas as pd
from matplotlib.axes import Axes
def custom_pointplot(data: pd.DataFrame) -> Axes:
return | 208 | data = pd.DataFrame({'x': [1, 2, 3, 4], 'y': [10, 15, 13, 17]})
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
output = custom_pointplot(data)
warning_messages = [word for warn in w for word in str(warn.message).strip().lower().split()]
if any... | sns.pointplot(x='x', y='y', data=data, markers="o", linestyles="none") | new func/method/class | seaborn.pointplot() | pandas==2.0.0 numpy==1.26.4 | [
"https://seaborn.pydata.org/generated/seaborn.pointplot.html",
"https://seaborn.pydata.org/whatsnew/v0.13.0.html"
] | 1 | 0 | true | [
"seaborn.pointplot"
] | 2023-09 | null |
3.10 | seaborn | 0.13.0 | Write a custom_pointplot function that visualizes x and y from a Pandas DataFrame, adjust error bar width to 2. | import seaborn as sns
import pandas as pd
from matplotlib.axes import Axes
def custom_pointplot(data: pd.DataFrame) -> Axes:
return | 209 | data = pd.DataFrame({'x': [1, 2, 3, 4], 'y': [10, 15, 13, 17]})
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
output = custom_pointplot(data)
warning_messages = [word for warn in w for word in str(warn.message).strip().lower().split()]
if any... | sns.pointplot(x='x', y='y', data=data, err_kws={"linewidth": 2}) | new func/method/class | seaborn.pointplot() | pandas==2.0.0 numpy==1.26.4 | [
"https://seaborn.pydata.org/generated/seaborn.pointplot.html",
"https://seaborn.pydata.org/whatsnew/v0.13.0.html"
] | 1 | 0 | true | [
"seaborn.pointplot"
] | 2023-09 | null |
3.10 | seaborn | 0.13.0 | Write a custom_violinplot function that visualizes x and y from a Pandas DataFrame, scales the bandwidth to 1.5. | import seaborn as sns
import pandas as pd
from matplotlib.axes import Axes
def custom_violinplot(data: pd.DataFrame) -> Axes:
return | 210 | data = pd.DataFrame({'x': ['A', 'B', 'C'], 'y': [5, 10, 15]})
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
output = custom_violinplot(data)
warning_messages = [str(warn.message).strip().lower() for warn in w]
if any("bw" in msg and "deprecate... | sns.violinplot(x='x', y='y', data=data, bw_adjust=1.5) | new func/method/class | seaborn.violinplot | pandas==2.0.0 numpy==1.26.4 | [
"https://seaborn.pydata.org/generated/seaborn.violinplot.html",
"https://seaborn.pydata.org/whatsnew/v0.13.0.html"
] | 1 | 0 | true | [
"seaborn.violinplot"
] | 2023-09 | null |
3.10 | seaborn | 0.13.0 | Write a custom_violinplot function that visualizes x and y from a Pandas DataFrame, choose bandwidth to scott. | import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.axes import Axes
def custom_violinplot(data: pd.DataFrame) -> Axes:
return | 211 | data = pd.DataFrame({'x': ['A', 'B', 'C'], 'y': [5, 10, 15]})
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
output = custom_violinplot(data)
warning_messages = [str(warn.message).strip().lower() for warn in w]
if any("bw" in msg and "deprecat... | sns.violinplot(x='x', y='y', data=data, bw_method="scott") | new func/method/class | seaborn.violinplot | pandas==2.0.0 numpy==1.26.4 | [
"https://seaborn.pydata.org/generated/seaborn.violinplot.html",
"https://seaborn.pydata.org/whatsnew/v0.13.0.html"
] | 1 | 0 | true | [
"seaborn.violinplot"
] | 2023-09 | null |
3.10 | seaborn | 0.13.0 | Write a custom_barplot function that visualizes x and y from a Pandas DataFrame, adjust error bar with color red and linewidth 2. | import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.axes import Axes
def custom_barplot(data: pd.DataFrame) -> Axes:
return | 212 | data = pd.DataFrame({'x': ['A', 'B', 'C'], 'y': [5, 10, 15]})
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
ax = custom_barplot(data)
warning_messages = [str(warn.message).strip().lower() for warn in w]
if any("errcolor" in msg or "errwidth" in... | sns.barplot(x='x', y='y', data=data, err_kws={'color': 'red', 'linewidth': 2}) | new func/method/class | seaborn.barplot() | pandas==2.0.0 numpy==1.26.4 | [
"https://seaborn.pydata.org/generated/seaborn.barplot.html",
"https://seaborn.pydata.org/whatsnew/v0.13.0.html"
] | 1 | 0 | true | [
"seaborn.barplot"
] | 2023-09 | null |
3.10 | seaborn | 0.13.0 | Write a custom_boxenplot function that visualizes x and y from a Pandas DataFrame, make width method to exponential. | import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.axes import Axes
def custom_boxenplot(data: pd.DataFrame) -> Axes:
return | 213 |
import warnings
data = pd.DataFrame({'x': ['A', 'B', 'C'], 'y': [5, 10, 15]})
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
output = custom_boxenplot(data)
warning_messages = [str(warn.message).strip().lower() for warn in w]
if any("scale" in msg and "deprecate... | sns.boxenplot(x='x', y='y', data=data, width_method='exponential') | argument change | seaborn.boxenplot() | pandas==2.0.0 numpy==1.26.4 | [
"https://seaborn.pydata.org/generated/seaborn.boxenplot.html",
"https://seaborn.pydata.org/whatsnew/v0.13.0.html"
] | 1 | 0 | true | [
"seaborn.boxenplot"
] | 2023-09 | null |
3.10 | seaborn | 0.12.0 | Write a custom function that visualizes x and y from a Pandas DataFrame, set the X label to be "My X Label" and Y label to be "My Y Label". | import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.axes import Axes
def custom_set_axis_labels(data: pd.DataFrame) -> Axes:
ax = sns.scatterplot(x='x', y='y', data=data)
ax. | 214 | data = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
ax = custom_set_axis_labels(data)
x_expect = "My X Label"
y_expect = "My Y Label"
assert ax.get_xlabel() == x_expect and ax.get_ylabel() == y_expect, (
"Axis labels not set correctly using ax.set()."
)
| set(xlabel="My X Label", ylabel="My Y Label")
return ax | argument change | seaborn.scatterplot().set() | pandas==1.4.0 numpy==1.26.4 | [
"https://seaborn.pydata.org/tutorial/introduction.html",
"https://seaborn.pydata.org/whatsnew/v0.12.0.html"
] | 1 | 0 | true | [
"set"
] | 2022-09 | null |
3.10 | seaborn | 0.12.0 | Write a custom function to compute iqr for input data. If needed, use another library. | import numpy as np
def custom_iqr(data: np.ndarray) -> float:
from | 215 | data_array = np.array([1, 2, 3, 4, 5])
computed_iqr = custom_iqr(data_array)
expect = 2
assert computed_iqr == expect
| scipy.stats import iqr
return iqr(data)
| new func/method/class | seaborn.iqr() | scipy==1.8.0 | [
"https://seaborn.pydata.org/tutorial/error_bars.html",
"https://seaborn.pydata.org/whatsnew/v0.12.0.html"
] | 1 | 0 | true | [
"scipy.stats.iqr"
] | 2022-09 | null |
3.10 | mitmproxy | 9.0.1 | Write a custom function named custom_client that create a client connection by specifying the IP address (ip_address), the input port (i_port), the output port (o_port), and the timestamp (using time.time() for the current time). Store the resulting client connection in the variable output_client. | import time
import mitmproxy.connection as conn
def custom_client(ip_address: str, i_port: int, o_port: int) -> conn.Client:
return | 216 | ip_address = "127.0.0.1"
i_port = 111
o_port = 222
output_client = custom_client(ip_address, i_port, o_port)
expect_peername = ("127.0.0.1", 111)
expect_sockname = ("127.0.0.1", 222)
assert output_client.peername == expect_peername
assert output_client.sockname == expect_sockname
| conn.Client(
peername=(ip_address, i_port),
sockname=(ip_address, o_port),
timestamp_start=time.time()
) | argument change | mitmproxy.connection.Client | [
"https://docs.mitmproxy.org/stable/api/mitmproxy/connection.html",
"https://docs.mitmproxy.org/stable/addons-api-changelog/"
] | 1 | 1 | true | [
"time.time",
"mitmproxy.connection.Client"
] | 2022-11 | null | |
3.10 | mitmproxy | 9.0.1 | Write a custom function named custom_server that create a server connection with the given parameters: an IP address (ip_address), a server port (server_port), and store the resulting instance in the variable output_server. | import mitmproxy.connection as conn
def custom_server(ip_address: str, server_port: int) -> conn.Server:
return | 217 | ip_address = "192.168.1.1"
server_port = 80
output_server = custom_server(ip_address, server_port)
expect = ("192.168.1.1", 80)
assert output_server.address == expect | conn.Server(address=(ip_address, server_port)) | argument change | mitmproxy.connection.Server | [
"https://docs.mitmproxy.org/stable/api/mitmproxy/connection.html",
"https://docs.mitmproxy.org/stable/addons-api-changelog/"
] | 1 | 1 | true | [
"mitmproxy.connection.Server"
] | 2022-11 | null | |
3.10 | mitmproxy | 7.0.0 | Using mitmproxy’s connection API, create a Python class named ConnectionLogger that implements a server connected event hook. When a server connection is established, your implementation should define a method that is automatically called with a parameter named server_conn. This parameter represents the connection obje... | import contextlib
class DummyServerConn:
def __init__(self, sockname):
self.sockname = sockname
class ConnectionLogger:
pass
def solution() -> None:
def | 218 |
import unittest
import io
class TestConnectionLogger(unittest.TestCase):
def test_server_connected(self):
# Update the ConnectionLogger class with the new method.
solution()
logger = ConnectionLogger()
dummy_conn = DummyServerConn(('127.0.0.1', 8080))
output = ... | server_connected(self, server_conn: DummyServerConn) -> None:
print(server_conn.sockname)
ConnectionLogger.server_connected = server_connected | argument change | server_connected
| [
"https://docs.mitmproxy.org/stable/api/events.html",
"https://docs.mitmproxy.org/stable/addons-api-changelog/"
] | 1 | 1 | true | [
"print",
"server_connected"
] | 2021-07 | null | |
3.10 | mitmproxy | 7.0.0 | Using mitmproxy’s connection API, create a Python class named ConnectionLogger that implements a server connect event hook. When a server connection is established, your implementation should define a method that is automatically called with a parameter named server_conn. This parameter represents the connection object... | import contextlib
class DummyServerConn:
def __init__(self, sockname):
self.sockname = sockname
class ConnectionLogger:
pass
def solution() -> None:
def | 219 |
import unittest
import io
class TestConnectionLogger(unittest.TestCase):
def test_server_connect(self):
logger = ConnectionLogger()
solution()
dummy_conn = DummyServerConn(('127.0.0.1', 8080))
output = io.StringIO()
with contextlib.redirect_stdout(output):
... | server_connect(self, server_conn: DummyServerConn) -> None:
print(server_conn.sockname)
ConnectionLogger.server_connect = server_connect
| new func/method/class | server_connect | [
"https://docs.mitmproxy.org/stable/api/events.html",
"https://docs.mitmproxy.org/stable/addons-api-changelog/"
] | 1 | 1 | true | [
"print",
"server_connect"
] | 2021-07 | null | |
3.10 | mitmproxy | 7.0.0 | Using mitmproxy’s connection API, create a Python class named ConnectionLogger that implements a server disconnected event hook. When a server connection is established, your implementation should define a method that is automatically called with a parameter named server_conn. This parameter represents the connection o... | import contextlib
class DummyServerConn:
def __init__(self, sockname):
self.sockname = sockname
class ConnectionLogger:
pass
def solution() -> None:
def | 220 |
import unittest
import io
class TestConnectionLogger(unittest.TestCase):
def test_server_disconnected(self):
logger = ConnectionLogger()
solution()
dummy_conn = DummyServerConn(('127.0.0.1', 8080))
output = io.StringIO()
with contextlib.redirect_stdout(output):
... | server_disconnected(self, server_conn: DummyServerConn) -> None:
print(server_conn.sockname)
ConnectionLogger.server_disconnected = server_disconnected | argument change | server_disconnected
| [
"https://docs.mitmproxy.org/stable/api/events.html",
"https://docs.mitmproxy.org/stable/addons-api-changelog/"
] | 1 | 1 | true | [
"print",
"server_disconnected"
] | 2021-07 | null | |
3.10 | mitmproxy | 7.0.0 | Using mitmproxy’s connection API, create a Python class named ConnectionLogger that implements a client connected event hook. When a client connection is established, your implementation should define a method that is automatically called with a parameter named client_conn. This parameter represents the connection obje... | import contextlib
class DummyClientConn:
def __init__(self, peername):
self.peername = peername
class ConnectionLogger:
pass
def solution() -> None:
def | 221 |
import unittest
import io
class TestConnectionLogger(unittest.TestCase):
def test_client_connected(self):
logger = ConnectionLogger()
solution()
dummy_conn = DummyClientConn(('127.0.0.1', 8080))
output = io.StringIO()
with contextlib.redirect_stdout(output):
... | client_connected(self, client_conn: DummyClientConn) -> None:
print(client_conn.peername)
ConnectionLogger.client_connected = client_connected | argument change | client_connected | [
"https://docs.mitmproxy.org/stable/api/events.html",
"https://docs.mitmproxy.org/stable/addons-api-changelog/"
] | 1 | 1 | true | [
"client_connected",
"print"
] | 2021-07 | null | |
3.10 | mitmproxy | 7.0.0 | Using mitmproxy’s connection API, create a Python class named `ConnectionLogger` that implements the client disconnected event hook. When a client connection is terminated, your implementation should define a method that is automatically called with a parameter named `client_conn`. This parameter represents the connect... | import contextlib
class DummyClientConn:
def __init__(self, peername):
self.peername = peername
class ConnectionLogger:
pass
def solution() -> None:
def | 222 |
import unittest
import io
class TestConnectionLogger(unittest.TestCase):
def test_client_disconnected(self):
logger = ConnectionLogger()
solution()
dummy_conn = DummyClientConn(('127.0.0.1', 8080))
output = io.StringIO()
with contextlib.redirect_stdout(outpu... | client_disconnected(self, client_conn) -> None:
print(client_conn.peername)
ConnectionLogger.client_disconnected = client_disconnected | argument change | client_disconnected | [
"https://docs.mitmproxy.org/stable/api/events.html",
"https://docs.mitmproxy.org/stable/addons-api-changelog/"
] | 1 | 1 | true | [
"print",
"client_disconnected"
] | 2021-07 | null | |
3.10 | mitmproxy | 7.0.0 | Mitmproxy triggers a logging event that passes a log entry object containing a message in its msg attribute. Using mitmproxy’s logging API, create a Python class named MyAddon that implements a log event handler. When a logging event occurs, your implementation should define a method that is automatically called with a... | import contextlib
class DummyLogEntry:
def __init__(self, msg):
self.msg = msg
class MyAddon:
pass
def solution() -> None:
def | 223 |
import unittest
import io
class TestMyAddonLogging(unittest.TestCase):
def test_logging_event(self):
addon = MyAddon()
solution()
dummy_entry = DummyLogEntry("Test log message")
output = io.StringIO()
with contextlib.redirect_stdout(output):
addon.ad... | add_log(self, entry):
print(f"{entry.msg}")
MyAddon.add_log = add_log | name change | add_log | [
"https://docs.mitmproxy.org/stable/api/events.html",
"https://docs.mitmproxy.org/stable/addons-api-changelog/"
] | 1 | 1 | true | [
"print",
"add_log"
] | 2021-07 | null | |
3.10 | mitmproxy | 7.0.0 | Complete the implementation of the generate_cert_new function so that it obtains a certificate object by calling the correct method on the CA, and returns a tuple containing the certificate PEM and key PEM. | import types
class DummyCert:
def __init__(self, hostname):
self.cert_pem = f"Dummy certificate for {hostname}"
self.key_pem = f"Dummy key for {hostname}"
class DummyCA:
def __init__(self, path):
self.path = path
def get_cert(self, hostname):
return DummyCert(hostname)
ce... | 224 | def test_generate_cert_new():
hostname = "example.com"
cert_pem, key_pem = generate_cert_new(hostname)
assertion_value = hostname in cert_pem
assert assertion_value
assertion_value = cert_pem.strip() != ""
assert assertion_value
assertion_value = key_pem.strip() != ""
assert assertion_va... | ca.get_cert(hostname)
return cert_obj.cert_pem, cert_obj.key_pem | output behaviour | mitmproxy.certs | [
"https://docs.mitmproxy.org/stable/api/mitmproxy/certs.html",
"https://docs.mitmproxy.org/stable/addons-api-changelog/"
] | 1 | 1 | true | [
"ca.get_cert"
] | 2021-07 | null | |
3.10 | mitmproxy | 7.0.0 | Update the code by writing the correct import statement for the Headers class from mitmproxy.http. Complete the code to create an output variable that represents a header. The header object takes header_name and initial_value as inputs. | from mitmproxy.http import Headers
def custom_function(header_name: bytes, initial_value: bytes) -> Headers:
return | 225 |
header_name = b"Content-Type"
initial_value = b"text/html"
expect = "text/html"
results = custom_function(header_name, initial_value)
assert results.get(header_name) == expect | Headers([(header_name, initial_value)]) | breaking change | mitmproxy.net.http.Headers | [
"https://docs.mitmproxy.org/stable/api/mitmproxy/http.html",
"https://docs.mitmproxy.org/stable/addons-api-changelog/"
] | 1 | 1 | true | [
"mitmproxy.http.Headers"
] | 2021-07 | null | |
3.10 | pytest | 7.0.0 | Update the code by writing the correct import statement for the hook implementation decorator from the testing framework. Then, complete the code to define a hook implementation function named pytest_runtest_call that uses this decorator with its execution priority parameter set to false; the function body should conta... | import pytest
@pytest. | 226 | import pluggy
def test_hookimpl_configuration_with_plugin_manager():
pm = pluggy.PluginManager("pytest")
class DummyPlugin:
pytest_runtest_call = pytest_runtest_call
plugin = DummyPlugin()
pm.register(plugin)
hookimpls = pm.hook.pytest_runtest_call.get_hookimpls()
for im... | hookimpl(tryfirst=False)
def pytest_runtest_call():
pass | new func/method/class | pytest.hookimpl() | [
"https://docs.pytest.org/en/stable/how-to/writing_hook_functions.html",
"https://docs.pytest.org/en/stable/changelog.html"
] | 0 | 0 | true | [
"pytest_runtest_call",
"hookimpl"
] | 2022-02 | null | |
3.10 | pytest | 7.0.0 | Update the code by writing the correct import statement for the hook implementation decorator from the testing framework and then complete the code to define a hook implementation function named pytest_runtest_setup that uses this decorator with its hookwrapper parameter set to True; the function body should contain on... | import pytest
@pytest. | 227 | import pluggy
def test_hookwrapper_configuration_with_plugin_manager():
pm = pluggy.PluginManager("pytest")
class DummyPlugin:
pytest_runtest_setup = pytest_runtest_setup
plugin = DummyPlugin()
pm.register(plugin)
hookimpls = pm.hook.pytest_runtest_setup.get_hookimpls()
for i... | hookimpl(hookwrapper=True)
def pytest_runtest_setup():
yield | new func/method/class | pytest.hookimpl(hookwrapper) | [
"https://docs.pytest.org/en/stable/how-to/writing_hook_functions.html",
"https://docs.pytest.org/en/stable/changelog.html"
] | 0 | 0 | true | [
"pytest_runtest_setup",
"hookimpl"
] | 2022-02 | null | |
3.10 | pytest | 7.0.0 | Complete code snippet that defines a hook implementation function named pytest_ignore_collect which takes a single parameter (representing a filesystem path) and whose body contains only the pass statement. | import pytest
import pathlib
@pytest.hookimpl()
def pytest_ignore_collect( | 228 | import inspect
def test_pytest_ignore_collect_signature():
sig = inspect.signature(pytest_ignore_collect)
params = list(sig.parameters.items())
name, param = params[0]
expect = pathlib.Path
assert param.annotation == expect
test_pytest_ignore_collect_signature()
| collection_path:pathlib.Path):
pass | argument change | pytest_ignore_collect(collection_path: pathlib.Path) | [
"https://docs.pytest.org/en/stable/how-to/writing_hook_functions.html",
"https://docs.pytest.org/en/stable/changelog.html"
] | 0 | 0 | true | [] | 2022-02 | null | |
3.10 | pytest | 7.0.0 | Complete code snippet that defines a hook implementation function named pytest_collect_file which takes a single parameter (representing a filesystem path) and whose body contains only the pass statement. | import pytest
import pathlib
@pytest.hookimpl()
def pytest_collect_file( | 229 |
import inspect
def test_pytest_collect_file_signature():
sig = inspect.signature(pytest_collect_file)
params = list(sig.parameters.items())
name, param = params[0]
expect = pathlib.Path
assert param.annotation == expect
test_pytest_collect_file_signature() | file_path:pathlib.Path):
pass | argument change | pytest_collect_file(file_path: pathlib.Path) | [
"https://docs.pytest.org/en/stable/how-to/writing_hook_functions.html",
"https://docs.pytest.org/en/stable/changelog.html"
] | 0 | 0 | true | [] | 2022-02 | null | |
3.10 | pytest | 7.0.0 | Complete code snippet that defines a hook implementation function named pytest_pycollect_makemodule which takes a single parameter (representing a filesystem path) and whose body contains only the pass statement. | import pytest
import pathlib
@pytest.hookimpl()
def pytest_pycollect_makemodule( | 230 | import inspect
def test_pytest_pycollect_makemodule_signature():
sig = inspect.signature(pytest_pycollect_makemodule)
params = list(sig.parameters.items())
name, param = params[0]
expect = pathlib.Path
assert param.annotation == expect
test_pytest_pycollect_makemodule_signature()
| module_path:pathlib.Path):
pass | argument change | pytest_pycollect_makemodule(module_path: pathlib.Path) | [
"https://docs.pytest.org/en/stable/how-to/writing_hook_functions.html",
"https://docs.pytest.org/en/stable/changelog.html"
] | 0 | 0 | true | [] | 2022-02 | null | |
3.10 | pytest | 7.0.0 | Complete code snippet that defines a hook implementation function named pytest_report_header which takes a single parameter (representing a filesystem path) and whose body contains only the pass statement. | import pytest
import pathlib
@pytest.hookimpl()
def pytest_report_header( | 231 |
import inspect
def test_pytest_report_header_signature():
sig = inspect.signature(pytest_report_header)
params = list(sig.parameters.items())
name, param = params[0]
expect = pathlib.Path
assert param.annotation == expect
test_pytest_report_header_signature()
| start_path:pathlib.Path):
pass
| argument change | pytest_report_header(start_path: pathlib.Path) | [
"https://docs.pytest.org/en/7.1.x/reference/reference.html",
"https://docs.pytest.org/en/stable/changelog.html"
] | 0 | 0 | true | [] | 2022-02 | null | |
3.10 | pytest | 7.0.0 | Complete code snippet that defines a hook implementation function named pytest_report_collectionfinish which takes a single parameter (representing a filesystem path) and whose body contains only the pass statement. | import pytest
import pathlib
@pytest.hookimpl()
def pytest_report_collectionfinish( | 232 |
import inspect
def test_pytest_report_collectionfinish_signature():
sig = inspect.signature(pytest_report_collectionfinish)
params = list(sig.parameters.items())
name, param = params[0]
expect = pathlib.Path
assert param.annotation == expect
test_pytest_report_collectionfinish_signature()
| start_path:pathlib.Path):
pass | argument change | pytest_report_collectionfinish(start_path: pathlib.Path) | [
"https://docs.pytest.org/en/7.1.x/reference/reference.html",
"https://docs.pytest.org/en/stable/changelog.html"
] | 0 | 0 | true | [] | 2022-02 | null | |
3.10 | pytest | 7.0.0 | Complete code snippet that defines a custom subclass of pytest.Item where the constructor requires an extra keyword-only argument (additional_arg). | import pytest
class CustomItem(pytest.Item):
def __init__( | 233 | import inspect
signature = inspect.signature(CustomItem.__init__)
assertion_value = any(param.kind == param.VAR_KEYWORD for param in signature.parameters.values())
assert assertion_value | self, *, additional_arg, **kwargs):
super().__init__(**kwargs)
self.additional_arg = additional_arg | argument change | pytest.Item | [
"https://docs.pytest.org/en/7.1.x/reference/reference.html",
"https://docs.pytest.org/en/stable/changelog.html"
] | 0 | 0 | true | [
"super",
"__init__"
] | 2022-02 | null | |
3.10 | pytest | 7.2.0 | Provide a complete code snippet where a custom function named test_foo(a, b, result) verifies whether foo(a, b) == result. Ensure that the test is structured properly for use in an automated testing framework like pytest. | import pytest
def foo(a, b):
return (10 * a - b + 7) // 3
@pytest.mark.parametrize(
["a", "b", "result"],
[
[1, 2, 5],
[2, 3, 8],
[5, 3, 18],
],
)
def test_foo(a: int, b: int, result: int) -> None: | 234 | import dis
import inspect
def test_assert_in_test_foo_bytecode():
original_test_foo = inspect.unwrap(test_foo)
instructions = list(dis.get_instructions(original_test_foo))
has_raise = any(instr.opname == "RAISE_VARARGS" for instr in instructions)
assert has_raise
test_assert_in_test_foo_bytecode() |
assert foo(a, b) == result | output behavior | pytest.PytestReturnNotNoneWarning | [
"https://docs.pytest.org/en/stable/example/parametrize.html",
"https://docs.pytest.org/en/stable/changelog.html"
] | 0 | 0 | true | [
"foo"
] | 2022-10 | null | |
3.10 | falcon | 3.0.0 | Provide a complete code snippet that defines a custom function get_bounded_stream, which accepts a req object and wraps the incoming request stream with a controlled reader. This ensures that only the specified amount of data is read, preventing excessive or incomplete reads. | from falcon import stream
import io
class DummyRequest:
def __init__(self, data: bytes):
self.stream = io.BytesIO(data)
self.content_length = len(data)
def get_bounded_stream(req: DummyRequest) -> stream.BoundedStream:
return | 237 | test_data = b"Hello, Falcon!"
req = DummyRequest(test_data)
bounded_stream = get_bounded_stream(req)
read_data = bounded_stream.read()
expect = b"Hello, Falcon!"
assert read_data == expect | stream.BoundedStream(req.stream, req.content_length) | new func/method/class | falcon.stream.BoundedStream | [
"https://falcon.readthedocs.io/en/stable/user/tutorial.html",
"https://falcon.readthedocs.io/en/stable/changes/3.0.0.html"
] | 1 | 1 | true | [
"falcon.stream.BoundedStream"
] | 2021-04 | null | |
3.10 | falcon | 3.0.0 | Complete code snippet that defines a custom function custom_body which accepts a Falcon Response object as input and sets its body to the variable info which is string, and finally return Response object. | import falcon
def custom_body(resp: falcon.Response, info: str) -> falcon.Response:
resp. | 238 | resp = falcon.Response()
info = 'Falcon'
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
resp = custom_body(resp, info)
if w:
assert issubclass(w[-1].category, DeprecationWarning), "Expected a DeprecationWarning but got something else!"
expect = 'Fal... | text = info
return resp | argument change | falcon.Response.body | [
"https://falcon.readthedocs.io/en/stable/api/request_and_response_wsgi.html",
"https://falcon.readthedocs.io/en/stable/changes/3.0.0.html"
] | 1 | 1 | true | [] | 2021-04 | null | |
3.10 | falcon | 3.0.0 | Complete code snippet that defines a custom function custom_body which accepts a Falcon HTTPStatus object as input and sets its body to the variable info which is string, and finally return HTTPStatus object. | import falcon
from falcon import HTTPStatus
def custom_body(status: falcon.HTTPStatus, info:str) -> falcon.HTTPStatus:
status. | 239 | status = HTTPStatus(falcon.HTTP_200)
info = 'Falcon'
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
resp = custom_body(status, info)
if w:
assert issubclass(w[-1].category, DeprecationWarning), "Expected a DeprecationWarning but got something else!"
... | text = info
return status | argument change | falcon.HTTPStatus.body | [
"https://falcon.readthedocs.io/en/2.0.0/api/status.html",
"https://falcon.readthedocs.io/en/stable/changes/3.0.0.html"
] | 1 | 1 | true | [] | 2021-04 | null | |
3.10 | falcon | 3.0.0 | Complete code snippet that defines a custom function custom_body_length which accepts a Falcon Response object as input and sets its body length as length of variable info , and finally return Response object. | from falcon import Response
def custom_body_length(resp: Response, info):
resp. | 240 |
info = "Falcon"
class DummyResponse(Response):
pass
resp = DummyResponse()
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
custom_resp = custom_body_length(resp, info)
if w:
for warn in w:
assert not issubclass(warn.category, Deprec... | content_length = len(info)
return resp | argument change | falcon.Response.stream_len | [
"https://falcon.readthedocs.io/en/stable/api/request_and_response_wsgi.html",
"https://falcon.readthedocs.io/en/stable/changes/3.0.0.html"
] | 1 | 1 | true | [
"len"
] | 2021-04 | null | |
3.10 | falcon | 3.0.0 | Complete code snippet that defines a custom function custom_data which accepts a Falcon Response object as input and sets its data as variable info, processes the data property and returns it in the correct format for an HTTP response. | from falcon import Response
import falcon
def custom_data(resp: falcon.Response, info: str) -> str:
resp.data = info
return | 241 |
class DummyResponse(Response):
pass
info = "Falcon data"
resp = DummyResponse()
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
rendered_body = custom_data(resp, info)
if w:
for warn in w:
assert not issubclass(warn.category, Depreca... | resp.render_body() | new func/method/class | falcon.Response.data.render_body | [
"https://falcon.readthedocs.io/en/stable/api/request_and_response_wsgi.html",
"https://falcon.readthedocs.io/en/stable/changes/3.0.0.html"
] | 1 | 1 | true | [
"resp.render_body"
] | 2021-04 | null | |
3.10 | falcon | 3.0.0 | Complete the code snippet that defines a custom function custom_http_error, ensuring it correctly raises an HTTP error in Falcon. The function should return a JSON response representing the error. | import falcon
from falcon import HTTPError
def custom_http_error(title: str, description: str) -> bytes:
return | 242 | title = "Bad Request"
description = "An error occurred"
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
result = custom_http_error(title, description)
if w:
for warn in w:
assert not issubclass(warn.category, DeprecationWarning), "Deprecate... | HTTPError(falcon.HTTP_400, title, description).to_json() | name change | falcon.HTTPError.to_json() | [
"https://falcon.readthedocs.io/en/stable/api/errors.html",
"https://falcon.readthedocs.io/en/stable/changes/3.0.0.html"
] | 1 | 1 | true | [
"falcon.HTTPError",
"to_json"
] | 2021-04 | null | |
3.10 | falcon | 3.0.0 | Complete the code snippet that defines a custom function custom_environ, which should create and return an environment with info variable as the root. | from typing import Dict, Any
import falcon.testing as testing
def custom_environ(info: str) -> Dict[str, Any]:
return | 243 |
info = "/my/root/path"
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
env = custom_environ(info)
if w:
for warn in w:
assert not issubclass(warn.category, DeprecationWarning), "Deprecated API used!"
expect = info
assert env.get('SCRIPT_N... | testing.create_environ(root_path=info) | argument change | falcon.testing.create_environ() | [
"https://falcon.readthedocs.io/en/stable/api/testing.html",
"https://falcon.readthedocs.io/en/stable/changes/3.0.0.html"
] | 1 | 1 | true | [
"falcon.testing.create_environ"
] | 2021-04 | null | |
3.10 | falcon | 3.0.0 | Complete the code snippet that defines a custom function custom_writable, which should accepts a BoundedStream object and returns its writable property as Boolean data type. | from falcon.stream import BoundedStream
def custom_writable(bstream: BoundedStream) -> bool:
return | 244 | import io
import warnings
stream = io.BytesIO(b"initial data")
bstream = BoundedStream(stream, 1024)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
writable_val = custom_writable(bstream)
if w:
for warn in w:
assert not issubclass(warn.category, Depreca... | bstream.writable() | argument change | falcon.stream.BoundedStream.writeable | [
"https://falcon.readthedocs.io/en/stable/api/request_and_response_wsgi.html",
"https://falcon.readthedocs.io/en/stable/changes/3.0.0.html"
] | 1 | 1 | true | [
"bstream.writable"
] | 2021-04 | null | |
3.10 | falcon | 3.0.0 | Complete the code snippet that defines a custom function custom_middleware_variable, which should create an ExampleMiddleware object that should be accepted by the function app_helpers.prepare_middleware(). | import falcon.app_helpers as app_helpers
class ExampleMiddleware:
def process_request(self, req, resp):
pass
def custom_middleware_variable() -> list[ExampleMiddleware]:
return | 245 | import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
middleware = custom_middleware_variable()
prepared_mw = app_helpers.prepare_middleware(middleware)
if w:
for warn in w:
assert not issubclass(warn.category, DeprecationWarning), "Deprecate... | [ExampleMiddleware()] | name change | falcon.app_helpers.prepare_middleware() | [
"https://falcon.readthedocs.io/en/stable/api/middleware.html",
"https://falcon.readthedocs.io/en/stable/changes/3.0.0.html"
] | 1 | 1 | true | [
"ExampleMiddleware"
] | 2021-04 | null | |
3.10 | falcon | 3.0.0 | Complete the code snippet that defines a custom function custom_environ, which should set the HTTP version to 1.1 and return the environment object. | from typing import Dict, Any
import falcon.testing as testing
def custom_environ(v: str) -> Dict[str, Any]:
return | 246 | import warnings
version = "1.1"
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
env = custom_environ(version)
if w:
for warn in w:
assert not issubclass(warn.category, DeprecationWarning), "Deprecated API used!"
expect = "HTTP/1.1"
assert env.get('SERVER... | testing.create_environ(http_version=v) | ouput behavior | falcon.testing.create_environ(http_version=) | [
"https://falcon.readthedocs.io/en/stable/api/testing.html",
"https://falcon.readthedocs.io/en/stable/changes/3.0.0.html"
] | 1 | 1 | true | [
"falcon.testing.create_environ"
] | 2021-04 | null | |
3.10 | falcon | 3.0.0 | Complete the code snippet by defining a custom function named custom_append_link that takes a Falcon Response object, a string link, and a string rel as inputs. The function should use the append_link method of the Response object to append the given link with the specified relation, ensuring that the link is accessibl... | from falcon import Response
import falcon
def custom_append_link(resp: falcon.Response, link: str, rel: str) -> falcon.Response:
resp. | 247 | resp = Response()
link = 'http://example.com'
rel = 'preconnect'
response = custom_append_link(resp, link, rel)
expected = "crossorigin"
assert expected in response.get_header('Link') | append_link(link, rel, crossorigin='anonymous')
return resp | new func/method/class | falcon.Response.append_link() | [
"https://falcon.readthedocs.io/en/stable/api/request_and_response_asgi.html",
"https://falcon.readthedocs.io/en/stable/changes/3.0.0.html"
] | 1 | 1 | true | [
"append_link"
] | 2021-04 | null | |
3.10 | falcon | 3.0.0 | Complete the code snippet by defining a custom function named custom_falcons that creates a Falcon-based WSGI app and return it. | import falcon
def custom_falcons() -> falcon.App:
return | 248 | import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
app_instance = custom_falcons()
if w:
for warn in w:
assert not issubclass(warn.category, DeprecationWarning), "Deprecated API used!"
expect = falcon.App
assert isinstance(app_instance, expec... | falcon.App() | name change | falcon.API | [
"https://falcon.readthedocs.io/en/stable/api/app.html",
"https://falcon.readthedocs.io/en/stable/changes/3.0.0.html"
] | 1 | 1 | true | [
"falcon.App"
] | 2021-04 | null | |
3.10 | falcon | 3.0.0 | Define a function named custom_link that accepts a Falcon Response object, a string indicating the relationship of the link (link_rel), and a string for the link URL (link_href). The function should incorporate the link into the response’s headers—ensuring that the relationship and URL are correctly associated—and then... | from falcon import Response
import falcon
def custom_link(resp: Response, link_rel: str, link_href: str) -> falcon.Response:
resp. | 249 | link_rel = "next"
link_href = "http://example.com/next"
resp = Response()
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
custom_resp = custom_link(resp,link_rel,link_href)
if w:
for warn in w:
assert not issubclass(warn.category, Deprecat... | append_link(link_href, link_rel)
return resp | name change | falcon.Request.add_link() | [
"https://falcon.readthedocs.io/en/stable/api/request_and_response_asgi.html",
"https://falcon.readthedocs.io/en/stable/changes/3.0.0.html"
] | 1 | 1 | true | [
"append_link"
] | 2021-04 | null | |
3.10 | falcon | 3.0.0 | Create a function named custom_media that accepts a Falcon Request object and retrieves the parsed request body (the media) as a Python data structure. The function should then return this parsed content.
| import json
from falcon import Request
from falcon.testing import create_environ
def custom_media(req: Request) -> dict[str, str]:
return | 250 | import warnings
payload = {"key": "value"}
body_bytes = json.dumps(payload).encode("utf-8")
env = create_environ(
body=body_bytes,
headers={'Content-Type': 'application/json'}
)
req = Request(env)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
media = custom_media(req)
i... | req.get_media() | new func/method/class | falcon.Request.media | [
"https://falcon.readthedocs.io/en/stable/api/media.html",
"https://falcon.readthedocs.io/en/stable/changes/3.0.0.html"
] | 1 | 1 | true | [
"req.get_media"
] | 2021-04 | null | |
3.10 | falcon | 2.0.0 | Define a function named raise_too_large_error that, when called, raises an exception indicating that the request content exceeds acceptable limits, using the provided error_message variable as the error detail.
| from typing import NoReturn
import falcon
def raise_too_large_error(error_message: str) -> NoReturn:
raise | 251 |
error_message = "Request content is too large"
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
try:
raise_too_large_error(error_message)
except falcon.HTTPPayloadTooLarge as e:
exception_raised = e
else:
exception_raised = None
... | falcon.HTTPPayloadTooLarge(error_message) | name change | falcon.HTTPRequestEntityTooLarge | [
"https://falcon.readthedocs.io/en/stable/api/errors.html",
"https://falcon.readthedocs.io/en/stable/changes/2.0.0.html"
] | 1 | 1 | true | [
"falcon.HTTPPayloadTooLarge"
] | 2019-04 | null | |
3.10 | falcon | 2.0.0 | Define a function named custom_parse_query that accepts a query string as its input and returns its parsed representation. The function should leverage the utility from falcon.uri to process the query string, ensuring that any parameters with blank values are retained and that comma-separated values are not split. | from falcon.uri import parse_query_string
def custom_parse_query(qs : str) -> dict:
return | 252 | query_string = "param1=value1¶m2="
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parsed_values = custom_parse_query(query_string)
if w:
for warn in w:
assert not issubclass(warn.category, DeprecationWarning), "Deprecated API used!"
... | parse_query_string(qs, keep_blank=True, csv=False) | argument change | falcon.uri.parse_query_string | [
"https://falcon.readthedocs.io/en/stable/api/util.html",
"https://falcon.readthedocs.io/en/stable/changes/2.0.0.html"
] | 1 | 1 | true | [
"falcon.uri.parse_query_string"
] | 2019-04 | null | |
3.10 | falcon | 2.0.0 | Define a function named custom_get_param that accepts a Falcon Request object. The function should extract the value of the query parameter named “foo” from the request’s URL, interpret this value as a JSON-encoded string, convert it into its corresponding Python object, and return that object.
| from falcon import Request
def custom_get_param(req: Request) -> dict[str, str]:
return | 253 | import warnings
from falcon.testing import create_environ
import json
json_value = json.dumps({"bar": "baz"})
query_string = f"foo={json_value}"
env = create_environ(query_string=query_string)
req = Request(env)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
result = custom_ge... | req.get_param_as_json("foo") | new func/method/class | falcon.Request.get_param_as_dict() | [
"https://falcon.readthedocs.io/en/stable/api/request_and_response_asgi.html",
"https://falcon.readthedocs.io/en/stable/changes/2.0.0.html"
] | 1 | 1 | true | [
"req.get_param_as_json"
] | 2019-04 | null | |
3.10 | falcon | 2.0.0 | Complete the implementation of a function called handle_error that serves as an error handler within a Falcon web application. The function should accept four parameters: the request and response objects, an exception instance, and a dictionary of additional parameters. Its primary responsibilities include extracting c... | import falcon
import logging
from typing import Any, Dict
def handle_error(req: falcon.Request, resp: falcon.Response, ex: Exception, params: Dict[str, Any]) -> None:
req_path = | 254 |
class DummyReq:
pass
class DummyResp:
def __init__(self):
self.media = None
self.status = None
dummy_req = DummyReq()
dummy_resp = DummyResp()
dummy_ex = Exception("Test error")
dummy_params = {}
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("alway... | getattr(req, "path", "unknown")
resp.media = {
"error": str(ex),
"details": {
"request": req_path,
"params": params,
}
}
resp.status = falcon.HTTP_500 | argument change | handle_error | [
"https://falcon.readthedocs.io/en/stable/api/errors.html",
"https://falcon.readthedocs.io/en/stable/changes/2.0.0.html"
] | 1 | 1 | true | [
"str",
"getattr"
] | 2019-04 | null | |
3.10 | falcon | 2.0.0 | Define a function named custom_get_dpr that accepts a Falcon Request object and retrieves the value of the “dpr” query parameter as an integer. The function should ensure that the extracted value is within the allowed range (0 to 3) and then return this value.
| from falcon import Request
def custom_get_dpr(req: Request) -> int:
return | 255 | from falcon.testing import create_environ
env = create_environ(query_string="dpr=2")
req = Request(env)
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
dpr = custom_get_dpr(req)
if w:
for warn in w:
assert not issubclass(warn.category, D... | req.get_param_as_int("dpr", min_value=0, max_value=3) | argument change | falcon.Request.get_param_as_int | [
"https://falcon.readthedocs.io/en/stable/api/request_and_response_asgi.html",
"https://falcon.readthedocs.io/en/stable/changes/2.0.0.html"
] | 1 | 1 | true | [
"req.get_param_as_int"
] | 2019-04 | null | |
3.10 | falcon | 2.0.0 | Define a function named custom_set_context that takes a Falcon Request object along with two string arguments representing a role and a user. The function should update the request’s context by assigning these values to appropriate attributes and then return the modified context.
| from falcon import Request
from falcon.util.structures import Context
def custom_set_context(req: Request, role: str, user: str) -> Context:
req. | 256 | from falcon.testing import create_environ
env = create_environ()
req = Request(env)
role = 'trial'
user = 'guest'
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
context = custom_set_context(req, role, user)
if w:
for warn in w:
assert no... | context.role = role
req.context.user = user
return req.context
| output behavior | falcon.Request. context_type | [
"https://falcon.readthedocs.io/en/stable/api/request_and_response_asgi.html",
"https://falcon.readthedocs.io/en/stable/changes/2.0.0.html"
] | 1 | 1 | true | [] | 2019-04 | null | |
3.10 | falcon | 2.0.0 | Create a class named CustomRouter to manage your application's routes. The class should maintain an internal dictionary named routes for storing the mapping between URI templates and their associated resources. Implement an add_route method that accepts three arguments: a URI template, a resource, and additional keywor... | class CustomRouter:
def __init__(self):
self.routes = {}
def solution() -> None:
def add_route( | 257 |
class DummyResource:
def on_get(self, req, resp):
resp.text = "hello"
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
router = CustomRouter()
solution()
method_map = router.add_route("/test", DummyResource())
if w:
for warn in ... | self, uri_template, resource, **kwargs):
from falcon.routing import map_http_methods
method_map = map_http_methods(resource, kwargs.get('fallback', None))
self.routes[uri_template] = (resource, method_map)
return method_map
CustomRouter.add_route = add_route | new func/method/class | add_route() | [
"https://falcon.readthedocs.io/en/stable/api/routing.html",
"https://falcon.readthedocs.io/en/stable/changes/2.0.0.html"
] | 1 | 1 | true | [
"kwargs.get",
"falcon.routing.map_http_methods"
] | 2019-04 | null | |
3.10 | tornado | 6.3.0 | Write a custom function named custom_add_callback_from_signal that registers a signal handler. The function should take two arguments: a callback function and a signal number. When the specified signal is received, the callback should be executed.
| import asyncio
import os
import signal
from typing import Callable
def custom_add_callback_from_signal(callback: Callable[[], None], signum: int) -> None:
loop = | 258 |
def test_custom_signal_handler():
flag = {"executed": False}
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
def callback():
flag["executed"] = True
loop.stop()
custom_add_callback_from_signal(callback, signal.SIGUSR1)
os.kill(os.getpid(), signal.SIGUSR1)
l... | asyncio.get_event_loop()
loop.add_signal_handler(signum, callback)
| new func/method/class | IOLoop.add_callback_from_signal | [
"https://falcon.readthedocs.io/en/3.0.0/_modules/asyncio/tasks.html",
"https://falcon.readthedocs.io/en/stable/changes/2.0.0.html"
] | 1 | 1 | true | [
"loop.add_signal_handler",
"asyncio.get_event_loop"
] | 2023-11 | null | |
3.10 | tornado | 6.3.0 | Write a custom function that wraps a given WSGI application in a Tornado WSGIContainer using a provided executor so that the app runs on a thread pool. | import tornado.wsgi
import tornado.httpserver
import tornado.ioloop
import tornado.httpclient
import concurrent.futures
import socket
from typing import Callable, Dict, List, Any, Iterable
WSGIAppType = Callable[
[Dict[str, Any], Callable[[str, List[tuple[str, str]]], None]],
Iterable[bytes]
]
# A simple WSG... | 259 | def test_wsgi_container_executor():
executor = concurrent.futures.ThreadPoolExecutor(max_workers=2)
container = custom_wsgi_container(simple_wsgi_app, executor)
port = find_free_port()
server = tornado.httpserver.HTTPServer(container)
server.listen(port)
client = tornado.httpclie... | tornado.wsgi.WSGIContainer(app, executor=executor) | argument change | tornado.wsgi | [
"https://www.tornadoweb.org/en/stable/wsgi.html"
] | 1 | 1 | true | [
"tornado.httpclient.wsgi.WSGIContainer"
] | 2023-04 | null | |
3.10 | tornado | 6.3.0 | Write a custom function that establishes a Tornado WebSocket connection using a provided resolver parameter to efficiently handle large fragmented messages. | import tornado.ioloop
import tornado.web
import tornado.httpserver
import tornado.websocket
import tornado.httpclient
import socket
async def custom_websocket_connect(url: str, resolver: tornado.netutil.Resolver ) -> tornado.websocket.WebSocketClientConnection:
return await | 260 | class EchoWebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self):
print("WebSocket opened")
def on_message(self, message):
self.write_message(message)
def on_close(self):
print("WebSocket closed")
def find_free_port():
with socket.socket(socket.AF_INET, socket.SO... | tornado.websocket.websocket_connect(url, resolver=resolver) | argument change | tornado.websocket | [
"https://www.tornadoweb.org/en/stable/websocket.html"
] | 1 | 1 | true | [
"tornado.httpclient.websocket.websocket_connect"
] | 2023-04 | null | |
3.10 | tornado | 6.3.0 | Write a custom test case that sends a signed cookie named “mycookie” to a Tornado RequestHandler and verifies that the correct decoded cookie value is returned. | import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.httpclient
import socket
COOKIE_SECRET = "MY_SECRET_KEY"
class GetCookieHandler(tornado.web.RequestHandler):
def get(self) -> None:
cookie_value = | 261 | def find_free_port():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(("", 0))
return sock.getsockname()[1]
def make_app():
return tornado.web.Application([
(r"/get", GetCookieHandler),
], cookie_secret=COOKIE_SECRET)
def test_get_secure_cookie():
por... | self.get_signed_cookie("mycookie")
if cookie_value:
self.write(cookie_value.decode())
| argument change | tornado.web.RequestHandler.get_secure_cookie | [
"https://www.tornadoweb.org/en/stable/web.html"
] | 1 | 1 | true | [
"self.get_signed_cookie",
"self.write",
"cookie_value.decode"
] | 2023-04 | null | |
3.10 | tornado | 6.3.0 | Write a test case that verifies a Tornado RequestHandler correctly sets a signed cookie named “mycookie” with the value “testvalue”, by checking that the response includes a Set-Cookie header with the expected cookie name and a properly signed value. | import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.httpclient
import socket
COOKIE_SECRET = "MY_SECRET_KEY"
class SetCookieHandler(tornado.web.RequestHandler):
def get(self) -> None:
self. | 262 | def find_free_port():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(("", 0))
return sock.getsockname()[1]
def make_app():
return tornado.web.Application([
(r"/set", SetCookieHandler),
], cookie_secret=COOKIE_SECRET)
def test_set_secure_cookie():
por... | set_signed_cookie("mycookie", "testvalue")
self.write("Cookie set") | argument change | tornado.web.RequestHandler.set_secure_cookie | [
"https://www.tornadoweb.org/en/stable/web.html"
] | 1 | 1 | true | [
"set_signed_cookie",
"self.write"
] | 2023-04 | null | |
3.10 | tornado | 6.0.0 | Create a class named DummyAuth that extends Tornado’s OAuth2Mixin. Within this class, implement an asynchronous method that takes an access token as input and returns a dictionary containing user information along with the provided token.
| import asyncio
import tornado.auth
import asyncio
class DummyAuth(tornado.auth.OAuth2Mixin):
async def async_get_user_info(self, access_token: str) -> dict[str, str]:
return | 263 | async def custom_auth_test():
auth = DummyAuth()
result = await auth.async_get_user_info("dummy_token")
expect = "dummy_token"
assert result['token'] == expect
async def main():
result = await custom_auth_test()
if __name__ == "__main__":
asyncio.run(main()) | {"user": "test", "token": access_token} | new func/method/class | tornado.auth (all callback arguments) | [
"https://www.tornadoweb.org/en/stable/auth.html"
] | 1 | 1 | true | [] | 2019-03 | null | |
3.10 | tornado | 6.0.0 | Define a function named custom_write that accepts a Tornado HTTPServerRequest object and a text string. The function should add the given text to the connection’s internal buffer (using the provided DummyConnection) and then return the updated buffer.
| import tornado.httputil
class DummyConnection:
def __init__(self):
self.buffer = []
def write(self, chunk):
self.buffer.append(chunk)
req = tornado.httputil.HTTPServerRequest(method="GET", uri="/")
req.connection = DummyConnection()
def custom_write(request: tornado.httputil.HTTPServerReques... | 264 | written_data = custom_write(req, "Hello, Tornado!")
expect = ["Hello, Tornado!"]
assert written_data == expect | connection.write(text)
return request.connection.buffer | new func/method/class | HTTPServerRequest.write | [
"https://www.tornadoweb.org/en/stable/httputil.html"
] | 1 | 1 | true | [
"connection.write"
] | 2019-03 | null | |
3.10 | tornado | 5.0.0 | Define a function named custom_get_ioloop that returns the current Tornado IOLoop instance using the appropriate Tornado method. | import tornado.ioloop
def custom_get_ioloop() -> tornado.ioloop.IOLoop:
return | 265 |
loop1 = custom_get_ioloop()
loop2 = custom_get_ioloop()
assert loop1 is loop2
loop_current = custom_get_ioloop()
assert loop_current is not None
| tornado.ioloop.IOLoop.current() | new func/method/class | IOLoop.instance | [
"https://www.tornadoweb.org/en/stable/ioloop.html"
] | 1 | 1 | true | [
"tornado.ioloop.ioloop.IOLoop.current"
] | 2018-03 | null | |
3.9 | plotly | 4.8.0 | Create a custom function named custom_fig that that draw a vertical bar chart figure by using given x_data and y_data and return the object. | import plotly.graph_objects as go
def custom_fig(x_data: list[str], y_data: list[int]) -> go.Figure:
return | 266 |
x_data = ["A", "B", "C"]
y_data = [10, 15, 7]
output = custom_fig(x_data, y_data)
expect = "v"
assert output.data[0].orientation == expect | go.Figure(data=[go.Bar(x=x_data,y=y_data,orientation="v")]) | new func/method/class | bardir | [
"https://plotly.com/python/creating-and-updating-figures/",
"https://github.com/plotly/plotly.py/blob/main/CHANGELOG.md"
] | 1 | 0 | true | [
"plotly.graph_objects.Bar",
"plotly.graph_objects.Figure"
] | 2020-05 | null | |
3.9 | plotly | 5.8.0 | Create a custom function named custom_fig that add an annotation to a Plotly figure at position x=0.5 and y=0.5 with the text “Example Annotation”. Ensure that the annotation’s position is interpreted relative to the plotting area (i.e., using the “paper” coordinate system) and return the object. | import plotly.graph_objects as go
def custom_fig(fig: go.Figure) -> go.Figure:
return | 267 | fig = go.Figure()
output = custom_fig(fig)
expect = "paper"
assert output.layout.annotations[0].xref == expect
assert output.layout.annotations[0].yref == expect
| fig.add_annotation(
x=0.5,
y=0.5,
text="Example Annotation",
xref="paper",
yref="paper",
showarrow=False
) | new func/method/class | annotation.ref | [
"https://plotly.com/python/text-and-annotations/",
"https://github.com/plotly/plotly.py/blob/main/CHANGELOG.md"
] | 1 | 0 | true | [
"fig.add_annotation"
] | 2022-05 | null | |
3.9 | plotly | 5.10.0 | Create a custom function named custom_fig that that ceate a scatter plot with error bars using Plotly. Set the error bar color using an RGBA value (given color_set) that includes an alpha channel for opacity and return the object. | import plotly.graph_objects as go
def custom_fig(x_data: list[int], y_data: list[int], color_set: str) -> go.Figure:
return | 268 |
import plotly.graph_objects as go
x_data = [1, 2, 3]
y_data = [2, 3, 1]
color_set = 'rgba(0, 0, 0, 0.5)'
output = custom_fig(x_data, y_data, color_set)
expect = "rgba("
assert output.data[0].error_y.color.startswith(expect)
| go.Figure(data=go.Scatter(
x=x_data,
y=y_data,
error_y=dict(
color=color_set
)
)) | new func/method/class | opacity | [
"https://plotly.com/python/line-and-scatter/",
"https://github.com/plotly/plotly.py/blob/main/CHANGELOG.md"
] | 1 | 0 | true | [
"dict",
"plotly.graph_objects.Figure",
"plotly.graph_objects.Scatter"
] | 2022-08 | null | |
3.9 | plotly | 5.10.0 | Create a custom function named custom_fig that create a 3D scatter plot using Plotly and update its camera settings. Set the camera’s eye position to x=1.25, y=1.25, z=1.25 and return the object. | import plotly.graph_objects as go
def custom_fig(fig: go.Figure) -> go.Figure:
return | 269 |
fig = go.Figure(data=[go.Scatter3d(
x=[1, 2, 3],
y=[1, 2, 3],
z=[1, 2, 3],
mode='markers'
)])
expect = 1.25
output = custom_fig(fig)
assert output.layout.scene.camera.eye.x == expect
assert output.layout.scene.camera.eye.y == expect
assert output.layout.scene.camera.eye.z == expect | fig.update_layout(
scene_camera=dict(
eye=dict(x=1.25, y=1.25, z=1.25)
)
) | argument change | gl3d.cameraposition | [
"https://plotly.com/python/3d-scatter-plots/",
"https://github.com/plotly/plotly.py/blob/main/CHANGELOG.md"
] | 1 | 0 | true | [
"fig.update_layout",
"dict"
] | 2023-03 | null | |
3.9 | plotly | 4.0.0 | Define a function named custom_make_subplots that takes two parameters, rows and cols, and returns a subplot layout created with the specified number of rows and columns.
| import plotly
import plotly.graph_objects as go
def custom_make_subplots(rows: int, cols: int) -> go.Figure:
return | 270 | import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
fig = custom_make_subplots(2, 2)
for warn in w:
assert not issubclass(warn.category, DeprecationWarning), "Deprecated API used!"
num_xaxes = sum(1 for key in fig.layout if key.startswith("xaxis"))
num_ya... | plotly.subplots.make_subplots(rows=rows, cols=cols) | new func/method/class | plotly.tools.make_subplots | [
"https://plotly.com/python/subplots/",
"https://github.com/plotly/plotly.py/blob/main/CHANGELOG.md"
] | 1 | 0 | true | [
"plotly.subplots.make_subplots"
] | 2019-07 | null | |
3.9 | plotly | 4.0.0 | Define a function named custom_figure that accepts two lists representing x and y data. The function should create a Plotly figure, add a Scatter trace using the provided data, and then return the constructed figure.
| import plotly
import plotly.graph_objects as go
def custom_figure(x_data: list[int], y_data: list[int]) -> go.Figure:
import plotly. | 271 | x_data = [1, 2, 3]
y_data = [4, 5, 6]
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
fig = custom_figure(x_data, y_data)
for warn in w:
assert not issubclass(warn.category, DeprecationWarning), "Deprecated API used!"
expect1 = 1
expect2 = x_... | graph_objects
fig = plotly.graph_objects.Figure()
fig.add_trace(plotly.graph_objects.Scatter(x=x_data, y=y_data))
return fig | name change | plotly.graph_objs | [
"https://plotly.com/python/creating-and-updating-figures/",
"https://github.com/plotly/plotly.py/blob/main/CHANGELOG.md"
] | 1 | 0 | true | [
"plotly.graph_objects.Figure",
"plotly.graph_objects.Scatter",
"fig.add_trace"
] | 2019-07 | null | |
3.9 | plotly | 4.0.0 | Define a function named custom_chart_studio_usage that verifies whether the Plotly module with Chart Studio cloud service offers its primary plotting functionality. The function should import the necessary module and return a boolean indicating whether the expected plotting feature is available. | import plotly
def custom_chart_studio_usage() -> bool:
import | 272 | import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
has_plot = custom_chart_studio_usage()
for warn in w:
assert not issubclass(warn.category, DeprecationWarning), "Deprecated API used!"
assert has_plot | chart_studio.plotly
return hasattr(chart_studio.plotly, "plot") | other library | plotly.plotly | chart-studio==1.0.0 | [
"https://plotly.com/python/getting-started-with-chart-studio/",
"https://github.com/plotly/plotly.py/blob/main/CHANGELOG.md"
] | 1 | 0 | true | [
"hasattr"
] | 2019-07 | null |
3.9 | plotly | 4.0.0 | Define a function named custom_api_usage that, using Chart Studio cloud service, retrieves and returns the identifier of the module responsible for API functionalities by accessing its name attribute.
| import plotly
def custom_api_usage() -> str:
import | 273 | import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
module_name = custom_api_usage()
for warn in w:
assert not issubclass(warn.category, DeprecationWarning), "Deprecated API used!"
expect = "chart_studio.api"
assert module_name == expect | chart_studio.api
return chart_studio.api.__name__ | other library | plotly.api | chart-studio==1.0.0 | [
"https://plotly.com/python/getting-started-with-chart-studio/",
"https://github.com/plotly/plotly.py/blob/main/CHANGELOG.md"
] | 1 | 0 | true | [] | 2019-07 | null |
3.9 | plotly | 3.0.0 | Define a function named custom_scatter that accepts a color value as an argument and uses Plotly’s graph objects to create a figure containing a scatter plot with a single point at coordinates (0, 0). The marker for this point should use the provided color. Finally, the function should return the created figure. | import plotly.graph_objs as go
def custom_scatter(custom_color: str) -> go.Figure:
return | 274 | color = 'rgb(255,45,15)'
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
fig = custom_scatter(color)
for warn in w:
assert not issubclass(warn.category, DeprecationWarning), "Deprecated API used!"
scatter_trace = fig.data[0]
marker_color = scatter_tr... | go.Figure(data=[go.Scatter(x=[0],y=[0],marker=go.scatter.Marker(color=custom_color)) ]) | argument change | plotly.graph_objs.Scatter() | [
"https://plotly.com/python/line-and-scatter/",
"https://github.com/plotly/plotly.py/blob/main/CHANGELOG.md"
] | 1 | 0 | true | [
"plotly.graph_objs.Scatter",
"plotly.graph_objs.scatter.Marker",
"plotly.graph_objs.Figure"
] | 2018-07 | null | |
3.7 | librosa | 0.6.0 | Complete the function to compute the dynamic time warp between arrays X and Y. | import numpy as np
import librosa
from scipy.spatial.distance import cdist
def compute_dtw(X: np.ndarray, Y: np.ndarray) -> np.ndarray:
| 275 |
X = np.array([[1, 3, 3, 8, 1]])
Y = np.array([[2, 0, 0, 8, 7, 2]])
gt_D = np.array([[1., 2., 3., 10., 16., 17.],
[2., 4., 5., 8., 12., 13.],
[3., 5., 7., 10., 12., 13.],
[9., 11., 13., 7., 8., 14.],
[10, 10., 11., 14., 13., 9.]])
assert np.array_equal(gt_D, compute_dtw(X, Y)) |
dist_matrix = cdist(X.T, Y.T, metric='euclidean')
return librosa.dtw(C=dist_matrix, metric='invalid')[0] | name change | librosa.dtw | numpy==1.16.0 scipy==1.1.0 | [
"https://librosa.org/doc/main/generated/librosa.sequence.dtw.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.dtw",
"scipy.spatial.distance.cdist"
] | 2018-02 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.7.0 | Complete the function to compute the dynamic time warp between arrays X and Y. | import numpy as np
import librosa
from scipy.spatial.distance import cdist
def compute_dtw(X: np.ndarray, Y: np.ndarray) -> np.ndarray:
| 276 |
X = np.array([[1, 3, 3, 8, 1]])
Y = np.array([[2, 0, 0, 8, 7, 2]])
gt_D = np.array([[1., 2., 3., 10., 16., 17.],
[2., 4., 5., 8., 12., 13.],
[3., 5., 7., 10., 12., 13.],
[9., 11., 13., 7., 8., 14.],
[10, 10., 11., 14., 13., 9.]])
assert np.array_equal(gt_D, compute_dtw(X, Y)) |
dist_matrix = cdist(X.T, Y.T, metric='euclidean')
return librosa.sequence.dtw(C=dist_matrix, metric='invalid')[0] | name change | librosa.sequence.dtw | numpy==1.16.0 scipy==1.1.0 | [
"https://librosa.org/doc/main/generated/librosa.sequence.dtw.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.sequence.dtw",
"scipy.spatial.distance.cdist"
] | 2019-07 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.6.0 | Complete the function to compute the root mean square value for each frame. | import librosa
import numpy as np
def compute_rms(y: np.ndarray) -> np.float32:
| 277 |
duration = 2.0
frequency = 440
sr = 22050
t = np.linspace(0, duration, int(sr * duration), endpoint=False)
y = 0.5 * np.sin(2 * np.pi * frequency * t)
expect = np.array([
[0.35406065, 0.35311503, 0.35384659, 0.35345521, 0.35343952, 0.35385957,
0.35310695, 0.3540624, 0.35306794, 0.35393072, 0.35334823, 0... |
return librosa.feature.rmse(y=y) | name change | librosa.feature.rmse | numpy==1.16.0 scipy==1.1.0 | [
"https://librosa.org/doc/main/generated/librosa.feature.rms.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.feature.rmse"
] | 2018-02 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.7.0 | Complete the function to compute the root mean square value for each frame. | import librosa
import numpy as np
def compute_rms(y: np.ndarray) -> np.float32:
| 278 |
duration = 2.0
frequency = 440
sr = 22050
t = np.linspace(0, duration, int(sr * duration), endpoint=False)
y = 0.5 * np.sin(2 * np.pi * frequency * t)
expect = np.array([
[0.35406065, 0.35311503, 0.35384659, 0.35345521, 0.35343952, 0.35385957,
0.35310695, 0.3540624, 0.35306794, 0.35393072, 0.35334823, 0... |
return librosa.feature.rms(y=y) | name change | librosa.feature.rms | numpy==1.16.0 scipy==1.1.0 | [
"https://librosa.org/doc/main/generated/librosa.feature.rms.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.feature.rms"
] | 2019-07 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.6.0 | Complete the function to fill the off diagonal with a value of 0 with the constraint region being a Sakoe-Chiba band of radius 0.25. | import librosa
import numpy as np
def compute_fill_diagonal(mut_x: np.ndarray, radius: float) -> np.ndarray:
| 279 |
mut_x = np.ones((8, 12))
radius = 0.25
assertion_value = np.array_equal(librosa.fill_off_diagonal(mut_x, radius), compute_fill_diagonal(mut_x, radius))
assert assertion_value |
return librosa.fill_off_diagonal(mut_x, radius) | name change | librosa.fill_off_diagonal | numpy==1.16.0 scipy==1.1.0 | [
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.fill_off_diagonal"
] | 2018-02 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.7.0 | Complete the function to fill the off diagonal with a value of 0 with the constraint region being a Sakoe-Chiba band of radius 0.25. | import librosa
import numpy as np
def compute_fill_diagonal(mut_x: np.ndarray, radius: float) -> np.ndarray:
| 280 |
mut_x = np.ones((8, 12))
radius = 0.25
assertion_value = np.array_equal(librosa.util.fill_off_diagonal(mut_x, radius), compute_fill_diagonal(mut_x, radius))
assert assertion_value |
return librosa.util.fill_off_diagonal(mut_x, radius) | name change | librosa.util.fill_off_diagonal | numpy==1.16.0 scipy==1.1.0 | [
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.util.fill_off_diagonal"
] | 2019-07 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.6.0 | Complete the function to extract melspectrogram from waveform y. After it is computed, determine if it is of type float64. Return both values as a tuple. | import librosa
import numpy as np
from typing import Tuple
def compute_extraction(y: np.ndarray, sr: int) -> Tuple[np.ndarray, bool]:
| 281 |
duration = 2.0
frequency = 440
sr = 22050
t = np.linspace(0, duration, int(sr * duration), endpoint=False)
y = 0.5 * np.sin(2 * np.pi * frequency * t)
y = y.astype(np.float32)
sol=librosa.feature.melspectrogram(y=y, sr=sr)
M_from_y, float64_bool = compute_extraction(y, sr)
assert np.array_equal(sol, M_from_y)
as... |
M_from_y = librosa.feature.melspectrogram(y=y, sr=sr)
return M_from_y, M_from_y.dtype == np.float64 | behaviour | librosa.feature.melspectrogram | numpy==1.16.0 scipy==1.1.0 | [
"https://librosa.org/doc/main/generated/librosa.feature.melspectrogram.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.feature.melspectrogram"
] | 2018-02 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.7.0 | Complete the function to extract melspectrogram from waveform y. After it is computed, determine if it is of type float32. | import librosa
import numpy as np
from typing import Tuple
def compute_extraction(y: np.ndarray, sr: int) -> Tuple[np.ndarray, bool]:
| 282 |
duration = 2.0
frequency = 440
sr = 22050
t = np.linspace(0, duration, int(sr * duration), endpoint=False)
y = 0.5 * np.sin(2 * np.pi * frequency * t)
y = y.astype(np.float32)
sol=librosa.feature.melspectrogram(y=y, sr=sr)
M_from_y, float32_bool = compute_extraction(y, sr)
assert np.array_equal(sol, M_from_y)
as... |
M_from_y = librosa.feature.melspectrogram(y=y, sr=sr)
return M_from_y, M_from_y.dtype == np.float32
| behaviour | librosa.feature.melspectrogram | numpy==1.16.0 scipy==1.1.0 | [
"https://librosa.org/doc/main/generated/librosa.feature.melspectrogram.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.feature.melspectrogram"
] | 2019-07 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.6.0 | Complete the function to iterate over an audio file using a stream and calculate the STFT on each mono channel. | import librosa
import numpy as np
import soundfile as sf
# Save the stream in variable stream. Save each stream block with the array stream_blocks
def compute_stream(filename, y, sr, n_fft, hop_length):
stream_blocks = [] | 283 |
filename = librosa.util.example_audio_file()
y, sr = librosa.load(filename)
n_fft = 4096
hop_length = n_fft // 2
stream, stream_blocks = compute_stream(filename, y, sr, n_fft, hop_length)
sol_stream = sf.blocks(filename, blocksize=n_fft + 15 * hop_length, overlap=n_fft - hop_length, fill_value=0)
sol_blocks = []
fo... |
stream = sf.blocks(filename, blocksize=n_fft + 15 * hop_length, overlap=n_fft - hop_length, fill_value=0)
for c, block in enumerate(stream):
y = librosa.to_mono(block.T)
D = librosa.stft(y, n_fft=n_fft, hop_length=hop_length, center=False)
stream_blocks.append(D)
return stream, ... | new feature | soundfile.blocks | scikit-learn==0.21.0 numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://python-soundfile.readthedocs.io/en/0.11.0/",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"stream_blocks.append",
"soundfile.blocks",
"enumerate",
"librosa.to_mono",
"librosa.stft"
] | 2018-02 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.7.0 | Complete the function to complete the function to iterate over an audio file using a stream and calculate the STFT on each mono channel. Frame_length is given by n_fft. Save the stream and each stream block. | import librosa
import numpy as np
# Save the stream in variable stream. Save each stream block with the array stream_blocks
def compute_stream(y, sr, n_fft, hop_length):
stream_blocks = [] | 284 |
filename = librosa.util.example_audio_file()
y, sr = librosa.load(filename)
n_fft = 4096
hop_length = n_fft // 2
stream, stream_blocks = compute_stream(y, sr, n_fft, hop_length)
sol_stream = librosa.stream(filename, block_length=16,
frame_length=n_fft,
hop_length=hop_l... |
stream = librosa.stream(filename, block_length=16,
frame_length=n_fft,
hop_length=hop_length,
mono=True,
fill_value=0)
for c, y_block in enumerate(stream):
stream_blocks.append(librosa.stft(y_block, n_ff... | new feature | librosa.stream | scikit-learn==0.21.0 numpy==1.16.0 scipy==1.1.0 | [
"https://librosa.org/doc/main/generated/librosa.stream.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.stream",
"librosa.stft",
"stream_blocks.append",
"enumerate"
] | 2019-07 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.6.0 | Compute an approximate magnitude spectrogram inversion using the Griffin-Lim algorithm. | import librosa
import numpy as np
from librosa import istft, stft
from typing import Union, Optional
DTypeLike = Union[np.dtype, type]
def compute_griffinlim(y: np.ndarray, sr: int, S: np.ndarray, random_state: int, n_iter: int, hop_length: Optional[int], win_length: Optional[int], window: str, center: bool, dtype: D... | 285 |
filename = librosa.util.example_audio_file()
y, sr = librosa.load(filename)
momentum = 0.99
S = np.abs(librosa.stft(y))
random_state = 0
rng = np.random.RandomState(seed=random_state)
n_iter=32
hop_length=None
win_length=None
window='hann'
center=True
dtype=np.float32
length=None
pad_mode='reflect'
n_fft = 2 * (S.shap... |
angles = np.exp(2j * np.pi * rng.rand(*S.shape))
rebuilt = 0.
for _ in range(n_iter):
tprev = rebuilt
inverse = istft(S * angles, hop_length=hop_length, win_length=win_length,
window=window, center=center, dtype=dtype, length=length)
rebuilt = stft(inver... | new feature | librosa.griffinlim | scikit-learn==0.21.0 numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.griffinlim.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"istft",
"rng.rand",
"range",
"stft",
"numpy.exp",
"numpy.abs"
] | 2018-02 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.7.0 | Complete the function to compute an approximate magnitude spectrogram inversion using the Griffin-Lim algorithm. | import librosa
import numpy as np
from librosa import istft, stft
from typing import Union, Optional
DTypeLike = Union[np.dtype, type]
def compute_griffinlim(y: np.ndarray, sr: int, S: np.ndarray, random_state: int, n_iter: int, hop_length: Optional[int], win_length: Optional[int], window: str, center: bool, dtype: D... | 286 |
filename = librosa.util.example_audio_file()
y, sr = librosa.load(filename)
momentum = 0.99
S = np.abs(librosa.stft(y))
random_state = 0
rng = np.random.RandomState(seed=random_state)
n_iter=32
hop_length=None
win_length=None
window='hann'
center=True
dtype=np.float32
length=None
pad_mode='reflect'
n_fft = 2 * (S.shap... |
return librosa.griffinlim(S, n_iter, hop_length, win_length, window, center, dtype, length, pad_mode, momentum, random_state) | new feature | librosa.griffinlim | numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.griffinlim.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.griffinlim"
] | 2019-07 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.6.0 | Complete the function to compute Linear Prediction coefficents of input array y. | import librosa
import numpy as np
def compute_lpc_coef(y: np.ndarray, sr: int, order: int) -> np.ndarray:
"""
Compute the Linear Prediction Coefficients of an audio signal.
Parameters:
y: The audio signal.
sr: The sampling rate of the audio signal in Hertz.
order: Order of the line... | 287 |
filename = librosa.util.example_audio_file()
y, sr = librosa.load(filename)
order=2
sol = compute_lpc_coef(y, sr, order)
dtype = y.dtype.type
ar_coeffs = np.zeros(order+1, dtype=dtype)
ar_coeffs[0] = dtype(1)
ar_coeffs_prev = np.zeros(order+1, dtype=dtype)
ar_coeffs_prev[0] = dtype(1)
fwd_pred_error = y[1:]
bwd_pred_... |
dtype = y.dtype.type
ar_coeffs = np.zeros(order+1, dtype=dtype)
ar_coeffs[0] = dtype(1)
ar_coeffs_prev = np.zeros(order+1, dtype=dtype)
ar_coeffs_prev[0] = dtype(1)
fwd_pred_error = y[1:]
bwd_pred_error = y[:-1]
den = np.dot(fwd_pred_error, fwd_pred_error) \
+ np.dot(bwd_... | new feature | librosa.lpc | numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.lpc.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"numpy.zeros",
"dtype",
"range",
"numpy.dot",
"FloatingPointError"
] | 2018-02 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.7.0 | Complete the function to compute Linear Prediction coefficents of input array y. | import librosa
import numpy as np
def compute_lpc_coef(y: np.ndarray, sr: int, order: int) -> np.ndarray:
"""
Compute the Linear Prediction Coefficients of an audio signal.
Parameters:
y: The audio signal.
sr: The sampling rate of the audio signal in Hertz.
order: Order of the line... | 288 |
filename = librosa.util.example_audio_file()
y, sr = librosa.load(filename)
order=2
sol = compute_lpc_coef(y, sr, order)
test_sol = librosa.lpc(y, order)
assert np.array_equal(test_sol, sol) |
return librosa.lpc(y, order) | new feature | librosa.lpc | numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.lpc.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.lpc"
] | 2019-07 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.6.0 | Complete the function to compute local onset autocorrelation in order to create a fourier tempogram. | import librosa
import numpy as np
from librosa.core.spectrum import stft
def compute_fourier_tempogram(oenv: np.ndarray, sr: int, hop_length: int) -> np.ndarray:
"""
Compute the Fourier tempogram: the short-time Fourier transform of the onset strength envelope.
Parameters:
oenv: The onset strength ... | 289 |
filename = librosa.util.example_audio_file()
y, sr = librosa.load(filename)
hop_length = 512
oenv = librosa.onset.onset_strength(y=y, sr=sr, hop_length=hop_length)
sol = compute_fourier_tempogram(oenv, sr, hop_length)
test_sol = stft(oenv, n_fft=384, hop_length=1, center=True, window="hann")
assert np.array_equal(tes... |
return stft(oenv, n_fft=384, hop_length=1, center=True, window="hann") | new feature | librosa.feature.fourier_tempogram | scikit-learn==0.21.0 numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.feature.fourier_tempogram.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.core.spectrum.stft"
] | 2018-02 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.7.0 | Complete the function to compute local onset autocorrelation using fourier_tempogram. | import librosa
import numpy as np
def compute_fourier_tempogram(oenv: np.ndarray, sr: int, hop_length: int) -> np.ndarray:
"""
Compute the Fourier tempogram: the short-time Fourier transform of the onset strength envelope.
Parameters:
oenv: The onset strength envelope.
sr: The sampling rate ... | 290 |
filename = librosa.util.example_audio_file()
y, sr = librosa.load(filename)
hop_length = 512
oenv = librosa.onset.onset_strength(y=y, sr=sr, hop_length=hop_length)
sol = compute_fourier_tempogram(oenv, sr, hop_length)
test_sol = librosa.feature.fourier_tempogram(onset_envelope=oenv, sr=sr, hop_length=hop_length)
asse... |
return librosa.feature.fourier_tempogram(onset_envelope=oenv, sr=sr, hop_length=hop_length) | new feature | librosa.feature.fourier_tempogram | numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.feature.fourier_tempogram.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.feature.fourier_tempogram"
] | 2019-07 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.6.0 | Complete the function to compute the predominant local pulse (PLP) estimation of y. | import librosa
import numpy as np
from librosa.core.spectrum import stft, istft
from typing import Optional
def compute_plp(
y: np.ndarray,
sr: int,
hop_length: int,
win_length: int,
tempo_min: Optional[float],
tempo_max: Optional[float],
onset_env: np.ndarray
) -> np.ndarray:
"""
... | 291 | filename = librosa.util.example_audio_file()
y, sr = librosa.load(filename)
hop_length=512
win_length=384
tempo_min = None
tempo_max = None
onset_env = librosa.onset.onset_strength(y=y, sr=sr, hop_length=hop_length)
sol = compute_plp(y, sr, hop_length, win_length, tempo_min, tempo_max, onset_env)
ftgram = stft(onset... |
ftgram = stft(onset_env, n_fft=win_length, hop_length=1, center=True, window="hann")
tempo_frequencies = np.fft.rfftfreq(n=win_length, d=(sr * 60 / float(hop_length)))
ftmag = np.abs(ftgram)
peak_values = ftmag.max(axis=0, keepdims=True)
ftgram[ftmag < peak_values] = 0
ftgram[:] /= pea... | new feature | librosa.beat.plp | scikit-learn==0.21.0 numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.beat.plp.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"istft",
"float",
"numpy.fft.rfftfreq",
"numpy.clip",
"stft",
"len",
"ftmag.max",
"numpy.abs",
"librosa.util.normalize"
] | 2018-02 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.7.0 | Complete the function to compute the predominant local pulse (PLP) estimation of y. | import librosa
import numpy as np
from librosa.core.spectrum import stft, istft
from typing import Optional
def compute_plp(
y: np.ndarray,
sr: int,
hop_length: int,
win_length: int,
tempo_min: Optional[float],
tempo_max: Optional[float],
onset_env: np.ndarray
) -> np.ndarray:
"""
... | 292 | filename = librosa.util.example_audio_file()
y, sr = librosa.load(filename)
hop_length=512
win_length=384
tempo_min = None
tempo_max = None
onset_env = librosa.onset.onset_strength(y=y, sr=sr, hop_length=hop_length)
sol = compute_plp(y, sr, hop_length, win_length, tempo_min, tempo_max, onset_env)
ftgram = stft(onset... |
return librosa.beat.plp(onset_envelope=onset_env, sr=sr, tempo_min=tempo_min, tempo_max=tempo_max) | new feature | librosa.beat.plp | numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.beat.plp.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.beat.plp"
] | 2019-07 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.6.0 | Complete the function to return an array of time values to match the time axis from a feature matrix. | import librosa
import numpy as np
def compute_times_like(y: np.ndarray, sr: int, hop_length: int, D: np.ndarray) -> np.ndarray:
"""
Compute the times vector of a spectrogram.
Parameters:
y: The audio signal.
sr: The sampling rate of the audio signal in Hertz.
hop_length: The number... | 293 |
filename = librosa.util.example_audio_file()
y, sr = librosa.load(filename)
D = librosa.stft(y)
hop_length = 512
sol = compute_times_like(y, sr, hop_length, D)
if np.isscalar(D):
frames = np.arange(D) # type: ignore
else:
frames = np.arange(D.shape[-1]) # type: ignore
offset = 0
samples = (np.asanyarray... |
if np.isscalar(D):
frames = np.arange(D) # type: ignore
else:
frames = np.arange(D.shape[-1]) # type: ignore
offset = 0
samples = (np.asanyarray(frames) * hop_length + offset).astype(int)
return np.asanyarray(samples) / float(sr) | new feature | librosa.times_like | scikit-learn==0.21.0 numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.times_like.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"numpy.asanyarray",
"numpy.arange",
"float",
"numpy.isscalar",
"astype"
] | 2018-02 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.7.0 | Complete the function to return an array of time values to match the time axis from a feature matrix. | import librosa
import numpy as np
def compute_times_like(y: np.ndarray, sr: int, hop_length: int, D: np.ndarray) -> np.ndarray:
"""
Compute the times vector of a spectrogram.
Parameters:
y: The audio signal.
sr: The sampling rate of the audio signal in Hertz.
hop_length: The number... | 294 |
filename = librosa.util.example_audio_file()
y, sr = librosa.load(filename)
D = librosa.stft(y)
hop_length = 512
sol = compute_times_like(y, sr, hop_length, D)
if np.isscalar(D):
frames = np.arange(D) # type: ignore
else:
frames = np.arange(D.shape[-1]) # type: ignore
offset = 0
samples = (np.asanyarray... |
return librosa.times_like(D, sr=sr) | new feature | librosa.times_like | numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.times_like.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.times_like"
] | 2019-07 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.6.0 | Complete the function to return an array of sample indices to match the time axis from a feature matrix. | import librosa
import numpy as np
def compute_samples_like(y: np.ndarray, sr: int, D: np.ndarray, hop_length: int) -> np.ndarray:
"""
Compute the samples vector of a spectrogram.
Parameters:
y: The audio signal.
sr: The sampling rate of the audio signal in Hertz.
D: The spectrogram... | 295 |
filename = librosa.util.example_audio_file()
y, sr = librosa.load(filename)
D = librosa.stft(y)
hop_length = 512
sol = compute_samples_like(y, sr, D, hop_length)
if np.isscalar(D):
frames = np.arange(D) # type: ignore
else:
frames = np.arange(D.shape[-1]) # type: ignore
offset = 0
test_sol = (np.asanyarray(... |
if np.isscalar(D):
frames = np.arange(D) # type: ignore
else:
frames = np.arange(D.shape[-1]) # type: ignore
offset = 0
return (np.asanyarray(frames) * hop_length + offset).astype(int)
| new feature | librosa.samples_like | scikit-learn==0.21.0 numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.samples_like.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"numpy.asanyarray",
"numpy.arange",
"numpy.isscalar",
"astype",
"return"
] | 2018-02 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.7.0 | Complete the function to return an array of sample indices to match the time axis from a feature matrix. | import librosa
import numpy as np
def compute_samples_like(y: np.ndarray, sr: int, D: np.ndarray, hop_length: int) -> np.ndarray:
"""
Compute the samples vector of a spectrogram.
Parameters:
y: The audio signal.
sr: The sampling rate of the audio signal in Hertz.
D: The spectrogram... | 296 |
filename = librosa.util.example_audio_file()
y, sr = librosa.load(filename)
D = librosa.stft(y)
hop_length = 512
sol = compute_samples_like(y, sr, D, hop_length)
if np.isscalar(D):
frames = np.arange(D) # type: ignore
else:
frames = np.arange(D.shape[-1]) # type: ignore
offset = 0
test_sol = (np.asanyarray(... |
return librosa.samples_like(D) | new feature | librosa.samples_like | numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.samples_like.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.samples_like"
] | 2019-07 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.6.0 | Complete the function to construct a pure tone (cosine) signal at a given frequency. | import librosa
import numpy as np
def compute_tone(frequency: int, sr: int, length: int) -> np.ndarray:
"""
Constructs a pure tone (cosine) signal at a given frequency.
Parameters:
frequency: The frequency of the tone in Hz.
sr: The sampling rate of the signal in Hz.
length: The le... | 297 |
frequency = 440
sr = 22050
length = sr
sol = compute_tone(frequency, sr, length)
phi = -np.pi * 0.5
test_sol = np.cos(2 * np.pi * frequency * np.arange(length) / sr + phi)
assert np.array_equal(test_sol, sol) |
phi = -np.pi * 0.5
return np.cos(2 * np.pi * frequency * np.arange(length) / sr + phi) | new feature | librosa.tone | scikit-learn==0.21.0 numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.tone.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"numpy.arange",
"numpy.cos"
] | 2018-02 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.7.0 | Complete the function to construct a pure tone (cosine) signal at a given frequency. | import librosa
import numpy as np
def compute_tone(frequency: int, sr: int, length: int) -> np.ndarray:
"""
Constructs a pure tone (cosine) signal at a given frequency.
Parameters:
frequency: The frequency of the tone in Hz.
sr: The sampling rate of the signal in Hz.
length: The le... | 298 |
frequency = 440
sr = 22050
length = sr
sol = compute_tone(frequency, sr, length)
test_sol = librosa.tone(frequency, sr=sr, length=length)
assert np.array_equal(test_sol, sol) |
return librosa.tone(frequency, sr=sr, length=length) | new feature | librosa.tone | numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.tone.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.tone"
] | 2019-07 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.6.0 | Complete the function to construct a “chirp” or “sine-sweep” signal. The chirp sweeps from frequency fmin to fmax (in Hz). | import librosa
import numpy as np
def compute_chirp(fmin: int, fmax: int, duration: int, sr: int, linear: bool) -> np.ndarray:
"""
Constructs a “chirp” or “sine-sweep” signal. The chirp sweeps from frequency fmin to fmax (in Hz).
Parameters:
fmin: The minimum frequency of the chirp in Hz.
... | 299 |
import scipy
fmin = 110
fmax = 110*64
duration = 1
sr = 22050
linear = True
sol = compute_chirp(fmin, fmax, duration, sr, linear)
period = 1.0 / sr
phi = -np.pi * 0.5
method = "linear" if linear else "logarithmic"
test_sol = scipy.signal.chirp(
np.arange(int(duration * sr)) / sr,
fmin,
duration,
fmax,
method=m... |
import scipy
period = 1.0 / sr
phi = -np.pi * 0.5
method = "linear" if linear else "logarithmic"
return scipy.signal.chirp(np.arange(int(duration * sr)) / sr, fmin, duration, fmax, method=method, phi=phi / np.pi * 180, ) | new feature | librosa.chirp | scikit-learn==0.21.0 numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.chirp.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"numpy.arange",
"int",
"scipy.signal.chirp"
] | 2018-02 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.7.0 | Complete the function to construct a “chirp” or “sine-sweep” signal. The chirp sweeps from frequency fmin to fmax (in Hz). | import librosa
import numpy as np
def compute_chirp(fmin: int, fmax: int, duration: int, sr: int, linear: bool) -> np.ndarray:
"""
Constructs a “chirp” or “sine-sweep” signal. The chirp sweeps from frequency fmin to fmax (in Hz).
Parameters:
fmin: The minimum frequency of the chirp in Hz.
... | 300 |
fmin = 110
fmax = 110*64
duration = 1
sr = 22050
linear = True
sol = compute_chirp(fmin, fmax, duration, sr, linear)
test_sol = librosa.chirp(fmin=fmin, fmax=fmax, duration=duration, sr=sr)
assert np.array_equal(test_sol, sol) |
return librosa.chirp(fmin=fmin, fmax=fmax, duration=duration, sr=sr) | new feature | librosa.chirp | numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.chirp.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.chirp"
] | 2019-07 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.7.0 | Complete the function to shear a matrix by a given factor. | import librosa
import numpy as np
def compute_shear(E: np.ndarray, factor: int, axis: int) -> np.ndarray:
| 301 |
E = np.eye(3)
factor=-1
axis=-1
sol = compute_shear(E, factor, axis)
gt = np.array([[1., 1., 1.],
[0., 0., 0.],
[0., 0., 0.]])
assert np.array_equal(gt, sol) |
E_shear = np.empty_like(E)
for i in range(E.shape[1]):
E_shear[:, i] = np.roll(E[:, i], factor * i)
return E_shear
| new feature | librosa.util.shear | numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.util.shear.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"numpy.roll",
"range",
"numpy.empty_like"
] | 2018-02 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
3.7 | librosa | 0.7.1 | Complete the function to shear a matrix by a given factor. | import librosa
import numpy as np
def compute_shear(E: np.ndarray, factor: int, axis: int) -> np.ndarray:
| 302 |
E = np.eye(3)
factor=-1
axis=-1
sol = compute_shear(E, factor, axis)
gt = np.array([[1., 1., 1.],
[0., 0., 0.],
[0., 0., 0.]])
assert np.array_equal(gt, sol) |
return librosa.util.shear(E, factor=factor, axis=axis) | new feature | librosa.util.shear | numpy==1.16.0 scipy==1.1.0 soundfile==0.10.2 | [
"https://librosa.org/doc/main/generated/librosa.util.shear.html",
"https://librosa.org/doc/main/changelog.html"
] | 1 | 0 | true | [
"librosa.util.shear"
] | 2019-07 | numba==0.46 llvmlite==0.30 joblib==0.12 numpy==1.16.0 audioread==2.1.5 scipy==1.1.0 resampy==0.2.2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.