cabbage972/GitChameleon-2.0 huggingface dataset:
Library: falcon==2.0.0 (Python 3.10, released 2019-04)

Problem: 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.


Starting code:
from falcon import Request
from falcon.util.structures import Context


def custom_set_context(req: Request, role: str, user: str) -> Context:
    req.

Solution:
context.role = role
    req.context.user = user
    return req.context


Test:
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 not issubclass(warn.category, DeprecationWarning), "Deprecated API used!"

expect1 = 'trial'
expect2 = 'guest'

assert context.role == expect1
assert context.user == expect2
Library: falcon==2.0.0 (Python 3.10, released 2019-04)

Problem: 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 keyword arguments. This method should use Falcon’s routing utility—specifically, the map_http_methods function from the falcon.routing module—to generate a mapping of HTTP methods to resource handlers. If a 'fallback' parameter is provided in the keyword arguments, it should be passed to map_http_methods. The method should then store a tuple consisting of the resource and the generated method mapping in the routes dictionary, using the URI template as the key, and finally return the generated method mapping. You must not modify the provided starting code, which includes the empty CustomRouter class. Instead, complete the solution by dynamically adding the required method in the solution() function.

Starting code:
class CustomRouter:
    def __init__(self):
        self.routes = {}

        
def solution() -> None:
    
    def add_route(

Solution:
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

Test:
    
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 w:
            assert not issubclass(warn.category, DeprecationWarning), "Deprecated API used!"
            
expect = "/test"
assertion_value = expect in router.routes
assert assertion_value
resource, mapping = router.routes["/test"]
assertion_value = callable(mapping.get("GET", None)) 
assert assertion_value
Library: tornado==6.3.0 (Python 3.10, released 2023-11)

Problem: 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.


Starting code:
import asyncio
import os
import signal
from typing import Callable

def custom_add_callback_from_signal(callback: Callable[[], None], signum: int) -> None:
    loop = 

Solution:
asyncio.get_event_loop()
    loop.add_signal_handler(signum, callback)


Test:

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)

    loop.run_forever()

    return flag["executed"]

result = test_custom_signal_handler()
assert result
Library: tornado==6.3.0 (Python 3.10, released 2023-04)

Problem: 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.

Starting code:
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 WSGI application that returns "Hello World"
def simple_wsgi_app(environ, start_response):
    status = "200 OK"
    headers = [("Content-Type", "text/plain")]
    start_response(status, headers)
    return [b"Hello World"]

def find_free_port():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.bind(("", 0))
        return sock.getsockname()[1]

def custom_wsgi_container(app: WSGIAppType, executor: concurrent.futures.Executor) -> tornado.wsgi.WSGIContainer:

    return 

Solution:
tornado.wsgi.WSGIContainer(app, executor=executor)

Test:
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.httpclient.AsyncHTTPClient()
    url = f"http://localhost:{port}"
    
    response = tornado.ioloop.IOLoop.current().run_sync(lambda: client.fetch(url))
    
    server.stop()
    executor.shutdown(wait=True)
    
    return response.body == b"Hello World"

result = test_wsgi_container_executor()
assert result
Library: tornado==6.3.0 (Python 3.10, released 2023-04)

Problem: Write a custom function that establishes a Tornado WebSocket connection using a provided resolver parameter to efficiently handle large fragmented messages.

Starting code:
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 

Solution:
tornado.websocket.websocket_connect(url, resolver=resolver)

Test:
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.SOCK_STREAM) as sock:
        sock.bind(("", 0))
        return sock.getsockname()[1]

def test_websocket_large_message():

    resolver = None

    app = tornado.web.Application([
        (r"/ws", EchoWebSocketHandler),
    ])
    port = find_free_port()
    server = tornado.httpserver.HTTPServer(app)
    server.listen(port)

    ws_url = f"ws://localhost:{port}/ws"

    large_message = "A" * 100000  # 100k characters

    async def run_test():
        conn = await custom_websocket_connect(ws_url, resolver)
        conn.write_message(large_message)
        echoed = await conn.read_message()
        conn.close()
        return echoed == large_message

    result = tornado.ioloop.IOLoop.current().run_sync(run_test)

    server.stop()
    return result

result = test_websocket_large_message()
assert result
Library: tornado==6.3.0 (Python 3.10, released 2023-04)

Problem: 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.

Starting code:
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 =

Solution:
self.get_signed_cookie("mycookie")
        if cookie_value:
            self.write(cookie_value.decode())


Test:
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():

    port = find_free_port()
    app = make_app()
    server = tornado.httpserver.HTTPServer(app)
    server.listen(port)
    
    # Create a signed cookie value for "testvalue"
    signed_cookie = tornado.web.create_signed_value(COOKIE_SECRET, "mycookie", "testvalue")
    cookie_header = "mycookie=" + signed_cookie.decode()

    client = tornado.httpclient.AsyncHTTPClient()
    url = f"http://localhost:{port}/get"
    
    # Include the signed cookie in the request headers.
    response = tornado.ioloop.IOLoop.current().run_sync(
        lambda: client.fetch(url, headers={"Cookie": cookie_header})
    )
    server.stop()
    return response.body.decode() == "testvalue"

result_get = test_get_secure_cookie()
assert result_get
Library: tornado==6.3.0 (Python 3.10, released 2023-04)

Problem: 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.

Starting code:
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.

Solution:
set_signed_cookie("mycookie", "testvalue")
        self.write("Cookie set")

Test:
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():

    port = find_free_port()
    app = make_app()
    server = tornado.httpserver.HTTPServer(app)
    server.listen(port)
    
    client = tornado.httpclient.AsyncHTTPClient()
    url = f"http://localhost:{port}/set"
    
    response = tornado.ioloop.IOLoop.current().run_sync(lambda: client.fetch(url))
    server.stop()
    # Check that a Set-Cookie header is present with the cookie name "mycookie="
    set_cookie_headers = response.headers.get_list("Set-Cookie")
    return any("mycookie=" in header for header in set_cookie_headers)

result_set = test_set_secure_cookie()
assert result_set
Library: tornado==6.0.0 (Python 3.10, released 2019-03)

Problem: 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.


Starting code:
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 

Solution:
{"user": "test", "token": access_token}

Test:
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())
Library: tornado==6.0.0 (Python 3.10, released 2019-03)

Problem: 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.


Starting code:
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.HTTPServerRequest, text: str) -> list[str]:
    request.

Solution:
connection.write(text)
    return request.connection.buffer

Test:
written_data = custom_write(req, "Hello, Tornado!")
expect = ["Hello, Tornado!"]
assert written_data == expect
Library: tornado==5.0.0 (Python 3.10, released 2018-03)

Problem: Define a function named custom_get_ioloop that returns the current Tornado IOLoop instance using the appropriate Tornado method.

Starting code:
import tornado.ioloop

def custom_get_ioloop() -> tornado.ioloop.IOLoop:
    return 

Solution:
tornado.ioloop.IOLoop.current()

Test:

loop1 = custom_get_ioloop()
loop2 = custom_get_ioloop()
assert loop1 is loop2

loop_current = custom_get_ioloop()
assert loop_current is not None
Library: plotly==4.8.0 (Python 3.9, released 2020-05)

Problem: 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.

Starting code:
import plotly.graph_objects as go


def custom_fig(x_data: list[str], y_data: list[int]) -> go.Figure:
    return 

Solution:
go.Figure(data=[go.Bar(x=x_data,y=y_data,orientation="v")])

Test:

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
Library: plotly==5.8.0 (Python 3.9, released 2022-05)

Problem: 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.

Starting code:
import plotly.graph_objects as go

def custom_fig(fig: go.Figure) -> go.Figure:
    return 

Solution:
fig.add_annotation(
        x=0.5,
        y=0.5,
        text="Example Annotation",
        xref="paper",
        yref="paper",
        showarrow=False
    )

Test:
fig = go.Figure()
output = custom_fig(fig)
expect = "paper"

assert output.layout.annotations[0].xref == expect
assert output.layout.annotations[0].yref == expect
Library: plotly==5.10.0 (Python 3.9, released 2022-08)

Problem: 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.

Starting code:
import plotly.graph_objects as go

def custom_fig(x_data: list[int], y_data: list[int], color_set: str) -> go.Figure:
    return 

Solution:
go.Figure(data=go.Scatter(
    x=x_data,
    y=y_data,
    error_y=dict(
        color=color_set
    )
))

Test:
    
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)
Library: plotly==5.10.0 (Python 3.9, released 2023-03)

Problem: 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.

Starting code:
import plotly.graph_objects as go

def custom_fig(fig: go.Figure) -> go.Figure:
    return 

Solution:
fig.update_layout(
    scene_camera=dict(
        eye=dict(x=1.25, y=1.25, z=1.25)
    )
)

Test:

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
Library: plotly==4.0.0 (Python 3.9, released 2019-07)

Problem: 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.


Starting code:
import plotly
import plotly.graph_objects as go

def custom_make_subplots(rows: int, cols: int) -> go.Figure:
    return 

Solution:
plotly.subplots.make_subplots(rows=rows, cols=cols)

Test:
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_yaxes = sum(1 for key in fig.layout if key.startswith("yaxis"))
expect1 = 4
expect2 = 4
assert num_xaxes == expect1
assert num_yaxes == expect2
Library: plotly==4.0.0 (Python 3.9, released 2019-07)

Problem: 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.


Starting code:
import plotly
import plotly.graph_objects as go


def custom_figure(x_data: list[int], y_data: list[int]) -> go.Figure:
    import plotly.

Solution:
graph_objects
    fig = plotly.graph_objects.Figure()
    fig.add_trace(plotly.graph_objects.Scatter(x=x_data, y=y_data))
    return fig

Test:
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_data
expect3 = y_data

assert len(fig.data) == expect1
trace = fig.data[0]

assert list(trace.x) == expect2
assert list(trace.y) == expect3
Library: plotly==4.0.0 (Python 3.9, released 2019-07)
Additional dependencies: chart-studio==1.0.0

Problem: 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.

Starting code:
import plotly
def custom_chart_studio_usage() -> bool:
    import 

Solution:
chart_studio.plotly
    return hasattr(chart_studio.plotly, "plot")

Test:
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
Library: plotly==4.0.0 (Python 3.9, released 2019-07)
Additional dependencies: chart-studio==1.0.0

Problem: 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.


Starting code:
import plotly
def custom_api_usage() -> str:
    import 

Solution:
chart_studio.api
    return chart_studio.api.__name__

Test:
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
Library: plotly==3.0.0 (Python 3.9, released 2018-07)

Problem: 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.

Starting code:
import plotly.graph_objs as go

def custom_scatter(custom_color: str) -> go.Figure:
    return 

Solution:
go.Figure(data=[go.Scatter(x=[0],y=[0],marker=go.scatter.Marker(color=custom_color)) ])

Test:
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_trace.marker.color
expect = color
assert marker_color == expect
Library: librosa==0.6.0 (Python 3.7, released 2018-02)
Additional dependencies: numpy==1.16.0 scipy==1.1.0

Problem: Complete the function to compute the dynamic time warp between arrays X and Y. 

Starting code:
import numpy as np
import librosa
from scipy.spatial.distance import cdist

def compute_dtw(X: np.ndarray, Y: np.ndarray) -> np.ndarray:
    


Solution:


    dist_matrix = cdist(X.T, Y.T, metric='euclidean')
    return librosa.dtw(C=dist_matrix, metric='invalid')[0]

Test:

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))
Library: librosa==0.7.0 (Python 3.7, released 2019-07)
Additional dependencies: numpy==1.16.0 scipy==1.1.0

Problem: Complete the function to compute the dynamic time warp between arrays X and Y. 

Starting code:
import numpy as np
import librosa
from scipy.spatial.distance import cdist

def compute_dtw(X: np.ndarray, Y: np.ndarray) -> np.ndarray:
    


Solution:


    dist_matrix = cdist(X.T, Y.T, metric='euclidean')
    return librosa.sequence.dtw(C=dist_matrix, metric='invalid')[0]

Test:

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))
Library: librosa==0.6.0 (Python 3.7, released 2018-02)
Additional dependencies: numpy==1.16.0 scipy==1.1.0

Problem: Complete the function to compute the root mean square value for each frame. 

Starting code:
import librosa
import numpy as np

def compute_rms(y: np.ndarray) -> np.float32:
    

Solution:


    return librosa.feature.rmse(y=y)

Test:

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.35355084,
     0.3537631,  0.35317223, 0.35403977, 0.35304415, 0.35399675, 0.35325105,
     0.35366224, 0.35365654, 0.35325578, 0.35399382, 0.35304479, 0.35404153,
     0.35316836, 0.3537684,  0.35354501, 0.35335359, 0.35392676, 0.35306983,
     0.35406292, 0.35310412, 0.35386422, 0.35343384, 0.35346095, 0.35384179,
     0.35311807, 0.35405989, 0.35306143, 0.35394511, 0.35332838, 0.3535727,
     0.35374297, 0.35318719, 0.35403259, 0.35304234, 0.35400722, 0.35323367,
     0.3536835,  0.35363504, 0.35327386, 0.35398233, 0.35304777, 0.35404758,
     0.35315429, 0.35378803, 0.35352315, 0.35337391, 0.3539115,  0.35307747,
     0.35406426, 0.35309403, 0.35388128, 0.35341269, 0.35348254, 0.35382349,
     0.35312999, 0.35405645, 0.35305581, 0.35395879, 0.35330893, 0.35359453,
     0.35372251, 0.35320281, 0.35402454, 0.35304147, 0.35401687, 0.35321688,
     0.35370452, 0.35361339, 0.35329244, 0.35397005, 0.35305168, 0.35405273,
     0.35314094, 0.35398808, 0.35359185]
])

assertion_value = np.allclose(expect, compute_rms(y))
assert assertion_value