language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol9.py | {
"start": 285,
"end": 686
} | class ____:
value: int
@property
def left(self) -> "SimpleTree | None":
return self._left
@property
def right(self) -> "SimpleTree | None":
return self._right
def __init__(self, value: int) -> None:
self.value = value
self._left: SimpleTree | None = None
self._right: SimpleTree | None = None
root: TreeLike = SimpleTree(0)
| SimpleTree |
python | google__jax | docs/autodidax.py | {
"start": 71490,
"end": 73279
} | class ____(NamedTuple):
aval: ShapedArray
const: Any | None
@classmethod
def known(cls, val: Any):
return PartialVal(get_aval(val), val)
@classmethod
def unknown(cls, aval: ShapedArray):
return PartialVal(aval, None)
is_known = property(lambda self: self.const is not None)
is_unknown = property(lambda self: self.const is None)
# Partial evaluation will take a list of `PartialVal`s representing inputs, and
# return a list of `PartialVal` outputs along with a jaxpr representing the
# delayed computation:
def partial_eval_flat(f: Callable, pvals_in: list[PartialVal]
) -> tuple[Jaxpr, list[PartialVal], list[Any]]:
with new_main(PartialEvalTrace) as main:
trace = PartialEvalTrace(main)
tracers_in = [trace.new_arg(pval) for pval in pvals_in]
outs = f(*tracers_in)
tracers_out = [full_raise(trace, out) for out in outs]
pvals_out = [t.pval for t in tracers_out]
unk_tracers_in = [t for t in tracers_in if t.pval.is_unknown]
unk_tracers_out = [t for t in tracers_out if t.pval.is_unknown]
jaxpr, consts = tracers_to_jaxpr(unk_tracers_in, unk_tracers_out)
return jaxpr, pvals_out, consts
# Next we need to implement `PartialEvalTrace` and its `PartialEvalTracer`. This
# interpreter will build a jaxpr on the fly while tracking data dependencies. To
# do so, it builds a bipartite directed acyclic graph (DAG) between
# `PartialEvalTracer` nodes, representing staged-out values, and `JaxprRecipe`
# nodes, representing formulas for how to compute some values from others. One
# kind of recipe is a `JaxprEqnRecipe`, corresponding to a `JaxprEqn`'s
# primitive application, but we also have recipe types for constants and lambda
# binders:
# +
from weakref import ref, ReferenceType
| PartialVal |
python | keras-team__keras | keras/src/trainers/trainer_test.py | {
"start": 2262,
"end": 2631
} | class ____(ExampleModel):
def train_step(self, state, data):
logs, state = super().train_step(state, data)
logs["my_custom_metric"] = 10.0
return logs, state
def test_step(self, state, data):
logs, state = super().test_step(state, data)
logs["my_custom_metric"] = 5.0
return logs, state
| JaxCustomTrainTestStepModel |
python | scipy__scipy | scipy/optimize/_dual_annealing.py | {
"start": 530,
"end": 5336
} | class ____:
"""
Class used to generate new coordinates based on the distorted
Cauchy-Lorentz distribution. Depending on the steps within the strategy
chain, the class implements the strategy for generating new location
changes.
Parameters
----------
lb : array_like
A 1-D NumPy ndarray containing lower bounds of the generated
components. Neither NaN or inf are allowed.
ub : array_like
A 1-D NumPy ndarray containing upper bounds for the generated
components. Neither NaN or inf are allowed.
visiting_param : float
Parameter for visiting distribution. Default value is 2.62.
Higher values give the visiting distribution a heavier tail, this
makes the algorithm jump to a more distant region.
The value range is (1, 3]. Its value is fixed for the life of the
object.
rng_gen : {`~numpy.random.Generator`}
A `~numpy.random.Generator` object for generating new locations.
(can be a `~numpy.random.RandomState` object until SPEC007 transition
is fully complete).
"""
TAIL_LIMIT = 1.e8
MIN_VISIT_BOUND = 1.e-10
def __init__(self, lb, ub, visiting_param, rng_gen):
# if you wish to make _visiting_param adjustable during the life of
# the object then _factor2, _factor3, _factor5, _d1, _factor6 will
# have to be dynamically calculated in `visit_fn`. They're factored
# out here so they don't need to be recalculated all the time.
self._visiting_param = visiting_param
self.rng_gen = rng_gen
self.lower = lb
self.upper = ub
self.bound_range = ub - lb
# these are invariant numbers unless visiting_param changes
self._factor2 = np.exp((4.0 - self._visiting_param) * np.log(
self._visiting_param - 1.0))
self._factor3 = np.exp((2.0 - self._visiting_param) * np.log(2.0)
/ (self._visiting_param - 1.0))
self._factor4_p = np.sqrt(np.pi) * self._factor2 / (self._factor3 * (
3.0 - self._visiting_param))
self._factor5 = 1.0 / (self._visiting_param - 1.0) - 0.5
self._d1 = 2.0 - self._factor5
self._factor6 = np.pi * (1.0 - self._factor5) / np.sin(
np.pi * (1.0 - self._factor5)) / np.exp(gammaln(self._d1))
def visiting(self, x, step, temperature):
""" Based on the step in the strategy chain, new coordinates are
generated by changing all components is the same time or only
one of them, the new values are computed with visit_fn method
"""
dim = x.size
if step < dim:
# Changing all coordinates with a new visiting value
visits = self.visit_fn(temperature, dim)
upper_sample, lower_sample = self.rng_gen.uniform(size=2)
visits[visits > self.TAIL_LIMIT] = self.TAIL_LIMIT * upper_sample
visits[visits < -self.TAIL_LIMIT] = -self.TAIL_LIMIT * lower_sample
x_visit = visits + x
a = x_visit - self.lower
b = np.fmod(a, self.bound_range) + self.bound_range
x_visit = np.fmod(b, self.bound_range) + self.lower
x_visit[np.fabs(
x_visit - self.lower) < self.MIN_VISIT_BOUND] += 1.e-10
else:
# Changing only one coordinate at a time based on strategy
# chain step
x_visit = np.copy(x)
visit = self.visit_fn(temperature, 1)[0]
if visit > self.TAIL_LIMIT:
visit = self.TAIL_LIMIT * self.rng_gen.uniform()
elif visit < -self.TAIL_LIMIT:
visit = -self.TAIL_LIMIT * self.rng_gen.uniform()
index = step - dim
x_visit[index] = visit + x[index]
a = x_visit[index] - self.lower[index]
b = np.fmod(a, self.bound_range[index]) + self.bound_range[index]
x_visit[index] = np.fmod(b, self.bound_range[
index]) + self.lower[index]
if np.fabs(x_visit[index] - self.lower[
index]) < self.MIN_VISIT_BOUND:
x_visit[index] += self.MIN_VISIT_BOUND
return x_visit
def visit_fn(self, temperature, dim):
""" Formula Visita from p. 405 of reference [2] """
x, y = self.rng_gen.normal(size=(dim, 2)).T
factor1 = np.exp(np.log(temperature) / (self._visiting_param - 1.0))
factor4 = self._factor4_p * factor1
# sigmax
x *= np.exp(-(self._visiting_param - 1.0) * np.log(
self._factor6 / factor4) / (3.0 - self._visiting_param))
den = np.exp((self._visiting_param - 1.0) * np.log(np.fabs(y)) /
(3.0 - self._visiting_param))
return x / den
| VisitingDistribution |
python | numpy__numpy | numpy/linalg/tests/test_linalg.py | {
"start": 65906,
"end": 68049
} | class ____:
@pytest.mark.parametrize(
'shape', [(1, 1), (2, 2), (3, 3), (50, 50), (3, 10, 10)]
)
@pytest.mark.parametrize(
'dtype', (np.float32, np.float64, np.complex64, np.complex128)
)
@pytest.mark.parametrize(
'upper', [False, True])
def test_basic_property(self, shape, dtype, upper):
np.random.seed(1)
a = np.random.randn(*shape)
if np.issubdtype(dtype, np.complexfloating):
a = a + 1j * np.random.randn(*shape)
t = list(range(len(shape)))
t[-2:] = -1, -2
a = np.matmul(a.transpose(t).conj(), a)
a = np.asarray(a, dtype=dtype)
c = np.linalg.cholesky(a, upper=upper)
# Check A = L L^H or A = U^H U
if upper:
b = np.matmul(c.transpose(t).conj(), c)
else:
b = np.matmul(c, c.transpose(t).conj())
atol = 500 * a.shape[0] * np.finfo(dtype).eps
assert_allclose(b, a, atol=atol, err_msg=f'{shape} {dtype}\n{a}\n{c}')
# Check diag(L or U) is real and positive
d = np.diagonal(c, axis1=-2, axis2=-1)
assert_(np.all(np.isreal(d)))
assert_(np.all(d >= 0))
def test_0_size(self):
class ArraySubclass(np.ndarray):
pass
a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
res = linalg.cholesky(a)
assert_equal(a.shape, res.shape)
assert_(res.dtype.type is np.float64)
# for documentation purpose:
assert_(isinstance(res, np.ndarray))
a = np.zeros((1, 0, 0), dtype=np.complex64).view(ArraySubclass)
res = linalg.cholesky(a)
assert_equal(a.shape, res.shape)
assert_(res.dtype.type is np.complex64)
assert_(isinstance(res, np.ndarray))
def test_upper_lower_arg(self):
# Explicit test of upper argument that also checks the default.
a = np.array([[1 + 0j, 0 - 2j], [0 + 2j, 5 + 0j]])
assert_equal(linalg.cholesky(a), linalg.cholesky(a, upper=False))
assert_equal(
linalg.cholesky(a, upper=True),
linalg.cholesky(a).T.conj()
)
| TestCholesky |
python | kubernetes-client__python | kubernetes/client/models/v1_job.py | {
"start": 383,
"end": 6986
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'api_version': 'str',
'kind': 'str',
'metadata': 'V1ObjectMeta',
'spec': 'V1JobSpec',
'status': 'V1JobStatus'
}
attribute_map = {
'api_version': 'apiVersion',
'kind': 'kind',
'metadata': 'metadata',
'spec': 'spec',
'status': 'status'
}
def __init__(self, api_version=None, kind=None, metadata=None, spec=None, status=None, local_vars_configuration=None): # noqa: E501
"""V1Job - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._api_version = None
self._kind = None
self._metadata = None
self._spec = None
self._status = None
self.discriminator = None
if api_version is not None:
self.api_version = api_version
if kind is not None:
self.kind = kind
if metadata is not None:
self.metadata = metadata
if spec is not None:
self.spec = spec
if status is not None:
self.status = status
@property
def api_version(self):
"""Gets the api_version of this V1Job. # noqa: E501
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:return: The api_version of this V1Job. # noqa: E501
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""Sets the api_version of this V1Job.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:param api_version: The api_version of this V1Job. # noqa: E501
:type: str
"""
self._api_version = api_version
@property
def kind(self):
"""Gets the kind of this V1Job. # noqa: E501
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:return: The kind of this V1Job. # noqa: E501
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""Sets the kind of this V1Job.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:param kind: The kind of this V1Job. # noqa: E501
:type: str
"""
self._kind = kind
@property
def metadata(self):
"""Gets the metadata of this V1Job. # noqa: E501
:return: The metadata of this V1Job. # noqa: E501
:rtype: V1ObjectMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Sets the metadata of this V1Job.
:param metadata: The metadata of this V1Job. # noqa: E501
:type: V1ObjectMeta
"""
self._metadata = metadata
@property
def spec(self):
"""Gets the spec of this V1Job. # noqa: E501
:return: The spec of this V1Job. # noqa: E501
:rtype: V1JobSpec
"""
return self._spec
@spec.setter
def spec(self, spec):
"""Sets the spec of this V1Job.
:param spec: The spec of this V1Job. # noqa: E501
:type: V1JobSpec
"""
self._spec = spec
@property
def status(self):
"""Gets the status of this V1Job. # noqa: E501
:return: The status of this V1Job. # noqa: E501
:rtype: V1JobStatus
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this V1Job.
:param status: The status of this V1Job. # noqa: E501
:type: V1JobStatus
"""
self._status = status
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1Job):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1Job):
return True
return self.to_dict() != other.to_dict()
| V1Job |
python | ray-project__ray | python/ray/serve/tests/test_proxy.py | {
"start": 948,
"end": 11774
} | class ____:
"""Test setting keep_alive_timeout_s in config and env."""
def get_proxy_actor(self) -> ActorHandle:
[proxy_actor] = list_actors(filters=[("class_name", "=", "ProxyActor")])
return ray.get_actor(proxy_actor.name, namespace=SERVE_NAMESPACE)
def test_default_keep_alive_timeout_s(self, ray_shutdown):
"""Test when no keep_alive_timeout_s is set.
When the keep_alive_timeout_s is not set, the uvicorn keep alive is 5.
"""
serve.start()
proxy_actor = self.get_proxy_actor()
assert (
ray.get(proxy_actor._get_http_options.remote()).keep_alive_timeout_s
== DEFAULT_UVICORN_KEEP_ALIVE_TIMEOUT_S
)
def test_set_keep_alive_timeout_in_http_configs(self, ray_shutdown):
"""Test when keep_alive_timeout_s is in http configs.
When the keep_alive_timeout_s is set in http configs, the uvicorn keep alive
is set correctly.
"""
keep_alive_timeout_s = 222
serve.start(http_options={"keep_alive_timeout_s": keep_alive_timeout_s})
proxy_actor = self.get_proxy_actor()
assert (
ray.get(proxy_actor._get_http_options.remote()).keep_alive_timeout_s
== keep_alive_timeout_s
)
@pytest.mark.parametrize(
"ray_instance",
[
{"RAY_SERVE_HTTP_KEEP_ALIVE_TIMEOUT_S": "333"},
],
indirect=True,
)
def test_set_keep_alive_timeout_in_env(self, ray_instance, ray_shutdown):
"""Test when keep_alive_timeout_s is in env.
When the keep_alive_timeout_s is set in env, the uvicorn keep alive
is set correctly.
"""
serve.start()
proxy_actor = self.get_proxy_actor()
assert (
ray.get(proxy_actor._get_http_options.remote()).keep_alive_timeout_s == 333
)
@pytest.mark.parametrize(
"ray_instance",
[
{"RAY_SERVE_HTTP_KEEP_ALIVE_TIMEOUT_S": "333"},
],
indirect=True,
)
def test_set_timeout_keep_alive_in_both_config_and_env(
self, ray_instance, ray_shutdown
):
"""Test when keep_alive_timeout_s is in both http configs and env.
When the keep_alive_timeout_s is set in env, the uvicorn keep alive
is set to the one in env.
"""
keep_alive_timeout_s = 222
serve.start(http_options={"keep_alive_timeout_s": keep_alive_timeout_s})
proxy_actor = self.get_proxy_actor()
assert (
ray.get(proxy_actor._get_http_options.remote()).keep_alive_timeout_s == 333
)
def test_grpc_proxy_on_draining_nodes(ray_cluster):
"""Test gRPC request on the draining node.
When there are no replicas on head node and some replicas on the worker node, the
ListApplications and Healthz methods should respond successfully. When there are
no replicas on any nodes, ListApplications and Healthz methods should continue to
succeeding on the head node. But should return draining response on the worker node.
Also note, this is to ensure the previous fix to serve downscaling also applies to
gRPC proxy. Head node will not need to be downscaled and never be in the draining
state. Worker nodes will be in draining when there is no replicas. We will fail the
health check in this case, so ALB knows not to route to this node anymore.
"""
head_node_grpc_port = 9000
worker_node_grpc_port = 9001
# Setup worker gRPC proxy to be pointing to port 9001. Head node gRPC proxy will
# continue to be pointing to the default port 9000.
os.environ["TEST_WORKER_NODE_GRPC_PORT"] = str(worker_node_grpc_port)
# Set up a cluster with 2 nodes.
cluster = ray_cluster
cluster.add_node(num_cpus=0)
cluster.add_node(num_cpus=2)
cluster.wait_for_nodes()
ray.init(address=cluster.address)
# Start serve with gRPC proxy
grpc_servicer_functions = [
"ray.serve.generated.serve_pb2_grpc.add_UserDefinedServiceServicer_to_server",
"ray.serve.generated.serve_pb2_grpc.add_FruitServiceServicer_to_server",
]
serve.start(
http_options={"location": "EveryNode"},
grpc_options=gRPCOptions(
port=head_node_grpc_port,
grpc_servicer_functions=grpc_servicer_functions,
),
)
# Deploy 2 replicas, both should be on the worker node.
@serve.deployment(num_replicas=2)
class HelloModel:
def __call__(self):
return serve_pb2.UserDefinedResponse(greeting="hello")
model = HelloModel.bind()
app_name = "app1"
serve.run(model, name=app_name)
# Ensure worker node has both replicas.
def check_replicas_on_worker_nodes():
return (
len(
{
a.node_id
for a in list_actors(address=cluster.address)
if a.class_name.startswith("ServeReplica")
}
)
== 1
)
wait_for_condition(check_replicas_on_worker_nodes)
# Ensure total actors of 2 proxies, 1 controller, and 2 replicas, and 2 nodes exist.
wait_for_condition(lambda: len(list_actors(address=cluster.address)) == 5)
assert len(ray.nodes()) == 2
# Set up gRPC channels.
head_node_channel = grpc.insecure_channel(
build_address("localhost", head_node_grpc_port)
)
worker_node_channel = grpc.insecure_channel(
build_address("localhost", worker_node_grpc_port)
)
# Ensures ListApplications method on the head node is succeeding.
wait_for_condition(
ping_grpc_list_applications, channel=head_node_channel, app_names=[app_name]
)
# Ensures Healthz method on the head node is succeeding.
ping_grpc_healthz(head_node_channel)
# Ensures ListApplications method on the worker node is succeeding.
wait_for_condition(
ping_grpc_list_applications,
channel=worker_node_channel,
app_names=[app_name],
timeout=30,
)
# Ensures Healthz method on the worker node is succeeding.
ping_grpc_healthz(worker_node_channel)
# Delete the deployment should bring the active actors down to 3 and drop
# replicas on all nodes.
serve.delete(name=app_name)
wait_for_condition(
lambda: len(
list_actors(address=cluster.address, filters=[("STATE", "=", "ALIVE")])
)
== 3,
)
# Ensures ListApplications method on the head node is succeeding.
wait_for_condition(
ping_grpc_list_applications, channel=head_node_channel, app_names=[]
)
# Ensures Healthz method on the head node is succeeding.
ping_grpc_healthz(head_node_channel)
# Ensures ListApplications method on the worker node is draining.
wait_for_condition(
ping_grpc_list_applications,
channel=worker_node_channel,
app_names=[],
test_draining=True,
)
# Ensures Healthz method on the worker node is draining.
ping_grpc_healthz(worker_node_channel, test_draining=True)
def test_drain_and_undrain_http_proxy_actors(
monkeypatch, shutdown_ray, call_ray_stop_only # noqa: F811
):
"""Test the state transtion of the proxy actor between
HEALTHY, DRAINING and DRAINED
"""
monkeypatch.setenv("RAY_SERVE_PROXY_MIN_DRAINING_PERIOD_S", "10")
cluster = Cluster()
head_node = cluster.add_node(num_cpus=0)
cluster.add_node(num_cpus=1)
cluster.add_node(num_cpus=1)
cluster.wait_for_nodes()
ray.init(address=head_node.address)
serve.start(http_options={"location": "EveryNode"})
@serve.deployment
class HelloModel:
def __call__(self):
return "hello"
serve.run(HelloModel.options(num_replicas=2).bind())
# 3 proxies, 1 controller, 2 replicas.
wait_for_condition(lambda: len(list_actors()) == 6)
assert len(ray.nodes()) == 3
client = _get_global_client()
serve_details = ServeInstanceDetails(
**ray.get(client._controller.get_serve_instance_details.remote())
)
proxy_actor_ids = {proxy.actor_id for _, proxy in serve_details.proxies.items()}
assert len(proxy_actor_ids) == 3
serve.run(HelloModel.options(num_replicas=1).bind())
# 1 proxy should be draining
def check_proxy_status(proxy_status_to_count):
serve_details = ServeInstanceDetails(
**ray.get(client._controller.get_serve_instance_details.remote())
)
proxy_status_list = [proxy.status for _, proxy in serve_details.proxies.items()]
print("all proxies!!!", [proxy for _, proxy in serve_details.proxies.items()])
current_status = {
status: proxy_status_list.count(status) for status in proxy_status_list
}
return current_status == proxy_status_to_count, current_status
wait_for_condition(
condition_predictor=check_proxy_status,
proxy_status_to_count={ProxyStatus.HEALTHY: 2, ProxyStatus.DRAINING: 1},
)
serve.run(HelloModel.options(num_replicas=2).bind())
# The draining proxy should become healthy.
wait_for_condition(
condition_predictor=check_proxy_status,
proxy_status_to_count={ProxyStatus.HEALTHY: 3},
)
serve_details = ServeInstanceDetails(
**ray.get(client._controller.get_serve_instance_details.remote())
)
assert {
proxy.actor_id for _, proxy in serve_details.proxies.items()
} == proxy_actor_ids
serve.run(HelloModel.options(num_replicas=1).bind())
# 1 proxy should be draining and eventually be drained.
wait_for_condition(
condition_predictor=check_proxy_status,
timeout=40,
proxy_status_to_count={ProxyStatus.HEALTHY: 2},
)
# Clean up serve.
serve.shutdown()
def _kill_http_proxies():
http_proxies = ray.get(
serve.context._global_client._controller.get_proxies.remote()
)
for http_proxy in http_proxies.values():
ray.kill(http_proxy, no_restart=False)
def test_http_proxy_failure(serve_instance):
@serve.deployment(name="proxy_failure")
def function(_):
return "hello1"
serve.run(function.bind())
assert request_with_retries(timeout=1.0).text == "hello1"
for _ in range(10):
response = request_with_retries(timeout=30)
assert response.text == "hello1"
_kill_http_proxies()
def function2(_):
return "hello2"
serve.run(function.options(func_or_class=function2).bind())
def check_new():
for _ in range(10):
response = request_with_retries(timeout=30)
if response.text != "hello2":
return False
return True
wait_for_condition(check_new)
if __name__ == "__main__":
sys.exit(pytest.main(["-v", "-s", __file__]))
| TestTimeoutKeepAliveConfig |
python | doocs__leetcode | solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/Solution2.py | {
"start": 0,
"end": 652
} | class ____:
def numberOfWays(
self, n: int, m: int, k: int, source: List[int], dest: List[int]
) -> int:
mod = 10**9 + 7
f = [1, 0, 0, 0]
for _ in range(k):
g = [0] * 4
g[0] = ((n - 1) * f[1] + (m - 1) * f[2]) % mod
g[1] = (f[0] + (n - 2) * f[1] + (m - 1) * f[3]) % mod
g[2] = (f[0] + (m - 2) * f[2] + (n - 1) * f[3]) % mod
g[3] = (f[1] + f[2] + (n - 2) * f[3] + (m - 2) * f[3]) % mod
f = g
if source[0] == dest[0]:
return f[0] if source[1] == dest[1] else f[2]
return f[1] if source[1] == dest[1] else f[3]
| Solution |
python | pennersr__django-allauth | examples/regular-django/example/users/models.py | {
"start": 96,
"end": 322
} | class ____(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
phone = models.CharField(max_length=16, unique=True, blank=True, null=True)
phone_verified = models.BooleanField(default=False)
| User |
python | kamyu104__LeetCode-Solutions | Python/count-the-number-of-incremovable-subarrays-ii.py | {
"start": 44,
"end": 635
} | class ____(object):
def incremovableSubarrayCount(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for j in reversed(xrange(1, len(nums))):
if not nums[j-1] < nums[j]:
break
else:
return (len(nums)+1)*len(nums)//2
result = len(nums)-j+1
for i in xrange(len(nums)-1):
while j < len(nums) and not (nums[i] < nums[j]):
j += 1
result += len(nums)-j+1
if not (nums[i] < nums[i+1]):
break
return result
| Solution |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 1065279,
"end": 1065449
} | class ____(sgqlc.types.Union):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__types__ = (Mannequin, Team, User)
| RequestedReviewer |
python | astropy__astropy | astropy/timeseries/periodograms/bls/core.py | {
"start": 783,
"end": 31469
} | class ____(BasePeriodogram):
"""Compute the box least squares periodogram.
This method is a commonly used tool for discovering transiting exoplanets
or eclipsing binaries in photometric time series datasets. This
implementation is based on the "box least squares (BLS)" method described
in [1]_ and [2]_.
Parameters
----------
t : array-like, `~astropy.units.Quantity`, `~astropy.time.Time`, or `~astropy.time.TimeDelta`
Sequence of observation times.
y : array-like or `~astropy.units.Quantity`
Sequence of observations associated with times ``t``.
dy : float, array-like, or `~astropy.units.Quantity`, optional
Error or sequence of observational errors associated with times ``t``.
Examples
--------
Generate noisy data with a transit:
>>> rand = np.random.default_rng(42)
>>> t = rand.uniform(0, 10, 500)
>>> y = np.ones_like(t)
>>> y[np.abs((t + 1.0)%2.0-1)<0.08] = 1.0 - 0.1
>>> y += 0.01 * rand.standard_normal(len(t))
Compute the transit periodogram on a heuristically determined period grid
and find the period with maximum power:
>>> model = BoxLeastSquares(t, y)
>>> results = model.autopower(0.16)
>>> results.period[np.argmax(results.power)] # doctest: +FLOAT_CMP
np.float64(2.000412388152837)
Compute the periodogram on a user-specified period grid:
>>> periods = np.linspace(1.9, 2.1, 5)
>>> results = model.power(periods, 0.16)
>>> results.power # doctest: +FLOAT_CMP
array([0.01723948, 0.0643028 , 0.1338783 , 0.09428816, 0.03577543])
If the inputs are AstroPy Quantities with units, the units will be
validated and the outputs will also be Quantities with appropriate units:
>>> from astropy import units as u
>>> t = t * u.day
>>> y = y * u.dimensionless_unscaled
>>> model = BoxLeastSquares(t, y)
>>> results = model.autopower(0.16 * u.day)
>>> results.period.unit
Unit("d")
>>> results.power.unit
Unit(dimensionless)
References
----------
.. [1] Kovacs, Zucker, & Mazeh (2002), A&A, 391, 369
(arXiv:astro-ph/0206099)
.. [2] Hartman & Bakos (2016), Astronomy & Computing, 17, 1
(arXiv:1605.06811)
"""
def __init__(self, t, y, dy=None):
# If t is a TimeDelta, convert it to a quantity. The units we convert
# to don't really matter since the user gets a Quantity back at the end
# so can convert to any units they like.
if isinstance(t, TimeDelta):
t = t.to("day")
# We want to expose self.t as being the times the user passed in, but
# if the times are absolute, we need to convert them to relative times
# internally, so we use self._trel and self._tstart for this.
self.t = t
if isinstance(self.t, (Time, TimeDelta)):
self._tstart = self.t[0]
trel = (self.t - self._tstart).to(u.day)
else:
self._tstart = None
trel = self.t
self._trel, self.y, self.dy = self._validate_inputs(trel, y, dy)
def autoperiod(
self,
duration,
minimum_period=None,
maximum_period=None,
minimum_n_transit=3,
frequency_factor=1.0,
):
"""Determine a suitable grid of periods.
This method uses a set of heuristics to select a conservative period
grid that is uniform in frequency. This grid might be too fine for
some user's needs depending on the precision requirements or the
sampling of the data. The grid can be made coarser by increasing
``frequency_factor``.
Parameters
----------
duration : float, array-like, or `~astropy.units.Quantity` ['time']
The set of durations that will be considered.
minimum_period, maximum_period : float or `~astropy.units.Quantity` ['time'], optional
The minimum/maximum periods to search. If not provided, these will
be computed as described in the notes below.
minimum_n_transit : int, optional
If ``maximum_period`` is not provided, this is used to compute the
maximum period to search by asserting that any systems with at
least ``minimum_n_transits`` will be within the range of searched
periods. Note that this is not the same as requiring that
``minimum_n_transits`` be required for detection. The default
value is ``3``.
frequency_factor : float, optional
A factor to control the frequency spacing as described in the
notes below. The default value is ``1.0``.
Returns
-------
period : array-like or `~astropy.units.Quantity` ['time']
The set of periods computed using these heuristics with the same
units as ``t``.
Notes
-----
The default minimum period is chosen to be twice the maximum duration
because there won't be much sensitivity to periods shorter than that.
The default maximum period is computed as
.. code-block:: python
maximum_period = (max(t) - min(t)) / minimum_n_transits
ensuring that any systems with at least ``minimum_n_transits`` are
within the range of searched periods.
The frequency spacing is given by
.. code-block:: python
df = frequency_factor * min(duration) / (max(t) - min(t))**2
so the grid can be made finer by decreasing ``frequency_factor`` or
coarser by increasing ``frequency_factor``.
"""
duration = self._validate_duration(duration)
baseline = strip_units(self._trel.max() - self._trel.min())
min_duration = strip_units(np.min(duration))
# Estimate the required frequency spacing
# Because of the sparsity of a transit, this must be much finer than
# the frequency resolution for a sinusoidal fit. For a sinusoidal fit,
# df would be 1/baseline (see LombScargle), but here this should be
# scaled proportionally to the duration in units of baseline.
df = frequency_factor * min_duration / baseline**2
# If a minimum period is not provided, choose one that is twice the
# maximum duration because we won't be sensitive to any periods
# shorter than that.
if minimum_period is None:
minimum_period = 2.0 * strip_units(np.max(duration))
else:
minimum_period = validate_unit_consistency(self._trel, minimum_period)
minimum_period = strip_units(minimum_period)
# If no maximum period is provided, choose one by requiring that
# all signals with at least minimum_n_transit should be detectable.
if maximum_period is None:
if minimum_n_transit <= 1:
raise ValueError("minimum_n_transit must be greater than 1")
maximum_period = baseline / (minimum_n_transit - 1)
else:
maximum_period = validate_unit_consistency(self._trel, maximum_period)
maximum_period = strip_units(maximum_period)
if maximum_period < minimum_period:
minimum_period, maximum_period = maximum_period, minimum_period
if minimum_period <= 0.0:
raise ValueError("minimum_period must be positive")
# Convert bounds to frequency
minimum_frequency = 1.0 / strip_units(maximum_period)
maximum_frequency = 1.0 / strip_units(minimum_period)
# Compute the number of frequencies and the frequency grid
nf = 1 + int(np.round((maximum_frequency - minimum_frequency) / df))
return 1.0 / (maximum_frequency - df * np.arange(nf)) * self._t_unit()
def autopower(
self,
duration,
objective=None,
method=None,
oversample=10,
minimum_n_transit=3,
minimum_period=None,
maximum_period=None,
frequency_factor=1.0,
):
"""Compute the periodogram at set of heuristically determined periods.
This method calls :func:`BoxLeastSquares.autoperiod` to determine
the period grid and then :func:`BoxLeastSquares.power` to compute
the periodogram. See those methods for documentation of the arguments.
"""
period = self.autoperiod(
duration,
minimum_n_transit=minimum_n_transit,
minimum_period=minimum_period,
maximum_period=maximum_period,
frequency_factor=frequency_factor,
)
return self.power(
period, duration, objective=objective, method=method, oversample=oversample
)
def power(self, period, duration, objective=None, method=None, oversample=10):
"""Compute the periodogram for a set of periods.
Parameters
----------
period : array-like or `~astropy.units.Quantity` ['time']
The periods where the power should be computed
duration : float, array-like, or `~astropy.units.Quantity` ['time']
The set of durations to test
objective : {'likelihood', 'snr'}, optional
The scalar that should be optimized to find the best fit phase,
duration, and depth. This can be either ``'likelihood'`` (default)
to optimize the log-likelihood of the model, or ``'snr'`` to
optimize the signal-to-noise with which the transit depth is
measured.
method : {'fast', 'slow'}, optional
The computational method used to compute the periodogram. This is
mainly included for the purposes of testing and most users will
want to use the optimized ``'fast'`` method (default) that is
implemented in Cython. ``'slow'`` is a brute-force method that is
used to test the results of the ``'fast'`` method.
oversample : int, optional
The number of bins per duration that should be used. This sets the
time resolution of the phase fit with larger values of
``oversample`` yielding a finer grid and higher computational cost.
Returns
-------
results : BoxLeastSquaresResults
The periodogram results as a :class:`BoxLeastSquaresResults`
object.
Raises
------
ValueError
If ``oversample`` is not an integer greater than 0 or if
``objective`` or ``method`` are not valid.
"""
period, duration = self._validate_period_and_duration(period, duration)
# Check for absurdities in the ``oversample`` choice
try:
oversample = int(oversample)
except TypeError:
raise ValueError(f"oversample must be an int, got {oversample}")
if oversample < 1:
raise ValueError("oversample must be greater than or equal to 1")
# Select the periodogram objective
if objective is None:
objective = "likelihood"
allowed_objectives = ["snr", "likelihood"]
if objective not in allowed_objectives:
raise ValueError(
f"Unrecognized method '{objective}'\n"
f"allowed methods are: {allowed_objectives}"
)
use_likelihood = objective == "likelihood"
# Select the computational method
if method is None:
method = "fast"
allowed_methods = ["fast", "slow"]
if method not in allowed_methods:
raise ValueError(
f"Unrecognized method '{method}'\n"
f"allowed methods are: {allowed_methods}"
)
# Format and check the input arrays
t = np.ascontiguousarray(strip_units(self._trel), dtype=np.float64)
t_ref = np.min(t)
y = np.ascontiguousarray(strip_units(self.y), dtype=np.float64)
if self.dy is None:
ivar = np.ones_like(y)
else:
ivar = (
1.0 / np.ascontiguousarray(strip_units(self.dy), dtype=np.float64) ** 2
)
# Make sure that the period and duration arrays are C-order
period_fmt = np.ascontiguousarray(strip_units(period), dtype=np.float64)
duration = np.ascontiguousarray(strip_units(duration), dtype=np.float64)
# Select the correct implementation for the chosen method
if method == "fast":
bls = methods.bls_fast
else:
bls = methods.bls_slow
# Run the implementation
results = bls(
t - t_ref,
y - np.median(y),
ivar,
period_fmt,
duration,
oversample,
use_likelihood,
)
return self._format_results(t_ref, objective, period, results)
def _as_relative_time(self, name, times):
"""
Convert the provided times (if absolute) to relative times using the
current _tstart value. If the times provided are relative, they are
returned without conversion (though we still do some checks).
"""
if isinstance(times, TimeDelta):
times = times.to("day")
if self._tstart is None:
if isinstance(times, Time):
raise TypeError(
f"{name} was provided as an absolute time but "
"the BoxLeastSquares class was initialized "
"with relative times."
)
else:
if isinstance(times, Time):
times = (times - self._tstart).to(u.day)
else:
raise TypeError(
f"{name} was provided as a relative time but "
"the BoxLeastSquares class was initialized "
"with absolute times."
)
times = validate_unit_consistency(self._trel, times)
return times
def _as_absolute_time_if_needed(self, name, times):
"""
Convert the provided times to absolute times using the current _tstart
value, if needed.
"""
if self._tstart is not None:
# Some time formats/scales can't represent dates/times too far
# off from the present, so we need to mask values offset by
# more than 100,000 yr (the periodogram algorithm can return
# transit times of e.g 1e300 for some periods).
reset = np.abs(times.to_value(u.year)) > 100000
times[reset] = 0
times = self._tstart + times
times[reset] = np.nan
return times
def model(self, t_model, period, duration, transit_time):
"""Compute the transit model at the given period, duration, and phase.
Parameters
----------
t_model : array-like, `~astropy.units.Quantity`, or `~astropy.time.Time`
Times at which to compute the model.
period : float or `~astropy.units.Quantity` ['time']
The period of the transits.
duration : float or `~astropy.units.Quantity` ['time']
The duration of the transit.
transit_time : float or `~astropy.units.Quantity` or `~astropy.time.Time`
The mid-transit time of a reference transit.
Returns
-------
y_model : array-like or `~astropy.units.Quantity`
The model evaluated at the times ``t_model`` with units of ``y``.
"""
period, duration = self._validate_period_and_duration(period, duration)
transit_time = self._as_relative_time("transit_time", transit_time)
t_model = strip_units(self._as_relative_time("t_model", t_model))
period = float(strip_units(period[0]))
duration = float(strip_units(duration[0]))
transit_time = float(strip_units(transit_time))
t = np.ascontiguousarray(strip_units(self._trel), dtype=np.float64)
y = np.ascontiguousarray(strip_units(self.y), dtype=np.float64)
if self.dy is None:
ivar = np.ones_like(y)
else:
ivar = (
1.0 / np.ascontiguousarray(strip_units(self.dy), dtype=np.float64) ** 2
)
# Compute the depth
hp = 0.5 * period
m_in = np.abs((t - transit_time + hp) % period - hp) < 0.5 * duration
m_out = ~m_in
y_in = np.sum(y[m_in] * ivar[m_in]) / np.sum(ivar[m_in])
y_out = np.sum(y[m_out] * ivar[m_out]) / np.sum(ivar[m_out])
# Evaluate the model
y_model = y_out + np.zeros_like(t_model)
m_model = np.abs((t_model - transit_time + hp) % period - hp) < 0.5 * duration
y_model[m_model] = y_in
return y_model * self._y_unit()
def compute_stats(self, period, duration, transit_time):
"""Compute descriptive statistics for a given transit model.
These statistics are commonly used for vetting of transit candidates.
Parameters
----------
period : float or `~astropy.units.Quantity` ['time']
The period of the transits.
duration : float or `~astropy.units.Quantity` ['time']
The duration of the transit.
transit_time : float or `~astropy.units.Quantity` or `~astropy.time.Time`
The mid-transit time of a reference transit.
Returns
-------
stats : dict
A dictionary containing several descriptive statistics:
- ``depth``: The depth and uncertainty (as a tuple with two
values) on the depth for the fiducial model.
- ``depth_odd``: The depth and uncertainty on the depth for a
model where the period is twice the fiducial period.
- ``depth_even``: The depth and uncertainty on the depth for a
model where the period is twice the fiducial period and the
phase is offset by one orbital period.
- ``depth_half``: The depth and uncertainty for a model with a
period of half the fiducial period.
- ``depth_phased``: The depth and uncertainty for a model with the
fiducial period and the phase offset by half a period.
- ``harmonic_amplitude``: The amplitude of the best fit sinusoidal
model.
- ``harmonic_delta_log_likelihood``: The difference in log
likelihood between a sinusoidal model and the transit model.
If ``harmonic_delta_log_likelihood`` is greater than zero, the
sinusoidal model is preferred.
- ``transit_times``: The mid-transit time for each transit in the
baseline.
- ``per_transit_count``: An array with a count of the number of
data points in each unique transit included in the baseline.
- ``per_transit_log_likelihood``: An array with the value of the
log likelihood for each unique transit included in the
baseline.
"""
period, duration = self._validate_period_and_duration(period, duration)
transit_time = self._as_relative_time("transit_time", transit_time)
period = float(strip_units(period[0]))
duration = float(strip_units(duration[0]))
transit_time = float(strip_units(transit_time))
t = np.ascontiguousarray(strip_units(self._trel), dtype=np.float64)
y = np.ascontiguousarray(strip_units(self.y), dtype=np.float64)
if self.dy is None:
ivar = np.ones_like(y)
else:
ivar = (
1.0 / np.ascontiguousarray(strip_units(self.dy), dtype=np.float64) ** 2
)
# This a helper function that will compute the depth for several
# different hypothesized transit models with different parameters
def _compute_depth(m, y_out=None, var_out=None):
if np.any(m) and (var_out is None or np.isfinite(var_out)):
var_m = 1.0 / np.sum(ivar[m])
y_m = np.sum(y[m] * ivar[m]) * var_m
if y_out is None:
return y_m, var_m
return y_out - y_m, np.sqrt(var_m + var_out)
return 0.0, np.inf
# Compute the depth of the fiducial model and the two models at twice
# the period
hp = 0.5 * period
m_in = np.abs((t - transit_time + hp) % period - hp) < 0.5 * duration
m_out = ~m_in
m_odd = np.abs((t - transit_time) % (2 * period) - period) < 0.5 * duration
m_even = (
np.abs((t - transit_time + period) % (2 * period) - period) < 0.5 * duration
)
y_out, var_out = _compute_depth(m_out)
depth = _compute_depth(m_in, y_out, var_out)
depth_odd = _compute_depth(m_odd, y_out, var_out)
depth_even = _compute_depth(m_even, y_out, var_out)
y_in = y_out - depth[0]
# Compute the depth of the model at a phase of 0.5*period
m_phase = np.abs((t - transit_time) % period - hp) < 0.5 * duration
depth_phase = _compute_depth(m_phase, *_compute_depth((~m_phase) & m_out))
# Compute the depth of a model with a period of 0.5*period
m_half = (
np.abs((t - transit_time + 0.25 * period) % (0.5 * period) - 0.25 * period)
< 0.5 * duration
)
depth_half = _compute_depth(m_half, *_compute_depth(~m_half))
# Compute the number of points in each transit
transit_id = np.round((t[m_in] - transit_time) / period).astype(int)
transit_times = (
period * np.arange(transit_id.min(), transit_id.max() + 1) + transit_time
)
unique_ids, unique_counts = np.unique(transit_id, return_counts=True)
unique_ids -= np.min(transit_id)
transit_id -= np.min(transit_id)
counts = np.zeros(np.max(transit_id) + 1, dtype=int)
counts[unique_ids] = unique_counts
# Compute the per-transit log likelihood
ll = -0.5 * ivar[m_in] * ((y[m_in] - y_in) ** 2 - (y[m_in] - y_out) ** 2)
lls = np.zeros(len(counts))
for i in unique_ids:
lls[i] = np.sum(ll[transit_id == i])
full_ll = -0.5 * np.sum(ivar[m_in] * (y[m_in] - y_in) ** 2)
full_ll -= 0.5 * np.sum(ivar[m_out] * (y[m_out] - y_out) ** 2)
# Compute the log likelihood of a sine model
A = np.vstack(
(
np.sin(2 * np.pi * t / period),
np.cos(2 * np.pi * t / period),
np.ones_like(t),
)
).T
w = np.linalg.solve(np.dot(A.T, A * ivar[:, None]), np.dot(A.T, y * ivar))
mod = np.dot(A, w)
sin_ll = -0.5 * np.sum((y - mod) ** 2 * ivar)
# Format the results
y_unit = self._y_unit()
ll_unit = 1
if self.dy is None:
ll_unit = y_unit * y_unit
return dict(
transit_times=self._as_absolute_time_if_needed(
"transit_times", transit_times * self._t_unit()
),
per_transit_count=counts,
per_transit_log_likelihood=lls * ll_unit,
depth=(depth[0] * y_unit, depth[1] * y_unit),
depth_phased=(depth_phase[0] * y_unit, depth_phase[1] * y_unit),
depth_half=(depth_half[0] * y_unit, depth_half[1] * y_unit),
depth_odd=(depth_odd[0] * y_unit, depth_odd[1] * y_unit),
depth_even=(depth_even[0] * y_unit, depth_even[1] * y_unit),
harmonic_amplitude=np.sqrt(np.sum(w[:2] ** 2)) * y_unit,
harmonic_delta_log_likelihood=(sin_ll - full_ll) * ll_unit,
)
def transit_mask(self, t, period, duration, transit_time):
"""Compute which data points are in transit for a given parameter set.
Parameters
----------
t : array-like or `~astropy.units.Quantity` ['time']
Times where the mask should be evaluated.
period : float or `~astropy.units.Quantity` ['time']
The period of the transits.
duration : float or `~astropy.units.Quantity` ['time']
The duration of the transit.
transit_time : float or `~astropy.units.Quantity` or `~astropy.time.Time`
The mid-transit time of a reference transit.
Returns
-------
transit_mask : array-like
A boolean array where ``True`` indicates and in transit point and
``False`` indicates and out-of-transit point.
"""
period, duration = self._validate_period_and_duration(period, duration)
transit_time = self._as_relative_time("transit_time", transit_time)
t = strip_units(self._as_relative_time("t", t))
period = float(strip_units(period[0]))
duration = float(strip_units(duration[0]))
transit_time = float(strip_units(transit_time))
hp = 0.5 * period
return np.abs((t - transit_time + hp) % period - hp) < 0.5 * duration
def _validate_inputs(self, t, y, dy):
"""Private method used to check the consistency of the inputs.
Parameters
----------
t : array-like, `~astropy.units.Quantity`, `~astropy.time.Time`, or `~astropy.time.TimeDelta`
Sequence of observation times.
y : array-like or `~astropy.units.Quantity`
Sequence of observations associated with times t.
dy : float, array-like, or `~astropy.units.Quantity`
Error or sequence of observational errors associated with times t.
Returns
-------
t, y, dy : array-like, `~astropy.units.Quantity`, or `~astropy.time.Time`
The inputs with consistent shapes and units.
Raises
------
ValueError
If the dimensions are incompatible or if the units of dy cannot be
converted to the units of y.
"""
# Validate shapes of inputs
if dy is None:
t, y = np.broadcast_arrays(t, y, subok=True)
else:
t, y, dy = np.broadcast_arrays(t, y, dy, subok=True)
if t.ndim != 1:
raise ValueError("Inputs (t, y, dy) must be 1-dimensional")
# validate units of inputs if any is a Quantity
if dy is not None:
dy = validate_unit_consistency(y, dy)
return t, y, dy
def _validate_duration(self, duration):
"""Private method used to check a set of test durations.
Parameters
----------
duration : float, array-like, or `~astropy.units.Quantity`
The set of durations that will be considered.
Returns
-------
duration : array-like or `~astropy.units.Quantity`
The input reformatted with the correct shape and units.
Raises
------
ValueError
If the units of duration cannot be converted to the units of t.
"""
duration = np.atleast_1d(np.abs(duration))
if duration.ndim != 1 or duration.size == 0:
raise ValueError("duration must be 1-dimensional")
return validate_unit_consistency(self._trel, duration)
def _validate_period_and_duration(self, period, duration):
"""Private method used to check a set of periods and durations.
Parameters
----------
period : float, array-like, or `~astropy.units.Quantity` ['time']
The set of test periods.
duration : float, array-like, or `~astropy.units.Quantity` ['time']
The set of durations that will be considered.
Returns
-------
period, duration : array-like or `~astropy.units.Quantity` ['time']
The inputs reformatted with the correct shapes and units.
Raises
------
ValueError
If the units of period or duration cannot be converted to the
units of t.
"""
duration = self._validate_duration(duration)
period = np.atleast_1d(np.abs(period))
if period.ndim != 1 or period.size == 0:
raise ValueError("period must be 1-dimensional")
period = validate_unit_consistency(self._trel, period)
if not np.min(period) > np.max(duration):
raise ValueError(
"The maximum transit duration must be shorter than the minimum period"
)
return period, duration
def _format_results(self, t_ref, objective, period, results):
"""A private method used to wrap and add units to the periodogram.
Parameters
----------
t_ref : float
The minimum time in the time series (a reference time).
objective : str
The name of the objective used in the optimization.
period : array-like or `~astropy.units.Quantity` ['time']
The set of trial periods.
results : tuple
The output of one of the periodogram implementations.
"""
(
power,
depth,
depth_err,
duration,
transit_time,
depth_snr,
log_likelihood,
) = results
transit_time += t_ref
if has_units(self._trel):
transit_time = units.Quantity(transit_time, unit=self._trel.unit)
transit_time = self._as_absolute_time_if_needed(
"transit_time", transit_time
)
duration = units.Quantity(duration, unit=self._trel.unit)
if has_units(self.y):
depth = units.Quantity(depth, unit=self.y.unit)
depth_err = units.Quantity(depth_err, unit=self.y.unit)
depth_snr = units.Quantity(depth_snr, unit=units.one)
if self.dy is None:
if objective == "likelihood":
power = units.Quantity(power, unit=self.y.unit**2)
else:
power = units.Quantity(power, unit=units.one)
log_likelihood = units.Quantity(log_likelihood, unit=self.y.unit**2)
else:
power = units.Quantity(power, unit=units.one)
log_likelihood = units.Quantity(log_likelihood, unit=units.one)
return BoxLeastSquaresResults(
objective,
period,
power,
depth,
depth_err,
duration,
transit_time,
depth_snr,
log_likelihood,
)
def _t_unit(self):
if has_units(self._trel):
return self._trel.unit
else:
return 1
def _y_unit(self):
if has_units(self.y):
return self.y.unit
else:
return 1
| BoxLeastSquares |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/utils_tests/test_typed_dict_utils.py | {
"start": 215,
"end": 572
} | class ____(TypedDict):
nested: MyNestedTypedDict
optional_field: Optional[str]
dict_field: dict[str, Any]
not_required_field: NotRequired[str]
def test_init_optional_typeddict():
assert init_optional_typeddict(MyTypedDict) == {
"nested": {"nested": None},
"optional_field": None,
"dict_field": {},
}
| MyTypedDict |
python | huggingface__transformers | src/transformers/models/csm/modular_csm.py | {
"start": 16974,
"end": 18341
} | class ____(LlamaModel):
def __init__(self, config):
super().__init__(config)
self.embed_tokens = CsmBackboneModelEmbeddings(config)
@check_model_inputs()
@auto_docstring
def forward(self, **super_kwargs):
r"""
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, num_codebooks) or (batch_size, sequence_length)`):
1. (batch_size, sequence_length): corresponds to the input sequence prepared with the processor from the text prompt. Such input
requires `input_values` to be provided so that audio can be encoded in codebook tokens and then merged with the text tokens.
2. (batch_size, sequence_length, num_codebooks): codebook tokens generated during the autoregressive decoding. Such input is not meant to be used by end users.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
"""
return super().forward(**super_kwargs)
@auto_docstring(
custom_intro="""
The Csm model consists of two llama-like auto-regressive transformer models: a backbone model that predicts the first codebook token and a depth decoder that predicts the other codebook tokens.
"""
)
| CsmBackboneModel |
python | doocs__leetcode | solution/2800-2899/2806.Account Balance After Rounded Purchase/Solution.py | {
"start": 0,
"end": 274
} | class ____:
def accountBalanceAfterPurchase(self, purchaseAmount: int) -> int:
diff, x = 100, 0
for y in range(100, -1, -10):
if (t := abs(y - purchaseAmount)) < diff:
diff = t
x = y
return 100 - x
| Solution |
python | pytorch__pytorch | test/torch_np/numpy_tests/linalg/test_linalg.py | {
"start": 22397,
"end": 23348
} | class ____(HermitianTestCase, HermitianGeneralizedTestCase):
def do(self, a, b, tags):
u, s, vt = linalg.svd(a, False, hermitian=True)
assert_allclose(
a,
dot_generalized(
np.asarray(u) * np.asarray(s)[..., None, :], np.asarray(vt)
),
rtol=get_rtol(u.dtype),
)
def hermitian(mat):
axes = list(range(mat.ndim))
axes[-1], axes[-2] = axes[-2], axes[-1]
return np.conj(np.transpose(mat, axes=axes))
assert_almost_equal(
np.matmul(u, hermitian(u)), np.broadcast_to(np.eye(u.shape[-1]), u.shape)
)
assert_almost_equal(
np.matmul(vt, hermitian(vt)),
np.broadcast_to(np.eye(vt.shape[-1]), vt.shape),
)
assert_equal(np.sort(s), np.flip(s, -1))
assert_(consistent_subclass(u, a))
assert_(consistent_subclass(vt, a))
| SVDHermitianCases |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | contents/8_Actor_Critic_Advantage/AC_CartPole.py | {
"start": 881,
"end": 2825
} | class ____(object):
def __init__(self, sess, n_features, n_actions, lr=0.001):
self.sess = sess
self.s = tf.placeholder(tf.float32, [1, n_features], "state")
self.a = tf.placeholder(tf.int32, None, "act")
self.td_error = tf.placeholder(tf.float32, None, "td_error") # TD_error
with tf.variable_scope('Actor'):
l1 = tf.layers.dense(
inputs=self.s,
units=20, # number of hidden units
activation=tf.nn.relu,
kernel_initializer=tf.random_normal_initializer(0., .1), # weights
bias_initializer=tf.constant_initializer(0.1), # biases
name='l1'
)
self.acts_prob = tf.layers.dense(
inputs=l1,
units=n_actions, # output units
activation=tf.nn.softmax, # get action probabilities
kernel_initializer=tf.random_normal_initializer(0., .1), # weights
bias_initializer=tf.constant_initializer(0.1), # biases
name='acts_prob'
)
with tf.variable_scope('exp_v'):
log_prob = tf.log(self.acts_prob[0, self.a])
self.exp_v = tf.reduce_mean(log_prob * self.td_error) # advantage (TD_error) guided loss
with tf.variable_scope('train'):
self.train_op = tf.train.AdamOptimizer(lr).minimize(-self.exp_v) # minimize(-exp_v) = maximize(exp_v)
def learn(self, s, a, td):
s = s[np.newaxis, :]
feed_dict = {self.s: s, self.a: a, self.td_error: td}
_, exp_v = self.sess.run([self.train_op, self.exp_v], feed_dict)
return exp_v
def choose_action(self, s):
s = s[np.newaxis, :]
probs = self.sess.run(self.acts_prob, {self.s: s}) # get probabilities for all actions
return np.random.choice(np.arange(probs.shape[1]), p=probs.ravel()) # return a int
| Actor |
python | tensorflow__tensorflow | tensorflow/python/training/saver_test.py | {
"start": 116166,
"end": 117398
} | class ____(test.TestCase):
def _get_test_dir(self, dirname):
test_dir = os.path.join(self.get_temp_dir(), dirname)
gfile.MakeDirs(test_dir)
return test_dir
def testWriteGraph(self):
test_dir = self._get_test_dir("write_graph_dir")
variable_v1.VariableV1([[1, 2, 3], [4, 5, 6]],
dtype=dtypes.float32,
name="v0")
path = graph_io.write_graph(ops_lib.get_default_graph(),
os.path.join(test_dir, "l1"), "graph.pbtxt")
truth = os.path.join(test_dir, "l1", "graph.pbtxt")
self.assertEqual(path, truth)
self.assertTrue(os.path.exists(path))
def testRecursiveCreate(self):
test_dir = self._get_test_dir("deep_dir")
variable_v1.VariableV1([[1, 2, 3], [4, 5, 6]],
dtype=dtypes.float32,
name="v0")
path = graph_io.write_graph(ops_lib.get_default_graph().as_graph_def(),
os.path.join(test_dir, "l1", "l2", "l3"),
"graph.pbtxt")
truth = os.path.join(test_dir, "l1", "l2", "l3", "graph.pbtxt")
self.assertEqual(path, truth)
self.assertTrue(os.path.exists(path))
| WriteGraphTest |
python | pyca__cryptography | tests/hazmat/primitives/decrepit/test_algorithms.py | {
"start": 3710,
"end": 4194
} | class ____:
test_cbc = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "Blowfish"),
["bf-cbc.txt"],
lambda key, **kwargs: Blowfish(binascii.unhexlify(key)),
lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)),
)
@pytest.mark.supported(
only_if=lambda backend: backend.cipher_supported(
Blowfish(b"\x00" * 56), OFB(b"\x00" * 8)
),
skip_message="Does not support Blowfish OFB",
)
| TestBlowfishModeCBC |
python | getsentry__sentry | tests/sentry/api/serializers/test_project.py | {
"start": 32348,
"end": 37509
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.date = datetime.datetime(2018, 1, 12, 3, 8, 25, tzinfo=UTC)
self.user = self.create_user(username="foo")
self.organization = self.create_organization(owner=self.user)
team = self.create_team(organization=self.organization)
self.project = self.create_project(teams=[team], organization=self.organization, name="foo")
self.project.flags.has_releases = True
self.project.save()
self.release = self.create_release(self.project)
def test_truncated_latest_release(self) -> None:
result = serialize(self.project, self.user, DetailedProjectSerializer())
assert result["id"] == str(self.project.id)
assert result["name"] == self.project.name
assert result["slug"] == self.project.slug
assert result["firstEvent"] == self.project.first_event
assert "releases" in result["features"]
assert result["platform"] == self.project.platform
assert result["latestRelease"] == {"version": self.release.version}
def test_symbol_sources(self) -> None:
ProjectOption.objects.set_value(
project=self.project,
key="sentry:symbol_sources",
value='[{"id":"1","name":"hello","password":"password",}]',
)
result = serialize(self.project, self.user, DetailedProjectSerializer())
assert "sentry:token" not in result["options"]
assert "sentry:symbol_sources" not in result["options"]
def test_feedback_flag_with_epochs(self) -> None:
result = serialize(self.project, self.user, DetailedProjectSerializer())
# new projects with default epoch should have feedback_user_report_notifications enabled
assert result["options"]["sentry:feedback_user_report_notifications"] is True
self.project.update_option("sentry:option-epoch", 1)
result = serialize(self.project, self.user, DetailedProjectSerializer())
assert result["options"]["sentry:feedback_user_report_notifications"] is False
self.project.update_option("sentry:feedback_user_report_notifications", True)
result = serialize(self.project, self.user, DetailedProjectSerializer())
assert result["options"]["sentry:feedback_user_report_notifications"] is True
self.project.update_option("sentry:feedback_user_report_notifications", False)
result = serialize(self.project, self.user, DetailedProjectSerializer())
assert result["options"]["sentry:feedback_user_report_notifications"] is False
def test_replay_rage_click_flag(self) -> None:
result = serialize(self.project, self.user, DetailedProjectSerializer())
# default should be true
assert result["options"]["sentry:replay_rage_click_issues"] is True
self.project.update_option("sentry:replay_rage_click_issues", False)
result = serialize(self.project, self.user, DetailedProjectSerializer())
assert result["options"]["sentry:replay_rage_click_issues"] is False
def test_replay_hydration_error_flag(self) -> None:
result = serialize(self.project, self.user, DetailedProjectSerializer())
# default should be true
assert result["options"]["sentry:replay_hydration_error_issues"] is True
self.project.update_option("sentry:replay_hydration_error_issues", False)
result = serialize(self.project, self.user, DetailedProjectSerializer())
assert result["options"]["sentry:replay_hydration_error_issues"] is False
def test_toolbar_allowed_origins(self) -> None:
# Does not allow trailing newline or extra whitespace.
# Default is empty:
result = serialize(self.project, self.user, DetailedProjectSerializer())
assert result["options"]["sentry:toolbar_allowed_origins"] == ""
origins = ["*.sentry.io", "example.net", "nugettrends.com"]
self.project.update_option("sentry:toolbar_allowed_origins", origins)
result = serialize(self.project, self.user, DetailedProjectSerializer())
assert result["options"]["sentry:toolbar_allowed_origins"].split("\n") == origins
def test_autofix_automation_tuning_flag(self) -> None:
# Default is "off"
result = serialize(self.project, self.user, DetailedProjectSerializer())
assert result["autofixAutomationTuning"] == "off"
# Update the value
self.project.update_option("sentry:autofix_automation_tuning", "high")
result = serialize(self.project, self.user, DetailedProjectSerializer())
assert result["autofixAutomationTuning"] == "high"
def test_seer_scanner_automation_flag(self) -> None:
# Default is "on"
result = serialize(self.project, self.user, DetailedProjectSerializer())
assert result["seerScannerAutomation"] is True
# Update the value
self.project.update_option("sentry:seer_scanner_automation", False)
result = serialize(self.project, self.user, DetailedProjectSerializer())
assert result["seerScannerAutomation"] is False
| DetailedProjectSerializerTest |
python | pydata__xarray | xarray/tests/test_dataarray.py | {
"start": 272796,
"end": 275061
} | class ____:
# https://github.com/pydata/xarray/issues/6051
def test_result_as_expected(self) -> None:
da = DataArray([[1, 2], [1, 2]], dims=("x", "y"))
result = da.stack(flat=[...])
expected = da.stack(flat=da.dims)
assert_identical(result, expected)
def test_error_on_ellipsis_without_list(self) -> None:
da = DataArray([[1, 2], [1, 2]], dims=("x", "y"))
with pytest.raises(ValueError):
da.stack(flat=...) # type: ignore[arg-type]
def test_nD_coord_dataarray() -> None:
# should succeed
da = DataArray(
np.ones((2, 4)),
dims=("x", "y"),
coords={
"x": (("x", "y"), np.arange(8).reshape((2, 4))),
"y": ("y", np.arange(4)),
},
)
_assert_internal_invariants(da, check_default_indexes=True)
da2 = DataArray(np.ones(4), dims=("y"), coords={"y": ("y", np.arange(4))})
da3 = DataArray(np.ones(4), dims=("z"))
_, actual = xr.align(da, da2)
assert_identical(da2, actual)
expected = da.drop_vars("x")
_, actual = xr.broadcast(da, da2)
assert_identical(expected, actual)
actual, _ = xr.broadcast(da, da3)
expected = da.expand_dims(z=4, axis=-1)
assert_identical(actual, expected)
da4 = DataArray(np.ones((2, 4)), coords={"x": 0}, dims=["x", "y"])
_assert_internal_invariants(da4, check_default_indexes=True)
assert "x" not in da4.xindexes
assert "x" in da4.coords
def test_lazy_data_variable_not_loaded():
# GH8753
array = InaccessibleArray(np.array([1, 2, 3]))
v = Variable(data=array, dims="x")
# No data needs to be accessed, so no error should be raised
da = xr.DataArray(v)
# No data needs to be accessed, so no error should be raised
xr.DataArray(da)
def test_unstack_index_var() -> None:
source = xr.DataArray(range(2), dims=["x"], coords=[["a", "b"]])
da = source.x
da = da.assign_coords(y=("x", ["c", "d"]), z=("x", ["e", "f"]))
da = da.set_index(x=["y", "z"])
actual = da.unstack("x")
expected = xr.DataArray(
np.array([["a", np.nan], [np.nan, "b"]], dtype=object),
coords={"y": ["c", "d"], "z": ["e", "f"]},
name="x",
)
assert_identical(actual, expected)
| TestStackEllipsis |
python | spyder-ide__spyder | spyder/widgets/helperwidgets.py | {
"start": 23543,
"end": 25014
} | class ____(QLineEdit):
"""Lineedit that validates its contents in focus out."""
sig_focus_out = Signal(str)
def __init__(
self,
validate_callback: Callable,
validate_reason: str,
text: str = "",
parent: QWidget | None = None,
):
super().__init__(text, parent)
# Attributes
self._validate_callback = validate_callback
self._validate_reason = validate_reason
self._is_show = False
# Action to signal that text is not valid
self.error_action = QAction(self)
self.error_action.setIcon(ima.icon("error"))
self.addAction(self.error_action, QLineEdit.TrailingPosition)
# Signals
self.sig_focus_out.connect(self._validate)
def focusOutEvent(self, event):
if self.text():
self.sig_focus_out.emit(self.text())
else:
self.error_action.setVisible(False)
super().focusOutEvent(event)
def focusInEvent(self, event):
self.error_action.setVisible(False)
super().focusInEvent(event)
def showEvent(self, event):
if not self._is_show:
self.error_action.setVisible(False)
self._is_show = True
super().showEvent(event)
def _validate(self, text):
if not self._validate_callback(text):
self.error_action.setVisible(True)
self.error_action.setToolTip(self._validate_reason)
| ValidationLineEdit |
python | django__django | tests/model_formsets/models.py | {
"start": 5207,
"end": 5379
} | class ____(models.Model):
poet = models.ForeignKey(Poet, models.CASCADE)
name = models.CharField(max_length=100)
def __str__(self):
return self.name
| Poem |
python | walkccc__LeetCode | solutions/3355. Zero Array Transformation I/3355.py | {
"start": 0,
"end": 338
} | class ____:
def isZeroArray(self, nums: list[int], queries: list[list[int]]) -> bool:
line = [0] * (len(nums) + 1)
decrement = 0
for l, r in queries:
line[l] += 1
line[r + 1] -= 1
for i, num in enumerate(nums):
decrement += line[i]
if decrement < num:
return False
return True
| Solution |
python | astropy__astropy | astropy/cosmology/_src/default.py | {
"start": 267,
"end": 2991
} | class ____(ScienceState):
"""The default cosmology to use.
To change it::
>>> from astropy.cosmology import default_cosmology, WMAP7
>>> with default_cosmology.set(WMAP7):
... # WMAP7 cosmology in effect
... pass
Or, you may use a string::
>>> with default_cosmology.set('WMAP7'):
... # WMAP7 cosmology in effect
... pass
To get the default cosmology:
>>> default_cosmology.get()
FlatLambdaCDM(name='Planck18', H0=<Quantity 67.66 km / (Mpc s)>,
Om0=0.30966, ...
"""
_default_value: ClassVar[str] = "Planck18"
_value: ClassVar[str | Cosmology] = "Planck18"
@classmethod
def validate(cls, value: Cosmology | str | None) -> Cosmology | None:
"""Return a Cosmology given a value.
Parameters
----------
value : None, str, or `~astropy.cosmology.Cosmology`
Returns
-------
`~astropy.cosmology.Cosmology` instance
Raises
------
TypeError
If ``value`` is not a string or |Cosmology|.
"""
# None -> default
if value is None:
value = cls._default_value
# Parse to Cosmology. Error if cannot.
if isinstance(value, str):
# special-case one string
if value == "no_default":
value = None
else:
value = cls._get_from_registry(value)
elif not isinstance(value, Cosmology):
raise TypeError(
"default_cosmology must be a string or Cosmology instance, "
f"not {value}."
)
return value
@classmethod
def _get_from_registry(cls, name: str) -> Cosmology:
"""Get a registered Cosmology realization.
Parameters
----------
name : str
The built-in |Cosmology| realization to retrieve.
Returns
-------
`astropy.cosmology.Cosmology`
The cosmology realization of `name`.
Raises
------
ValueError
If ``name`` is a str, but not for a built-in Cosmology.
TypeError
If ``name`` is for a non-Cosmology object.
"""
from astropy.cosmology import realizations
try:
value = getattr(realizations, name)
except AttributeError:
msg = f"Unknown cosmology {name!r}. Valid cosmologies:\n{realizations.available}"
raise ValueError(msg) from None
if not isinstance(value, Cosmology):
raise TypeError(f"cannot find a Cosmology realization called {name}.")
return value
| default_cosmology |
python | google__jax | jax/_src/core.py | {
"start": 27377,
"end": 32552
} | class ____(Generic[TracerType]):
__slots__ = ("__weakref__", "_invalidated", "_weakref", "requires_low")
def __init__(self):
self._invalidated = False
# We frequently need a weakref to a trace, so let's precompute one.
self._weakref = weakref.ref(self)
self.requires_low = True
def process_primitive(self, primitive, tracers, params):
raise NotImplementedError("must override")
def invalidate(self):
self._invalidated = True
def is_valid(self):
return not self._invalidated
def __repr__(self):
return f'{self.__class__.__name__}'
def process_call(self, call_primitive, f, tracers, params):
msg = (f"{type(self)} must override process_call to handle call-like "
"primitives")
raise NotImplementedError(msg)
def process_map(self, map_primitive, f, tracers, params):
msg = (f"{type(self)} must override process_map to handle map-like "
"primitives")
raise NotImplementedError(msg)
def process_custom_jvp_call(self, primitive, fun, jvp, tracers, *,
symbolic_zeros):
msg = (f"{type(self)} must override process_custom_jvp_call "
"to handle custom_jvp primitives")
raise NotImplementedError(msg)
def process_custom_transpose(self, prim: Primitive,
call: lu.WrappedFun, tracers, **params):
msg = (f"{type(self)} must override process_custom_transpose "
"to handle custom_transpose_call primitives")
raise NotImplementedError(msg)
def process_custom_vjp_call(self, primitive, fun, fwd, bwd, tracers,
out_trees, symbolic_zeros):
msg = (f"{type(self)} must override process_custom_vjp_call "
"to handle custom_vjp primitives")
raise NotImplementedError(msg)
# TODO(dougalm): deprecate/delete
def full_raise(self, x):
return x
# TODO(dougalm): deprecate/delete
@property
def main(self):
return getattr(self, "tag", None)
def escaped_tracer_error(tracer, detail=None):
num_frames = _TRACER_ERROR_NUM_TRACEBACK_FRAMES.value
msg = ('Encountered an unexpected tracer. A function transformed by JAX '
'had a side effect, allowing for a reference to an intermediate value '
f'with type {tracer.aval.str_short()} wrapped in a '
f'{type(tracer).__name__} to escape the scope of the transformation.\n'
'JAX transformations require that functions explicitly return their '
'outputs, and disallow saving intermediate values to global state.')
dbg = getattr(tracer, '_debug_info', None)
if dbg is not None:
msg += ('\nThe function being traced when the value leaked was '
f'{dbg.func_src_info} traced for {dbg.traced_for}.')
line_info = getattr(tracer, '_line_info', None)
if line_info is not None:
divider = '\n' + '-'*30 + '\n'
msg += divider
msg += ('The leaked intermediate value was created on line '
f'{source_info_util.summarize(line_info)}. ')
msg += divider
if num_frames > 0:
msg += (f'When the value was created, the final {num_frames} stack '
'frames (most recent last) excluding JAX-internal frames were:')
msg += divider + source_info_util.summarize(
line_info, num_frames=num_frames) + divider
msg += ('\nTo catch the leak earlier, try setting the environment variable '
'JAX_CHECK_TRACER_LEAKS or using the `jax.checking_leaks` context '
'manager.')
if detail:
msg += f'Detail: {detail}'
return UnexpectedTracerError(msg)
def check_scalar_conversion(arr: Array):
if arr.ndim > 0:
raise TypeError("Only scalar arrays can be converted to Python scalars; "
f"got {arr.ndim=}")
def check_integer_conversion(arr: Array):
if not (arr.shape == () and dtypes.issubdtype(arr.dtype, np.integer)):
raise TypeError("Only integer scalar arrays can be converted to a scalar index.")
def check_bool_conversion(arr: Array):
if arr.size == 0:
raise ValueError("The truth value of an empty array is ambiguous. Use"
" `array.size > 0` to check that an array is not empty.")
if arr.size > 1:
raise ValueError("The truth value of an array with more than one element"
" is ambiguous. Use a.any() or a.all()")
pytype_aval_mappings: dict[type, Callable[[Any], AbstractValue]] = {}
def _str_abstractify(x):
raise TypeError(f"Argument '{x}' of type {type(x)} is not a valid JAX type")
pytype_aval_mappings[str] = _str_abstractify
def _aval_property(name):
return property(lambda self: getattr(self.aval, name))
if TYPE_CHECKING or jaxlib_extension_version < 388:
# We want Python type checkers to accept `some_tracer: jax.Array`, even though
# tracers can represent non-arrays. That is, ideally we would only accept that
# annotation when the Tracer instance has a ShapedArray aval, but we can't
# decide that at Python type checking time. So instead we're overly permissive
# and allow all Tracer instances to typecheck against a jax.Array annotation.
TracerBase = Array
TracerMeta = StrictABCMeta
else:
TracerBase = object
TracerMeta = type
| Trace |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 568331,
"end": 568943
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("ReactingUserEdge"), graphql_name="edges"
)
nodes = sgqlc.types.Field(sgqlc.types.list_of("User"), graphql_name="nodes")
page_info = sgqlc.types.Field(
sgqlc.types.non_null(PageInfo), graphql_name="pageInfo"
)
total_count = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="totalCount"
)
| ReactingUserConnection |
python | django__django | django/views/generic/dates.py | {
"start": 13354,
"end": 13527
} | class ____(MultipleObjectTemplateResponseMixin, BaseArchiveIndexView):
"""Top-level archive of date-based items."""
template_name_suffix = "_archive"
| ArchiveIndexView |
python | django__django | tests/foreign_object/test_forms.py | {
"start": 106,
"end": 1108
} | class ____(TestCase):
# ForeignObjects should not have any form fields, currently the user needs
# to manually deal with the foreignobject relation.
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = "__all__"
def test_foreign_object_form(self):
# A very crude test checking that the non-concrete fields do not get
# form fields.
form = FormsTests.ArticleForm()
self.assertIn("id_pub_date", form.as_table())
self.assertNotIn("active_translation", form.as_table())
form = FormsTests.ArticleForm(data={"pub_date": str(datetime.date.today())})
self.assertTrue(form.is_valid())
a = form.save()
self.assertEqual(a.pub_date, datetime.date.today())
form = FormsTests.ArticleForm(instance=a, data={"pub_date": "2013-01-01"})
a2 = form.save()
self.assertEqual(a.pk, a2.pk)
self.assertEqual(a2.pub_date, datetime.date(2013, 1, 1))
| FormsTests |
python | numba__numba | numba/tests/test_ir.py | {
"start": 3410,
"end": 11632
} | class ____(CheckEquality):
"""
Tests IR nodes
"""
def test_terminator(self):
# terminator base class inst should always be equal
t1 = ir.Terminator()
t2 = ir.Terminator()
self.check(t1, same=[t2])
def test_jump(self):
a = ir.Jump(1, self.loc1)
b = ir.Jump(1, self.loc1)
c = ir.Jump(1, self.loc2)
d = ir.Jump(2, self.loc1)
self.check(a, same=[b, c], different=[d])
def test_return(self):
a = ir.Return(self.var_a, self.loc1)
b = ir.Return(self.var_a, self.loc1)
c = ir.Return(self.var_a, self.loc2)
d = ir.Return(self.var_b, self.loc1)
self.check(a, same=[b, c], different=[d])
def test_raise(self):
a = ir.Raise(self.var_a, self.loc1)
b = ir.Raise(self.var_a, self.loc1)
c = ir.Raise(self.var_a, self.loc2)
d = ir.Raise(self.var_b, self.loc1)
self.check(a, same=[b, c], different=[d])
def test_staticraise(self):
a = ir.StaticRaise(AssertionError, None, self.loc1)
b = ir.StaticRaise(AssertionError, None, self.loc1)
c = ir.StaticRaise(AssertionError, None, self.loc2)
e = ir.StaticRaise(AssertionError, ("str",), self.loc1)
d = ir.StaticRaise(RuntimeError, None, self.loc1)
self.check(a, same=[b, c], different=[d, e])
def test_branch(self):
a = ir.Branch(self.var_a, 1, 2, self.loc1)
b = ir.Branch(self.var_a, 1, 2, self.loc1)
c = ir.Branch(self.var_a, 1, 2, self.loc2)
d = ir.Branch(self.var_b, 1, 2, self.loc1)
e = ir.Branch(self.var_a, 2, 2, self.loc1)
f = ir.Branch(self.var_a, 1, 3, self.loc1)
self.check(a, same=[b, c], different=[d, e, f])
def test_expr(self):
a = ir.Expr('some_op', self.loc1)
b = ir.Expr('some_op', self.loc1)
c = ir.Expr('some_op', self.loc2)
d = ir.Expr('some_other_op', self.loc1)
self.check(a, same=[b, c], different=[d])
def test_setitem(self):
a = ir.SetItem(self.var_a, self.var_b, self.var_c, self.loc1)
b = ir.SetItem(self.var_a, self.var_b, self.var_c, self.loc1)
c = ir.SetItem(self.var_a, self.var_b, self.var_c, self.loc2)
d = ir.SetItem(self.var_d, self.var_b, self.var_c, self.loc1)
e = ir.SetItem(self.var_a, self.var_d, self.var_c, self.loc1)
f = ir.SetItem(self.var_a, self.var_b, self.var_d, self.loc1)
self.check(a, same=[b, c], different=[d, e, f])
def test_staticsetitem(self):
a = ir.StaticSetItem(self.var_a, 1, self.var_b, self.var_c, self.loc1)
b = ir.StaticSetItem(self.var_a, 1, self.var_b, self.var_c, self.loc1)
c = ir.StaticSetItem(self.var_a, 1, self.var_b, self.var_c, self.loc2)
d = ir.StaticSetItem(self.var_d, 1, self.var_b, self.var_c, self.loc1)
e = ir.StaticSetItem(self.var_a, 2, self.var_b, self.var_c, self.loc1)
f = ir.StaticSetItem(self.var_a, 1, self.var_d, self.var_c, self.loc1)
g = ir.StaticSetItem(self.var_a, 1, self.var_b, self.var_d, self.loc1)
self.check(a, same=[b, c], different=[d, e, f, g])
def test_delitem(self):
a = ir.DelItem(self.var_a, self.var_b, self.loc1)
b = ir.DelItem(self.var_a, self.var_b, self.loc1)
c = ir.DelItem(self.var_a, self.var_b, self.loc2)
d = ir.DelItem(self.var_c, self.var_b, self.loc1)
e = ir.DelItem(self.var_a, self.var_c, self.loc1)
self.check(a, same=[b, c], different=[d, e])
def test_del(self):
a = ir.Del(self.var_a.name, self.loc1)
b = ir.Del(self.var_a.name, self.loc1)
c = ir.Del(self.var_a.name, self.loc2)
d = ir.Del(self.var_b.name, self.loc1)
self.check(a, same=[b, c], different=[d])
def test_setattr(self):
a = ir.SetAttr(self.var_a, 'foo', self.var_b, self.loc1)
b = ir.SetAttr(self.var_a, 'foo', self.var_b, self.loc1)
c = ir.SetAttr(self.var_a, 'foo', self.var_b, self.loc2)
d = ir.SetAttr(self.var_c, 'foo', self.var_b, self.loc1)
e = ir.SetAttr(self.var_a, 'bar', self.var_b, self.loc1)
f = ir.SetAttr(self.var_a, 'foo', self.var_c, self.loc1)
self.check(a, same=[b, c], different=[d, e, f])
def test_delattr(self):
a = ir.DelAttr(self.var_a, 'foo', self.loc1)
b = ir.DelAttr(self.var_a, 'foo', self.loc1)
c = ir.DelAttr(self.var_a, 'foo', self.loc2)
d = ir.DelAttr(self.var_c, 'foo', self.loc1)
e = ir.DelAttr(self.var_a, 'bar', self.loc1)
self.check(a, same=[b, c], different=[d, e])
def test_assign(self):
a = ir.Assign(self.var_a, self.var_b, self.loc1)
b = ir.Assign(self.var_a, self.var_b, self.loc1)
c = ir.Assign(self.var_a, self.var_b, self.loc2)
d = ir.Assign(self.var_c, self.var_b, self.loc1)
e = ir.Assign(self.var_a, self.var_c, self.loc1)
self.check(a, same=[b, c], different=[d, e])
def test_print(self):
a = ir.Print((self.var_a,), self.var_b, self.loc1)
b = ir.Print((self.var_a,), self.var_b, self.loc1)
c = ir.Print((self.var_a,), self.var_b, self.loc2)
d = ir.Print((self.var_c,), self.var_b, self.loc1)
e = ir.Print((self.var_a,), self.var_c, self.loc1)
self.check(a, same=[b, c], different=[d, e])
def test_storemap(self):
a = ir.StoreMap(self.var_a, self.var_b, self.var_c, self.loc1)
b = ir.StoreMap(self.var_a, self.var_b, self.var_c, self.loc1)
c = ir.StoreMap(self.var_a, self.var_b, self.var_c, self.loc2)
d = ir.StoreMap(self.var_d, self.var_b, self.var_c, self.loc1)
e = ir.StoreMap(self.var_a, self.var_d, self.var_c, self.loc1)
f = ir.StoreMap(self.var_a, self.var_b, self.var_d, self.loc1)
self.check(a, same=[b, c], different=[d, e, f])
def test_yield(self):
a = ir.Yield(self.var_a, self.loc1, 0)
b = ir.Yield(self.var_a, self.loc1, 0)
c = ir.Yield(self.var_a, self.loc2, 0)
d = ir.Yield(self.var_b, self.loc1, 0)
e = ir.Yield(self.var_a, self.loc1, 1)
self.check(a, same=[b, c], different=[d, e])
def test_enterwith(self):
a = ir.EnterWith(self.var_a, 0, 1, self.loc1)
b = ir.EnterWith(self.var_a, 0, 1, self.loc1)
c = ir.EnterWith(self.var_a, 0, 1, self.loc2)
d = ir.EnterWith(self.var_b, 0, 1, self.loc1)
e = ir.EnterWith(self.var_a, 1, 1, self.loc1)
f = ir.EnterWith(self.var_a, 0, 2, self.loc1)
self.check(a, same=[b, c], different=[d, e, f])
def test_arg(self):
a = ir.Arg('foo', 0, self.loc1)
b = ir.Arg('foo', 0, self.loc1)
c = ir.Arg('foo', 0, self.loc2)
d = ir.Arg('bar', 0, self.loc1)
e = ir.Arg('foo', 1, self.loc1)
self.check(a, same=[b, c], different=[d, e])
def test_const(self):
a = ir.Const(1, self.loc1)
b = ir.Const(1, self.loc1)
c = ir.Const(1, self.loc2)
d = ir.Const(2, self.loc1)
self.check(a, same=[b, c], different=[d])
def test_global(self):
a = ir.Global('foo', 0, self.loc1)
b = ir.Global('foo', 0, self.loc1)
c = ir.Global('foo', 0, self.loc2)
d = ir.Global('bar', 0, self.loc1)
e = ir.Global('foo', 1, self.loc1)
self.check(a, same=[b, c], different=[d, e])
def test_var(self):
a = ir.Var(None, 'foo', self.loc1)
b = ir.Var(None, 'foo', self.loc1)
c = ir.Var(None, 'foo', self.loc2)
d = ir.Var(ir.Scope(None, ir.unknown_loc), 'foo', self.loc1)
e = ir.Var(None, 'bar', self.loc1)
self.check(a, same=[b, c, d], different=[e])
def test_undefinedtype(self):
a = ir.UndefinedType()
b = ir.UndefinedType()
self.check(a, same=[b])
def test_loop(self):
a = ir.Loop(1, 3)
b = ir.Loop(1, 3)
c = ir.Loop(2, 3)
d = ir.Loop(1, 4)
self.check(a, same=[b], different=[c, d])
def test_with(self):
a = ir.With(1, 3)
b = ir.With(1, 3)
c = ir.With(2, 3)
d = ir.With(1, 4)
self.check(a, same=[b], different=[c, d])
# used later
_GLOBAL = 1234
| TestIRNodes |
python | pypa__pip | src/pip/_internal/metadata/base.py | {
"start": 21347,
"end": 24813
} | class ____:
"""An environment containing distributions to introspect."""
@classmethod
def default(cls) -> BaseEnvironment:
raise NotImplementedError()
@classmethod
def from_paths(cls, paths: list[str] | None) -> BaseEnvironment:
raise NotImplementedError()
def get_distribution(self, name: str) -> BaseDistribution | None:
"""Given a requirement name, return the installed distributions.
The name may not be normalized. The implementation must canonicalize
it for lookup.
"""
raise NotImplementedError()
def _iter_distributions(self) -> Iterator[BaseDistribution]:
"""Iterate through installed distributions.
This function should be implemented by subclass, but never called
directly. Use the public ``iter_distribution()`` instead, which
implements additional logic to make sure the distributions are valid.
"""
raise NotImplementedError()
def iter_all_distributions(self) -> Iterator[BaseDistribution]:
"""Iterate through all installed distributions without any filtering."""
for dist in self._iter_distributions():
# Make sure the distribution actually comes from a valid Python
# packaging distribution. Pip's AdjacentTempDirectory leaves folders
# e.g. ``~atplotlib.dist-info`` if cleanup was interrupted. The
# valid project name pattern is taken from PEP 508.
project_name_valid = re.match(
r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$",
dist.canonical_name,
flags=re.IGNORECASE,
)
if not project_name_valid:
logger.warning(
"Ignoring invalid distribution %s (%s)",
dist.canonical_name,
dist.location,
)
continue
yield dist
def iter_installed_distributions(
self,
local_only: bool = True,
skip: Container[str] = stdlib_pkgs,
include_editables: bool = True,
editables_only: bool = False,
user_only: bool = False,
) -> Iterator[BaseDistribution]:
"""Return a list of installed distributions.
This is based on ``iter_all_distributions()`` with additional filtering
options. Note that ``iter_installed_distributions()`` without arguments
is *not* equal to ``iter_all_distributions()``, since some of the
configurations exclude packages by default.
:param local_only: If True (default), only return installations
local to the current virtualenv, if in a virtualenv.
:param skip: An iterable of canonicalized project names to ignore;
defaults to ``stdlib_pkgs``.
:param include_editables: If False, don't report editables.
:param editables_only: If True, only report editables.
:param user_only: If True, only report installations in the user
site directory.
"""
it = self.iter_all_distributions()
if local_only:
it = (d for d in it if d.local)
if not include_editables:
it = (d for d in it if not d.editable)
if editables_only:
it = (d for d in it if d.editable)
if user_only:
it = (d for d in it if d.in_usersite)
return (d for d in it if d.canonical_name not in skip)
| BaseEnvironment |
python | ApeWorX__ape | src/ape_accounts/accounts.py | {
"start": 1684,
"end": 2425
} | class ____(AccountContainerAPI):
loaded_accounts: dict[str, "KeyfileAccount"] = {}
@property
def _keyfiles(self) -> Iterator[Path]:
return self.data_folder.glob("*.json")
@property
def aliases(self) -> Iterator[str]:
for p in self._keyfiles:
yield p.stem
@property
def accounts(self) -> Iterator[AccountAPI]:
for keyfile in self._keyfiles:
if keyfile.stem not in self.loaded_accounts:
keyfile_account = KeyfileAccount(keyfile_path=keyfile)
self.loaded_accounts[keyfile.stem] = keyfile_account
yield self.loaded_accounts[keyfile.stem]
def __len__(self) -> int:
return len([*self._keyfiles])
| AccountContainer |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/strategies/_internal/random.py | {
"start": 11767,
"end": 12779
} | class ____(HypothesisRandom):
def __init__(self, seed, note_method_calls):
super().__init__(note_method_calls=note_method_calls)
self.__seed = seed
self.__random = Random(seed)
def _hypothesis_do_random(self, method, kwargs):
fn = getattr(self.__random, method)
try:
return fn(**kwargs)
except TypeError:
pass
args, kwargs = convert_kwargs(method, kwargs)
return fn(*args, **kwargs)
def __copy__(self) -> "TrueRandom":
result = TrueRandom(
seed=self.__seed,
note_method_calls=self._note_method_calls,
)
result.setstate(self.getstate())
return result
def __repr__(self) -> str:
return f"Random({self.__seed!r})"
def seed(self, seed):
self.__random.seed(seed)
self.__seed = seed
def getstate(self):
return self.__random.getstate()
def setstate(self, state):
self.__random.setstate(state)
| TrueRandom |
python | ray-project__ray | python/ray/exceptions.py | {
"start": 28238,
"end": 28469
} | class ____(RayError):
"""Raised when the corresponding placement group was removed."""
def __str__(self):
return "The placement group corresponding to this task has been removed."
@PublicAPI
| TaskPlacementGroupRemoved |
python | cython__cython | runtests.py | {
"start": 63415,
"end": 64833
} | class ____(TextTestResult):
def __init__(self, base_result):
TextTestResult.__init__(
self, self._StringIO(), True,
base_result.dots + base_result.showAll*2)
def strip_error_results(self, results):
for test_case, error in results:
for attr_name in filter(is_private_field, dir(test_case)):
if attr_name == '_dt_test':
test_case._dt_test = _FakeClass(
name=test_case._dt_test.name)
elif attr_name != '_shortDescription':
setattr(test_case, attr_name, None)
def data(self):
self.strip_error_results(self.failures)
self.strip_error_results(self.errors)
return (self.failures, self.errors, self.skipped, self.testsRun,
self.stream.getvalue())
def join_results(result, data):
"""Static method for merging the result back into the main
result object.
"""
failures, errors, skipped, tests_run, output = data
if output:
result.stream.write(output)
result.errors.extend(errors)
result.skipped.extend(skipped)
result.failures.extend(failures)
result.testsRun += tests_run
join_results = staticmethod(join_results)
class _StringIO(StringIO):
def writeln(self, line):
self.write("%s\n" % line)
| PartialTestResult |
python | getsentry__sentry | src/sentry/uptime/migrations/0001_squashed_0042_extra_uptime_indexes.py | {
"start": 466,
"end": 11481
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# of a table.
# Here are some things that make sense to mark as post deployment:
# - Large data migrations. Typically we want these to be run manually so that they can be
# monitored and not block the deploy for a long period of time while they run.
# - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
# run this outside deployments so that we don't block them. Note that while adding an index
# is a schema change, it's completely safe to run the operation after the code has deployed.
# Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment
is_post_deployment = True
replaces = [
("uptime", "0001_uptime_subscriptions"),
("uptime", "0002_remove_separate_remote_subscription"),
("uptime", "0003_drop_remote_subscription"),
("uptime", "0004_projectuptimesubscription_mode"),
("uptime", "0005_uptime_status"),
("uptime", "0006_projectuptimesubscription_name_owner"),
("uptime", "0007_update_detected_subscription_interval"),
("uptime", "0008_uptime_url_suffix"),
("uptime", "0009_better_name_for_uptime_rdap_columns"),
("uptime", "0010_remove_uptime_whois_columns_state"),
("uptime", "0011_remove_uptime_whois_columns_db"),
("uptime", "0012_uptime_subscription_request_fields"),
("uptime", "0013_uptime_subscription_new_unique"),
("uptime", "0014_add_uptime_enviromnet"),
("uptime", "0015_headers_deafult_empty_list"),
("uptime", "0016_translate_uptime_object_headers_to_lists"),
("uptime", "0017_unique_on_timeout"),
("uptime", "0018_add_trace_sampling_field_to_uptime"),
("uptime", "0019_uptime_region"),
("uptime", "0020_drop_region"),
("uptime", "0021_drop_region_table_col"),
("uptime", "0022_add_trace_sampling_to_uptime_monitors"),
("uptime", "0023_translate_uptime_object_headers_to_lists_take_two"),
("uptime", "0024_add_status_to_project_uptime_subscription"),
("uptime", "0025_uptime_migrate_constraint"),
("uptime", "0026_region_mode_col"),
("uptime", "0027_remove_migrated_and_unique_constraint"),
("uptime", "0028_drop_migrated_column"),
("uptime", "0029_uptime_subscription_index_domain_cols"),
("uptime", "0030_status_update_date"),
("uptime", "0031_translate_uptime_object_headers_to_lists_take_three"),
("uptime", "0032_stats_on_subscription"),
("uptime", "0033_uptime_backfill_to_detectors"),
("uptime", "0034_uptime_backfill_uptime_status"),
("uptime", "0035_uptime_backfill_detector_enabled"),
("uptime", "0036_uptime_status_indexes"),
("uptime", "0037_fix_drift_default_to_db_default"),
("uptime", "0038_uptime_drop_project_subscription_uptime_status"),
("uptime", "0039_uptime_drop_project_subscription_uptime_status_db"),
("uptime", "0040_uptime_backfill_detector_conditions"),
("uptime", "0041_uptime_backfill_detector_grouphash"),
("uptime", "0042_extra_uptime_indexes"),
]
initial = True
checked = False # This is an initial migration and can take locks
dependencies = [
("sentry", "0001_squashed_0904_onboarding_task_project_id_idx"),
]
operations = [
migrations.CreateModel(
name="UptimeSubscription",
fields=[
(
"id",
sentry.db.models.fields.bounded.BoundedBigAutoField(
primary_key=True, serialize=False
),
),
("date_updated", models.DateTimeField(default=django.utils.timezone.now)),
("date_added", models.DateTimeField(default=django.utils.timezone.now, null=True)),
("type", models.TextField()),
("status", models.SmallIntegerField(db_default=0, default=0)),
("subscription_id", models.TextField(null=True, unique=True)),
("url", models.CharField(max_length=255)),
("url_domain", models.CharField(db_default="", default="", max_length=255)),
("url_domain_suffix", models.CharField(db_default="", default="", max_length=255)),
("host_provider_id", models.CharField(db_index=True, max_length=255, null=True)),
("host_provider_name", models.CharField(db_index=True, max_length=255, null=True)),
("interval_seconds", models.IntegerField()),
("timeout_ms", models.IntegerField()),
("method", models.CharField(db_default="GET", max_length=20)),
(
"headers",
sentry.db.models.fields.jsonfield.JSONField(db_default=[], default=dict),
),
("body", models.TextField(null=True)),
("trace_sampling", models.BooleanField(db_default=False, default=False)),
("uptime_status", models.PositiveSmallIntegerField(db_default=1)),
(
"uptime_status_update_date",
models.DateTimeField(db_default=django.db.models.functions.datetime.Now()),
),
],
options={
"db_table": "uptime_uptimesubscription",
"indexes": [
models.Index(
fields=["url_domain_suffix", "url_domain"],
name="uptime_upti_url_dom_ead522_idx",
),
models.Index(
fields=["uptime_status", "uptime_status_update_date"],
name="uptime_upti_uptime__546c70_idx",
),
],
},
),
migrations.CreateModel(
name="ProjectUptimeSubscription",
fields=[
(
"id",
sentry.db.models.fields.bounded.BoundedBigAutoField(
primary_key=True, serialize=False
),
),
("date_updated", models.DateTimeField(default=django.utils.timezone.now)),
("date_added", models.DateTimeField(default=django.utils.timezone.now, null=True)),
(
"status",
sentry.db.models.fields.bounded.BoundedPositiveBigIntegerField(db_default=0),
),
("mode", models.SmallIntegerField(db_default=1, default=1)),
("name", models.TextField()),
(
"owner_user_id",
sentry.db.models.fields.hybrid_cloud_foreign_key.HybridCloudForeignKey(
"sentry.User", db_index=True, null=True, on_delete="SET_NULL"
),
),
(
"environment",
sentry.db.models.fields.foreignkey.FlexibleForeignKey(
db_constraint=False,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="sentry.environment",
),
),
(
"owner_team",
sentry.db.models.fields.foreignkey.FlexibleForeignKey(
null=True, on_delete=django.db.models.deletion.SET_NULL, to="sentry.team"
),
),
(
"project",
sentry.db.models.fields.foreignkey.FlexibleForeignKey(
on_delete=django.db.models.deletion.CASCADE, to="sentry.project"
),
),
(
"uptime_subscription",
sentry.db.models.fields.foreignkey.FlexibleForeignKey(
on_delete=django.db.models.deletion.PROTECT, to="uptime.uptimesubscription"
),
),
],
options={
"db_table": "uptime_projectuptimesubscription",
"indexes": [
models.Index(fields=["project", "mode"], name="uptime_proj_project_30b94a_idx")
],
"constraints": [
models.UniqueConstraint(
condition=models.Q(("mode", 1)),
fields=("project_id", "uptime_subscription"),
name="uptime_projectuptimesubscription_unique_manual_project_subscription",
),
models.UniqueConstraint(
condition=models.Q(("mode__in", (2, 3))),
fields=("project_id", "uptime_subscription"),
name="uptime_projectuptimesubscription_unique_auto_project_subscription",
),
],
},
),
migrations.CreateModel(
name="UptimeSubscriptionRegion",
fields=[
(
"id",
sentry.db.models.fields.bounded.BoundedBigAutoField(
primary_key=True, serialize=False
),
),
("date_updated", models.DateTimeField(auto_now=True)),
("date_added", models.DateTimeField(auto_now_add=True)),
("region_slug", models.CharField(db_default="", db_index=True, max_length=255)),
(
"mode",
models.CharField(
db_default=sentry.uptime.models.UptimeSubscriptionRegion.RegionMode[
"ACTIVE"
],
max_length=32,
),
),
(
"uptime_subscription",
sentry.db.models.fields.foreignkey.FlexibleForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="regions",
to="uptime.uptimesubscription",
),
),
],
options={
"db_table": "uptime_uptimesubscriptionregion",
"constraints": [
models.UniqueConstraint(
models.F("uptime_subscription"),
models.F("region_slug"),
name="uptime_uptimesubscription_region_slug_unique",
)
],
},
),
]
| Migration |
python | django__django | tests/template_tests/filter_tests/test_floatformat.py | {
"start": 1006,
"end": 8698
} | class ____(SimpleTestCase):
def test_inputs(self):
self.assertEqual(floatformat(7.7), "7.7")
self.assertEqual(floatformat(7.0), "7")
self.assertEqual(floatformat(0.7), "0.7")
self.assertEqual(floatformat(-0.7), "-0.7")
self.assertEqual(floatformat(0.07), "0.1")
self.assertEqual(floatformat(-0.07), "-0.1")
self.assertEqual(floatformat(0.007), "0.0")
self.assertEqual(floatformat(0.0), "0")
self.assertEqual(floatformat(7.7, 0), "8")
self.assertEqual(floatformat(7.7, 3), "7.700")
self.assertEqual(floatformat(6.000000, 3), "6.000")
self.assertEqual(floatformat(6.200000, 3), "6.200")
self.assertEqual(floatformat(6.200000, -3), "6.200")
self.assertEqual(floatformat(13.1031, -3), "13.103")
self.assertEqual(floatformat(11.1197, -2), "11.12")
self.assertEqual(floatformat(11.0000, -2), "11")
self.assertEqual(floatformat(11.000001, -2), "11.00")
self.assertEqual(floatformat(8.2798, 3), "8.280")
self.assertEqual(floatformat(5555.555, 2), "5555.56")
self.assertEqual(floatformat(001.3000, 2), "1.30")
self.assertEqual(floatformat(0.12345, 2), "0.12")
self.assertEqual(floatformat(Decimal("555.555"), 2), "555.56")
self.assertEqual(floatformat(Decimal("09.000")), "9")
self.assertEqual(
floatformat(Decimal("123456.123456789012345678901"), 21),
"123456.123456789012345678901",
)
self.assertEqual(floatformat(13.1031, "bar"), "13.1031")
self.assertEqual(floatformat(18.125, 2), "18.13")
self.assertEqual(
floatformat(-1.323297138040798e35, 2),
"-132329713804079800000000000000000000.00",
)
self.assertEqual(
floatformat(-1.323297138040798e35, -2),
"-132329713804079800000000000000000000",
)
self.assertEqual(floatformat(1.5e-15, 20), "0.00000000000000150000")
self.assertEqual(floatformat(1.5e-15, -20), "0.00000000000000150000")
self.assertEqual(floatformat(1.00000000000000015, 16), "1.0000000000000002")
self.assertEqual(floatformat("1e199"), "1" + "0" * 199)
def test_invalid_inputs(self):
cases = [
# Non-numeric strings.
None,
[],
{},
object(),
"abc123",
"123abc",
"foo",
"error",
"¿Cómo esta usted?",
# Scientific notation - missing exponent value.
"1e",
"1e+",
"1e-",
# Scientific notation - missing base number.
"e400",
"e+400",
"e-400",
# Scientific notation - invalid exponent value.
"1e^2",
"1e2e3",
"1e2a",
"1e2.0",
"1e2,0",
# Scientific notation - misplaced decimal point.
"1e.2",
"1e2.",
# Scientific notation - misplaced '+' sign.
"1+e2",
"1e2+",
]
for value in cases:
with self.subTest(value=value):
self.assertEqual(floatformat(value), "")
with self.subTest(value=value, arg="bar"):
self.assertEqual(floatformat(value, "bar"), "")
def test_force_grouping(self):
with translation.override("en"):
self.assertEqual(floatformat(10000, "g"), "10,000")
self.assertEqual(floatformat(66666.666, "1g"), "66,666.7")
# Invalid suffix.
self.assertEqual(floatformat(10000, "g2"), "10000")
with translation.override("de", deactivate=True):
self.assertEqual(floatformat(10000, "g"), "10.000")
self.assertEqual(floatformat(66666.666, "1g"), "66.666,7")
# Invalid suffix.
self.assertEqual(floatformat(10000, "g2"), "10000")
def test_unlocalize(self):
with translation.override("de", deactivate=True):
self.assertEqual(floatformat(66666.666, "2"), "66666,67")
self.assertEqual(floatformat(66666.666, "2u"), "66666.67")
with self.settings(
USE_THOUSAND_SEPARATOR=True,
NUMBER_GROUPING=3,
THOUSAND_SEPARATOR="!",
):
self.assertEqual(floatformat(66666.666, "2gu"), "66!666.67")
self.assertEqual(floatformat(66666.666, "2ug"), "66!666.67")
# Invalid suffix.
self.assertEqual(floatformat(66666.666, "u2"), "66666.666")
def test_zero_values(self):
self.assertEqual(floatformat(0, 6), "0.000000")
self.assertEqual(floatformat(0, 7), "0.0000000")
self.assertEqual(floatformat(0, 10), "0.0000000000")
self.assertEqual(
floatformat(0.000000000000000000015, 20), "0.00000000000000000002"
)
self.assertEqual(floatformat("0.00", 0), "0")
self.assertEqual(floatformat(Decimal("0.00"), 0), "0")
self.assertEqual(floatformat("0.0000", 2), "0.00")
self.assertEqual(floatformat(Decimal("0.0000"), 2), "0.00")
self.assertEqual(floatformat("0.000000", 4), "0.0000")
self.assertEqual(floatformat(Decimal("0.000000"), 4), "0.0000")
def test_negative_zero_values(self):
tests = [
(-0.01, -1, "0.0"),
(-0.001, 2, "0.00"),
(-0.499, 0, "0"),
]
for num, decimal_places, expected in tests:
with self.subTest(num=num, decimal_places=decimal_places):
self.assertEqual(floatformat(num, decimal_places), expected)
def test_infinity(self):
pos_inf = float(1e30000)
neg_inf = float(-1e30000)
self.assertEqual(floatformat(pos_inf), "inf")
self.assertEqual(floatformat(neg_inf), "-inf")
self.assertEqual(floatformat(pos_inf / pos_inf), "nan")
self.assertEqual(floatformat("inf"), "inf")
self.assertEqual(floatformat("NaN"), "NaN")
def test_too_many_digits_to_render(self):
cases = [
"1e200",
"1E200",
"1E10000000000000000",
"-1E10000000000000000",
"1e10000000000000000",
"-1e10000000000000000",
]
for value in cases:
with self.subTest(value=value):
self.assertEqual(floatformat(value), value)
def test_too_many_digits_to_render_very_long(self):
value = "1" + "0" * 1_000_000
if PYPY:
# PyPy casts decimal parts to int, which reaches the integer string
# conversion length limit (default 4300 digits, CVE-2020-10735).
with self.assertRaises(ValueError):
floatformat(value)
else:
self.assertEqual(floatformat(value), value)
def test_float_dunder_method(self):
class FloatWrapper:
def __init__(self, value):
self.value = value
def __float__(self):
return self.value
self.assertEqual(floatformat(FloatWrapper(11.000001), -2), "11.00")
def test_low_decimal_precision(self):
"""
#15789
"""
with localcontext() as ctx:
ctx.prec = 2
self.assertEqual(floatformat(1.2345, 2), "1.23")
self.assertEqual(floatformat(15.2042, -3), "15.204")
self.assertEqual(floatformat(1.2345, "2"), "1.23")
self.assertEqual(floatformat(15.2042, "-3"), "15.204")
self.assertEqual(floatformat(Decimal("1.2345"), 2), "1.23")
self.assertEqual(floatformat(Decimal("15.2042"), -3), "15.204")
| FunctionTests |
python | apache__airflow | providers/databricks/tests/unit/databricks/hooks/test_databricks.py | {
"start": 55667,
"end": 56979
} | class ____:
def test_is_terminal_true(self):
terminal_states = ["TERMINATED", "SKIPPED", "INTERNAL_ERROR"]
for state in terminal_states:
run_state = RunState(state, "", "")
assert run_state.is_terminal
def test_is_terminal_false(self):
non_terminal_states = ["PENDING", "RUNNING", "TERMINATING", "QUEUED"]
for state in non_terminal_states:
run_state = RunState(state, "", "")
assert not run_state.is_terminal
def test_is_terminal_with_nonexistent_life_cycle_state(self):
with pytest.raises(AirflowException):
RunState("blah", "", "")
def test_is_successful(self):
run_state = RunState("TERMINATED", "SUCCESS", "")
assert run_state.is_successful
def test_to_json(self):
run_state = RunState("TERMINATED", "SUCCESS", "")
expected = json.dumps(
{"life_cycle_state": "TERMINATED", "result_state": "SUCCESS", "state_message": ""}
)
assert expected == run_state.to_json()
def test_from_json(self):
state = {"life_cycle_state": "TERMINATED", "result_state": "SUCCESS", "state_message": ""}
expected = RunState("TERMINATED", "SUCCESS", "")
assert expected == RunState.from_json(json.dumps(state))
| TestRunState |
python | google__jax | jax/_src/debugger/web_debugger.py | {
"start": 1161,
"end": 3433
} | class ____(cli_debugger.CliDebugger):
"""A web-based debugger."""
prompt = '(jdb) '
use_rawinput: bool = False
def __init__(self, frames: list[debugger_core.DebuggerFrame], thread_id,
completekey: str = "tab", host: str = "", port: int = 5555):
if (host, port) not in _web_consoles:
import web_pdb # pytype: disable=import-error
_web_consoles[host, port] = web_pdb.WebConsole(host, port, self)
# Clobber the debugger in the web console
_web_console = _web_consoles[host, port]
_web_console._debugger = weakref.proxy(self)
super().__init__(frames, thread_id, stdin=_web_console, stdout=_web_console,
completekey=completekey)
def get_current_frame_data(self):
# Constructs the info needed for the web console to display info
current_frame = self.current_frame()
filename = current_frame.filename
lines = current_frame.source
current_line = None
if current_frame.offset is not None:
current_line = current_frame.offset + 1
if _web_pdb_version() < (1, 4, 4):
return {
'filename': filename,
'listing': '\n'.join(lines),
'curr_line': current_line,
'total_lines': len(lines),
'breaklist': [],
}
return {
'dirname': os.path.dirname(os.path.abspath(filename)) + os.path.sep,
'filename': os.path.basename(filename),
'file_listing': '\n'.join(lines),
'current_line': current_line,
'breakpoints': [],
'globals': self.get_globals(),
'locals': self.get_locals(),
}
def get_globals(self):
current_frame = self.current_frame()
return "\n".join(
f"{key} = {value}"
for key, value in sorted(current_frame.globals.items()))
def get_locals(self):
current_frame = self.current_frame()
return "\n".join(
f"{key} = {value}"
for key, value in sorted(current_frame.locals.items()))
def run(self):
return self.cmdloop()
def run_debugger(frames: list[debugger_core.DebuggerFrame],
thread_id: int | None, **kwargs: Any):
WebDebugger(frames, thread_id, **kwargs).run()
if importlib.util.find_spec("web_pdb") is not None:
debugger_core.register_debugger("web", run_debugger, -2)
| WebDebugger |
python | pydantic__pydantic | pydantic/networks.py | {
"start": 26494,
"end": 27349
} | class ____(_BaseMultiHostUrl):
"""A type that will accept any MongoDB DSN.
* User info not required
* Database name not required
* Port not required
* User info may be passed without user part (e.g., `mongodb://mongodb0.example.com:27017`).
!!! warning
If a port isn't specified, the default MongoDB port `27017` will be used. If this behavior is
undesirable, you can use the following:
```python
from typing import Annotated
from pydantic_core import MultiHostUrl
from pydantic import UrlConstraints
MongoDsnNoDefaultPort = Annotated[
MultiHostUrl,
UrlConstraints(allowed_schemes=['mongodb', 'mongodb+srv']),
]
```
"""
_constraints = UrlConstraints(allowed_schemes=['mongodb', 'mongodb+srv'], default_port=27017)
| MongoDsn |
python | pytorch__pytorch | torch/_dynamo/variables/constant.py | {
"start": 13508,
"end": 15552
} | class ____(VariableTracker):
"""VariableTracker for enum.Enum and enum.IntEnum instances
Provides specialized handling for Python enum types, supporting
both standard Enum and IntEnum with proper value tracking and comparison.
"""
def __init__(self, value: Union[enum.Enum, enum.IntEnum], **kwargs: Any) -> None:
super().__init__(**kwargs)
self.value = value
@classmethod
def create(
cls, cls_type: Any, value_vt: VariableTracker, options: Any
) -> "EnumVariable":
if isinstance(value_vt, variables.ConstantVariable):
for member in list(cls_type):
if member.value == value_vt.as_python_constant():
return cls(member, **options)
unimplemented(
gb_type="Failed to construct Enum variable",
context=f"value: {value_vt}, allowed enum values: {list(cls_type)}",
explanation="Attempted to construct an Enum value that is non-constant (e.g. int, string) "
"or is not an acceptable value for the Enum. "
f"Acceptable values for Enum `{cls_type}`: {list(cls_type)}.",
hints=[*graph_break_hints.USER_ERROR, *graph_break_hints.SUPPORTABLE],
)
def as_proxy(self) -> Union[enum.Enum, int]:
if isinstance(self.value, int):
return int(self.value) # convert IntEnum to a normal int
return self.value
def __repr__(self) -> str:
return f"EnumVariable({type(self.value)})"
def as_python_constant(self) -> Union[enum.Enum, enum.IntEnum]:
return self.value
def var_getattr(self, tx: "InstructionTranslator", name: str) -> VariableTracker:
if not hasattr(self.value, name):
raise NotImplementedError
if name in cmp_name_to_op_mapping:
return variables.GetAttrVariable(self, name)
member = getattr(self.value, name)
source = self.source and AttrSource(self.source, name)
return VariableTracker.build(tx, member, source=source)
| EnumVariable |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 212182,
"end": 212517
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("BranchProtectionRule", graphql_name="node")
| BranchProtectionRuleEdge |
python | fluentpython__example-code-2e | 24-class-metaprog/evaltime/metalib.py | {
"start": 382,
"end": 1211
} | class ____(type):
print('% MetaKlass body')
@classmethod # <1>
def __prepare__(meta_cls, cls_name, bases): # <2>
args = (meta_cls, cls_name, bases)
print(f'% MetaKlass.__prepare__{args!r}')
return NosyDict() # <3>
def __new__(meta_cls, cls_name, bases, cls_dict): # <4>
args = (meta_cls, cls_name, bases, cls_dict)
print(f'% MetaKlass.__new__{args!r}')
def inner_2(self):
print(f'% MetaKlass.__new__:inner_2({self!r})')
cls = super().__new__(meta_cls, cls_name, bases, cls_dict.data) # <5>
cls.method_c = inner_2 # <6>
return cls # <7>
def __repr__(cls): # <8>
cls_name = cls.__name__
return f"<class {cls_name!r} built by MetaKlass>"
print('% metalib module end')
# end::METALIB_BOTTOM[]
| MetaKlass |
python | openai__gym | tests/test_core.py | {
"start": 386,
"end": 875
} | class ____(core.Env):
observation_space = spaces.Box(low=0, high=255, shape=(64, 64, 3), dtype=np.uint8)
action_space = spaces.Discrete(3)
def reset(self, *, seed: Optional[int] = None, options: Optional[dict] = None):
super().reset(seed=seed)
return self.observation_space.sample(), {"info": "dummy"}
def step(self, action):
observation = self.observation_space.sample() # Dummy observation
return (observation, 0.0, False, {})
| UnittestEnv |
python | keon__algorithms | tests/test_dfs.py | {
"start": 1725,
"end": 2049
} | class ____(unittest.TestCase):
def test_sudoku_solver(self):
board = [["5", "3", "."], ["6", ".", "."], [".", "9", "8"]]
test_obj = Sudoku(board, 3, 3)
test_obj.solve()
self.assertEqual([['5', '3', '1'], ['6', '1', '2'],
['1', '9', '8']], test_obj.board)
| TestSudoku |
python | huggingface__transformers | examples/modular-transformers/modeling_roberta.py | {
"start": 21851,
"end": 22484
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = RobertaPredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
def forward(self, hidden_states):
hidden_states = self.transform(hidden_states)
hidden_states = self.decoder(hidden_states)
return hidden_states
@auto_docstring
| RobertaLMPredictionHead |
python | scipy__scipy | scipy/_build_utils/tempita/_tempita.py | {
"start": 2282,
"end": 13666
} | class ____:
default_namespace = {
'start_braces': '{{',
'end_braces': '}}',
'looper': looper,
}
default_encoding = 'utf8'
default_inherit = None
def __init__(self, content, name=None, namespace=None, stacklevel=None,
get_template=None, default_inherit=None, line_offset=0,
delimiters=None, delimeters=None):
self.content = content
# set delimiters
if delimeters:
import warnings
warnings.warn(
"'delimeters' kwarg is being deprecated in favor of correctly"
" spelled 'delimiters'. Please adjust your code.",
DeprecationWarning
)
if delimiters is None:
delimiters = delimeters
if delimiters is None:
delimiters = (self.default_namespace['start_braces'],
self.default_namespace['end_braces'])
else:
#assert len(delimiters) == 2 and all([isinstance(delimiter, basestring)
# for delimiter in delimiters])
self.default_namespace = self.__class__.default_namespace.copy()
self.default_namespace['start_braces'] = delimiters[0]
self.default_namespace['end_braces'] = delimiters[1]
self.delimiters = self.delimeters = delimiters # Keep a legacy read-only copy, but don't use it.
self._unicode = isinstance(content, str)
if name is None and stacklevel is not None:
try:
caller = sys._getframe(stacklevel)
except ValueError:
pass
else:
globals = caller.f_globals
lineno = caller.f_lineno
if '__file__' in globals:
name = globals['__file__']
if name.endswith('.pyc') or name.endswith('.pyo'):
name = name[:-1]
elif '__name__' in globals:
name = globals['__name__']
else:
name = '<string>'
if lineno:
name += ':%s' % lineno
self.name = name
self._parsed = parse(content, name=name, line_offset=line_offset, delimiters=self.delimiters)
if namespace is None:
namespace = {}
self.namespace = namespace
self.get_template = get_template
if default_inherit is not None:
self.default_inherit = default_inherit
def from_filename(cls, filename, namespace=None, encoding=None,
default_inherit=None, get_template=get_file_template):
with open(filename, 'rb') as f:
c = f.read()
if encoding:
c = c.decode(encoding)
return cls(content=c, name=filename, namespace=namespace,
default_inherit=default_inherit, get_template=get_template)
from_filename = classmethod(from_filename)
def __repr__(self):
return '<%s %s name=%r>' % (
self.__class__.__name__,
hex(id(self))[2:], self.name)
def substitute(self, *args, **kw):
if args:
if kw:
raise TypeError(
"You can only give positional *or* keyword arguments")
if len(args) > 1:
raise TypeError(
"You can only give one positional argument")
if not hasattr(args[0], 'items'):
raise TypeError(
"If you pass in a single argument, you must pass in a dictionary-like object (with a .items() method); you gave %r"
% (args[0],))
kw = args[0]
ns = kw
ns['__template_name__'] = self.name
if self.namespace:
ns.update(self.namespace)
result, defs, inherit = self._interpret(ns)
if not inherit:
inherit = self.default_inherit
if inherit:
result = self._interpret_inherit(result, defs, inherit, ns)
return result
def _interpret(self, ns):
__traceback_hide__ = True
parts = []
defs = {}
self._interpret_codes(self._parsed, ns, out=parts, defs=defs)
if '__inherit__' in defs:
inherit = defs.pop('__inherit__')
else:
inherit = None
return ''.join(parts), defs, inherit
def _interpret_inherit(self, body, defs, inherit_template, ns):
__traceback_hide__ = True
if not self.get_template:
raise TemplateError(
'You cannot use inheritance without passing in get_template',
position=None, name=self.name)
templ = self.get_template(inherit_template, self)
self_ = TemplateObject(self.name)
for name, value in defs.items():
setattr(self_, name, value)
self_.body = body
ns = ns.copy()
ns['self'] = self_
return templ.substitute(ns)
def _interpret_codes(self, codes, ns, out, defs):
__traceback_hide__ = True
for item in codes:
if isinstance(item, basestring_):
out.append(item)
else:
self._interpret_code(item, ns, out, defs)
def _interpret_code(self, code, ns, out, defs):
__traceback_hide__ = True
name, pos = code[0], code[1]
if name == 'py':
self._exec(code[2], ns, pos)
elif name == 'continue':
raise _TemplateContinue()
elif name == 'break':
raise _TemplateBreak()
elif name == 'for':
vars, expr, content = code[2], code[3], code[4]
expr = self._eval(expr, ns, pos)
self._interpret_for(vars, expr, content, ns, out, defs)
elif name == 'cond':
parts = code[2:]
self._interpret_if(parts, ns, out, defs)
elif name == 'expr':
parts = code[2].split('|')
base = self._eval(parts[0], ns, pos)
for part in parts[1:]:
func = self._eval(part, ns, pos)
base = func(base)
out.append(self._repr(base, pos))
elif name == 'default':
var, expr = code[2], code[3]
if var not in ns:
result = self._eval(expr, ns, pos)
ns[var] = result
elif name == 'inherit':
expr = code[2]
value = self._eval(expr, ns, pos)
defs['__inherit__'] = value
elif name == 'def':
name = code[2]
signature = code[3]
parts = code[4]
ns[name] = defs[name] = TemplateDef(self, name, signature, body=parts, ns=ns,
pos=pos)
elif name == 'comment':
return
else:
assert 0, "Unknown code: %r" % name
def _interpret_for(self, vars, expr, content, ns, out, defs):
__traceback_hide__ = True
for item in expr:
if len(vars) == 1:
ns[vars[0]] = item
else:
if len(vars) != len(item):
raise ValueError(
'Need %i items to unpack (got %i items)'
% (len(vars), len(item)))
for name, value in zip(vars, item):
ns[name] = value
try:
self._interpret_codes(content, ns, out, defs)
except _TemplateContinue:
continue
except _TemplateBreak:
break
def _interpret_if(self, parts, ns, out, defs):
__traceback_hide__ = True
# @@: if/else/else gets through
for part in parts:
assert not isinstance(part, basestring_)
name, pos = part[0], part[1]
if name == 'else':
result = True
else:
result = self._eval(part[2], ns, pos)
if result:
self._interpret_codes(part[3], ns, out, defs)
break
def _eval(self, code, ns, pos):
__traceback_hide__ = True
try:
try:
value = eval(code, self.default_namespace, ns)
except SyntaxError as e:
raise SyntaxError(
'invalid syntax in expression: %s' % code)
return value
except Exception as e:
if getattr(e, 'args', None):
arg0 = e.args[0]
else:
arg0 = coerce_text(e)
e.args = (self._add_line_info(arg0, pos),)
raise
def _exec(self, code, ns, pos):
__traceback_hide__ = True
try:
exec(code, self.default_namespace, ns)
except Exception as e:
if e.args:
e.args = (self._add_line_info(e.args[0], pos),)
else:
e.args = (self._add_line_info(None, pos),)
raise
def _repr(self, value, pos):
__traceback_hide__ = True
try:
if value is None:
return ''
if self._unicode:
try:
value = str(value)
except UnicodeDecodeError:
value = bytes(value)
else:
if not isinstance(value, basestring_):
value = coerce_text(value)
if (isinstance(value, str)
and self.default_encoding):
value = value.encode(self.default_encoding)
except Exception as e:
e.args = (self._add_line_info(e.args[0], pos),)
raise
else:
if self._unicode and isinstance(value, bytes):
if not self.default_encoding:
raise UnicodeDecodeError(
'Cannot decode bytes value %r into unicode '
'(no default_encoding provided)' % value)
try:
value = value.decode(self.default_encoding)
except UnicodeDecodeError as e:
raise UnicodeDecodeError(
e.encoding,
e.object,
e.start,
e.end,
e.reason + ' in string %r' % value)
elif not self._unicode and isinstance(value, str):
if not self.default_encoding:
raise UnicodeEncodeError(
'Cannot encode unicode value %r into bytes '
'(no default_encoding provided)' % value)
value = value.encode(self.default_encoding)
return value
def _add_line_info(self, msg, pos):
msg = "%s at line %s column %s" % (
msg, pos[0], pos[1])
if self.name:
msg += " in file %s" % self.name
return msg
def sub(content, delimiters=None, **kw):
name = kw.get('__name')
delimeters = kw.pop('delimeters') if 'delimeters' in kw else None # for legacy code
tmpl = Template(content, name=name, delimiters=delimiters, delimeters=delimeters)
return tmpl.substitute(kw)
def paste_script_template_renderer(content, vars, filename=None):
tmpl = Template(content, name=filename)
return tmpl.substitute(vars)
| Template |
python | huggingface__transformers | src/transformers/models/videomae/modeling_videomae.py | {
"start": 20217,
"end": 28089
} | class ____(VideoMAEPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
self.videomae = VideoMAEModel(config)
self.encoder_to_decoder = nn.Linear(config.hidden_size, config.decoder_hidden_size, bias=False)
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.decoder_hidden_size))
self.position_embeddings = get_sinusoid_encoding_table(
self.videomae.embeddings.num_patches, config.decoder_hidden_size
)
self.decoder = VideoMAEDecoder(config)
# Initialize weights and apply final processing
self.post_init()
@can_return_tuple
@auto_docstring
def forward(
self,
pixel_values: torch.FloatTensor,
bool_masked_pos: torch.BoolTensor,
**kwargs: Unpack[TransformersKwargs],
) -> VideoMAEForPreTrainingOutput:
r"""
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Each video in the
batch must have the same number of masked patches. Sequence length is `(num_frames // tubelet_size) *
(image_size // patch_size) ** 2`.
Examples:
```python
>>> from transformers import AutoImageProcessor, VideoMAEForPreTraining
>>> import numpy as np
>>> import torch
>>> num_frames = 16
>>> video = list(np.random.randint(0, 256, (num_frames, 3, 224, 224)))
>>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base")
>>> model = VideoMAEForPreTraining.from_pretrained("MCG-NJU/videomae-base")
>>> pixel_values = image_processor(video, return_tensors="pt").pixel_values
>>> num_patches_per_frame = (model.config.image_size // model.config.patch_size) ** 2
>>> seq_length = (num_frames // model.config.tubelet_size) * num_patches_per_frame
>>> bool_masked_pos = torch.randint(0, 2, (1, seq_length)).bool()
>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
>>> loss = outputs.loss
```"""
outputs: BaseModelOutput = self.videomae(pixel_values, bool_masked_pos=bool_masked_pos, **kwargs)
sequence_output = outputs.last_hidden_state
sequence_output = self.encoder_to_decoder(sequence_output)
# [batch_size, num_visible_patches, decoder_hidden_size]
batch_size, _, num_channels = sequence_output.shape
# we don't unshuffle the correct visible token order, but shuffle the position embeddings accordingly.
if bool_masked_pos is None:
raise ValueError("One must provided a boolean mask ")
expanded_position_embeddings = self.position_embeddings.expand(batch_size, -1, -1).type_as(pixel_values)
expanded_position_embeddings = expanded_position_embeddings.detach().to(device=pixel_values.device, copy=True)
pos_emb_visible = expanded_position_embeddings[~bool_masked_pos].reshape(batch_size, -1, num_channels)
pos_emb_mask = expanded_position_embeddings[bool_masked_pos].reshape(batch_size, -1, num_channels)
# [batch_size, num_patches, decoder_hidden_size]
x_full = torch.cat([sequence_output + pos_emb_visible, self.mask_token + pos_emb_mask], dim=1)
# [batch_size, num_masked_patches, num_channels * patch_size * patch_size]
decoder_outputs: VideoMAEDecoderOutput = self.decoder(x_full, pos_emb_mask.shape[1])
logits = decoder_outputs.logits
loss = None
with torch.no_grad():
# calculate the labels to be predicted
if self.config.num_channels != 3:
# Can't unnormalize with default means/stds
frames = pixel_values
else:
# first, unnormalize the frames
device = pixel_values.device
dtype = pixel_values.dtype
mean = torch.as_tensor(IMAGENET_DEFAULT_MEAN).to(device=device, dtype=dtype)[None, None, :, None, None]
std = torch.as_tensor(IMAGENET_DEFAULT_STD).to(device=device, dtype=dtype)[None, None, :, None, None]
frames = pixel_values * std + mean # in [0, 1]
batch_size, time, num_channels, height, width = frames.shape
tubelet_size, patch_size = self.config.tubelet_size, self.config.patch_size
if self.config.norm_pix_loss:
# step 1: split up dimensions (time by tubelet_size, height by patch_size, width by patch_size)
frames = frames.view(
batch_size,
time // tubelet_size,
tubelet_size,
num_channels,
height // patch_size,
patch_size,
width // patch_size,
patch_size,
)
# step 2: move dimensions to concatenate:
frames = frames.permute(0, 1, 4, 6, 2, 5, 7, 3).contiguous()
# step 3: concatenate:
frames = frames.view(
batch_size,
time // tubelet_size * height // patch_size * width // patch_size,
tubelet_size * patch_size * patch_size,
num_channels,
)
# step 4: normalize. The authors find that the mean is about 0.48 and standard deviation is about 0.08.
frames_norm = (frames - frames.mean(dim=-2, keepdim=True)) / (
frames.var(dim=-2, unbiased=True, keepdim=True).sqrt() + 1e-6
)
# step 5: reshape to (batch_size, T//ts * H//ps * W//ps, ts * ps * ps * C)
videos_patch = frames_norm.view(
batch_size,
time // tubelet_size * height // patch_size * width // patch_size,
tubelet_size * patch_size * patch_size * num_channels,
)
else:
if self.config.num_channels != 3:
raise ValueError(
"Can't unnormalize non-RGB images. Consider setting config.norm_pix_loss to False."
)
# step 1: split up dimensions (time by tubelet_size, height by patch_size, width by patch_size)
frames = frames.view(
batch_size,
time // tubelet_size,
tubelet_size,
num_channels,
height // patch_size,
patch_size,
width // patch_size,
patch_size,
)
# step 2: move dimensions to concatenate: (batch_size, T//ts, H//ps, W//ps, ts, ps, ps, C)
frames = frames.permute(0, 1, 4, 6, 2, 5, 7, 3).contiguous()
# step 3: concatenate
videos_patch = frames.view(
batch_size,
time // tubelet_size * height // patch_size * width // patch_size,
tubelet_size * patch_size * patch_size * num_channels,
)
batch_size, _, num_channels = videos_patch.shape
labels = videos_patch[bool_masked_pos].reshape(batch_size, -1, num_channels)
loss_fct = MSELoss()
loss = loss_fct(logits, labels)
return VideoMAEForPreTrainingOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@auto_docstring(
custom_intro="""
VideoMAE Model transformer with a video classification head on top (a linear layer on top of the average pooled hidden
states of all tokens) e.g. for ImageNet.
"""
)
| VideoMAEForPreTraining |
python | fastapi__sqlmodel | docs_src/tutorial/where/tutorial004_py310.py | {
"start": 71,
"end": 1549
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
secret_name: str
age: int | None = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def create_heroes():
hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson")
hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)
hero_4 = Hero(name="Tarantula", secret_name="Natalia Roman-on", age=32)
hero_5 = Hero(name="Black Lion", secret_name="Trevor Challa", age=35)
hero_6 = Hero(name="Dr. Weird", secret_name="Steve Weird", age=36)
hero_7 = Hero(name="Captain North America", secret_name="Esteban Rogelios", age=93)
with Session(engine) as session:
session.add(hero_1)
session.add(hero_2)
session.add(hero_3)
session.add(hero_4)
session.add(hero_5)
session.add(hero_6)
session.add(hero_7)
session.commit()
def select_heroes():
with Session(engine) as session:
statement = select(Hero).where(Hero.age >= 35)
results = session.exec(statement)
for hero in results:
print(hero)
def main():
create_db_and_tables()
create_heroes()
select_heroes()
if __name__ == "__main__":
main()
| Hero |
python | getsentry__sentry-python | tests/integrations/litellm/test_litellm.py | {
"start": 1879,
"end": 2044
} | class ____:
def __init__(self, message=None):
self.message = message or MockMessage()
self.index = 0
self.finish_reason = "stop"
| MockChoice |
python | openai__openai-python | src/openai/types/realtime/realtime_response_create_audio_output_param.py | {
"start": 910,
"end": 999
} | class ____(TypedDict, total=False):
output: Output
| RealtimeResponseCreateAudioOutputParam |
python | doocs__leetcode | solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/Solution.py | {
"start": 0,
"end": 470
} | class ____:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
s1, s2 = sum(nums1), sum(nums2)
if s1 == s2:
return 0
if s1 > s2:
return self.minOperations(nums2, nums1)
arr = [6 - v for v in nums1] + [v - 1 for v in nums2]
d = s2 - s1
for i, v in enumerate(sorted(arr, reverse=True), 1):
d -= v
if d <= 0:
return i
return -1
| Solution |
python | Pylons__pyramid | src/pyramid/config/actions.py | {
"start": 5385,
"end": 10966
} | class ____:
def __init__(self):
# NB "actions" is an API, dep'd upon by pyramid_zcml's load_zcml func
self.actions = []
self._seen_files = set()
def processSpec(self, spec):
"""Check whether a callable needs to be processed. The ``spec``
refers to a unique identifier for the callable.
Return True if processing is needed and False otherwise. If
the callable needs to be processed, it will be marked as
processed, assuming that the caller will process the callable if
it needs to be processed.
"""
if spec in self._seen_files:
return False
self._seen_files.add(spec)
return True
def action(
self,
discriminator,
callable=None,
args=(),
kw=None,
order=0,
includepath=(),
info=None,
introspectables=(),
**extra,
):
"""Add an action with the given discriminator, callable, and
arguments"""
if kw is None:
kw = {}
action = extra
action.update(
dict(
discriminator=discriminator,
callable=callable,
args=args,
kw=kw,
includepath=includepath,
info=info,
order=order,
introspectables=introspectables,
)
)
self.actions.append(action)
def execute_actions(self, clear=True, introspector=None):
"""Execute the configuration actions
This calls the action callables after resolving conflicts
For example:
>>> output = []
>>> def f(*a, **k):
... output.append(('f', a, k))
>>> context = ActionState()
>>> context.actions = [
... (1, f, (1,)),
... (1, f, (11,), {}, ('x', )),
... (2, f, (2,)),
... ]
>>> context.execute_actions()
>>> output
[('f', (1,), {}), ('f', (2,), {})]
If the action raises an error, we convert it to a
ConfigurationExecutionError.
>>> output = []
>>> def bad():
... bad.xxx
>>> context.actions = [
... (1, f, (1,)),
... (1, f, (11,), {}, ('x', )),
... (2, f, (2,)),
... (3, bad, (), {}, (), 'oops')
... ]
>>> try:
... v = context.execute_actions()
... except ConfigurationExecutionError, v:
... pass
>>> print(v)
exceptions.AttributeError: 'function' object has no attribute 'xxx'
in:
oops
Note that actions executed before the error still have an effect:
>>> output
[('f', (1,), {}), ('f', (2,), {})]
The execution is re-entrant such that actions may be added by other
actions with the one caveat that the order of any added actions must
be equal to or larger than the current action.
>>> output = []
>>> def f(*a, **k):
... output.append(('f', a, k))
... context.actions.append((3, g, (8,), {}))
>>> def g(*a, **k):
... output.append(('g', a, k))
>>> context.actions = [
... (1, f, (1,)),
... ]
>>> context.execute_actions()
>>> output
[('f', (1,), {}), ('g', (8,), {})]
"""
try:
all_actions = []
executed_actions = []
action_iter = iter([])
conflict_state = ConflictResolverState()
while True:
# We clear the actions list prior to execution so if there
# are some new actions then we add them to the mix and resolve
# conflicts again. This orders the new actions as well as
# ensures that the previously executed actions have no new
# conflicts.
if self.actions:
all_actions.extend(self.actions)
action_iter = resolveConflicts(
self.actions, state=conflict_state
)
self.actions = []
action = next(action_iter, None)
if action is None:
# we are done!
break
callable = action['callable']
args = action['args']
kw = action['kw']
info = action['info']
# we use "get" below in case an action was added via a ZCML
# directive that did not know about introspectables
introspectables = action.get('introspectables', ())
try:
if callable is not None:
callable(*args, **kw)
except Exception:
t, v, tb = sys.exc_info()
try:
reraise(
ConfigurationExecutionError,
ConfigurationExecutionError(t, v, info),
tb,
)
finally:
del t, v, tb
if introspector is not None:
for introspectable in introspectables:
introspectable.register(introspector, info)
executed_actions.append(action)
self.actions = all_actions
return executed_actions
finally:
if clear:
self.actions = []
| ActionState |
python | ray-project__ray | python/ray/util/joblib/ray_backend.py | {
"start": 320,
"end": 3343
} | class ____(MultiprocessingBackend):
"""Ray backend uses ray, a system for scalable distributed computing.
More info about Ray is available here: https://docs.ray.io.
"""
def __init__(
self,
nesting_level: Optional[int] = None,
inner_max_num_threads: Optional[int] = None,
ray_remote_args: Optional[Dict[str, Any]] = None,
**kwargs
):
"""``ray_remote_args`` will be used to configure Ray Actors
making up the pool."""
usage_lib.record_library_usage("util.joblib")
self.ray_remote_args = ray_remote_args
super().__init__(
nesting_level=nesting_level,
inner_max_num_threads=inner_max_num_threads,
**kwargs
)
# ray_remote_args is used both in __init__ and configure to allow for it to be
# set in both `parallel_backend` and `Parallel` respectively
def configure(
self,
n_jobs: int = 1,
parallel: Optional[Parallel] = None,
prefer: Optional[str] = None,
require: Optional[str] = None,
ray_remote_args: Optional[Dict[str, Any]] = None,
**memmappingpool_args
):
"""Make Ray Pool the father class of PicklingPool. PicklingPool is a
father class that inherits Pool from multiprocessing.pool. The next
line is a patch, which changes the inheritance of Pool to be from
ray.util.multiprocessing.pool.
``ray_remote_args`` will be used to configure Ray Actors making up the pool.
This will override ``ray_remote_args`` set during initialization.
"""
PicklingPool.__bases__ = (Pool,)
"""Use all available resources when n_jobs == -1. Must set RAY_ADDRESS
variable in the environment or run ray.init(address=..) to run on
multiple nodes.
"""
if n_jobs == -1:
if not ray.is_initialized():
import os
if "RAY_ADDRESS" in os.environ:
logger.info(
"Connecting to ray cluster at address='{}'".format(
os.environ["RAY_ADDRESS"]
)
)
else:
logger.info("Starting local ray cluster")
ray.init()
ray_cpus = int(ray._private.state.cluster_resources()["CPU"])
n_jobs = ray_cpus
eff_n_jobs = super(RayBackend, self).configure(
n_jobs,
parallel,
prefer,
require,
ray_remote_args=ray_remote_args
if ray_remote_args is not None
else self.ray_remote_args,
**memmappingpool_args
)
return eff_n_jobs
def effective_n_jobs(self, n_jobs):
eff_n_jobs = super(RayBackend, self).effective_n_jobs(n_jobs)
if n_jobs == -1:
ray_cpus = int(ray._private.state.cluster_resources()["CPU"])
eff_n_jobs = ray_cpus
return eff_n_jobs
| RayBackend |
python | ray-project__ray | rllib/algorithms/tests/test_algorithm_save_load_checkpoint_connectors.py | {
"start": 3901,
"end": 8721
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
ray.init()
@classmethod
def tearDownClass(cls) -> None:
ray.shutdown()
def test_save_and_restore_w_remote_env_runners(self):
num_env_runners = 2
for algo_name in algorithms_and_configs:
config = algorithms_and_configs[algo_name]
with tempfile.TemporaryDirectory() as tmpdir:
# create an algorithm, checkpoint it, then train for 2 iterations
connector_states_algo_1 = ray.get(
save_train_and_get_states.remote(
config, num_env_runners, "CartPole-v1", tmpdir
)
)
# load that checkpoint into a new algorithm and check the states.
connector_states_algo_2 = ray.get( # noqa
load_and_get_states.remote(
config, num_env_runners, "CartPole-v1", tmpdir
)
)
# Assert that all running stats are the same.
self._assert_running_stats_consistency(
connector_states_algo_1, connector_states_algo_2
)
def test_save_and_restore_w_remote_env_runners_and_wo_local_env_runner(self):
num_env_runners = 2
for algo_name in algorithms_and_configs:
config = algorithms_and_configs[algo_name].env_runners(
create_local_env_runner=False
)
with tempfile.TemporaryDirectory() as tmpdir:
# create an algorithm, checkpoint it, then train for 2 iterations
connector_states_algo_1 = ray.get(
save_train_and_get_states.remote(
config, num_env_runners, "CartPole-v1", tmpdir
)
)
# load that checkpoint into a new algorithm and check the states.
connector_states_algo_2 = ray.get( # noqa
load_and_get_states.remote(
config, num_env_runners, "CartPole-v1", tmpdir
)
)
# Assert that all running stats are the same.
self._assert_running_stats_consistency(
connector_states_algo_1, connector_states_algo_2
)
def _assert_running_stats_consistency(
self, connector_states_algo_1: list, connector_states_algo_2: list
):
"""
Asserts consistency of running stats within and between algorithms.
"""
running_stats_states_algo_1 = [
state[COMPONENT_ENV_TO_MODULE_CONNECTOR]["MeanStdFilter"][None][
"running_stats"
]
for state in connector_states_algo_1
]
running_stats_states_algo_2 = [
state[COMPONENT_ENV_TO_MODULE_CONNECTOR]["MeanStdFilter"][None][
"running_stats"
]
for state in connector_states_algo_2
]
running_stats_states_algo_1 = [
[RunningStat.from_state(s) for s in running_stats_state]
for running_stats_state in running_stats_states_algo_1
]
running_stats_states_algo_2 = [
[RunningStat.from_state(s) for s in running_stats_state]
for running_stats_state in running_stats_states_algo_2
]
running_stats_states_algo_1 = [
(
running_stat[0].n,
running_stat[0].mean_array,
running_stat[0].sum_sq_diff_array,
)
for running_stat in running_stats_states_algo_1
]
running_stats_states_algo_2 = [
(
running_stat[0].n,
running_stat[0].mean_array,
running_stat[0].sum_sq_diff_array,
)
for running_stat in running_stats_states_algo_2
]
# The number of env-runners must be two for the following checks to make sense.
self.assertEqual(len(running_stats_states_algo_1), 2)
self.assertEqual(len(running_stats_states_algo_2), 2)
# Assert that all running stats in algo-1 are the same (for consistency).
check(running_stats_states_algo_1[0][0], running_stats_states_algo_1[1][0])
# Now ensure that the connector states on remote `EnvRunner`s were restored.
check(running_stats_states_algo_1[0][0], running_stats_states_algo_2[0][0])
# Ensure also that all states are the same in algo-2 (for consistency).
check(running_stats_states_algo_2[0][0], running_stats_states_algo_2[1][0])
if __name__ == "__main__":
import sys
import pytest
sys.exit(pytest.main(["-v", __file__]))
| TestAlgorithmWithConnectorsSaveAndRestore |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/operate/configuration/run_config/resource_example/resources.py | {
"start": 23,
"end": 147
} | class ____:
def execute(self, query: str): ...
def get_engine(connection_url: str) -> Engine:
return Engine()
| Engine |
python | django-import-export__django-import-export | tests/core/tests/test_resources/test_import_export.py | {
"start": 1517,
"end": 12091
} | class ____(TestCase):
class BaseBookResource(resources.ModelResource):
def __init__(self):
self.field_names = []
def get_queryset(self):
return Book.objects.all().order_by("id")
def import_field(self, field, obj, data, is_m2m=False, **kwargs):
# mock out import_field() so that we can see the order
# fields were called
self.field_names.append(field.column_name)
class UnorderedBookResource(BaseBookResource):
class Meta:
fields = ("price", "id", "name")
model = Book
class OrderedBookResource(BaseBookResource):
class Meta:
fields = ("price", "id", "name")
import_order = ["price", "name", "id"]
export_order = ("price", "name", "id")
model = Book
class SubsetOrderedBookResource(BaseBookResource):
class Meta:
fields = ("price", "id", "name", "published")
import_order = ("name",)
export_order = ("published",)
model = Book
class DuplicateFieldsBookResource(BaseBookResource):
class Meta:
fields = ("id", "price", "name", "price")
model = Book
class FieldsAsListBookResource(BaseBookResource):
class Meta:
fields = ["id", "price", "name"]
model = Book
class MixedIterableBookResource(BaseBookResource):
class Meta:
fields = ("price", "id", "name")
import_order = ["price", "name", "id"]
model = Book
class DeclaredModelFieldBookResource(BaseBookResource):
# Non-model field, should come after model fields by default
author_full_name = fields.Field(
attribute="author",
column_name="author full name",
)
# Order of declared fields in `ModelResource` shouldn't change export order
categories = fields.Field(
attribute="categories",
column_name="categories",
widget=widgets.ManyToManyWidget(model=Category, field="name"),
)
published = fields.Field(
attribute="published",
column_name="published",
widget=widgets.DateWidget("%d.%m.%Y"),
)
author = fields.Field(attribute="author__name", column_name="author")
class Meta:
model = Book
def dehydrate_author_full_name(self, obj):
if obj.author:
return f"{obj.author.name} Bar"
return ""
def setUp(self):
super().setUp()
self.pk = Book.objects.create(name="Ulysses", price="1.99").pk
self.dataset = tablib.Dataset(headers=["id", "name", "price"])
row = [self.pk, "Some book", "19.99"]
self.dataset.append(row)
def test_mixed_iterable(self):
# 1878
self.resource = ImportExportFieldOrderTest.MixedIterableBookResource()
self.resource.import_data(self.dataset)
self.assertEqual(["price", "name", "id"], self.resource.field_names)
def test_defined_import_order(self):
self.resource = ImportExportFieldOrderTest.OrderedBookResource()
self.resource.import_data(self.dataset)
self.assertEqual(["price", "name", "id"], self.resource.field_names)
def test_undefined_import_order(self):
self.resource = ImportExportFieldOrderTest.UnorderedBookResource()
self.resource.import_data(self.dataset)
self.assertEqual(["price", "id", "name"], self.resource.field_names)
def test_defined_export_order(self):
self.resource = ImportExportFieldOrderTest.OrderedBookResource()
data = self.resource.export()
target = f"price,name,id\r\n1.99,Ulysses,{self.pk}\r\n"
self.assertEqual(target, data.csv)
def test_undefined_export_order(self):
# When export order is not defined,
# exported order should correspond with 'fields' definition
self.resource = ImportExportFieldOrderTest.UnorderedBookResource()
data = self.resource.export()
target = f"price,id,name\r\n1.99,{self.pk},Ulysses\r\n"
self.assertEqual(target, data.csv)
def test_subset_import_order(self):
self.resource = ImportExportFieldOrderTest.SubsetOrderedBookResource()
self.resource.import_data(self.dataset)
self.assertEqual(
["name", "price", "id", "published"], self.resource.field_names
)
def test_subset_export_order(self):
self.resource = ImportExportFieldOrderTest.SubsetOrderedBookResource()
data = self.resource.export()
target = f"published,price,id,name\r\n,1.99,{self.pk},Ulysses\r\n"
self.assertEqual(target, data.csv)
def test_duplicate_import_order(self):
self.resource = ImportExportFieldOrderTest.DuplicateFieldsBookResource()
self.resource.import_data(self.dataset)
self.assertEqual(["id", "price", "name"], self.resource.field_names)
def test_duplicate_export_order(self):
self.resource = ImportExportFieldOrderTest.DuplicateFieldsBookResource()
data = self.resource.export()
target = f"id,price,name\r\n{self.pk},1.99,Ulysses\r\n"
self.assertEqual(target, data.csv)
def test_fields_as_list_import_order(self):
self.resource = ImportExportFieldOrderTest.FieldsAsListBookResource()
self.resource.import_data(self.dataset)
self.assertEqual(["id", "price", "name"], self.resource.field_names)
def test_fields_as_list_export_order(self):
self.resource = ImportExportFieldOrderTest.FieldsAsListBookResource()
data = self.resource.export()
target = f"id,price,name\r\n{self.pk},1.99,Ulysses\r\n"
self.assertEqual(target, data.csv)
def test_declared_model_fields_not_alter_export_order(self):
# Issue (#1663)
categories = [
Category.objects.create(name="sci-fi"),
Category.objects.create(name="romance"),
]
author = Author.objects.create(name="Foo")
book = Book.objects.create(
name="The Lord Of The Rings", author=author, published=date(2022, 2, 2)
)
book.categories.set(categories)
self.resource = ImportExportFieldOrderTest.DeclaredModelFieldBookResource()
declared_field_names = (
"published",
"author", # FK
"categories", # M2M
)
export_order = self.resource.get_export_order()
model_fields_names = [
field.name for field in self.resource._meta.model._meta.get_fields()
]
for declared_field_name in declared_field_names:
self.assertEqual(
model_fields_names.index(declared_field_name),
export_order.index(declared_field_name),
)
# Validate non-model field is exported last unless specified
self.assertEqual(export_order[-1], "author_full_name")
def test_meta_fields_not_alter_export_order(self):
class DeclaredModelFieldBookResource(
ImportExportFieldOrderTest.BaseBookResource
):
# Non-model field, should come after model fields by default
author_full_name = fields.Field(
attribute="author",
column_name="author full name",
)
# Order of declared fields in `ModelResource` shouldn't change export order
categories = fields.Field(
attribute="categories",
column_name="categories",
widget=widgets.ManyToManyWidget(model=Category, field="name"),
)
published = fields.Field(
attribute="published",
column_name="published",
widget=widgets.DateWidget("%d.%m.%Y"),
)
author = fields.Field(attribute="author__name", column_name="author")
class Meta:
model = Book
fields = (
"id",
"author__name",
"author",
"author_full_name",
"categories",
"published",
)
def dehydrate_author_full_name(self, obj):
if obj.author:
return f"{obj.author.name} Bar"
return ""
self.resource = DeclaredModelFieldBookResource()
self.assertEqual(self.resource.get_export_order(), self.resource._meta.fields)
def test_declared_field_export_order(self):
# issue 1848
class DeclaredModelFieldBookResource(
ImportExportFieldOrderTest.BaseBookResource
):
published = fields.Field(
attribute="published",
column_name="date published",
widget=widgets.DateWidget("%d.%m.%Y"),
)
class Meta:
model = Book
fields = (
"id",
"author",
"published",
)
export_order = (
"published",
"id",
"author",
)
self.resource = DeclaredModelFieldBookResource()
data = self.resource.export()
target = f"date published,id,author\r\n,{self.pk},\r\n"
self.assertEqual(target, data.csv)
def test_export_fields_column_name(self):
"""Test export with declared export_fields and custom column_name"""
# issue 1846
class DeclaredModelFieldBookResource(resources.ModelResource):
published = fields.Field(
attribute="published",
column_name="datePublished",
widget=widgets.DateWidget("%d.%m.%Y"),
)
author = fields.Field(column_name="AuthorFooName")
class Meta:
model = Book
fields = (
"id",
"author",
"published",
)
export_order = (
"published",
"id",
"author",
)
def dehydrate_author(self, obj):
return obj.author
self.resource = DeclaredModelFieldBookResource()
data = self.resource.export()
target = f"datePublished,id,AuthorFooName\r\n,{self.pk},\r\n"
self.assertEqual(target, data.csv)
| ImportExportFieldOrderTest |
python | getsentry__sentry | src/sentry/api/serializers/models/project.py | {
"start": 25212,
"end": 25362
} | class ____(TypedDict, total=False):
latestDeploys: dict[str, dict[str, str]] | None
options: dict[str, Any]
| _OrganizationProjectOptionalResponse |
python | arrow-py__arrow | arrow/formatter.py | {
"start": 917,
"end": 5139
} | class ____:
# This pattern matches characters enclosed in square brackets are matched as
# an atomic group. For more info on atomic groups and how to they are
# emulated in Python's re library, see https://stackoverflow.com/a/13577411/2701578
_FORMAT_RE: Final[Pattern[str]] = re.compile(
r"(\[(?:(?=(?P<literal>[^]]))(?P=literal))*\]|YYY?Y?|MM?M?M?|Do|DD?D?D?|d?dd?d?|HH?|hh?|mm?|ss?|SS?S?S?S?S?|ZZ?Z?|a|A|X|x|W)"
)
locale: locales.Locale
def __init__(self, locale: str = DEFAULT_LOCALE) -> None:
self.locale = locales.get_locale(locale)
def format(cls, dt: datetime, fmt: str) -> str:
# FIXME: _format_token() is nullable
return cls._FORMAT_RE.sub(
lambda m: cast(str, cls._format_token(dt, m.group(0))), fmt
)
def _format_token(self, dt: datetime, token: Optional[str]) -> Optional[str]:
if token and token.startswith("[") and token.endswith("]"):
return token[1:-1]
if token == "YYYY":
return self.locale.year_full(dt.year)
if token == "YY":
return self.locale.year_abbreviation(dt.year)
if token == "MMMM":
return self.locale.month_name(dt.month)
if token == "MMM":
return self.locale.month_abbreviation(dt.month)
if token == "MM":
return f"{dt.month:02d}"
if token == "M":
return f"{dt.month}"
if token == "DDDD":
return f"{dt.timetuple().tm_yday:03d}"
if token == "DDD":
return f"{dt.timetuple().tm_yday}"
if token == "DD":
return f"{dt.day:02d}"
if token == "D":
return f"{dt.day}"
if token == "Do":
return self.locale.ordinal_number(dt.day)
if token == "dddd":
return self.locale.day_name(dt.isoweekday())
if token == "ddd":
return self.locale.day_abbreviation(dt.isoweekday())
if token == "d":
return f"{dt.isoweekday()}"
if token == "HH":
return f"{dt.hour:02d}"
if token == "H":
return f"{dt.hour}"
if token == "hh":
return f"{dt.hour if 0 < dt.hour < 13 else abs(dt.hour - 12):02d}"
if token == "h":
return f"{dt.hour if 0 < dt.hour < 13 else abs(dt.hour - 12)}"
if token == "mm":
return f"{dt.minute:02d}"
if token == "m":
return f"{dt.minute}"
if token == "ss":
return f"{dt.second:02d}"
if token == "s":
return f"{dt.second}"
if token == "SSSSSS":
return f"{dt.microsecond:06d}"
if token == "SSSSS":
return f"{dt.microsecond // 10:05d}"
if token == "SSSS":
return f"{dt.microsecond // 100:04d}"
if token == "SSS":
return f"{dt.microsecond // 1000:03d}"
if token == "SS":
return f"{dt.microsecond // 10000:02d}"
if token == "S":
return f"{dt.microsecond // 100000}"
if token == "X":
return f"{dt.timestamp()}"
if token == "x":
return f"{dt.timestamp() * 1_000_000:.0f}"
if token == "ZZZ":
return dt.tzname()
if token in ["ZZ", "Z"]:
separator = ":" if token == "ZZ" else ""
tz = timezone.utc if dt.tzinfo is None else dt.tzinfo
# `dt` must be aware object. Otherwise, this line will raise AttributeError
# https://github.com/arrow-py/arrow/pull/883#discussion_r529866834
# datetime awareness: https://docs.python.org/3/library/datetime.html#aware-and-naive-objects
total_minutes = int(cast(timedelta, tz.utcoffset(dt)).total_seconds() / 60)
sign = "+" if total_minutes >= 0 else "-"
total_minutes = abs(total_minutes)
hour, minute = divmod(total_minutes, 60)
return f"{sign}{hour:02d}{separator}{minute:02d}"
if token in ("a", "A"):
return self.locale.meridian(dt.hour, token)
if token == "W":
year, week, day = dt.isocalendar()
return f"{year}-W{week:02d}-{day}"
| DateTimeFormatter |
python | bokeh__bokeh | src/bokeh/io/state.py | {
"start": 2692,
"end": 7919
} | class ____:
''' Manage state related to controlling Bokeh output.
'''
_file: FileConfig | None
_notebook: bool
_notebook_type: NotebookType | None
last_comms_handle: CommsHandle | None
uuid_to_server: dict[ID, Server]
def __init__(self) -> None:
self.last_comms_handle = None
self.uuid_to_server = {} # Mapping from uuid to server instance
self.reset()
# Properties --------------------------------------------------------------
@property
def document(self) -> Document:
''' A default |Document| to use for all output operations.
'''
return self._document
@document.setter
def document(self, doc: Document) -> None:
self._document = doc
@property
def file(self) -> FileConfig | None:
''' A structure with the default configuration for file output (READ ONLY)
See :class:`~bokeh.io.state.FileConfig`.
'''
return self._file
@property
def notebook(self) -> bool:
''' Whether to generate notebook output on show operations. (READ ONLY)
'''
return self._notebook
@property
def notebook_type(self) -> NotebookType | None:
''' Notebook type
'''
return self._notebook_type
@notebook_type.setter
def notebook_type(self, notebook_type: NotebookType) -> None:
''' Notebook type, acceptable values are 'jupyter' as well as any names
defined by external notebook hooks that have been installed.
'''
if notebook_type is None or not isinstance(notebook_type, str):
raise ValueError("Notebook type must be a string")
self._notebook_type = cast("NotebookType", notebook_type.lower())
# Public methods ----------------------------------------------------------
def output_file(self, filename: PathLike, title: str = "Bokeh Plot",
mode: ResourcesMode | None = None, root_dir: PathLike | None = None) -> None:
''' Configure output to a standalone HTML file.
Calling ``output_file`` does not clear the effects of any other calls to
|output_notebook|, etc. It adds an additional output destination
(publishing to HTML files). Any other active output modes continue
to be active.
Args:
filename (PathLike, e.g. str, Path) : a filename for saving the HTML document
title (str, optional) : a title for the HTML document
mode (str, optional) : how to include BokehJS (default: ``'cdn'``)
One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or
``'absolute(-dev)'``. See :class:`~bokeh.resources.Resources`
for more details.
root_dir (str, optional) : root dir to use for absolute resources
(default: None)
This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``.
.. warning::
The specified output file will be overwritten on every save, e.g.,
every time ``show()`` or ``save()`` is called.
'''
self._file = FileConfig(
filename=filename,
resources=Resources(mode=mode, root_dir=root_dir),
title=title,
)
if os.path.isfile(filename):
log.info(f"Session output file '{filename}' already exists, will be overwritten.")
def output_notebook(self, notebook_type: NotebookType = "jupyter") -> None:
''' Generate output in notebook cells.
Calling ``output_notebook`` does not clear the effects of any other
calls to |output_file|, etc. It adds an additional output destination
(publishing to notebook output cells). Any other active output modes
continue to be active.
Returns:
None
'''
self._notebook = True
self.notebook_type = notebook_type
def reset(self) -> None:
''' Deactivate all currently active output modes and set ``curdoc()``
to a fresh empty ``Document``.
Subsequent calls to ``show()`` will not render until a new output mode
is activated.
Returns:
None
'''
from ..document import Document
self._reset_with_doc(Document())
# Private methods ---------------------------------------------------------
def _reset_keeping_doc(self) -> None:
''' Reset output modes but DO NOT replace the default Document
'''
self._file = None
self._notebook = False
self._notebook_type = None
def _reset_with_doc(self, doc: Document) -> None:
''' Reset output modes but DO replace the default Document
'''
self._document = doc
self._reset_keeping_doc()
def curstate() -> State:
''' Return the current State object
Returns:
State : the current default State object
'''
global _STATE
if _STATE is None:
_STATE = State()
return _STATE
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
@dataclass(frozen=True)
| State |
python | sanic-org__sanic | sanic/app.py | {
"start": 3182,
"end": 93005
} | class ____(
Generic[config_type, ctx_type],
StaticHandleMixin,
BaseSanic,
StartupMixin,
CommandMixin,
metaclass=TouchUpMeta,
):
"""The main application instance
You will create an instance of this class and use it to register
routes, listeners, middleware, blueprints, error handlers, etc.
By convention, it is often called `app`. It must be named using
the `name` parameter and is roughly constrained to the same
restrictions as a Python module name, however, it can contain
hyphens (`-`).
```python
# will cause an error because it contains spaces
Sanic("This is not legal")
```
```python
# this is legal
Sanic("Hyphens-are-legal_or_also_underscores")
```
Args:
name (str): The name of the application. Must be a valid
Python module name (including hyphens).
config (Optional[config_type]): The configuration to use for
the application. Defaults to `None`.
ctx (Optional[ctx_type]): The context to use for the
application. Defaults to `None`.
router (Optional[Router]): The router to use for the
application. Defaults to `None`.
signal_router (Optional[SignalRouter]): The signal router to
use for the application. Defaults to `None`.
error_handler (Optional[ErrorHandler]): The error handler to
use for the application. Defaults to `None`.
env_prefix (Optional[str]): The prefix to use for environment
variables. Defaults to `SANIC_`.
request_class (Optional[Type[Request]]): The request class to
use for the application. Defaults to `Request`.
strict_slashes (bool): Whether to enforce strict slashes.
Defaults to `False`.
log_config (Optional[Dict[str, Any]]): The logging configuration
to use for the application. Defaults to `None`.
configure_logging (bool): Whether to configure logging.
Defaults to `True`.
dumps (Optional[Callable[..., AnyStr]]): The function to use
for serializing JSON. Defaults to `None`.
loads (Optional[Callable[..., Any]]): The function to use
for deserializing JSON. Defaults to `None`.
inspector (bool): Whether to enable the inspector. Defaults
to `False`.
inspector_class (Optional[Type[Inspector]]): The inspector
class to use for the application. Defaults to `None`.
certloader_class (Optional[Type[CertLoader]]): The certloader
class to use for the application. Defaults to `None`.
"""
__touchup__ = (
"handle_request",
"handle_exception",
"_run_response_middleware",
"_run_request_middleware",
)
__slots__ = (
"_asgi_app",
"_asgi_lifespan",
"_asgi_client",
"_blueprint_order",
"_delayed_tasks",
"_ext",
"_future_commands",
"_future_exceptions",
"_future_listeners",
"_future_middleware",
"_future_registry",
"_future_routes",
"_future_signals",
"_future_statics",
"_inspector",
"_manager",
"_state",
"_task_registry",
"_test_client",
"_test_manager",
"blueprints",
"certloader_class",
"config",
"configure_logging",
"ctx",
"error_handler",
"inspector_class",
"go_fast",
"listeners",
"multiplexer",
"named_request_middleware",
"named_response_middleware",
"repl_ctx",
"request_class",
"request_middleware",
"response_middleware",
"router",
"shared_ctx",
"signal_router",
"sock",
"strict_slashes",
"websocket_enabled",
"websocket_tasks",
)
_app_registry: ClassVar[dict[str, Sanic]] = {}
test_mode: ClassVar[bool] = False
@overload
def __init__(
self: Sanic[Config, SimpleNamespace],
name: str,
config: None = None,
ctx: None = None,
router: Optional[Router] = None,
signal_router: Optional[SignalRouter] = None,
error_handler: Optional[ErrorHandler] = None,
env_prefix: Optional[str] = SANIC_PREFIX,
request_class: Optional[type[Request]] = None,
strict_slashes: bool = False,
log_config: Optional[dict[str, Any]] = None,
configure_logging: bool = True,
dumps: Optional[Callable[..., AnyStr]] = None,
loads: Optional[Callable[..., Any]] = None,
inspector: bool = False,
inspector_class: Optional[type[Inspector]] = None,
certloader_class: Optional[type[CertLoader]] = None,
) -> None: ...
@overload
def __init__(
self: Sanic[config_type, SimpleNamespace],
name: str,
config: Optional[config_type] = None,
ctx: None = None,
router: Optional[Router] = None,
signal_router: Optional[SignalRouter] = None,
error_handler: Optional[ErrorHandler] = None,
env_prefix: Optional[str] = SANIC_PREFIX,
request_class: Optional[type[Request]] = None,
strict_slashes: bool = False,
log_config: Optional[dict[str, Any]] = None,
configure_logging: bool = True,
dumps: Optional[Callable[..., AnyStr]] = None,
loads: Optional[Callable[..., Any]] = None,
inspector: bool = False,
inspector_class: Optional[type[Inspector]] = None,
certloader_class: Optional[type[CertLoader]] = None,
) -> None: ...
@overload
def __init__(
self: Sanic[Config, ctx_type],
name: str,
config: None = None,
ctx: Optional[ctx_type] = None,
router: Optional[Router] = None,
signal_router: Optional[SignalRouter] = None,
error_handler: Optional[ErrorHandler] = None,
env_prefix: Optional[str] = SANIC_PREFIX,
request_class: Optional[type[Request]] = None,
strict_slashes: bool = False,
log_config: Optional[dict[str, Any]] = None,
configure_logging: bool = True,
dumps: Optional[Callable[..., AnyStr]] = None,
loads: Optional[Callable[..., Any]] = None,
inspector: bool = False,
inspector_class: Optional[type[Inspector]] = None,
certloader_class: Optional[type[CertLoader]] = None,
) -> None: ...
@overload
def __init__(
self: Sanic[config_type, ctx_type],
name: str,
config: Optional[config_type] = None,
ctx: Optional[ctx_type] = None,
router: Optional[Router] = None,
signal_router: Optional[SignalRouter] = None,
error_handler: Optional[ErrorHandler] = None,
env_prefix: Optional[str] = SANIC_PREFIX,
request_class: Optional[type[Request]] = None,
strict_slashes: bool = False,
log_config: Optional[dict[str, Any]] = None,
configure_logging: bool = True,
dumps: Optional[Callable[..., AnyStr]] = None,
loads: Optional[Callable[..., Any]] = None,
inspector: bool = False,
inspector_class: Optional[type[Inspector]] = None,
certloader_class: Optional[type[CertLoader]] = None,
) -> None: ...
def __init__(
self,
name: str,
config: Optional[config_type] = None,
ctx: Optional[ctx_type] = None,
router: Optional[Router] = None,
signal_router: Optional[SignalRouter] = None,
error_handler: Optional[ErrorHandler] = None,
env_prefix: Optional[str] = SANIC_PREFIX,
request_class: Optional[type[Request]] = None,
strict_slashes: bool = False,
log_config: Optional[dict[str, Any]] = None,
configure_logging: bool = True,
dumps: Optional[Callable[..., AnyStr]] = None,
loads: Optional[Callable[..., Any]] = None,
inspector: bool = False,
inspector_class: Optional[type[Inspector]] = None,
certloader_class: Optional[type[CertLoader]] = None,
) -> None:
super().__init__(name=name)
# logging
if configure_logging:
dict_config = log_config or LOGGING_CONFIG_DEFAULTS
logging.config.dictConfig(dict_config) # type: ignore
if config and env_prefix != SANIC_PREFIX:
raise SanicException(
"When instantiating Sanic with config, you cannot also pass "
"env_prefix"
)
# First setup config
self.config: config_type = cast(
config_type, config or Config(env_prefix=env_prefix)
)
if inspector:
self.config.INSPECTOR = inspector
# Then we can do the rest
self._asgi_app: Optional[ASGIApp] = None
self._asgi_lifespan: Optional[Lifespan] = None
self._asgi_client: Any = None
self._blueprint_order: list[Blueprint] = []
self._delayed_tasks: list[str] = []
self._future_registry: FutureRegistry = FutureRegistry()
self._inspector: Optional[Inspector] = None
self._manager: Optional[WorkerManager] = None
self._state: ApplicationState = ApplicationState(app=self)
self._task_registry: dict[str, Union[Task, None]] = {}
self._test_client: Any = None
self._test_manager: Any = None
self.asgi = False
self.auto_reload = False
self.blueprints: dict[str, Blueprint] = {}
self.certloader_class: type[CertLoader] = (
certloader_class or CertLoader
)
self.configure_logging: bool = configure_logging
self.ctx: ctx_type = cast(ctx_type, ctx or SimpleNamespace())
self.error_handler: ErrorHandler = error_handler or ErrorHandler()
self.inspector_class: type[Inspector] = inspector_class or Inspector
self.listeners: dict[str, list[ListenerType[Any]]] = defaultdict(list)
self.named_request_middleware: dict[str, Deque[Middleware]] = {}
self.named_response_middleware: dict[str, Deque[Middleware]] = {}
self.repl_ctx: REPLContext = REPLContext()
self.request_class = request_class or Request
self.request_middleware: Deque[Middleware] = deque()
self.response_middleware: Deque[Middleware] = deque()
self.router: Router = router or Router()
self.shared_ctx: SharedContext = SharedContext()
self.signal_router: SignalRouter = signal_router or SignalRouter()
self.sock: Optional[socket] = None
self.strict_slashes: bool = strict_slashes
self.websocket_enabled: bool = False
self.websocket_tasks: set[Future[Any]] = set()
# Register alternative method names
self.go_fast = self.run
self.router.ctx.app = self
self.signal_router.ctx.app = self
self.__class__.register_app(self)
if dumps:
BaseHTTPResponse._dumps = dumps # type: ignore
if loads:
Request._loads = loads # type: ignore
@property
def loop(self) -> AbstractEventLoop:
"""Synonymous with asyncio.get_event_loop().
.. note::
Only supported when using the `app.run` method.
Returns:
AbstractEventLoop: The event loop for the application.
Raises:
SanicException: If the application is not running.
"""
if self.state.stage is ServerStage.STOPPED and self.asgi is False:
raise SanicException(
"Loop can only be retrieved after the app has started "
"running. Not supported with `create_server` function"
)
try:
return get_running_loop()
except RuntimeError: # no cov
if sys.version_info > (3, 10):
return asyncio.get_event_loop_policy().get_event_loop()
else:
return asyncio.get_event_loop()
# -------------------------------------------------------------------- #
# Registration
# -------------------------------------------------------------------- #
def register_listener(
self,
listener: ListenerType[SanicVar],
event: str,
*,
priority: int = 0,
) -> ListenerType[SanicVar]:
"""Register the listener for a given event.
Args:
listener (Callable): The listener to register.
event (str): The event to listen for.
Returns:
Callable: The listener that was registered.
"""
try:
_event = ListenerEvent[event.upper()]
except (ValueError, AttributeError):
valid = ", ".join(
map(lambda x: x.lower(), ListenerEvent.__members__.keys())
)
raise BadRequest(f"Invalid event: {event}. Use one of: {valid}")
if "." in _event:
self.signal(_event.value, priority=priority)(
partial(self._listener, listener=listener)
)
else:
if priority:
error_logger.warning(
f"Priority is not supported for {_event.value}"
)
self.listeners[_event.value].append(listener)
return listener
def register_middleware(
self,
middleware: Union[MiddlewareType, Middleware],
attach_to: str = "request",
*,
priority: Union[Default, int] = _default,
) -> Union[MiddlewareType, Middleware]:
"""Register a middleware to be called before a request is handled.
Args:
middleware (Callable): A callable that takes in a request.
attach_to (str): Whether to attach to request or response.
Defaults to `'request'`.
priority (int): The priority level of the middleware.
Lower numbers are executed first. Defaults to `0`.
Returns:
Union[Callable, Callable[[Callable], Callable]]: The decorated
middleware function or a partial function depending on how
the method was called.
"""
retval = middleware
location = MiddlewareLocation[attach_to.upper()]
if not isinstance(middleware, Middleware):
middleware = Middleware(
middleware,
location=location,
priority=priority if isinstance(priority, int) else 0,
)
elif middleware.priority != priority and isinstance(priority, int):
middleware = Middleware(
middleware.func,
location=middleware.location,
priority=priority,
)
if location is MiddlewareLocation.REQUEST:
if middleware not in self.request_middleware:
self.request_middleware.append(middleware)
if location is MiddlewareLocation.RESPONSE:
if middleware not in self.response_middleware:
self.response_middleware.appendleft(middleware)
return retval
def register_named_middleware(
self,
middleware: MiddlewareType,
route_names: Iterable[str],
attach_to: str = "request",
*,
priority: Union[Default, int] = _default,
):
"""Used to register named middleqare (middleware typically on blueprints)
Args:
middleware (Callable): A callable that takes in a request.
route_names (Iterable[str]): The route names to attach the
middleware to.
attach_to (str): Whether to attach to request or response.
Defaults to `'request'`.
priority (int): The priority level of the middleware.
Lower numbers are executed first. Defaults to `0`.
Returns:
Union[Callable, Callable[[Callable], Callable]]: The decorated
middleware function or a partial function depending on how
the method was called.
""" # noqa: E501
retval = middleware
location = MiddlewareLocation[attach_to.upper()]
if not isinstance(middleware, Middleware):
middleware = Middleware(
middleware,
location=location,
priority=priority if isinstance(priority, int) else 0,
)
elif middleware.priority != priority and isinstance(priority, int):
middleware = Middleware(
middleware.func,
location=middleware.location,
priority=priority,
)
if location is MiddlewareLocation.REQUEST:
for _rn in route_names:
if _rn not in self.named_request_middleware:
self.named_request_middleware[_rn] = deque()
if middleware not in self.named_request_middleware[_rn]:
self.named_request_middleware[_rn].append(middleware)
if location is MiddlewareLocation.RESPONSE:
for _rn in route_names:
if _rn not in self.named_response_middleware:
self.named_response_middleware[_rn] = deque()
if middleware not in self.named_response_middleware[_rn]:
self.named_response_middleware[_rn].appendleft(middleware)
return retval
def _apply_exception_handler(
self,
handler: FutureException,
route_names: Optional[list[str]] = None,
):
"""Decorate a function to be registered as a handler for exceptions
:param exceptions: exceptions
:return: decorated function
"""
for exception in handler.exceptions:
if isinstance(exception, (tuple, list)):
for e in exception:
self.error_handler.add(e, handler.handler, route_names)
else:
self.error_handler.add(exception, handler.handler, route_names)
return handler.handler
def _apply_listener(self, listener: FutureListener):
return self.register_listener(
listener.listener, listener.event, priority=listener.priority
)
def _apply_route(
self, route: FutureRoute, overwrite: bool = False
) -> list[Route]:
params = route._asdict()
params["overwrite"] = overwrite
websocket = params.pop("websocket", False)
subprotocols = params.pop("subprotocols", None)
if websocket:
self.enable_websocket()
websocket_handler = partial(
self._websocket_handler,
route.handler,
subprotocols=subprotocols,
)
websocket_handler.__name__ = route.handler.__name__ # type: ignore
websocket_handler.is_websocket = True # type: ignore
params["handler"] = websocket_handler
ctx = params.pop("route_context")
with self.amend():
routes = self.router.add(**params)
if isinstance(routes, Route):
routes = [routes]
for r in routes:
r.extra.websocket = websocket
r.extra.static = params.get("static", False)
r.ctx.__dict__.update(ctx)
return routes
def _apply_middleware(
self,
middleware: FutureMiddleware,
route_names: Optional[list[str]] = None,
):
with self.amend():
if route_names:
return self.register_named_middleware(
middleware.middleware, route_names, middleware.attach_to
)
else:
return self.register_middleware(
middleware.middleware, middleware.attach_to
)
def _apply_signal(self, signal: FutureSignal) -> Signal:
with self.amend():
return self.signal_router.add(
handler=signal.handler,
event=signal.event,
condition=signal.condition,
exclusive=signal.exclusive,
priority=signal.priority,
)
@overload
def dispatch(
self,
event: str,
*,
condition: Optional[dict[str, str]] = None,
context: Optional[dict[str, Any]] = None,
fail_not_found: bool = True,
inline: Literal[True],
reverse: bool = False,
) -> Coroutine[Any, Any, Awaitable[Any]]: ...
@overload
def dispatch(
self,
event: str,
*,
condition: Optional[dict[str, str]] = None,
context: Optional[dict[str, Any]] = None,
fail_not_found: bool = True,
inline: Literal[False] = False,
reverse: bool = False,
) -> Coroutine[Any, Any, Awaitable[Task]]: ...
def dispatch(
self,
event: str,
*,
condition: Optional[dict[str, str]] = None,
context: Optional[dict[str, Any]] = None,
fail_not_found: bool = True,
inline: bool = False,
reverse: bool = False,
) -> Coroutine[Any, Any, Awaitable[Union[Task, Any]]]:
"""Dispatches an event to the signal router.
Args:
event (str): Name of the event to dispatch.
condition (Optional[Dict[str, str]]): Condition for the
event dispatch.
context (Optional[Dict[str, Any]]): Context for the event dispatch.
fail_not_found (bool): Whether to fail if the event is not found.
Default is `True`.
inline (bool): If `True`, returns the result directly. If `False`,
returns a `Task`. Default is `False`.
reverse (bool): Whether to reverse the dispatch order.
Default is `False`.
Returns:
Coroutine[Any, Any, Awaitable[Union[Task, Any]]]: An awaitable
that returns the result directly if `inline=True`, or a `Task`
if `inline=False`.
Examples:
```python
@app.signal("user.registration.created")
async def send_registration_email(**context):
await send_email(context["email"], template="registration")
@app.post("/register")
async def handle_registration(request):
await do_registration(request)
await request.app.dispatch(
"user.registration.created",
context={"email": request.json.email}
})
```
"""
return self.signal_router.dispatch(
event,
context=context,
condition=condition,
inline=inline,
reverse=reverse,
fail_not_found=fail_not_found,
)
async def event(
self,
event: Union[str, Enum],
timeout: Optional[Union[int, float]] = None,
*,
condition: Optional[dict[str, Any]] = None,
exclusive: bool = True,
) -> None:
"""Wait for a specific event to be triggered.
This method waits for a named event to be triggered and can be used
in conjunction with the signal system to wait for specific signals.
If the event is not found and auto-registration of events is enabled,
the event will be registered and then waited on. If the event is not
found and auto-registration is not enabled, a `NotFound` exception
is raised.
Auto-registration can be handled by setting the `EVENT_AUTOREGISTER`
config value to `True`.
```python
app.config.EVENT_AUTOREGISTER = True
```
Args:
event (str): The name of the event to wait for.
timeout (Optional[Union[int, float]]): An optional timeout value
in seconds. If provided, the wait will be terminated if the
timeout is reached. Defaults to `None`, meaning no timeout.
condition: If provided, method will only return when the signal
is dispatched with the given condition.
exclusive: When true (default), the signal can only be dispatched
when the condition has been met. When ``False``, the signal can
be dispatched either with or without it.
Raises:
NotFound: If the event is not found and auto-registration of
events is not enabled.
Returns:
The context dict of the dispatched signal.
Examples:
```python
async def wait_for_event(app):
while True:
print("> waiting")
await app.event("foo.bar.baz")
print("> event found")
@app.after_server_start
async def after_server_start(app, loop):
app.add_task(wait_for_event(app))
```
"""
waiter = self.signal_router.get_waiter(event, condition, exclusive)
if not waiter and self.config.EVENT_AUTOREGISTER:
self.signal_router.reset()
self.add_signal(None, event)
waiter = self.signal_router.get_waiter(event, condition, exclusive)
self.signal_router.finalize()
if not waiter:
raise NotFound(f"Could not find signal {event}")
return await wait_for(waiter.wait(), timeout=timeout)
def report_exception(
self, handler: Callable[[Sanic, Exception], Coroutine[Any, Any, None]]
) -> Callable[[Exception], Coroutine[Any, Any, None]]:
"""Register a handler to report exceptions.
A convenience method to register a handler for the signal that
is emitted when an exception occurs. It is typically used to
report exceptions to an external service.
It is equivalent to:
```python
@app.signal(Event.SERVER_EXCEPTION_REPORT)
async def report(exception):
await do_something_with_error(exception)
```
Args:
handler (Callable[[Sanic, Exception], Coroutine[Any, Any, None]]):
The handler to register.
Returns:
Callable[[Sanic, Exception], Coroutine[Any, Any, None]]: The
handler that was registered.
"""
@wraps(handler)
async def report(exception: Exception) -> None:
await handler(self, exception)
self.add_signal(
handler=report, event=Event.SERVER_EXCEPTION_REPORT.value
)
return report
def enable_websocket(self, enable: bool = True) -> None:
"""Enable or disable the support for websocket.
Websocket is enabled automatically if websocket routes are
added to the application. This typically will not need to be
called manually.
Args:
enable (bool, optional): If set to `True`, enables websocket
support. If set to `False`, disables websocket support.
Defaults to `True`.
Returns:
None
"""
if not self.websocket_enabled:
# if the server is stopped, we want to cancel any ongoing
# websocket tasks, to allow the server to exit promptly
self.listener("before_server_stop")(self._cancel_websocket_tasks)
self.websocket_enabled = enable
def blueprint(
self,
blueprint: Union[Blueprint, Iterable[Blueprint], BlueprintGroup],
*,
url_prefix: Optional[str] = None,
version: Optional[Union[int, float, str]] = None,
strict_slashes: Optional[bool] = None,
version_prefix: Optional[str] = None,
name_prefix: Optional[str] = None,
) -> None:
"""Register a blueprint on the application.
See [Blueprints](/en/guide/best-practices/blueprints) for more information.
Args:
blueprint (Union[Blueprint, Iterable[Blueprint], BlueprintGroup]): Blueprint object or (list, tuple) thereof.
url_prefix (Optional[str]): Prefix for all URLs bound to the blueprint. Defaults to `None`.
version (Optional[Union[int, float, str]]): Version prefix for URLs. Defaults to `None`.
strict_slashes (Optional[bool]): Enforce the trailing slashes. Defaults to `None`.
version_prefix (Optional[str]): Prefix for version. Defaults to `None`.
name_prefix (Optional[str]): Prefix for the blueprint name. Defaults to `None`.
Example:
```python
app = Sanic("TestApp")
bp = Blueprint('TestBP')
@bp.route('/route')
def handler(request):
return text('Hello, Blueprint!')
app.blueprint(bp, url_prefix='/blueprint')
```
""" # noqa: E501
options: dict[str, Any] = {}
if url_prefix is not None:
options["url_prefix"] = url_prefix
if version is not None:
options["version"] = version
if strict_slashes is not None:
options["strict_slashes"] = strict_slashes
if version_prefix is not None:
options["version_prefix"] = version_prefix
if name_prefix is not None:
options["name_prefix"] = name_prefix
if isinstance(blueprint, (Iterable, BlueprintGroup)):
for item in blueprint:
params: dict[str, Any] = {**options}
if isinstance(blueprint, BlueprintGroup):
merge_from = [
options.get("url_prefix", ""),
blueprint.url_prefix or "",
]
if not isinstance(item, BlueprintGroup):
merge_from.append(item.url_prefix or "")
merged_prefix = "/".join(
str(u).strip("/") for u in merge_from if u
).rstrip("/")
params["url_prefix"] = f"/{merged_prefix}"
for _attr in ["version", "strict_slashes"]:
if getattr(item, _attr) is None:
params[_attr] = getattr(
blueprint, _attr
) or options.get(_attr)
if item.version_prefix == "/v":
if blueprint.version_prefix == "/v":
params["version_prefix"] = options.get(
"version_prefix"
)
else:
params["version_prefix"] = blueprint.version_prefix
name_prefix = getattr(blueprint, "name_prefix", None)
if name_prefix and "name_prefix" not in params:
params["name_prefix"] = name_prefix
self.blueprint(item, **params)
return
if blueprint.name in self.blueprints:
assert self.blueprints[blueprint.name] is blueprint, (
'A blueprint with the name "%s" is already registered. '
"Blueprint names must be unique." % (blueprint.name,)
)
else:
self.blueprints[blueprint.name] = blueprint
self._blueprint_order.append(blueprint)
if (
self.strict_slashes is not None
and blueprint.strict_slashes is None
):
blueprint.strict_slashes = self.strict_slashes
blueprint.register(self, options)
def url_for(self, view_name: str, **kwargs):
"""Build a URL based on a view name and the values provided.
This method constructs URLs for a given view name, taking into account
various special keyword arguments that can be used to modify the resulting
URL. It can handle internal routing as well as external URLs with different
schemes.
There are several special keyword arguments that can be used to modify
the URL that is built. They each begin with an underscore. They are:
- `_anchor`
- `_external`
- `_host`
- `_server`
- `_scheme`
Args:
view_name (str): String referencing the view name.
_anchor (str): Adds an "#anchor" to the end.
_scheme (str): Should be either "http" or "https", default is "http".
_external (bool): Whether to return the path or a full URL with scheme and host.
_host (str): Used when one or more hosts are defined for a route to tell Sanic which to use.
_server (str): If not using "_host", this will be used for defining the hostname of the URL.
**kwargs: Keys and values that are used to build request parameters and
query string arguments.
Raises:
URLBuildError: If there are issues with constructing the URL.
Returns:
str: The built URL.
Examples:
Building a URL for a specific view with parameters:
```python
url_for('view_name', param1='value1', param2='value2')
# /view-name?param1=value1¶m2=value2
```
Creating an external URL with a specific scheme and anchor:
```python
url_for('view_name', _scheme='https', _external=True, _anchor='section1')
# https://example.com/view-name#section1
```
Creating a URL with a specific host:
```python
url_for('view_name', _host='subdomain.example.com')
# http://subdomain.example.com/view-name
""" # noqa: E501
# find the route by the supplied view name
kw: dict[str, str] = {}
# special static files url_for
if "." not in view_name:
view_name = f"{self.name}.{view_name}"
if view_name.endswith(".static"):
name = kwargs.pop("name", None)
if name:
view_name = view_name.replace("static", name)
kw.update(name=view_name)
route = self.router.find_route_by_view_name(view_name, **kw)
if not route:
raise URLBuildError(
f"Endpoint with name `{view_name}` was not found"
)
uri = route.path
if getattr(route.extra, "static", None):
filename = kwargs.pop("filename", "")
# it's static folder
if "__file_uri__" in uri:
folder_ = uri.split("<__file_uri__:", 1)[0]
if folder_.endswith("/"):
folder_ = folder_[:-1]
if filename.startswith("/"):
filename = filename[1:]
kwargs["__file_uri__"] = filename
if (
uri != "/"
and uri.endswith("/")
and not route.strict
and not route.raw_path[:-1]
):
uri = uri[:-1]
if not uri.startswith("/"):
uri = f"/{uri}"
out = uri
# _method is only a placeholder now, don't know how to support it
kwargs.pop("_method", None)
anchor = kwargs.pop("_anchor", "")
# _external need SERVER_NAME in config or pass _server arg
host = kwargs.pop("_host", None)
external = kwargs.pop("_external", False) or bool(host)
scheme = kwargs.pop("_scheme", "")
if route.extra.hosts and external:
if not host and len(route.extra.hosts) > 1:
raise ValueError(
f"Host is ambiguous: {', '.join(route.extra.hosts)}"
)
elif host and host not in route.extra.hosts:
raise ValueError(
f"Requested host ({host}) is not available for this "
f"route: {route.extra.hosts}"
)
elif not host:
host = list(route.extra.hosts)[0]
if scheme and not external:
raise ValueError("When specifying _scheme, _external must be True")
netloc = kwargs.pop("_server", None)
if netloc is None and external:
netloc = host or self.config.get("SERVER_NAME", "")
if external:
if not scheme:
if ":" in netloc[:8]:
scheme = netloc[:8].split(":", 1)[0]
else:
scheme = "http"
# Replace http/https with ws/wss for WebSocket handlers
if route.extra.websocket:
scheme = scheme.replace("http", "ws")
if "://" in netloc[:8]:
netloc = netloc.split("://", 1)[-1]
# find all the parameters we will need to build in the URL
# matched_params = re.findall(self.router.parameter_pattern, uri)
route.finalize()
for param_info in route.params.values():
# name, _type, pattern = self.router.parse_parameter_string(match)
# we only want to match against each individual parameter
try:
supplied_param = str(kwargs.pop(param_info.name))
except KeyError:
raise URLBuildError(
f"Required parameter `{param_info.name}` was not "
"passed to url_for"
)
# determine if the parameter supplied by the caller
# passes the test in the URL
if param_info.pattern:
pattern = (
param_info.pattern[1]
if isinstance(param_info.pattern, tuple)
else param_info.pattern
)
passes_pattern = pattern.match(supplied_param)
if not passes_pattern:
if param_info.cast is not str:
msg = (
f'Value "{supplied_param}" '
f"for parameter `{param_info.name}` does "
"not match pattern for type "
f"`{param_info.cast.__name__}`: "
f"{pattern.pattern}"
)
else:
msg = (
f'Value "{supplied_param}" for parameter '
f"`{param_info.name}` does not satisfy "
f"pattern {pattern.pattern}"
)
raise URLBuildError(msg)
# replace the parameter in the URL with the supplied value
replacement_regex = f"(<{param_info.name}.*?>)"
out = re.sub(replacement_regex, supplied_param, out)
# parse the remainder of the keyword arguments into a querystring
query_string = urlencode(kwargs, doseq=True) if kwargs else ""
# scheme://netloc/path;parameters?query#fragment
out = urlunparse((scheme, netloc, out, "", query_string, anchor))
return out
# -------------------------------------------------------------------- #
# Request Handling
# -------------------------------------------------------------------- #
async def handle_exception(
self,
request: Request,
exception: BaseException,
run_middleware: bool = True,
) -> None: # no cov
"""A handler that catches specific exceptions and outputs a response.
.. note::
This method is typically used internally, and you should not need
to call it directly.
Args:
request (Request): The current request object.
exception (BaseException): The exception that was raised.
run_middleware (bool): Whether to run middleware. Defaults
to `True`.
Raises:
ServerError: response 500.
"""
response = None
if not getattr(exception, "__dispatched__", False):
... # DO NOT REMOVE THIS LINE. IT IS NEEDED FOR TOUCHUP.
await self.dispatch(
"server.exception.report",
context={"exception": exception},
)
await self.dispatch(
"http.lifecycle.exception",
inline=True,
context={"request": request, "exception": exception},
)
if (
request.stream is not None
and request.stream.stage is not Stage.HANDLER
):
error_logger.exception(exception, exc_info=True)
logger.error(
"The error response will not be sent to the client for "
f'the following exception:"{exception}". A previous response '
"has at least partially been sent."
)
handler = self.error_handler._lookup(
exception, request.name if request else None
)
if handler:
logger.warning(
"An error occurred while handling the request after at "
"least some part of the response was sent to the client. "
"The response from your custom exception handler "
f"{handler.__name__} will not be sent to the client."
"Exception handlers should only be used to generate the "
"exception responses. If you would like to perform any "
"other action on a raised exception, consider using a "
"signal handler like "
'`@app.signal("http.lifecycle.exception")`\n'
"For further information, please see the docs: "
"https://sanicframework.org/en/guide/advanced/"
"signals.html",
)
return
# -------------------------------------------- #
# Request Middleware
# -------------------------------------------- #
if run_middleware:
try:
middleware = (
request.route and request.route.extra.request_middleware
) or self.request_middleware
response = await self._run_request_middleware(
request, middleware
)
except Exception as e:
return await self.handle_exception(request, e, False)
# No middleware results
if not response:
try:
response = self.error_handler.response(request, exception)
if isawaitable(response):
response = await response
except Exception as e:
if isinstance(e, SanicException):
response = self.error_handler.default(request, e)
elif self.debug:
response = HTTPResponse(
(
f"Error while handling error: {e}\n"
f"Stack: {format_exc()}"
),
status=500,
)
else:
response = HTTPResponse(
"An error occurred while handling an error", status=500
)
if response is not None:
try:
request.reset_response()
response = await request.respond(response)
except BaseException:
# Skip response middleware
if request.stream:
request.stream.respond(response)
await response.send(end_stream=True)
raise
else:
if request.stream:
response = request.stream.response
# Marked for cleanup and DRY with handle_request/handle_exception
# when ResponseStream is no longer supporder
if isinstance(response, BaseHTTPResponse):
await self.dispatch(
"http.lifecycle.response",
inline=True,
context={
"request": request,
"response": response,
},
)
await response.send(end_stream=True)
elif isinstance(response, ResponseStream):
resp = await response(request)
await self.dispatch(
"http.lifecycle.response",
inline=True,
context={
"request": request,
"response": resp,
},
)
await response.eof()
else:
raise ServerError(
f"Invalid response type {response!r} (need HTTPResponse)"
)
async def handle_request(self, request: Request) -> None: # no cov
"""Handles a request by dispatching it to the appropriate handler.
.. note::
This method is typically used internally, and you should not need
to call it directly.
Args:
request (Request): The current request object.
Raises:
ServerError: response 500.
"""
__tracebackhide__ = True
await self.dispatch(
"http.lifecycle.handle",
inline=True,
context={"request": request},
)
# Define `response` var here to remove warnings about
# allocation before assignment below.
response: Optional[
Union[
BaseHTTPResponse,
Coroutine[Any, Any, Optional[BaseHTTPResponse]],
ResponseStream,
]
] = None
run_middleware = True
try:
await self.dispatch(
"http.routing.before",
inline=True,
context={"request": request},
)
# Fetch handler from router
route, handler, kwargs = self.router.get(
request.path,
request.method,
request.headers.getone("host", None),
)
request._match_info = {**kwargs}
request.route = route
await self.dispatch(
"http.routing.after",
inline=True,
context={
"request": request,
"route": route,
"kwargs": kwargs,
"handler": handler,
},
)
if (
request.stream
and request.stream.request_body
and not route.extra.ignore_body
):
if hasattr(handler, "is_stream"):
# Streaming handler: lift the size limit
request.stream.request_max_size = float("inf")
else:
# Non-streaming handler: preload body
await request.receive_body()
# -------------------------------------------- #
# Request Middleware
# -------------------------------------------- #
run_middleware = False
if request.route.extra.request_middleware:
response = await self._run_request_middleware(
request, request.route.extra.request_middleware
)
# No middleware results
if not response:
# -------------------------------------------- #
# Execute Handler
# -------------------------------------------- #
if handler is None:
raise ServerError(
"'None' was returned while requesting a "
"handler from the router"
)
# Run response handler
await self.dispatch(
"http.handler.before",
inline=True,
context={"request": request},
)
response = handler(request, **request.match_info)
if isawaitable(response):
response = await response
await self.dispatch(
"http.handler.after",
inline=True,
context={"request": request},
)
if request.responded:
if response is not None:
error_logger.error(
"The response object returned by the route handler "
"will not be sent to client. The request has already "
"been responded to."
)
if request.stream is not None:
response = request.stream.response
elif response is not None:
response = await request.respond(response) # type: ignore
elif not hasattr(handler, "is_websocket"):
response = request.stream.response # type: ignore
# Marked for cleanup and DRY with handle_request/handle_exception
# when ResponseStream is no longer supporder
if isinstance(response, BaseHTTPResponse):
await self.dispatch(
"http.lifecycle.response",
inline=True,
context={
"request": request,
"response": response,
},
)
...
await response.send(end_stream=True)
elif isinstance(response, ResponseStream):
resp = await response(request)
await self.dispatch(
"http.lifecycle.response",
inline=True,
context={
"request": request,
"response": resp,
},
)
await response.eof()
else:
if not hasattr(handler, "is_websocket"):
raise ServerError(
f"Invalid response type {response!r} "
"(need HTTPResponse)"
)
except CancelledError: # type: ignore
raise
except Exception as e:
# Response Generation Failed
await self.handle_exception(
request, e, run_middleware=run_middleware
)
async def _websocket_handler(
self, handler, request, *args, subprotocols=None, **kwargs
):
if self.asgi:
ws = request.transport.get_websocket_connection()
await ws.accept(subprotocols)
else:
protocol = request.transport.get_protocol()
ws = await protocol.websocket_handshake(request, subprotocols)
await self.dispatch(
"websocket.handler.before",
inline=True,
context={"request": request, "websocket": ws},
fail_not_found=False,
)
# schedule the application handler
# its future is kept in self.websocket_tasks in case it
# needs to be cancelled due to the server being stopped
fut = ensure_future(handler(request, ws, *args, **kwargs))
self.websocket_tasks.add(fut)
cancelled = False
try:
await fut
await self.dispatch(
"websocket.handler.after",
inline=True,
context={"request": request, "websocket": ws},
reverse=True,
fail_not_found=False,
)
except (CancelledError, ConnectionClosed): # type: ignore
cancelled = True
except Exception as e:
self.error_handler.log(request, e)
await self.dispatch(
"websocket.handler.exception",
inline=True,
context={"request": request, "websocket": ws, "exception": e},
reverse=True,
fail_not_found=False,
)
finally:
self.websocket_tasks.remove(fut)
if cancelled:
ws.end_connection(1000)
else:
await ws.close()
# -------------------------------------------------------------------- #
# Testing
# -------------------------------------------------------------------- #
@property
def test_client(self) -> SanicTestClient: # type: ignore # noqa
"""A testing client that uses httpx and a live running server to reach into the application to execute handlers.
This property is available if the `sanic-testing` package is installed.
See [Test Clients](/en/plugins/sanic-testing/clients#wsgi-client-sanictestclient) for details.
Returns:
SanicTestClient: A testing client from the `sanic-testing` package.
""" # noqa: E501
if self._test_client:
return self._test_client
elif self._test_manager:
return self._test_manager.test_client
from sanic_testing.testing import SanicTestClient # type: ignore
self._test_client = SanicTestClient(self)
return self._test_client
@property
def asgi_client(self) -> SanicASGITestClient: # type: ignore # noqa
"""A testing client that uses ASGI to reach into the application to execute handlers.
This property is available if the `sanic-testing` package is installed.
See [Test Clients](/en/plugins/sanic-testing/clients#asgi-async-client-sanicasgitestclient) for details.
Returns:
SanicASGITestClient: A testing client from the `sanic-testing` package.
""" # noqa: E501
if self._asgi_client:
return self._asgi_client
elif self._test_manager:
return self._test_manager.asgi_client
from sanic_testing.testing import SanicASGITestClient # type: ignore
self._asgi_client = SanicASGITestClient(self)
return self._asgi_client
# -------------------------------------------------------------------- #
# Execution
# -------------------------------------------------------------------- #
async def _run_request_middleware(
self, request, middleware_collection
): # no cov
request._request_middleware_started = True
for middleware in middleware_collection:
await self.dispatch(
"http.middleware.before",
inline=True,
context={
"request": request,
"response": None,
},
condition={"attach_to": "request"},
)
response = middleware(request)
if isawaitable(response):
response = await response
await self.dispatch(
"http.middleware.after",
inline=True,
context={
"request": request,
"response": None,
},
condition={"attach_to": "request"},
)
if response:
return response
return None
async def _run_response_middleware(
self, request, response, middleware_collection
): # no cov
for middleware in middleware_collection:
await self.dispatch(
"http.middleware.before",
inline=True,
context={
"request": request,
"response": response,
},
condition={"attach_to": "response"},
)
_response = middleware(request, response)
if isawaitable(_response):
_response = await _response
await self.dispatch(
"http.middleware.after",
inline=True,
context={
"request": request,
"response": _response if _response else response,
},
condition={"attach_to": "response"},
)
if _response:
response = _response
if isinstance(response, BaseHTTPResponse):
response = request.stream.respond(response)
break
return response
def _build_endpoint_name(self, *parts):
parts = [self.name, *parts]
return ".".join(parts)
@classmethod
def _cancel_websocket_tasks(cls, app, loop):
for task in app.websocket_tasks:
task.cancel()
@staticmethod
async def _listener(
app: Sanic, loop: AbstractEventLoop, listener: ListenerType
):
try:
maybe_coro = listener(app) # type: ignore
except TypeError:
maybe_coro = listener(app, loop) # type: ignore
if maybe_coro and isawaitable(maybe_coro):
await maybe_coro
# -------------------------------------------------------------------- #
# Task management
# -------------------------------------------------------------------- #
@classmethod
def _prep_task(
cls,
task,
app,
loop,
):
async def do(task):
try:
if callable(task):
try:
task = task(app)
except TypeError:
task = task()
if isawaitable(task):
await task
except CancelledError:
error_logger.warning(
f"Task {task} was cancelled before it completed."
)
raise
except Exception as e:
await app.dispatch(
"server.exception.report",
context={"exception": e},
)
raise
return do(task)
@classmethod
def _loop_add_task(
cls,
task,
app,
loop,
*,
name: Optional[str] = None,
register: bool = True,
) -> Task:
tsk: Task = task
if not isinstance(task, Future):
prepped = cls._prep_task(task, app, loop)
tsk = loop.create_task(prepped, name=name)
if name and register:
app._task_registry[name] = tsk
return tsk
@staticmethod
async def dispatch_delayed_tasks(
app: Sanic,
loop: AbstractEventLoop,
) -> None:
"""Signal handler for dispatching delayed tasks.
This is used to dispatch tasks that were added before the loop was
started, and will be called after the loop has started. It is
not typically used directly.
Args:
app (Sanic): The Sanic application instance.
loop (AbstractEventLoop): The event loop in which the tasks are
being run.
Returns:
None
"""
for name in app._delayed_tasks:
await app.dispatch(name, context={"app": app, "loop": loop})
app._delayed_tasks.clear()
@staticmethod
async def run_delayed_task(
app: Sanic,
loop: AbstractEventLoop,
task: Union[Future[Any], Task[Any], Awaitable[Any]],
) -> None:
"""Executes a delayed task within the context of a given app and loop.
This method prepares a given task by invoking the app's private
`_prep_task` method and then awaits the execution of the prepared task.
Args:
app (Any): The application instance on which the task will
be executed.
loop (AbstractEventLoop): The event loop where the task will
be scheduled.
task (Task[Any]): The task function that will be prepared
and executed.
Returns:
None
"""
prepped = app._prep_task(task, app, loop)
await prepped
def add_task(
self,
task: Union[Future[Any], Coroutine[Any, Any, Any], Awaitable[Any]],
*,
name: Optional[str] = None,
register: bool = True,
) -> Optional[Task[Any]]:
"""Schedule a task to run later, after the loop has started.
While this is somewhat similar to `asyncio.create_task`, it can be
used before the loop has started (in which case it will run after the
loop has started in the `before_server_start` listener).
Naming tasks is a good practice as it allows you to cancel them later,
and allows Sanic to manage them when the server is stopped, if needed.
[See user guide re: background tasks](/en/guide/basics/tasks#background-tasks)
Args:
task (Union[Future[Any], Coroutine[Any, Any, Any], Awaitable[Any]]):
The future, coroutine, or awaitable to schedule.
name (Optional[str], optional): The name of the task, if needed for
later reference. Defaults to `None`.
register (bool, optional): Whether to register the task. Defaults
to `True`.
Returns:
Optional[Task[Any]]: The task that was scheduled, if applicable.
""" # noqa: E501
try:
loop = self.loop # Will raise SanicError if loop is not started
return self._loop_add_task(
task, self, loop, name=name, register=register
)
except SanicException:
task_name = f"sanic.delayed_task.{hash(task)}"
if not self._delayed_tasks:
self.after_server_start(partial(self.dispatch_delayed_tasks))
if name:
raise RuntimeError(
"Cannot name task outside of a running application"
)
self.signal(task_name)(partial(self.run_delayed_task, task=task))
self._delayed_tasks.append(task_name)
return None
@overload
def get_task(
self, name: str, *, raise_exception: Literal[True]
) -> Task: ...
@overload
def get_task(
self, name: str, *, raise_exception: Literal[False]
) -> Optional[Task]: ...
@overload
def get_task(
self, name: str, *, raise_exception: bool
) -> Optional[Task]: ...
def get_task(
self, name: str, *, raise_exception: bool = True
) -> Optional[Task]:
"""Get a named task.
This method is used to get a task by its name. Optionally, you can
control whether an exception should be raised if the task is not found.
Args:
name (str): The name of the task to be retrieved.
raise_exception (bool): If `True`, an exception will be raised if
the task is not found. Defaults to `True`.
Returns:
Optional[Task]: The task, if found.
"""
try:
return self._task_registry[name]
except KeyError:
if raise_exception:
raise SanicException(
f'Registered task named "{name}" not found.'
)
return None
async def cancel_task(
self,
name: str,
msg: Optional[str] = None,
*,
raise_exception: bool = True,
) -> None:
"""Cancel a named task.
This method is used to cancel a task by its name. Optionally, you can
provide a message that describes why the task was canceled, and control
whether an exception should be raised if the task is not found.
Args:
name (str): The name of the task to be canceled.
msg (Optional[str]): Optional message describing why the task was canceled. Defaults to None.
raise_exception (bool): If True, an exception will be raised if the task is not found. Defaults to True.
Example:
```python
async def my_task():
try:
await asyncio.sleep(10)
except asyncio.CancelledError as e:
current_task = asyncio.current_task()
print(f"Task {current_task.get_name()} was cancelled. {e}")
# Task sleepy_task was cancelled. No more sleeping!
@app.before_server_start
async def before_start(app):
app.add_task(my_task, name="sleepy_task")
await asyncio.sleep(1)
await app.cancel_task("sleepy_task", msg="No more sleeping!")
```
""" # noqa: E501
task = self.get_task(name, raise_exception=raise_exception)
if task and not task.cancelled():
args: tuple[str, ...] = ()
if msg:
args = (msg,)
task.cancel(*args)
try:
await task
except CancelledError:
...
def purge_tasks(self) -> None:
"""Purges completed and cancelled tasks from the task registry.
This method iterates through the task registry, identifying any tasks
that are either done or cancelled, and then removes those tasks,
leaving only the pending tasks in the registry.
"""
for key, task in self._task_registry.items():
if task is None:
continue
if task.done() or task.cancelled():
self._task_registry[key] = None
self._task_registry = {
k: v for k, v in self._task_registry.items() if v is not None
}
def shutdown_tasks(
self, timeout: Optional[float] = None, increment: float = 0.1
) -> None:
"""Cancel all tasks except the server task.
This method is used to cancel all tasks except the server task. It
iterates through the task registry, cancelling all tasks except the
server task, and then waits for the tasks to complete. Optionally, you
can provide a timeout and an increment to control how long the method
will wait for the tasks to complete.
Args:
timeout (Optional[float]): The amount of time to wait for the tasks
to complete. Defaults to `None`.
increment (float): The amount of time to wait between checks for
whether the tasks have completed. Defaults to `0.1`.
"""
for task in self.tasks:
if task.get_name() != "RunServer":
task.cancel()
if timeout is None:
timeout = self.config.GRACEFUL_SHUTDOWN_TIMEOUT
while len(self._task_registry) and timeout:
with suppress(RuntimeError):
running_loop = get_running_loop()
running_loop.run_until_complete(asyncio.sleep(increment))
self.purge_tasks()
timeout -= increment
@property
def tasks(self) -> Iterable[Task[Any]]:
"""The tasks that are currently registered with the application.
Returns:
Iterable[Task[Any]]: The tasks that are currently registered with
the application.
"""
return (
task
for task in iter(self._task_registry.values())
if task is not None
)
# -------------------------------------------------------------------- #
# ASGI
# -------------------------------------------------------------------- #
async def __call__(self, scope, receive, send):
"""
To be ASGI compliant, our instance must be a callable that accepts
three arguments: scope, receive, send. See the ASGI reference for more
details: https://asgi.readthedocs.io/en/latest
"""
if scope["type"] == "lifespan":
setup_logging(self.state.is_debug, self.config.NO_COLOR)
self.asgi = True
self.motd("")
self._asgi_lifespan = Lifespan(self, scope, receive, send)
await self._asgi_lifespan()
else:
self._asgi_app = await ASGIApp.create(self, scope, receive, send)
await self._asgi_app()
_asgi_single_callable = True # We conform to ASGI 3.0 single-callable
# -------------------------------------------------------------------- #
# Configuration
# -------------------------------------------------------------------- #
def update_config(self, config: Union[bytes, str, dict, Any]) -> None:
"""Update the application configuration.
This method is used to update the application configuration. It can
accept a configuration object, a dictionary, or a path to a file that
contains a configuration object or dictionary.
See [Configuration](/en/guide/deployment/configuration) for details.
Args:
config (Union[bytes, str, dict, Any]): The configuration object,
dictionary, or path to a configuration file.
"""
self.config.update_config(config)
@property
def asgi(self) -> bool:
"""Whether the app is running in ASGI mode."""
return self.state.asgi
@asgi.setter
def asgi(self, value: bool):
self.state.asgi = value
@property
def debug(self) -> bool:
"""Whether the app is running in debug mode."""
return self.state.is_debug
@property
def auto_reload(self) -> bool:
"""Whether the app is running in auto-reload mode."""
return self.config.AUTO_RELOAD
@auto_reload.setter
def auto_reload(self, value: bool):
self.config.AUTO_RELOAD = value
self.state.auto_reload = value
@property
def state(self) -> ApplicationState: # type: ignore
"""The application state.
Returns:
ApplicationState: The current state of the application.
"""
return self._state
@property
def reload_dirs(self) -> set[Path]:
"""The directories that are monitored for auto-reload.
Returns:
Set[str]: The set of directories that are monitored for
auto-reload.
"""
return self.state.reload_dirs
# -------------------------------------------------------------------- #
# Sanic Extensions
# -------------------------------------------------------------------- #
@property
def ext(self) -> Extend:
"""Convenience property for accessing Sanic Extensions.
This property is available if the `sanic-ext` package is installed.
See [Sanic Extensions](/en/plugins/sanic-ext/getting-started)
for details.
Returns:
Extend: The Sanic Extensions instance.
Examples:
A typical use case might be for registering a dependency injection.
```python
app.ext.dependency(SomeObject())
```
"""
if not hasattr(self, "_ext"):
setup_ext(self, fail=True)
if not hasattr(self, "_ext"):
raise RuntimeError(
"Sanic Extensions is not installed. You can add it to your "
"environment using:\n$ pip install sanic[ext]\nor\n$ pip "
"install sanic-ext"
)
return self._ext # type: ignore
def extend(
self,
*,
extensions: Optional[list[type[Extension]]] = None,
built_in_extensions: bool = True,
config: Optional[Union[Config, dict[str, Any]]] = None,
**kwargs,
) -> Extend:
"""Extend Sanic with additional functionality using Sanic Extensions.
This method enables you to add one or more Sanic Extensions to the
current Sanic instance. It allows for more control over the Extend
object, such as enabling or disabling built-in extensions or providing
custom configuration.
See [Sanic Extensions](/en/plugins/sanic-ext/getting-started)
for details.
Args:
extensions (Optional[List[Type[Extension]]], optional): A list of
extensions to add. Defaults to `None`, meaning only built-in
extensions are added.
built_in_extensions (bool, optional): Whether to enable built-in
extensions. Defaults to `True`.
config (Optional[Union[Config, Dict[str, Any]]], optional):
Optional custom configuration for the extensions. Defaults
to `None`.
**kwargs: Additional keyword arguments that might be needed by
specific extensions.
Returns:
Extend: The Sanic Extensions instance.
Raises:
RuntimeError: If an attempt is made to extend Sanic after Sanic
Extensions has already been set up.
Examples:
A typical use case might be to add a custom extension along with
built-in ones.
```python
app.extend(
extensions=[MyCustomExtension],
built_in_extensions=True
)
```
"""
if hasattr(self, "_ext"):
raise RuntimeError(
"Cannot extend Sanic after Sanic Extensions has been setup."
)
setup_ext(
self,
extensions=extensions,
built_in_extensions=built_in_extensions,
config=config,
fail=True,
**kwargs,
)
return self.ext
# -------------------------------------------------------------------- #
# Class methods
# -------------------------------------------------------------------- #
@classmethod
def register_app(cls, app: Sanic) -> None:
"""Register a Sanic instance with the class registry.
This method adds a Sanic application instance to the class registry,
which is used for tracking all instances of the application. It is
usually used internally, but can be used to register an application
that may have otherwise been created outside of the class registry.
Args:
app (Sanic): The Sanic instance to be registered.
Raises:
SanicException: If the app is not an instance of Sanic or if the
name of the app is already in use (unless in test mode).
Examples:
```python
Sanic.register_app(my_app)
```
"""
if not isinstance(app, cls):
raise SanicException("Registered app must be an instance of Sanic")
name = app.name
if name in cls._app_registry and not cls.test_mode:
raise SanicException(f'Sanic app name "{name}" already in use.')
cls._app_registry[name] = app
@classmethod
def unregister_app(cls, app: Sanic) -> None:
"""Unregister a Sanic instance from the class registry.
This method removes a previously registered Sanic application instance
from the class registry. This can be useful for cleanup purposes,
especially in testing or when an app instance is no longer needed. But,
it is typically used internally and should not be needed in most cases.
Args:
app (Sanic): The Sanic instance to be unregistered.
Raises:
SanicException: If the app is not an instance of Sanic.
Examples:
```python
Sanic.unregister_app(my_app)
```
"""
if not isinstance(app, cls):
raise SanicException("Registered app must be an instance of Sanic")
name = app.name
if name in cls._app_registry:
del cls._app_registry[name]
@classmethod
def get_app(
cls, name: Optional[str] = None, *, force_create: bool = False
) -> Sanic:
"""Retrieve an instantiated Sanic instance by name.
This method is best used when needing to get access to an already
defined application instance in another part of an app.
.. warning::
Be careful when using this method in the global scope as it is
possible that the import path running will cause it to error if
the imported global scope runs before the application instance
is created.
It is typically best used in a function or method that is called
after the application instance has been created.
```python
def setup_routes():
app = Sanic.get_app()
app.add_route(handler_1, '/route1')
app.add_route(handler_2, '/route2')
```
Args:
name (Optional[str], optional): Name of the application instance
to retrieve. When not specified, it will return the only
application instance if there is only one. If not specified
and there are multiple application instances, it will raise
an exception. Defaults to `None`.
force_create (bool, optional): If `True` and the named app does
not exist, a new instance will be created. Defaults to `False`.
Returns:
Sanic: The requested Sanic app instance.
Raises:
SanicException: If there are multiple or no Sanic apps found, or
if the specified name is not found.
Example:
```python
app1 = Sanic("app1")
app2 = Sanic.get_app("app1") # app2 is the same instance as app1
```
"""
if name is None:
if len(cls._app_registry) > 1:
raise SanicException(
'Multiple Sanic apps found, use Sanic.get_app("app_name")'
)
elif len(cls._app_registry) == 0:
raise SanicException("No Sanic apps have been registered.")
else:
return list(cls._app_registry.values())[0]
try:
return cls._app_registry[name]
except KeyError:
if name == "__main__":
return cls.get_app("__mp_main__", force_create=force_create)
if force_create:
return cls(name)
raise SanicException(
f"Sanic app name '{name}' not found.\n"
"App instantiation must occur outside "
"if __name__ == '__main__' "
"block or by using an AppLoader.\nSee "
"https://sanic.dev/en/guide/deployment/app-loader.html"
" for more details."
)
@classmethod
def _check_uvloop_conflict(cls) -> None:
values = {app.config.USE_UVLOOP for app in cls._app_registry.values()}
if len(values) > 1:
error_logger.warning(
"It looks like you're running several apps with different "
"uvloop settings. This is not supported and may lead to "
"unintended behaviour."
)
# -------------------------------------------------------------------- #
# Lifecycle
# -------------------------------------------------------------------- #
@contextmanager
def amend(self) -> Iterator[None]:
"""Context manager to allow changes to the app after it has started.
Typically, once an application has started and is running, you cannot
make certain changes, like adding routes, middleware, or signals. This
context manager allows you to make those changes, and then finalizes
the app again when the context manager exits.
Yields:
None
Example:
```python
with app.amend():
app.add_route(handler, '/new_route')
```
"""
if not self.state.is_started:
yield
else:
do_router = self.router.finalized
do_signal_router = self.signal_router.finalized
if do_router:
self.router.reset()
if do_signal_router:
self.signal_router.reset()
yield
if do_signal_router:
self.signalize(cast(bool, self.config.TOUCHUP))
if do_router:
self.finalize()
def finalize(self) -> None:
"""Finalize the routing configuration for the Sanic application.
This method completes the routing setup by calling the router's
finalize method, and it also finalizes any middleware that has been
added to the application. If the application is not in test mode,
any finalization errors will be raised.
Finalization consists of identifying defined routes and optimizing
Sanic's performance to meet the application's specific needs. If
you are manually adding routes, after Sanic has started, you will
typically want to use the `amend` context manager rather than
calling this method directly.
.. note::
This method is usually called internally during the server setup
process and does not typically need to be invoked manually.
Raises:
FinalizationError: If there is an error during the finalization
process, and the application is not in test mode.
Example:
```python
app.finalize()
```
"""
try:
self.router.finalize()
except FinalizationError as e:
if not Sanic.test_mode:
raise e
self.finalize_middleware()
def signalize(self, allow_fail_builtin: bool = True) -> None:
"""Finalize the signal handling configuration for the Sanic application.
This method completes the signal handling setup by calling the signal
router's finalize method. If the application is not in test mode,
any finalization errors will be raised.
Finalization consists of identifying defined signaliz and optimizing
Sanic's performance to meet the application's specific needs. If
you are manually adding signals, after Sanic has started, you will
typically want to use the `amend` context manager rather than
calling this method directly.
.. note::
This method is usually called internally during the server setup
process and does not typically need to be invoked manually.
Args:
allow_fail_builtin (bool, optional): If set to `True`, will allow
built-in signals to fail during the finalization process.
Defaults to `True`.
Raises:
FinalizationError: If there is an error during the signal
finalization process, and the application is not in test mode.
Example:
```python
app.signalize(allow_fail_builtin=False)
```
""" # noqa: E501
self.signal_router.allow_fail_builtin = allow_fail_builtin
try:
self.signal_router.finalize()
except FinalizationError as e:
if not Sanic.test_mode:
raise e
async def _startup(self):
self._future_registry.clear()
if not hasattr(self, "_ext"):
setup_ext(self)
if hasattr(self, "_ext"):
self.ext._display()
if self.state.is_debug and self.config.TOUCHUP is not True:
self.config.TOUCHUP = False
elif isinstance(self.config.TOUCHUP, Default):
self.config.TOUCHUP = True
# Setup routers
self.signalize(self.config.TOUCHUP)
self.finalize()
route_names = [route.extra.ident for route in self.router.routes]
duplicates = {
name for name in route_names if route_names.count(name) > 1
}
if duplicates:
names = ", ".join(duplicates)
message = (
f"Duplicate route names detected: {names}. You should rename "
"one or more of them explicitly by using the `name` param, "
"or changing the implicit name derived from the class and "
"function name. For more details, please see "
"https://sanic.dev/en/guide/release-notes/v23.3.html#duplicated-route-names-are-no-longer-allowed" # noqa
)
raise ServerError(message)
Sanic._check_uvloop_conflict()
# Startup time optimizations
if self.state.primary:
# TODO:
# - Raise warning if secondary apps have error handler config
if self.config.TOUCHUP:
TouchUp.run(self)
self.state.is_started = True
def ack(self) -> None:
"""Shorthand to send an ack message to the Server Manager.
In general, this should usually not need to be called manually.
It is used to tell the Manager that a process is operational and
ready to begin operation.
"""
if hasattr(self, "multiplexer"):
self.multiplexer.ack()
def set_serving(self, serving: bool) -> None:
"""Set the serving state of the application.
This method is used to set the serving state of the application.
It is used internally by Sanic and should not typically be called
manually.
Args:
serving (bool): Whether the application is serving.
"""
self.state.is_running = serving
if hasattr(self, "multiplexer"):
self.multiplexer.set_serving(serving)
async def _server_event(
self,
concern: str,
action: str,
loop: Optional[AbstractEventLoop] = None,
) -> None:
event = f"server.{concern}.{action}"
if action not in ("before", "after") or concern not in (
"init",
"shutdown",
):
raise SanicException(f"Invalid server event: {event}")
logger.debug(
f"Triggering server events: {event}", extra={"verbosity": 1}
)
reverse = concern == "shutdown"
if loop is None:
loop = self.loop
await self.dispatch(
event,
fail_not_found=False,
reverse=reverse,
inline=True,
context={
"app": self,
"loop": loop,
},
)
# -------------------------------------------------------------------- #
# Process Management
# -------------------------------------------------------------------- #
def refresh(
self,
passthru: Optional[dict[str, Any]] = None,
) -> Sanic:
"""Refresh the application instance. **This is used internally by Sanic**.
.. warning::
This method is intended for internal use only and should not be
called directly.
Args:
passthru (Optional[Dict[str, Any]], optional): Optional dictionary
of attributes to pass through to the new instance. Defaults to
`None`.
Returns:
Sanic: The refreshed application instance.
""" # noqa: E501
registered = self.__class__.get_app(self.name)
if self is not registered:
if not registered.state.server_info:
registered.state.server_info = self.state.server_info
self = registered
if passthru:
for attr, info in passthru.items():
if isinstance(info, dict):
for key, value in info.items():
setattr(getattr(self, attr), key, value)
else:
setattr(self, attr, info)
if hasattr(self, "multiplexer"):
self.shared_ctx.lock()
return self
@property
def inspector(self) -> Inspector:
"""An instance of Inspector for accessing the application's state.
This can only be accessed from a worker process, and only if the
inspector has been enabled.
See [Inspector](/en/guide/deployment/inspector) for details.
Returns:
Inspector: An instance of Inspector.
"""
if environ.get("SANIC_WORKER_PROCESS") or not self._inspector:
raise SanicException(
"Can only access the inspector from the main process "
"after main_process_start has run. For example, you most "
"likely want to use it inside the @app.main_process_ready "
"event listener."
)
return self._inspector
@property
def manager(self) -> WorkerManager:
"""
Property to access the WorkerManager instance.
This property provides access to the WorkerManager object controlling
the worker processes. It can only be accessed from the main process.
.. note::
Make sure to only access this property from the main process,
as attempting to do so from a worker process will result
in an exception.
See [WorkerManager](/en/guide/deployment/manager) for details.
Returns:
WorkerManager: The manager responsible for managing
worker processes.
Raises:
SanicException: If an attempt is made to access the manager
from a worker process or if the manager is not initialized.
Example:
```python
app.manager.manage(...)
```
"""
if environ.get("SANIC_WORKER_PROCESS") or not self._manager:
raise SanicException(
"Can only access the manager from the main process "
"after main_process_start has run. For example, you most "
"likely want to use it inside the @app.main_process_ready "
"event listener."
)
return self._manager
| Sanic |
python | sympy__sympy | sympy/physics/control/lti.py | {
"start": 106306,
"end": 116900
} | class ____(SISOLinearTimeInvariant):
r"""
A class for representing a parallel configuration of SISO systems.
Parameters
==========
args : SISOLinearTimeInvariant
SISO systems in a parallel arrangement.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``Parallel(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed.
Examples
========
>>> from sympy import Matrix
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel, Series, StateSpace
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf3 = TransferFunction(p**2, p + s, s)
>>> P1 = Parallel(tf1, tf2)
>>> P1
Parallel(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s))
>>> P1.var
s
>>> P2 = Parallel(tf2, Series(tf3, -tf1))
>>> P2
Parallel(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), Series(TransferFunction(p**2, p + s, s), TransferFunction(-a*p**2 - b*s, -p + s, s)))
>>> P2.var
s
>>> P3 = Parallel(Series(tf1, tf2), Series(tf2, tf3))
>>> P3
Parallel(Series(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)), Series(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), TransferFunction(p**2, p + s, s)))
>>> P3.var
s
You can get the resultant transfer function by using ``.doit()`` method:
>>> Parallel(tf1, tf2, -tf3).doit()
TransferFunction(-p**2*(-p + s)*(s**4 + 5*s + 6) + (-p + s)*(p + s)*(s**3 - 2) + (p + s)*(a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
>>> Parallel(tf2, Series(tf1, -tf3)).doit()
TransferFunction(-p**2*(a*p**2 + b*s)*(s**4 + 5*s + 6) + (-p + s)*(p + s)*(s**3 - 2), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
Parallel can be used to connect SISO ``StateSpace`` systems together.
>>> A1 = Matrix([[-1]])
>>> B1 = Matrix([[1]])
>>> C1 = Matrix([[-1]])
>>> D1 = Matrix([1])
>>> A2 = Matrix([[0]])
>>> B2 = Matrix([[1]])
>>> C2 = Matrix([[1]])
>>> D2 = Matrix([[0]])
>>> ss1 = StateSpace(A1, B1, C1, D1)
>>> ss2 = StateSpace(A2, B2, C2, D2)
>>> P4 = Parallel(ss1, ss2)
>>> P4
Parallel(StateSpace(Matrix([[-1]]), Matrix([[1]]), Matrix([[-1]]), Matrix([[1]])), StateSpace(Matrix([[0]]), Matrix([[1]]), Matrix([[1]]), Matrix([[0]])))
``doit()`` can be used to find ``StateSpace`` equivalent for the system containing ``StateSpace`` objects.
>>> P4.doit()
StateSpace(Matrix([
[-1, 0],
[ 0, 0]]), Matrix([
[1],
[1]]), Matrix([[-1, 1]]), Matrix([[1]]))
>>> P4.rewrite(TransferFunction)
TransferFunction(s*(s + 1) + 1, s*(s + 1), s)
Notes
=====
All the transfer functions should use the same complex variable
``var`` of the Laplace transform.
See Also
========
Series, TransferFunction, Feedback
"""
def __new__(cls, *args, evaluate=False):
args = _flatten_args(args, Parallel)
obj = super().__new__(cls, *args)
# For StateSpace parallel connection
if args and _any_state_space_systems(args):
# Check for SISO
if any(not arg.is_SISO for arg in args):
raise ValueError(filldedent("""
To use Parallel connection for MIMO systems use
MIMOParallel instead."""))
obj._is_parallel_StateSpace = True
else:
obj._is_parallel_StateSpace = False
obj._check_args(args)
_check_time_compatibility(args)
obj._is_continuous = args[0].is_continuous
return obj.doit() if evaluate else obj
def __repr__(self):
systems_repr = ', '.join(repr(system) for system in self.args)
return f"Parallel({systems_repr})"
__str__ = __repr__
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, Parallel, Series
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> Parallel(G1, G2).var
p
>>> Parallel(-G3, Series(G1, G2)).var
p
"""
return self.args[0].var
def doit(self, **hints):
"""
Returns the resultant transfer function or state space obtained by
parallel connection of transfer functions or state space objects.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> Parallel(tf2, tf1).doit()
TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s)
>>> Parallel(-tf1, -tf2).doit()
TransferFunction((2 - s**3)*(-p + s) + (-a*p**2 - b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s)
"""
if self._is_parallel_StateSpace:
# Return the equivalent StateSpace model
ss_class = StateSpace if self.is_continuous else DiscreteStateSpace
res = self.args[0].doit()
if not isinstance(res, ss_class):
res = res.rewrite(ss_class)
for arg in self.args[1:]:
if not isinstance(arg, ss_class):
arg = arg.doit().rewrite(ss_class)
res += arg
return res
_arg = (arg.doit().to_expr() for arg in self.args)
res = Add(*_arg).as_numer_denom()
sampling_time = self.args[0].sampling_time
return create_transfer_function(*res, self.var, sampling_time)
def _eval_rewrite_as_TransferFunction(self, *args, **kwargs):
if not self.is_continuous:
raise TypeError("""
Cannot rewrite a discrete-time Parallel object as a
TransferFunction.""")
if self._is_parallel_StateSpace:
return self.doit().rewrite(TransferFunction)[0][0]
return self.doit()
def _eval_rewrite_as_DiscreteTransferFunction(self, *args, **kwargs):
if self.is_continuous:
raise TypeError("""
Cannot rewrite a continuous-time Parallel object as a
DiscreteTransferFunction.""")
if self._is_parallel_StateSpace:
return self.doit().rewrite(DiscreteTransferFunction)[0][0]
return self.doit()
@_compatibility_decorator
@_check_other_SISO
def __add__(self, other):
self_arg_list = list(self.args)
return Parallel(*self_arg_list, other)
__radd__ = __add__
@_compatibility_decorator
@_check_other_SISO
def __sub__(self, other):
return self + (-other)
@_compatibility_decorator
def __rsub__(self, other):
return -self + other
@_compatibility_decorator
@_check_other_SISO
def __mul__(self, other):
if isinstance(other, Series):
arg_list = list(other.args)
return Series(self, *arg_list)
return Series(self, other)
def __neg__(self):
return Series(create_transfer_function(-1, 1, self.var, self.sampling_time), self)
def to_expr(self):
"""Returns the equivalent ``Expr`` object."""
return Add(*(arg.to_expr() for arg in self.args), evaluate=False)
@property
def is_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is less than or equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
>>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*s + 2, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> P1 = Parallel(-tf2, tf1)
>>> P1.is_proper
False
>>> P2 = Parallel(tf2, tf3)
>>> P2.is_proper
True
"""
return self.doit().is_proper
@property
def is_strictly_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is strictly less than degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> P1 = Parallel(tf1, tf2)
>>> P1.is_strictly_proper
False
>>> P2 = Parallel(tf2, tf3)
>>> P2.is_strictly_proper
True
"""
return self.doit().is_strictly_proper
@property
def is_biproper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(p**2, p + s, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> P1 = Parallel(tf1, -tf2)
>>> P1.is_biproper
True
>>> P2 = Parallel(tf2, tf3)
>>> P2.is_biproper
False
"""
return self.doit().is_biproper
@property
def is_StateSpace_object(self):
return self._is_parallel_StateSpace
@property
def sampling_time(self):
return self.args[0].sampling_time
| Parallel |
python | pypa__setuptools | setuptools/_static.py | {
"start": 2406,
"end": 3209
} | class ____(list, Static):
"""
:meta private:
>>> x = List([1, 2, 3])
>>> is_static(x)
True
>>> x += [0] # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
SetuptoolsDeprecationWarning: Direct modification ...
>>> is_static(x) # no longer static after modification
False
>>> y = list(x)
>>> y.clear()
>>> y
[]
>>> y == x
False
>>> is_static(List(y))
True
"""
# Make `List` immutable-ish
# (certain places of setuptools/distutils issue a warn if we use tuple instead of list)
for _method in (
'__delitem__',
'__iadd__',
'__setitem__',
'append',
'clear',
'extend',
'insert',
'remove',
'reverse',
'pop',
):
_prevent_modification(List, _method, "`list(value)`")
| List |
python | numba__llvmlite | llvmlite/ir/values.py | {
"start": 31149,
"end": 31551
} | class ____(_BaseArgument):
"""
The specification of a function argument.
"""
def __str__(self):
attrs = self.attributes._to_list(self.type)
if attrs:
return "{0} {1} {2}".format(self.type, ' '.join(attrs),
self.get_reference())
else:
return "{0} {1}".format(self.type, self.get_reference())
| Argument |
python | django__django | django/contrib/gis/feeds.py | {
"start": 4906,
"end": 5455
} | class ____(Rss201rev2Feed, GeoFeedMixin):
def rss_attributes(self):
attrs = super().rss_attributes()
attrs["xmlns:geo"] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
return attrs
def add_item_elements(self, handler, item):
super().add_item_elements(handler, item)
self.add_georss_element(handler, item, w3c_geo=True)
def add_root_elements(self, handler):
super().add_root_elements(handler)
self.add_georss_element(handler, self.feed, w3c_geo=True)
# ### Feed subclass ###
| W3CGeoFeed |
python | pallets__click | src/click/core.py | {
"start": 75122,
"end": 77203
} | class ____(Group):
"""A :class:`Group` that looks up subcommands on other groups. If a command
is not found on this group, each registered source is checked in order.
Parameters on a source are not added to this group, and a source's callback
is not invoked when invoking its commands. In other words, this "flattens"
commands in many groups into this one group.
:param name: The name of the group command.
:param sources: A list of :class:`Group` objects to look up commands from.
:param kwargs: Other arguments passed to :class:`Group`.
.. versionchanged:: 8.2
This is a subclass of ``Group``. Commands are looked up first on this
group, then each of its sources.
"""
def __init__(
self,
name: str | None = None,
sources: list[Group] | None = None,
**kwargs: t.Any,
) -> None:
super().__init__(name, **kwargs)
#: The list of registered groups.
self.sources: list[Group] = sources or []
def add_source(self, group: Group) -> None:
"""Add a group as a source of commands."""
self.sources.append(group)
def get_command(self, ctx: Context, cmd_name: str) -> Command | None:
rv = super().get_command(ctx, cmd_name)
if rv is not None:
return rv
for source in self.sources:
rv = source.get_command(ctx, cmd_name)
if rv is not None:
if self.chain:
_check_nested_chain(self, cmd_name, rv)
return rv
return None
def list_commands(self, ctx: Context) -> list[str]:
rv: set[str] = set(super().list_commands(ctx))
for source in self.sources:
rv.update(source.list_commands(ctx))
return sorted(rv)
def _check_iter(value: t.Any) -> cabc.Iterator[t.Any]:
"""Check if the value is iterable but not a string. Raises a type
error, or return an iterator over the value.
"""
if isinstance(value, str):
raise TypeError
return iter(value)
| CommandCollection |
python | falconry__falcon | tests/test_before_hooks.py | {
"start": 2918,
"end": 3181
} | class ____:
@falcon.before(validate_param, 'limit', 100)
@falcon.before(parse_body)
def on_get(self, req, resp, doc=None):
self.req = req
self.resp = resp
self.doc = doc
@falcon.before(bunnies)
| WrappedRespondersBodyParserResource |
python | ray-project__ray | python/ray/_private/serialization.py | {
"start": 4776,
"end": 32085
} | class ____:
"""Initialize the serialization library.
This defines a custom serializer for object refs and also tells ray to
serialize several exception classes that we define for error handling.
"""
def __init__(self, worker):
self.worker = worker
self._thread_local = threading.local()
# This flag is to mark whether the custom serializer for torch.Tensor has
# been registered. If the method is decorated with
# `@ray.method(tensor_transport="xxx")`, it will use external transport
# (e.g. gloo, nccl, etc.) for tensor communication between actors,
# instead of the normal serialize -> object store -> deserialize codepath.
self._torch_custom_serializer_registered = False
# Enable zero-copy serialization of tensors if the environment variable is set.
self._zero_copy_tensors_enabled = (
ray_constants.RAY_ENABLE_ZERO_COPY_TORCH_TENSORS
)
if self._zero_copy_tensors_enabled:
try:
import torch
self._register_cloudpickle_reducer(
torch.Tensor, tensor_serialization_utils.zero_copy_tensors_reducer
)
except ImportError:
# Warn and disable zero-copy tensor serialization when PyTorch is missing,
# even if RAY_ENABLE_ZERO_COPY_TORCH_TENSORS is set.
warnings.warn(
"PyTorch is not installed. Disabling zero-copy tensor serialization "
"even though RAY_ENABLE_ZERO_COPY_TORCH_TENSORS is set.",
tensor_serialization_utils.ZeroCopyTensorsWarning,
stacklevel=3,
)
self._zero_copy_tensors_enabled = False
def actor_handle_reducer(obj):
ray._private.worker.global_worker.check_connected()
serialized, actor_handle_id, weak_ref = obj._serialization_helper()
# Update ref counting for the actor handle
if not weak_ref:
self.add_contained_object_ref(
actor_handle_id,
# Right now, so many tests are failing when this is set.
# Allow it for now, but we should eventually disallow it here.
allow_out_of_band_serialization=True,
)
return _actor_handle_deserializer, (serialized, weak_ref)
self._register_cloudpickle_reducer(ray.actor.ActorHandle, actor_handle_reducer)
def compiled_dag_ref_reducer(obj):
raise TypeError("Serialization of CompiledDAGRef is not supported.")
self._register_cloudpickle_reducer(CompiledDAGRef, compiled_dag_ref_reducer)
def object_ref_reducer(obj):
worker = ray._private.worker.global_worker
worker.check_connected()
self.add_contained_object_ref(
obj,
allow_out_of_band_serialization=(
ALLOW_OUT_OF_BAND_OBJECT_REF_SERIALIZATION
),
call_site=obj.call_site(),
)
obj, owner_address, object_status = worker.core_worker.serialize_object_ref(
obj
)
# Check if this is a GPU ObjectRef being serialized inside a collection
if (
self.is_in_band_serialization()
and worker.gpu_object_manager.is_managed_object(obj.hex())
):
gpu_object_manager = (
ray._private.worker.global_worker.gpu_object_manager
)
gpu_object_meta = gpu_object_manager._get_gpu_object_metadata(obj)
return _gpu_object_ref_deserializer, (
obj.binary(),
obj.call_site(),
owner_address,
object_status,
obj.tensor_transport(),
gpu_object_meta,
)
return _object_ref_deserializer, (
obj.binary(),
obj.call_site(),
owner_address,
object_status,
obj.tensor_transport(),
)
self._register_cloudpickle_reducer(ray.ObjectRef, object_ref_reducer)
def object_ref_generator_reducer(obj):
return DynamicObjectRefGenerator, (obj._refs,)
self._register_cloudpickle_reducer(
DynamicObjectRefGenerator, object_ref_generator_reducer
)
serialization_addons.apply(self)
def _register_cloudpickle_reducer(self, cls, reducer):
pickle.CloudPickler.dispatch[cls] = reducer
def _unregister_cloudpickle_reducer(self, cls):
pickle.CloudPickler.dispatch.pop(cls, None)
def _register_cloudpickle_serializer(
self, cls, custom_serializer, custom_deserializer
):
def _CloudPicklerReducer(obj):
return custom_deserializer, (custom_serializer(obj),)
# construct a reducer
pickle.CloudPickler.dispatch[cls] = _CloudPicklerReducer
def is_in_band_serialization(self):
return getattr(self._thread_local, "in_band", False)
def set_in_band_serialization(self):
self._thread_local.in_band = True
def set_out_of_band_serialization(self):
self._thread_local.in_band = False
def get_outer_object_ref(self):
stack = getattr(self._thread_local, "object_ref_stack", [])
return stack[-1] if stack else None
def get_and_clear_contained_object_refs(self):
if not hasattr(self._thread_local, "object_refs"):
self._thread_local.object_refs = set()
return set()
object_refs = self._thread_local.object_refs
self._thread_local.object_refs = set()
return object_refs
def add_contained_object_ref(
self,
object_ref: "ray.ObjectRef",
*,
allow_out_of_band_serialization: bool,
call_site: Optional[str] = None,
):
if self.is_in_band_serialization():
# This object ref is being stored in an object. Add the ID to the
# list of IDs contained in the object so that we keep the inner
# object value alive as long as the outer object is in scope.
if not hasattr(self._thread_local, "object_refs"):
self._thread_local.object_refs = set()
self._thread_local.object_refs.add(object_ref)
else:
if not allow_out_of_band_serialization:
raise ray.exceptions.OufOfBandObjectRefSerializationException(
f"It is not allowed to serialize ray.ObjectRef {object_ref.hex()}. "
"If you want to allow serialization, "
"set `RAY_allow_out_of_band_object_ref_serialization=1.` "
"If you set the env var, the object is pinned forever in the "
"lifetime of the worker process and can cause Ray object leaks. "
"See the callsite and trace to find where the serialization "
"occurs.\nCallsite: "
f"{call_site or 'Disabled. Set RAY_record_ref_creation_sites=1'}"
)
else:
# If this serialization is out-of-band (e.g., from a call to
# cloudpickle directly or captured in a remote function/actor),
# then pin the object for the lifetime of this worker by adding
# a local reference that won't ever be removed.
ray._private.worker.global_worker.core_worker.add_object_ref_reference(
object_ref
)
def _deserialize_pickle5_data(
self,
data: Any,
out_of_band_tensors: Optional[List["torch.Tensor"]],
) -> Any:
"""
Args:
data: The data to deserialize.
out_of_band_tensors: Tensors that were sent out-of-band. If this is
not None, then the serialized data will contain placeholders
that need to be replaced with these tensors.
Returns:
Any: The deserialized object.
"""
from ray.experimental.channel import ChannelContext
ctx = ChannelContext.get_current().serialization_context
enable_gpu_objects = out_of_band_tensors is not None
if enable_gpu_objects:
ctx.reset_out_of_band_tensors(out_of_band_tensors)
try:
in_band, buffers = unpack_pickle5_buffers(data)
if len(buffers) > 0:
obj = pickle.loads(in_band, buffers=buffers)
else:
obj = pickle.loads(in_band)
# cloudpickle does not provide error types
except pickle.pickle.PicklingError:
raise DeserializationError()
finally:
if enable_gpu_objects:
ctx.reset_out_of_band_tensors([])
return obj
def _deserialize_msgpack_data(
self,
data,
metadata_fields,
out_of_band_tensors: Optional[List["torch.Tensor"]] = None,
):
msgpack_data, pickle5_data = split_buffer(data)
if metadata_fields[0] == ray_constants.OBJECT_METADATA_TYPE_PYTHON:
python_objects = self._deserialize_pickle5_data(
pickle5_data, out_of_band_tensors
)
else:
python_objects = []
try:
def _python_deserializer(index):
return python_objects[index]
obj = MessagePackSerializer.loads(msgpack_data, _python_deserializer)
except Exception:
raise DeserializationError()
return obj
def _deserialize_error_info(self, data, metadata_fields):
assert data
pb_bytes = self._deserialize_msgpack_data(data, metadata_fields)
assert pb_bytes
ray_error_info = RayErrorInfo()
ray_error_info.ParseFromString(pb_bytes)
return ray_error_info
def _deserialize_actor_died_error(self, data, metadata_fields):
if not data:
return ActorDiedError()
ray_error_info = self._deserialize_error_info(data, metadata_fields)
assert ray_error_info.HasField("actor_died_error")
if ray_error_info.actor_died_error.HasField("creation_task_failure_context"):
return RayError.from_ray_exception(
ray_error_info.actor_died_error.creation_task_failure_context
)
else:
assert ray_error_info.actor_died_error.HasField("actor_died_error_context")
return ActorDiedError(
cause=ray_error_info.actor_died_error.actor_died_error_context
)
def _deserialize_object(
self,
data,
metadata,
object_ref,
out_of_band_tensors: Optional[List["torch.Tensor"]],
):
if metadata:
metadata_fields = metadata.split(b",")
if metadata_fields[0] in [
ray_constants.OBJECT_METADATA_TYPE_CROSS_LANGUAGE,
ray_constants.OBJECT_METADATA_TYPE_PYTHON,
]:
return self._deserialize_msgpack_data(
data, metadata_fields, out_of_band_tensors
)
# Check if the object should be returned as raw bytes.
if metadata_fields[0] == ray_constants.OBJECT_METADATA_TYPE_RAW:
if data is None:
return b""
return data.to_pybytes()
elif metadata_fields[0] == ray_constants.OBJECT_METADATA_TYPE_ACTOR_HANDLE:
obj = self._deserialize_msgpack_data(
data, metadata_fields, out_of_band_tensors
)
# The last character is a 1 if weak_ref=True and 0 else.
serialized, weak_ref = obj[:-1], obj[-1:] == b"1"
return _actor_handle_deserializer(serialized, weak_ref)
# Otherwise, return an exception object based on
# the error type.
try:
error_type = int(metadata_fields[0])
except Exception:
raise Exception(
f"Can't deserialize object: {object_ref}, " f"metadata: {metadata}"
)
# RayTaskError is serialized with pickle5 in the data field.
# TODO (kfstorm): exception serialization should be language
# independent.
if error_type == ErrorType.Value("TASK_EXECUTION_EXCEPTION"):
obj = self._deserialize_msgpack_data(
data, metadata_fields, out_of_band_tensors
)
return RayError.from_bytes(obj)
elif error_type == ErrorType.Value("WORKER_DIED"):
return WorkerCrashedError()
elif error_type == ErrorType.Value("ACTOR_DIED"):
return self._deserialize_actor_died_error(data, metadata_fields)
elif error_type == ErrorType.Value("LOCAL_RAYLET_DIED"):
return LocalRayletDiedError()
elif error_type == ErrorType.Value("TASK_CANCELLED"):
# Task cancellations are serialized in two ways, so check both
# deserialization paths.
# TODO(swang): We should only have one serialization path.
try:
# Deserialization from C++ (the CoreWorker task submitter).
# The error info will be stored as a RayErrorInfo.
error_message = ""
if data:
error_info = self._deserialize_error_info(data, metadata_fields)
error_message = error_info.error_message
return TaskCancelledError(error_message=error_message)
except google.protobuf.message.DecodeError:
# Deserialization from Python. The TaskCancelledError is
# serialized and returned directly.
obj = self._deserialize_msgpack_data(
data, metadata_fields, out_of_band_tensors
)
return RayError.from_bytes(obj)
elif error_type == ErrorType.Value("OBJECT_LOST"):
return ObjectLostError(
object_ref.hex(), object_ref.owner_address(), object_ref.call_site()
)
elif error_type == ErrorType.Value("OBJECT_FETCH_TIMED_OUT"):
return ObjectFetchTimedOutError(
object_ref.hex(), object_ref.owner_address(), object_ref.call_site()
)
elif error_type == ErrorType.Value("OUT_OF_DISK_ERROR"):
return OutOfDiskError(
object_ref.hex(), object_ref.owner_address(), object_ref.call_site()
)
elif error_type == ErrorType.Value("OUT_OF_MEMORY"):
error_info = self._deserialize_error_info(data, metadata_fields)
return OutOfMemoryError(error_info.error_message)
elif error_type == ErrorType.Value("NODE_DIED"):
error_info = self._deserialize_error_info(data, metadata_fields)
return NodeDiedError(error_info.error_message)
elif error_type == ErrorType.Value("OBJECT_DELETED"):
return ReferenceCountingAssertionError(
object_ref.hex(), object_ref.owner_address(), object_ref.call_site()
)
elif error_type == ErrorType.Value("OBJECT_FREED"):
return ObjectFreedError(
object_ref.hex(), object_ref.owner_address(), object_ref.call_site()
)
elif error_type == ErrorType.Value("OWNER_DIED"):
return OwnerDiedError(
object_ref.hex(), object_ref.owner_address(), object_ref.call_site()
)
elif error_type == ErrorType.Value("OBJECT_UNRECONSTRUCTABLE"):
return ObjectReconstructionFailedError(
object_ref.hex(), object_ref.owner_address(), object_ref.call_site()
)
elif error_type == ErrorType.Value(
"OBJECT_UNRECONSTRUCTABLE_MAX_ATTEMPTS_EXCEEDED"
):
return ObjectReconstructionFailedMaxAttemptsExceededError(
object_ref.hex(), object_ref.owner_address(), object_ref.call_site()
)
elif error_type == ErrorType.Value(
"OBJECT_UNRECONSTRUCTABLE_LINEAGE_EVICTED"
):
return ObjectReconstructionFailedLineageEvictedError(
object_ref.hex(), object_ref.owner_address(), object_ref.call_site()
)
elif error_type == ErrorType.Value("RUNTIME_ENV_SETUP_FAILED"):
error_info = self._deserialize_error_info(data, metadata_fields)
# TODO(sang): Assert instead once actor also reports error messages.
error_msg = ""
if error_info.HasField("runtime_env_setup_failed_error"):
error_msg = error_info.runtime_env_setup_failed_error.error_message
return RuntimeEnvSetupError(error_message=error_msg)
elif error_type == ErrorType.Value("TASK_PLACEMENT_GROUP_REMOVED"):
return TaskPlacementGroupRemoved()
elif error_type == ErrorType.Value("ACTOR_PLACEMENT_GROUP_REMOVED"):
return ActorPlacementGroupRemoved()
elif error_type == ErrorType.Value("TASK_UNSCHEDULABLE_ERROR"):
error_info = self._deserialize_error_info(data, metadata_fields)
return TaskUnschedulableError(error_info.error_message)
elif error_type == ErrorType.Value("ACTOR_UNSCHEDULABLE_ERROR"):
error_info = self._deserialize_error_info(data, metadata_fields)
return ActorUnschedulableError(error_info.error_message)
elif error_type == ErrorType.Value("END_OF_STREAMING_GENERATOR"):
return ObjectRefStreamEndOfStreamError()
elif error_type == ErrorType.Value("ACTOR_UNAVAILABLE"):
error_info = self._deserialize_error_info(data, metadata_fields)
if error_info.HasField("actor_unavailable_error"):
actor_id = error_info.actor_unavailable_error.actor_id
else:
actor_id = None
return ActorUnavailableError(error_info.error_message, actor_id)
else:
return RaySystemError("Unrecognized error type " + str(error_type))
elif data:
raise ValueError("non-null object should always have metadata")
else:
# Object isn't available in plasma. This should never be returned
# to the user. We should only reach this line if this object was
# deserialized as part of a list, and another object in the list
# throws an exception.
return PlasmaObjectNotAvailable
def deserialize_objects(
self,
serialized_ray_objects: List[SerializedRayObject],
object_refs,
gpu_objects: Dict[str, List["torch.Tensor"]],
):
assert len(serialized_ray_objects) == len(object_refs)
# initialize the thread-local field
if not hasattr(self._thread_local, "object_ref_stack"):
self._thread_local.object_ref_stack = []
results = []
for object_ref, (data, metadata, transport) in zip(
object_refs, serialized_ray_objects
):
try:
# Push the object ref to the stack, so the object under
# the object ref knows where it comes from.
self._thread_local.object_ref_stack.append(object_ref)
object_tensors = None
if object_ref is not None:
object_id = object_ref.hex()
if object_id in gpu_objects:
object_tensors = gpu_objects[object_id]
obj = self._deserialize_object(
data,
metadata,
object_ref,
object_tensors,
)
except Exception as e:
logger.exception(e)
obj = RaySystemError(e, traceback.format_exc())
finally:
# Must clear ObjectRef to not hold a reference.
if self._thread_local.object_ref_stack:
self._thread_local.object_ref_stack.pop()
results.append(obj)
return results
def _serialize_to_pickle5(self, metadata, value):
writer = Pickle5Writer()
# TODO(swang): Check that contained_object_refs is empty.
try:
self.set_in_band_serialization()
inband = pickle.dumps(
value, protocol=5, buffer_callback=writer.buffer_callback
)
except Exception as e:
self.get_and_clear_contained_object_refs()
raise e
finally:
self.set_out_of_band_serialization()
return Pickle5SerializedObject(
metadata, inband, writer, self.get_and_clear_contained_object_refs()
)
def _serialize_to_msgpack(self, value):
# Only RayTaskError is possible to be serialized here. We don't
# need to deal with other exception types here.
contained_object_refs = []
if isinstance(value, RayTaskError):
if issubclass(value.cause.__class__, TaskCancelledError):
# Handle task cancellation errors separately because we never
# want to warn about tasks that were intentionally cancelled by
# the user.
metadata = str(ErrorType.Value("TASK_CANCELLED")).encode("ascii")
value = value.to_bytes()
else:
metadata = str(ErrorType.Value("TASK_EXECUTION_EXCEPTION")).encode(
"ascii"
)
value = value.to_bytes()
elif isinstance(value, ray.actor.ActorHandle):
# TODO(fyresone): ActorHandle should be serialized via the
# custom type feature of cross-language.
serialized, actor_handle_id, weak_ref = value._serialization_helper()
if not weak_ref:
contained_object_refs.append(actor_handle_id)
# Update ref counting for the actor handle
metadata = ray_constants.OBJECT_METADATA_TYPE_ACTOR_HANDLE
# Append a 1 to mean weak ref or 0 for strong ref.
# We do this here instead of in the main serialization helper
# because msgpack expects a bytes object. We cannot serialize
# `weak_ref` in the C++ code because the weak_ref property is only
# available in the Python ActorHandle instance.
value = serialized + (b"1" if weak_ref else b"0")
else:
metadata = ray_constants.OBJECT_METADATA_TYPE_CROSS_LANGUAGE
python_objects = []
def _python_serializer(o):
index = len(python_objects)
python_objects.append(o)
return index
msgpack_data = MessagePackSerializer.dumps(value, _python_serializer)
if python_objects:
metadata = ray_constants.OBJECT_METADATA_TYPE_PYTHON
pickle5_serialized_object = self._serialize_to_pickle5(
metadata, python_objects
)
else:
pickle5_serialized_object = None
return MessagePackSerializedObject(
metadata, msgpack_data, contained_object_refs, pickle5_serialized_object
)
def serialize_gpu_objects(
self,
value: Any,
) -> Tuple[MessagePackSerializedObject, List["torch.Tensor"]]:
"""Retrieve GPU data from `value` and store it in the GPU object store. Then, return the serialized value.
Args:
value: The value to serialize.
Returns:
Serialized value.
"""
if not self._torch_custom_serializer_registered:
# Register a custom serializer for torch.Tensor. If the method is
# decorated with `@ray.method(tensor_transport="xxx")`, it will
# use external transport (e.g. gloo, nccl, etc.) for tensor
# communication between actors, instead of the normal serialize ->
# object store -> deserialize codepath.
from ray.experimental.channel.torch_tensor_type import TorchTensorType
TorchTensorType().register_custom_serializer()
self._torch_custom_serializer_registered = True
serialized_val, tensors = self._serialize_and_retrieve_tensors(value)
return serialized_val, tensors
def store_gpu_objects(self, obj_id: str, tensors: List["torch.Tensor"]):
"""
Store GPU objects in the GPU object store.
Args:
obj_id: The object ID of the value. `obj_id` is required, and the GPU data (e.g. tensors) in `value`
will be stored in the GPU object store with the key `obj_id`.
tensors: The tensors to store in the GPU object store.
"""
assert (
obj_id is not None
), "`obj_id` is required, and it is the key to retrieve corresponding tensors from the GPU object store."
# Regardless of whether `tensors` is empty, we always store the GPU object
# in the GPU object store. This ensures that `get_tensor_transport_metadata` is not
# blocked indefinitely.
worker = ray._private.worker.global_worker
gpu_object_manager = worker.gpu_object_manager
gpu_object_manager.gpu_object_store.add_object(obj_id, tensors, is_primary=True)
def serialize(
self, value: Any
) -> Union[RawSerializedObject, MessagePackSerializedObject]:
"""Serialize an object.
Args:
value: The value to serialize.
Returns:
Serialized value.
"""
if isinstance(value, bytes):
# If the object is a byte array, skip serializing it and
# use a special metadata to indicate it's raw binary. So
# that this object can also be read by Java.
return RawSerializedObject(value)
else:
return self._serialize_to_msgpack(value)
def _serialize_and_retrieve_tensors(
self, value: Any
) -> Tuple[MessagePackSerializedObject, List["torch.Tensor"]]:
"""
Serialize `value` and return the serialized value and any tensors retrieved from `value`.
This is only used for GPU objects.
"""
from ray.experimental.channel import ChannelContext
ctx = ChannelContext.get_current().serialization_context
prev_use_external_transport = ctx.use_external_transport
ctx.set_use_external_transport(True)
try:
serialized_val = self._serialize_to_msgpack(value)
finally:
ctx.set_use_external_transport(prev_use_external_transport)
tensors, _ = ctx.reset_out_of_band_tensors([])
return serialized_val, tensors
| SerializationContext |
python | pytorch__pytorch | test/inductor/test_flex_attention.py | {
"start": 5309,
"end": 5876
} | class ____:
dtypes: list[torch.dtype]
dtypes_fast: list[torch.dtype]
TEST_ON_CUDA = (
torch.cuda.is_available()
and torch.utils._triton.has_triton()
and torch.cuda.get_device_capability() >= (8, 0)
)
TEST_ON_XPU = torch.xpu.is_available() and torch.utils._triton.has_triton()
device_configs = {}
if HAS_GPU:
if TEST_ON_CUDA:
test_device = (
"cuda",
"cpu",
)
elif TEST_ON_XPU:
torch._C._set_onednn_allow_tf32(True)
test_device = ("xpu",)
else:
test_device = ("cpu",)
| DeviceConfig |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF009_attrs.py | {
"start": 1542,
"end": 1954
} | class ____:
def __init__(self, *, default):
self._default = default
def __set_name__(self, owner, name):
self._name = "_" + name
def __get__(self, obj, type):
if obj is None:
return self._default
return getattr(obj, self._name, self._default)
def __set__(self, obj, value):
setattr(obj, self._name, int(value))
@frozen
| IntConversionDescriptor |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/xcom.py | {
"start": 1043,
"end": 2045
} | class ____(BaseModel):
"""Serializer for a xcom item."""
key: str
timestamp: datetime
logical_date: datetime | None
map_index: int
task_id: str
dag_id: str
run_id: str
dag_display_name: str = Field(validation_alias=AliasPath("dag_run", "dag_model", "dag_display_name"))
task_display_name: str = Field(validation_alias=AliasPath("task", "task_display_name"))
def _stringify_if_needed(value):
"""
Check whether value is JSON-encodable (recursively if needed); stringify it if not.
The list of JSON-ecodable types are taken from Python documentation:
https://docs.python.org/3/library/json.html#json.JSONEncoder
"""
if value is None or isinstance(value, (str, int, float, bool)):
return value
if isinstance(value, dict):
return {str(k): _stringify_if_needed(v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [_stringify_if_needed(v) for v in value]
return str(value)
| XComResponse |
python | sqlalchemy__sqlalchemy | examples/sharding/asyncio.py | {
"start": 3190,
"end": 3576
} | class ____(Base):
__tablename__ = "weather_locations"
id: Mapped[int] = mapped_column(primary_key=True, default=id_generator)
continent: Mapped[str]
city: Mapped[str]
reports: Mapped[list[Report]] = relationship(back_populates="location")
def __init__(self, continent: str, city: str):
self.continent = continent
self.city = city
| WeatherLocation |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_dataspec.py | {
"start": 4283,
"end": 9452
} | class ____:
def test_field(self) -> None:
class Foo(HasProps):
col = bcpd.ColorSpec("colorfield")
desc = Foo.__dict__["col"]
f = Foo()
assert f.col == "colorfield"
assert desc.get_value(f) == Field("colorfield")
f.col = "myfield"
assert f.col == "myfield"
assert desc.get_value(f) == Field("myfield")
def test_field_default(self) -> None:
class Foo(HasProps):
col = bcpd.ColorSpec(default="red")
desc = Foo.__dict__["col"]
f = Foo()
assert f.col == "red"
assert desc.get_value(f) == Value("red")
f.col = "myfield"
assert f.col == "myfield"
assert desc.get_value(f) == Field("myfield")
def test_default_tuple(self) -> None:
class Foo(HasProps):
col = bcpd.ColorSpec(default=(128, 255, 124))
desc = Foo.__dict__["col"]
f = Foo()
assert f.col == (128, 255, 124)
assert desc.get_value(f) == Value((128, 255, 124))
def test_fixed_value(self) -> None:
class Foo(HasProps):
col = bcpd.ColorSpec("gray")
desc = Foo.__dict__["col"]
f = Foo()
assert f.col == "gray"
assert desc.get_value(f) == Value("gray")
def test_named_value(self) -> None:
class Foo(HasProps):
col = bcpd.ColorSpec("colorfield")
desc = Foo.__dict__["col"]
f = Foo()
f.col = "red"
assert f.col == "red"
assert desc.get_value(f) == Value("red")
f.col = "forestgreen"
assert f.col == "forestgreen"
assert desc.get_value(f) == Value("forestgreen")
def test_case_insensitive_named_value(self) -> None:
class Foo(HasProps):
col = bcpd.ColorSpec("colorfield")
desc = Foo.__dict__["col"]
f = Foo()
f.col = "RED"
assert f.col == "RED"
assert desc.get_value(f) == Value("RED")
f.col = "ForestGreen"
assert f.col == "ForestGreen"
assert desc.get_value(f) == Value("ForestGreen")
def test_named_value_set_none(self) -> None:
class Foo(HasProps):
col = bcpd.ColorSpec("colorfield")
desc = Foo.__dict__["col"]
f = Foo()
f.col = None
assert desc.get_value(f) == Value(None)
def test_named_value_unset(self) -> None:
class Foo(HasProps):
col = bcpd.ColorSpec("colorfield")
desc = Foo.__dict__["col"]
f = Foo()
assert desc.get_value(f) == Field("colorfield")
def test_named_color_overriding_default(self) -> None:
class Foo(HasProps):
col = bcpd.ColorSpec("colorfield")
desc = Foo.__dict__["col"]
f = Foo()
f.col = "forestgreen"
assert f.col == "forestgreen"
assert desc.get_value(f) == Value("forestgreen")
f.col = "myfield"
assert f.col == "myfield"
assert desc.get_value(f) == Field("myfield")
def test_hex_value(self) -> None:
class Foo(HasProps):
col = bcpd.ColorSpec("colorfield")
desc = Foo.__dict__["col"]
f = Foo()
f.col = "#FF004A"
assert f.col == "#FF004A"
assert desc.get_value(f) == Value("#FF004A")
f.col = "myfield"
assert f.col == "myfield"
assert desc.get_value(f) == Field("myfield")
def test_tuple_value(self) -> None:
class Foo(HasProps):
col = bcpd.ColorSpec("colorfield")
desc = Foo.__dict__["col"]
f = Foo()
f.col = (128, 200, 255)
assert f.col == (128, 200, 255)
assert desc.get_value(f) == Value((128, 200, 255))
f.col = "myfield"
assert f.col == "myfield"
assert desc.get_value(f) == Field("myfield")
f.col = (100, 150, 200, 0.5)
assert f.col == (100, 150, 200, 0.5)
assert desc.get_value(f) == Value((100, 150, 200, 0.5))
def test_set_dict(self) -> None:
class Foo(HasProps):
col = bcpd.ColorSpec("colorfield")
desc = Foo.__dict__["col"]
f = Foo()
f.col = {"field": "myfield"}
assert f.col == field("myfield")
f.col = "field2"
assert f.col == "field2"
assert desc.get_value(f) == Field("field2")
def test_isconst(self) -> None:
assert bcpd.ColorSpec.isconst("red")
assert bcpd.ColorSpec.isconst("#ff1234")
assert not bcpd.ColorSpec.isconst(None)
assert not bcpd.ColorSpec.isconst(10)
assert not bcpd.ColorSpec.isconst((1, 2, 3, 0.5))
def test_is_color_tuple_shape(self) -> None:
assert bcpd.ColorSpec.is_color_tuple_shape((1, 2, 3, 0.5))
assert bcpd.ColorSpec.is_color_tuple_shape((1.0, 2, 3, 0.5))
assert bcpd.ColorSpec.is_color_tuple_shape((1, 2.0, 3, 0.5))
assert bcpd.ColorSpec.is_color_tuple_shape((1, 2, 3.0, 0.5))
assert not bcpd.ColorSpec.is_color_tuple_shape("red")
assert not bcpd.ColorSpec.is_color_tuple_shape("#ff1234")
assert not bcpd.ColorSpec.is_color_tuple_shape(None)
assert not bcpd.ColorSpec.is_color_tuple_shape(10)
| Test_ColorSpec |
python | huggingface__transformers | examples/pytorch/contrastive-image-text/run_clip.py | {
"start": 2281,
"end": 4557
} | class ____:
"""
Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
"""
model_name_or_path: str = field(
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"},
)
config_name: Optional[str] = field(
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
)
tokenizer_name: Optional[str] = field(
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
)
image_processor_name: str = field(default=None, metadata={"help": "Name or path of preprocessor config."})
cache_dir: Optional[str] = field(
default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
)
model_revision: str = field(
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
use_fast_tokenizer: bool = field(
default=True,
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
)
token: str = field(
default=None,
metadata={
"help": (
"The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
"generated when running `hf auth login` (stored in `~/.huggingface`)."
)
},
)
trust_remote_code: bool = field(
default=False,
metadata={
"help": (
"Whether to trust the execution of code from datasets/models defined on the Hub."
" This option should only be set to `True` for repositories you trust and in which you have read the"
" code, as it will execute code present on the Hub on your local machine."
)
},
)
freeze_vision_model: bool = field(
default=False, metadata={"help": "Whether to freeze the vision model parameters or not."}
)
freeze_text_model: bool = field(
default=False, metadata={"help": "Whether to freeze the text model parameters or not."}
)
@dataclass
| ModelArguments |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 317110,
"end": 317797
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of UnlinkRepositoryFromProject"""
__schema__ = github_schema
__field_names__ = ("project_id", "repository_id", "client_mutation_id")
project_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectId")
"""The ID of the Project linked to the Repository."""
repository_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="repositoryId")
"""The ID of the Repository linked to the Project."""
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
| UnlinkRepositoryFromProjectInput |
python | huggingface__transformers | src/transformers/models/cpmant/modeling_cpmant.py | {
"start": 21431,
"end": 21931
} | class ____(PreTrainedModel):
config: CpmAntConfig
base_model_prefix = "cpmant"
@torch.no_grad()
def _init_weights(self, module):
"""Initialize the weights"""
super()._init_weights(module)
if isinstance(module, CpmAntLayerNorm):
init.ones_(module.weight)
elif isinstance(module, CpmAntSegmentPositionEmbedding):
init.normal_(module.relative_attention_bias, mean=0.0, std=self.config.init_std)
@auto_docstring
| CpmAntPreTrainedModel |
python | django__django | tests/admin_inlines/admin.py | {
"start": 3650,
"end": 3759
} | class ____(admin.TabularInline):
model = ReadOnlyInline
readonly_fields = ["name"]
| ReadOnlyInlineInline |
python | python-pillow__Pillow | src/PIL/WalImageFile.py | {
"start": 795,
"end": 5685
} | class ____(ImageFile.ImageFile):
format = "WAL"
format_description = "Quake2 Texture"
def _open(self) -> None:
self._mode = "P"
# read header fields
header = self.fp.read(32 + 24 + 32 + 12)
self._size = i32(header, 32), i32(header, 36)
Image._decompression_bomb_check(self.size)
# load pixel data
offset = i32(header, 40)
self.fp.seek(offset)
# strings are null-terminated
self.info["name"] = header[:32].split(b"\0", 1)[0]
if next_name := header[56 : 56 + 32].split(b"\0", 1)[0]:
self.info["next_name"] = next_name
def load(self) -> Image.core.PixelAccess | None:
if self._im is None:
self.im = Image.core.new(self.mode, self.size)
self.frombytes(self.fp.read(self.size[0] * self.size[1]))
self.putpalette(quake2palette)
return Image.Image.load(self)
def open(filename: StrOrBytesPath | IO[bytes]) -> WalImageFile:
"""
Load texture from a Quake2 WAL texture file.
By default, a Quake2 standard palette is attached to the texture.
To override the palette, use the :py:func:`PIL.Image.Image.putpalette()` method.
:param filename: WAL file name, or an opened file handle.
:returns: An image instance.
"""
return WalImageFile(filename)
quake2palette = (
# default palette taken from piffo 0.93 by Hans Häggström
b"\x01\x01\x01\x0b\x0b\x0b\x12\x12\x12\x17\x17\x17\x1b\x1b\x1b\x1e"
b"\x1e\x1e\x22\x22\x22\x26\x26\x26\x29\x29\x29\x2c\x2c\x2c\x2f\x2f"
b"\x2f\x32\x32\x32\x35\x35\x35\x37\x37\x37\x3a\x3a\x3a\x3c\x3c\x3c"
b"\x24\x1e\x13\x22\x1c\x12\x20\x1b\x12\x1f\x1a\x10\x1d\x19\x10\x1b"
b"\x17\x0f\x1a\x16\x0f\x18\x14\x0d\x17\x13\x0d\x16\x12\x0d\x14\x10"
b"\x0b\x13\x0f\x0b\x10\x0d\x0a\x0f\x0b\x0a\x0d\x0b\x07\x0b\x0a\x07"
b"\x23\x23\x26\x22\x22\x25\x22\x20\x23\x21\x1f\x22\x20\x1e\x20\x1f"
b"\x1d\x1e\x1d\x1b\x1c\x1b\x1a\x1a\x1a\x19\x19\x18\x17\x17\x17\x16"
b"\x16\x14\x14\x14\x13\x13\x13\x10\x10\x10\x0f\x0f\x0f\x0d\x0d\x0d"
b"\x2d\x28\x20\x29\x24\x1c\x27\x22\x1a\x25\x1f\x17\x38\x2e\x1e\x31"
b"\x29\x1a\x2c\x25\x17\x26\x20\x14\x3c\x30\x14\x37\x2c\x13\x33\x28"
b"\x12\x2d\x24\x10\x28\x1f\x0f\x22\x1a\x0b\x1b\x14\x0a\x13\x0f\x07"
b"\x31\x1a\x16\x30\x17\x13\x2e\x16\x10\x2c\x14\x0d\x2a\x12\x0b\x27"
b"\x0f\x0a\x25\x0f\x07\x21\x0d\x01\x1e\x0b\x01\x1c\x0b\x01\x1a\x0b"
b"\x01\x18\x0a\x01\x16\x0a\x01\x13\x0a\x01\x10\x07\x01\x0d\x07\x01"
b"\x29\x23\x1e\x27\x21\x1c\x26\x20\x1b\x25\x1f\x1a\x23\x1d\x19\x21"
b"\x1c\x18\x20\x1b\x17\x1e\x19\x16\x1c\x18\x14\x1b\x17\x13\x19\x14"
b"\x10\x17\x13\x0f\x14\x10\x0d\x12\x0f\x0b\x0f\x0b\x0a\x0b\x0a\x07"
b"\x26\x1a\x0f\x23\x19\x0f\x20\x17\x0f\x1c\x16\x0f\x19\x13\x0d\x14"
b"\x10\x0b\x10\x0d\x0a\x0b\x0a\x07\x33\x22\x1f\x35\x29\x26\x37\x2f"
b"\x2d\x39\x35\x34\x37\x39\x3a\x33\x37\x39\x30\x34\x36\x2b\x31\x34"
b"\x27\x2e\x31\x22\x2b\x2f\x1d\x28\x2c\x17\x25\x2a\x0f\x20\x26\x0d"
b"\x1e\x25\x0b\x1c\x22\x0a\x1b\x20\x07\x19\x1e\x07\x17\x1b\x07\x14"
b"\x18\x01\x12\x16\x01\x0f\x12\x01\x0b\x0d\x01\x07\x0a\x01\x01\x01"
b"\x2c\x21\x21\x2a\x1f\x1f\x29\x1d\x1d\x27\x1c\x1c\x26\x1a\x1a\x24"
b"\x18\x18\x22\x17\x17\x21\x16\x16\x1e\x13\x13\x1b\x12\x12\x18\x10"
b"\x10\x16\x0d\x0d\x12\x0b\x0b\x0d\x0a\x0a\x0a\x07\x07\x01\x01\x01"
b"\x2e\x30\x29\x2d\x2e\x27\x2b\x2c\x26\x2a\x2a\x24\x28\x29\x23\x27"
b"\x27\x21\x26\x26\x1f\x24\x24\x1d\x22\x22\x1c\x1f\x1f\x1a\x1c\x1c"
b"\x18\x19\x19\x16\x17\x17\x13\x13\x13\x10\x0f\x0f\x0d\x0b\x0b\x0a"
b"\x30\x1e\x1b\x2d\x1c\x19\x2c\x1a\x17\x2a\x19\x14\x28\x17\x13\x26"
b"\x16\x10\x24\x13\x0f\x21\x12\x0d\x1f\x10\x0b\x1c\x0f\x0a\x19\x0d"
b"\x0a\x16\x0b\x07\x12\x0a\x07\x0f\x07\x01\x0a\x01\x01\x01\x01\x01"
b"\x28\x29\x38\x26\x27\x36\x25\x26\x34\x24\x24\x31\x22\x22\x2f\x20"
b"\x21\x2d\x1e\x1f\x2a\x1d\x1d\x27\x1b\x1b\x25\x19\x19\x21\x17\x17"
b"\x1e\x14\x14\x1b\x13\x12\x17\x10\x0f\x13\x0d\x0b\x0f\x0a\x07\x07"
b"\x2f\x32\x29\x2d\x30\x26\x2b\x2e\x24\x29\x2c\x21\x27\x2a\x1e\x25"
b"\x28\x1c\x23\x26\x1a\x21\x25\x18\x1e\x22\x14\x1b\x1f\x10\x19\x1c"
b"\x0d\x17\x1a\x0a\x13\x17\x07\x10\x13\x01\x0d\x0f\x01\x0a\x0b\x01"
b"\x01\x3f\x01\x13\x3c\x0b\x1b\x39\x10\x20\x35\x14\x23\x31\x17\x23"
b"\x2d\x18\x23\x29\x18\x3f\x3f\x3f\x3f\x3f\x39\x3f\x3f\x31\x3f\x3f"
b"\x2a\x3f\x3f\x20\x3f\x3f\x14\x3f\x3c\x12\x3f\x39\x0f\x3f\x35\x0b"
b"\x3f\x32\x07\x3f\x2d\x01\x3d\x2a\x01\x3b\x26\x01\x39\x21\x01\x37"
b"\x1d\x01\x34\x1a\x01\x32\x16\x01\x2f\x12\x01\x2d\x0f\x01\x2a\x0b"
b"\x01\x27\x07\x01\x23\x01\x01\x1d\x01\x01\x17\x01\x01\x10\x01\x01"
b"\x3d\x01\x01\x19\x19\x3f\x3f\x01\x01\x01\x01\x3f\x16\x16\x13\x10"
b"\x10\x0f\x0d\x0d\x0b\x3c\x2e\x2a\x36\x27\x20\x30\x21\x18\x29\x1b"
b"\x10\x3c\x39\x37\x37\x32\x2f\x31\x2c\x28\x2b\x26\x21\x30\x22\x20"
)
| WalImageFile |
python | dagster-io__dagster | python_modules/dagster/dagster/_config/errors.py | {
"start": 1234,
"end": 1328
} | class ____:
field_name: str
aliased_field_name: str
@record
| FieldAliasCollisionErrorData |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/validators/actions/test_pagerduty.py | {
"start": 321,
"end": 2347
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
services = [
{
"id": 123,
"service_name": "moo-deng",
},
{
"id": 321,
"service_name": "moo-waan",
},
]
self.integration, self.org_integration = self.create_provider_integration_for(
self.organization,
self.user,
provider="pagerduty",
name="Example PagerDuty",
external_id="example-pagerduty",
metadata={"services": services},
)
with assume_test_silo_mode(SiloMode.CONTROL):
self.org_integration.config["pagerduty_services"] = services
self.org_integration.save()
self.valid_data = {
"type": Action.Type.PAGERDUTY,
"config": {"targetIdentifier": "123", "targetType": "specific"},
"data": {},
"integrationId": self.integration.id,
}
def test_validate(self) -> None:
validator = BaseActionValidator(
data=self.valid_data,
context={"organization": self.organization},
)
result = validator.is_valid()
assert result is True
validator.save()
def test_validate__invalid_service(self) -> None:
validator = BaseActionValidator(
data={
**self.valid_data,
"config": {
"targetType": "specific",
"targetIdentifier": "54321",
},
},
context={"organization": self.organization},
)
result = validator.is_valid()
assert result is False
assert validator.errors == {
"service": [
ErrorDetail(
string="Select a valid choice. 54321 is not one of the available choices.",
code="invalid",
)
]
}
| TestPagerDutyActionValidator |
python | pandas-dev__pandas | pandas/tests/series/indexing/test_setitem.py | {
"start": 34451,
"end": 36078
} | class ____(SetitemCastingEquivalents):
# some nat-like values should be cast to datetime64/timedelta64 when
# inserting into a datetime64/timedelta64 series. Others should coerce
# to object and retain their dtypes.
# GH#18586 for td64 and boolean mask case
@pytest.fixture(
params=["m8[ns]", "M8[ns]", "datetime64[ns, UTC]", "datetime64[ns, US/Central]"]
)
def dtype(self, request):
return request.param
@pytest.fixture
def obj(self, dtype):
i8vals = date_range("2016-01-01", periods=3).asi8
idx = Index(i8vals, dtype=dtype)
assert idx.dtype == dtype
return Series(idx)
@pytest.fixture(
params=[
None,
np.nan,
NaT,
np.timedelta64("NaT", "ns"),
np.datetime64("NaT", "ns"),
]
)
def val(self, request):
return request.param
@pytest.fixture
def is_inplace(self, val, obj):
# td64 -> cast to object iff val is datetime64("NaT")
# dt64 -> cast to object iff val is timedelta64("NaT")
# dt64tz -> cast to object with anything _but_ NaT
return val is NaT or val is None or val is np.nan or obj.dtype == val.dtype
@pytest.fixture
def expected(self, obj, val, is_inplace):
dtype = obj.dtype if is_inplace else object
expected = Series([val] + list(obj[1:]), dtype=dtype)
return expected
@pytest.fixture
def key(self):
return 0
@pytest.fixture
def raises(self, is_inplace):
return False if is_inplace else True
| TestSetitemNADatetimeLikeDtype |
python | graphql-python__graphene | graphene/types/generic.py | {
"start": 242,
"end": 1297
} | class ____(Scalar):
"""
The `GenericScalar` scalar type represents a generic
GraphQL scalar value that could be:
String, Boolean, Int, Float, List or Object.
"""
@staticmethod
def identity(value):
return value
serialize = identity
parse_value = identity
@staticmethod
def parse_literal(ast, _variables=None):
if isinstance(ast, (StringValueNode, BooleanValueNode)):
return ast.value
elif isinstance(ast, IntValueNode):
num = int(ast.value)
if MIN_INT <= num <= MAX_INT:
return num
elif isinstance(ast, FloatValueNode):
return float(ast.value)
elif isinstance(ast, ListValueNode):
return [GenericScalar.parse_literal(value) for value in ast.values]
elif isinstance(ast, ObjectValueNode):
return {
field.name.value: GenericScalar.parse_literal(field.value)
for field in ast.fields
}
else:
return None
| GenericScalar |
python | PyCQA__pylint | tests/functional/ext/docparams/return/missing_return_doc_Google.py | {
"start": 3119,
"end": 3555
} | class ____:
"""test_useless_docs_ignored_argument_names_google
Example of a method documenting the return type that an
implementation should return.
"""
def foo_method(self, arg, _, _ignored): # [useless-type-doc, useless-param-doc]
"""docstring ...
Args:
arg (int): An argument.
_ (float): Another argument.
_ignored: Ignored argument.
"""
pass
| Foo |
python | kamyu104__LeetCode-Solutions | Python/swim-in-rising-water.py | {
"start": 491,
"end": 1333
} | class ____(object):
def swimInWater(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid)
positions = [None] * (n**2)
for i in xrange(n):
for j in xrange(n):
positions[grid[i][j]] = (i, j)
directions = ((-1, 0), (1, 0), (0, -1), (0, 1))
union_find = UnionFind(n**2)
for elevation in xrange(n**2):
i, j = positions[elevation]
for direction in directions:
x, y = i+direction[0], j+direction[1]
if 0 <= x < n and 0 <= y < n and grid[x][y] <= elevation:
union_find.union_set(i*n+j, x*n+y)
if union_find.find_set(0) == union_find.find_set(n**2-1):
return elevation
return n**2-1
| Solution |
python | sympy__sympy | sympy/utilities/codegen.py | {
"start": 47296,
"end": 54844
} | class ____(CodeGen):
"""Generator for Julia code.
The .write() method inherited from CodeGen will output a code file
<prefix>.jl.
"""
code_extension = "jl"
def __init__(self, project='project', printer=None):
super().__init__(project)
self.printer = printer or JuliaCodePrinter()
def routine(self, name, expr, argument_sequence, global_vars):
"""Specialized Routine creation for Julia."""
if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)):
if not expr:
raise ValueError("No expression given")
expressions = Tuple(*expr)
else:
expressions = Tuple(expr)
# local variables
local_vars = {i.label for i in expressions.atoms(Idx)}
# global variables
global_vars = set() if global_vars is None else set(global_vars)
# symbols that should be arguments
old_symbols = expressions.free_symbols - local_vars - global_vars
symbols = set()
for s in old_symbols:
if isinstance(s, Idx):
symbols.update(s.args[1].free_symbols)
elif not isinstance(s, Indexed):
symbols.add(s)
# Julia supports multiple return values
return_vals = []
output_args = []
for (i, expr) in enumerate(expressions):
if isinstance(expr, Equality):
out_arg = expr.lhs
expr = expr.rhs
symbol = out_arg
if isinstance(out_arg, Indexed):
dims = tuple([ (S.One, dim) for dim in out_arg.shape])
symbol = out_arg.base.label
output_args.append(InOutArgument(symbol, out_arg, expr, dimensions=dims))
if not isinstance(out_arg, (Indexed, Symbol, MatrixSymbol)):
raise CodeGenError("Only Indexed, Symbol, or MatrixSymbol "
"can define output arguments.")
return_vals.append(Result(expr, name=symbol, result_var=out_arg))
if not expr.has(symbol):
# this is a pure output: remove from the symbols list, so
# it doesn't become an input.
symbols.remove(symbol)
else:
# we have no name for this output
return_vals.append(Result(expr, name='out%d' % (i+1)))
# setup input argument list
output_args.sort(key=lambda x: str(x.name))
arg_list = list(output_args)
array_symbols = {}
for array in expressions.atoms(Indexed):
array_symbols[array.base.label] = array
for array in expressions.atoms(MatrixSymbol):
array_symbols[array] = array
for symbol in sorted(symbols, key=str):
arg_list.append(InputArgument(symbol))
if argument_sequence is not None:
# if the user has supplied IndexedBase instances, we'll accept that
new_sequence = []
for arg in argument_sequence:
if isinstance(arg, IndexedBase):
new_sequence.append(arg.label)
else:
new_sequence.append(arg)
argument_sequence = new_sequence
missing = [x for x in arg_list if x.name not in argument_sequence]
if missing:
msg = "Argument list didn't specify: {0} "
msg = msg.format(", ".join([str(m.name) for m in missing]))
raise CodeGenArgumentListError(msg, missing)
# create redundant arguments to produce the requested sequence
name_arg_dict = {x.name: x for x in arg_list}
new_args = []
for symbol in argument_sequence:
try:
new_args.append(name_arg_dict[symbol])
except KeyError:
new_args.append(InputArgument(symbol))
arg_list = new_args
return Routine(name, arg_list, return_vals, local_vars, global_vars)
def _get_header(self):
"""Writes a common header for the generated files."""
code_lines = []
tmp = header_comment % {"version": sympy_version,
"project": self.project}
for line in tmp.splitlines():
if line == '':
code_lines.append("#\n")
else:
code_lines.append("# %s\n" % line)
return code_lines
def _preprocessor_statements(self, prefix):
return []
def _get_routine_opening(self, routine):
"""Returns the opening statements of the routine."""
code_list = []
code_list.append("function ")
# Inputs
args = []
for arg in routine.arguments:
if isinstance(arg, OutputArgument):
raise CodeGenError("Julia: invalid argument of type %s" %
str(type(arg)))
if isinstance(arg, (InputArgument, InOutArgument)):
args.append("%s" % self._get_symbol(arg.name))
args = ", ".join(args)
code_list.append("%s(%s)\n" % (routine.name, args))
code_list = [ "".join(code_list) ]
return code_list
def _declare_arguments(self, routine):
return []
def _declare_globals(self, routine):
return []
def _declare_locals(self, routine):
return []
def _get_routine_ending(self, routine):
outs = []
for result in routine.results:
if isinstance(result, Result):
# Note: name not result_var; want `y` not `y[i]` for Indexed
s = self._get_symbol(result.name)
else:
raise CodeGenError("unexpected object in Routine results")
outs.append(s)
return ["return " + ", ".join(outs) + "\nend\n"]
def _call_printer(self, routine):
declarations = []
code_lines = []
for result in routine.results:
if isinstance(result, Result):
assign_to = result.result_var
else:
raise CodeGenError("unexpected object in Routine results")
constants, not_supported, jl_expr = self._printer_method_with_settings(
'doprint', {"human": False, "strict": False}, result.expr, assign_to=assign_to)
for obj, v in sorted(constants, key=str):
declarations.append(
"%s = %s\n" % (obj, v))
for obj in sorted(not_supported, key=str):
if isinstance(obj, Function):
name = obj.func
else:
name = obj
declarations.append(
"# unsupported: %s\n" % (name))
code_lines.append("%s\n" % (jl_expr))
return declarations + code_lines
def _indent_code(self, codelines):
# Note that indenting seems to happen twice, first
# statement-by-statement by JuliaPrinter then again here.
p = JuliaCodePrinter({'human': False, "strict": False})
return p.indent_code(codelines)
def dump_jl(self, routines, f, prefix, header=True, empty=True):
self.dump_code(routines, f, prefix, header, empty)
dump_jl.extension = code_extension # type: ignore
dump_jl.__doc__ = CodeGen.dump_code.__doc__
# This list of dump functions is used by CodeGen.write to know which dump
# functions it has to call.
dump_fns = [dump_jl]
| JuliaCodeGen |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-core/dagster_dg_core_tests/utils_tests/test_sample_yaml.py | {
"start": 316,
"end": 1015
} | class ____(Model, Resolvable):
sub_scoped: Annotated[SampleSubModel, ResolvableFieldInfo(required_scope={"outer_scope"})]
sub_optional: SampleSubModel
sub_list: Sequence[SampleSubModel]
def test_generate_sample_yaml():
yaml = generate_sample_yaml(
component_type=".sample", json_schema=SampleModel.model_json_schema()
)
assert (
yaml
== """type: .sample
attributes:
sub_scoped: # Available scope: {'outer_scope'}
str_field: '...' # Available scope: {'outer_scope'}
int_field: 0 # Available scope: {'outer_scope'}
sub_optional:
str_field: '...'
int_field: 0
sub_list:
- str_field: '...'
int_field: 0
"""
)
| SampleModel |
python | pytorch__pytorch | torch/testing/_internal/common_quantization.py | {
"start": 100827,
"end": 101486
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.emb = torch.nn.EmbeddingBag(num_embeddings=10, embedding_dim=12)
self.fc = torch.nn.Linear(4, 2)
self.emb.qconfig = float_qparams_weight_only_qconfig
self.qconfig = default_qconfig
self.quant = QuantStub()
self.dequant = DeQuantStub()
def forward(self, indices, offsets, linear_in):
emb = self.emb(indices, offsets)
q_x = self.quant(linear_in)
fc = self.fc(q_x)
fc = self.dequant(fc)
features = torch.cat([fc] + [emb], dim=1)
return features
| EmbeddingWithStaticLinear |
python | pytorch__pytorch | torch/_inductor/custom_graph_pass.py | {
"start": 206,
"end": 1995
} | class ____(ABC):
"""
Implement this interface for custom Graph passes:
1) The __call__() method contains the implementation of the custom pass.
2) The uuid() method enables inductor to cache compiled graphs when your custom
passes are applied. This method can return any identifier as long as it uniquely
identifies your implementation (and can be pickled). The caching logic includes this
identifier in its key calculation, i.e., any new value will effectively invalidate
existing entries. We expect custom passes would typically depend purely on the
textual representation of the implementation. In that case, we recommend using the
'get_hash_for_files' helper below to compute a unique hash from the contents of a
static list of source files, i.e., the source(s) containing the custom pass
implementation. That approach ensures that any change to the implementation will
mean a new uuid.
** IMPORTANT ** If your custom pass's behavior depends on some external state, then
you'll need to implement something more complicated (or disable caching).
EXAMPLE:
class MyCustomGraphPass(CustomGraphPass):
def __call__(self, graph: torch.fx.graph.Graph) -> None:
# my custom graph optimization pass
# ...
def uuid(self) -> Optional[Any]:
return get_hash_for_files((__file__,))
"""
@abstractmethod
def __call__(self, graph: torch.fx.graph.Graph) -> None:
"""
Implementation of the custom pass.
"""
@abstractmethod
def uuid(self) -> Optional[Any]:
"""
Return an ID to uniquely identify your custom pass implementation. Return None
to skip inductor code caching entirely.
"""
| CustomGraphPass |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_cloud_storage_transfer_service.py | {
"start": 31036,
"end": 39043
} | class ____:
def setup_method(self):
with mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__",
new=mock_base_gcp_hook_no_default_project_id,
):
self.gct_hook = CloudDataTransferServiceHook(gcp_conn_id="test")
@mock.patch(
"airflow.providers.google.cloud.hooks.cloud_storage_transfer_service"
".CloudDataTransferServiceHook._authorize"
)
@mock.patch("airflow.providers.google.cloud.hooks.cloud_storage_transfer_service.build")
def test_gct_client_creation(self, mock_build, mock_authorize):
result = self.gct_hook.get_conn()
mock_build.assert_called_once_with(
"storagetransfer", "v1", http=mock_authorize.return_value, cache_discovery=False
)
assert mock_build.return_value == result
assert self.gct_hook._conn == result
@mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id",
new_callable=PropertyMock,
return_value=None,
)
@mock.patch(
"airflow.providers.google.cloud.hooks.cloud_storage_transfer_service"
".CloudDataTransferServiceHook.get_conn"
)
def test_create_transfer_job(self, get_conn, mock_project_id):
create_method = get_conn.return_value.transferJobs.return_value.create
execute_method = create_method.return_value.execute
execute_method.return_value = deepcopy(TEST_TRANSFER_JOB)
with pytest.raises(AirflowException) as ctx:
self.gct_hook.create_transfer_job(body=_without_key(TEST_BODY, PROJECT_ID))
assert (
str(ctx.value) == "The project id must be passed either as `projectId` key in `body` "
"parameter or as project_id "
"extra in Google Cloud connection definition. Both are not set!"
)
@mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id",
new_callable=PropertyMock,
return_value=None,
)
@mock.patch(
"airflow.providers.google.cloud.hooks.cloud_storage_transfer_service"
".CloudDataTransferServiceHook.get_conn"
)
def test_get_transfer_job(self, get_conn, mock_project_id):
get_method = get_conn.return_value.transferJobs.return_value.get
execute_method = get_method.return_value.execute
execute_method.return_value = TEST_TRANSFER_JOB
with pytest.raises(AirflowException) as ctx:
self.gct_hook.get_transfer_job(job_name=TEST_TRANSFER_JOB_NAME)
assert (
str(ctx.value) == "The project id must be passed either as keyword project_id "
"parameter or as project_id extra in Google Cloud connection definition. "
"Both are not set!"
)
@mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id",
new_callable=PropertyMock,
return_value=None,
)
@mock.patch(
"airflow.providers.google.cloud.hooks.cloud_storage_transfer_service"
".CloudDataTransferServiceHook.get_conn"
)
def test_list_transfer_job(self, get_conn, mock_project_id):
list_method = get_conn.return_value.transferJobs.return_value.list
list_execute_method = list_method.return_value.execute
list_execute_method.return_value = {"transferJobs": [TEST_TRANSFER_JOB]}
list_next = get_conn.return_value.transferJobs.return_value.list_next
list_next.return_value = None
with pytest.raises(AirflowException) as ctx:
self.gct_hook.list_transfer_job(
request_filter=_without_key(TEST_TRANSFER_JOB_FILTER, FILTER_PROJECT_ID)
)
assert (
str(ctx.value)
== "The project id must be passed either as `project_id` key in `filter` parameter or as "
"project_id extra in Google Cloud connection definition. Both are not set!"
)
@mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id",
new_callable=PropertyMock,
return_value=None,
)
@mock.patch(
"airflow.providers.google.cloud.hooks.cloud_storage_transfer_service"
".CloudDataTransferServiceHook.get_conn"
)
def test_list_transfer_operation_multiple_page(self, get_conn, mock_project_id):
pages_requests = [
mock.Mock(**{"execute.return_value": {"operations": [TEST_TRANSFER_OPERATION]}}) for _ in range(4)
]
transfer_operation_mock = mock.Mock(
**{"list.return_value": pages_requests[1], "list_next.side_effect": pages_requests[1:] + [None]}
)
get_conn.return_value.transferOperations.return_value = transfer_operation_mock
res = self.gct_hook.list_transfer_operations(request_filter=TEST_TRANSFER_OPERATION_FILTER)
assert res == [TEST_TRANSFER_OPERATION] * 4
@mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id",
new_callable=PropertyMock,
return_value=None,
)
@mock.patch(
"airflow.providers.google.cloud.hooks.cloud_storage_transfer_service"
".CloudDataTransferServiceHook.get_conn"
)
def test_update_transfer_job(self, get_conn, mock_project_id):
update_method = get_conn.return_value.transferJobs.return_value.patch
execute_method = update_method.return_value.execute
execute_method.return_value = TEST_TRANSFER_JOB
with pytest.raises(AirflowException) as ctx:
self.gct_hook.update_transfer_job(
job_name=TEST_TRANSFER_JOB_NAME, body=_without_key(TEST_UPDATE_TRANSFER_JOB_BODY, PROJECT_ID)
)
assert (
str(ctx.value)
== "The project id must be passed either as `projectId` key in `body` parameter or as project_id "
"extra in Google Cloud connection definition. Both are not set!"
)
@mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id",
new_callable=PropertyMock,
return_value=None,
)
@mock.patch(
"airflow.providers.google.cloud.hooks.cloud_storage_transfer_service"
".CloudDataTransferServiceHook.get_conn"
)
def test_delete_transfer_job(self, get_conn, mock_project_id):
with pytest.raises(AirflowException) as ctx:
self.gct_hook.delete_transfer_job(job_name=TEST_TRANSFER_JOB_NAME)
assert (
str(ctx.value)
== "The project id must be passed either as keyword project_id parameter or as project_id extra in "
"Google Cloud connection definition. Both are not set!"
)
@mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id",
new_callable=PropertyMock,
return_value=None,
)
@mock.patch(
"airflow.providers.google.cloud.hooks.cloud_storage_transfer_service"
".CloudDataTransferServiceHook.get_conn"
)
def test_list_transfer_operation(self, get_conn, mock_project_id):
list_method = get_conn.return_value.transferOperations.return_value.list
list_execute_method = list_method.return_value.execute
list_execute_method.return_value = {"operations": [TEST_TRANSFER_OPERATION]}
list_next = get_conn.return_value.transferOperations.return_value.list_next
list_next.return_value = None
with pytest.raises(AirflowException) as ctx:
self.gct_hook.list_transfer_operations(
request_filter=_without_key(TEST_TRANSFER_OPERATION_FILTER, FILTER_PROJECT_ID)
)
assert (
str(ctx.value)
== "The project id must be passed either as `project_id` key in `filter` parameter or as project_id "
"extra in Google Cloud connection definition. Both are not set!"
)
| TestGCPTransferServiceHookWithoutProjectId |
python | doocs__leetcode | solution/2600-2699/2670.Find the Distinct Difference Array/Solution.py | {
"start": 0,
"end": 405
} | class ____:
def distinctDifferenceArray(self, nums: List[int]) -> List[int]:
n = len(nums)
suf = [0] * (n + 1)
s = set()
for i in range(n - 1, -1, -1):
s.add(nums[i])
suf[i] = len(s)
s.clear()
ans = [0] * n
for i, x in enumerate(nums):
s.add(x)
ans[i] = len(s) - suf[i + 1]
return ans
| Solution |
python | sympy__sympy | sympy/functions/special/polynomials.py | {
"start": 36041,
"end": 39251
} | class ____(OrthogonalPolynomial):
r"""
``hermite_prob(n, x)`` gives the $n$th probabilist's Hermite polynomial
in $x$, $He_n(x)$.
Explanation
===========
The probabilist's Hermite polynomials are orthogonal on $(-\infty, \infty)$
with respect to the weight $\exp\left(-\frac{x^2}{2}\right)$. They are monic
polynomials, related to the plain Hermite polynomials (:py:class:`~.hermite`) by
.. math :: He_n(x) = 2^{-n/2} H_n(x/\sqrt{2})
Examples
========
>>> from sympy import hermite_prob, diff, I
>>> from sympy.abc import x, n
>>> hermite_prob(1, x)
x
>>> hermite_prob(5, x)
x**5 - 10*x**3 + 15*x
>>> diff(hermite_prob(n,x), x)
n*hermite_prob(n - 1, x)
>>> hermite_prob(n, -x)
(-1)**n*hermite_prob(n, x)
The sum of absolute values of coefficients of $He_n(x)$ is the number of
matchings in the complete graph $K_n$ or telephone number, A000085 in the OEIS:
>>> [hermite_prob(n,I) / I**n for n in range(11)]
[1, 1, 2, 4, 10, 26, 76, 232, 764, 2620, 9496]
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.hermite_prob_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Hermite_polynomial
.. [2] https://mathworld.wolfram.com/HermitePolynomial.html
"""
_ortho_poly = staticmethod(hermite_prob_poly)
@classmethod
def eval(cls, n, x):
if not n.is_Number:
if x.could_extract_minus_sign():
return S.NegativeOne**n * hermite_prob(n, -x)
if x.is_zero:
return sqrt(S.Pi) / gamma((S.One-n) / 2)
elif x is S.Infinity:
return S.Infinity
else:
if n.is_negative:
ValueError("n must be a nonnegative integer, not %r" % n)
else:
return cls._eval_at_order(n, x)
def fdiff(self, argindex=2):
if argindex == 2:
n, x = self.args
return n*hermite_prob(n-1, x)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Sum(self, n, x, **kwargs):
from sympy.concrete.summations import Sum
k = Dummy("k")
kern = (-S.Half)**k * x**(n-2*k) / (factorial(k) * factorial(n-2*k))
return factorial(n)*Sum(kern, (k, 0, floor(n/2)))
def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
# This function is just kept for backwards compatibility
# but should not be used
return self._eval_rewrite_as_Sum(n, x, **kwargs)
def _eval_rewrite_as_hermite(self, n, x, **kwargs):
return sqrt(2)**(-n) * hermite(n, x/sqrt(2))
#----------------------------------------------------------------------------
# Laguerre polynomials
#
| hermite_prob |
python | walkccc__LeetCode | solutions/3302. Find the Lexicographically Smallest Valid Sequence/3302.py | {
"start": 0,
"end": 706
} | class ____:
def validSequence(self, word1: str, word2: str) -> list[int]:
ans = []
# last[j] := the index i of the last occurrence in word1, where
# word1[i] == word2[j]
last = [-1] * len(word2)
i = len(word1) - 1
j = len(word2) - 1
while i >= 0 and j >= 0:
if word1[i] == word2[j]:
last[j] = i
j -= 1
i -= 1
canSkip = True
j = 0
for i, c in enumerate(word1):
if j == len(word2):
break
if c == word2[j]:
ans.append(i)
j += 1
elif canSkip and (j == len(word2) - 1 or i < last[j + 1]):
canSkip = False
ans.append(i)
j += 1
return ans if j == len(word2) else []
| Solution |
python | huggingface__transformers | src/transformers/models/cohere2/modular_cohere2.py | {
"start": 11122,
"end": 14468
} | class ____(CohereAttention):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: Cohere2Config, layer_idx: Optional[int] = None):
nn.Module.__init__(self)
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
self.scaling = self.head_dim**-0.5
self.attention_dropout = config.attention_dropout
self.is_causal = True
layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
self.sliding_window = config.sliding_window if layer_type == "sliding_attention" else None
self.q_proj = nn.Linear(
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
)
self.k_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.v_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.o_proj = nn.Linear(
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: Optional[torch.Tensor],
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
cos, sin = position_embeddings
if self.sliding_window is not None:
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
if past_key_values is not None:
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.attention_dropout,
scaling=self.scaling,
sliding_window=self.sliding_window,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
| Cohere2Attention |
python | wandb__wandb | tests/system_tests/test_functional/dspy/dspy_callback_completions.py | {
"start": 95,
"end": 259
} | class ____(dspy.Module):
def __init__(self) -> None:
super().__init__()
self.predict = dspy.Predict("question: str -> answer: str")
| MinimalProgram |
python | pytorch__pytorch | test/test_ops.py | {
"start": 90698,
"end": 99943
} | class ____(TestCase):
# Tests that
# 1. The operator's output for physically conjugated/negated tensors and conjugate/negative view tensors
# produces the same value
# 2. The gradients are same in both cases mentioned in (1)
# 3. If the operator's inplace variant is supported, tests that the inplace operation
# produces the correct value when called on a conjugate/negative view tensor and that the output
# has its conj/neg bit set to true
# This test only runs for C -> R and C -> C functions
# TODO: add tests for `R->C` functions
# Note: This test runs for functions that take both tensors and tensorlists as input.
def _test_math_view(
self,
device,
dtype,
op,
samples,
math_op_physical,
math_op_view,
is_bit_set,
out_type,
):
inplace_variant = op.inplace_variant
# helper function to clone and conjugate/negate the input if its a tensor
# else clone the sequence and conjugate/negate the first element in the sequence
# If a requires_grad argument is provided the tensor being conjugated/negated will
# have its requires_grad set to that value.
def clone_and_perform_view(input, **kwargs):
if isinstance(input, torch.Tensor):
requires_grad = kwargs.get("requires_grad", input.requires_grad)
with torch.no_grad():
# Ensure view represents the original sample input
input = math_op_physical(input)
# Note: .conj() is not called under no_grad mode since it's not allowed to modify a
# view created in no_grad mode. Here it's ok to do so, so as a workaround we call conj
# before resetting the requires_grad field for input
input = math_op_view(input)
assert input.is_leaf
return input.requires_grad_(requires_grad)
if isinstance(input, Sequence):
out = list(map(clone_input_helper, input))
out[0] = clone_and_perform_view(out[0])
return tuple(out)
for sample in samples:
tensor = (
sample.input
if isinstance(sample.input, torch.Tensor)
else sample.input[0]
)
cloned1 = clone_and_perform_view(sample.input)
# Computes function forward value with a physically conjugated/negated tensor and
# a conj/neg view tensor and verifies that the output in both case are equal.
expected_forward = op(sample.input, *sample.args, **sample.kwargs)
forward_with_mathview = op(cloned1, *sample.args, **sample.kwargs)
self.assertEqual(expected_forward, forward_with_mathview)
# If the op has an inplace variant, and the input doesn't require broadcasting
# and has the same dtype as output, verify that the inplace operation on a conjugated/negated
# input produces correct output, and the output tensor has the conj/neg bit set to True
if inplace_variant is not None and not sample.broadcasts_input:
cloned2 = clone_and_perform_view(tensor, requires_grad=False)
if (
isinstance(expected_forward, torch.Tensor)
and expected_forward.dtype is tensor.dtype
):
inplace_forward = inplace_variant(
cloned2, *sample.args, **sample.kwargs
)
self.assertTrue(is_bit_set(inplace_forward))
self.assertEqual(inplace_forward, expected_forward)
# TODO: backward consistency only supported for single tensor outputs
# TODO: backward consistency only checked on sample.input, not all
# tensor inputs
# TODO: update to handle checking grads of all tensor inputs as
# derived from each tensor output
if (
isinstance(expected_forward, torch.Tensor)
and expected_forward.requires_grad
):
output_process_fn_grad = sample.output_process_fn_grad or (lambda x: x)
expected_forward = output_process_fn_grad(expected_forward)
forward_with_mathview = output_process_fn_grad(forward_with_mathview)
tensor = (
sample.input
if isinstance(sample.input, torch.Tensor)
else sample.input[0]
)
expected_forward.sum().abs().backward(retain_graph=True)
forward_with_mathview.sum().abs().backward(retain_graph=True)
if tensor.grad is not None:
cloned1_tensor = (
cloned1 if isinstance(cloned1, torch.Tensor) else cloned1[0]
)
self.assertEqual(tensor.grad, cloned1_tensor.grad)
tensor.grad, cloned1_tensor.grad = None, None
# a repeat of the above test if output is not complex valued
if out_type(expected_forward):
grad = torch.randn_like(expected_forward)
expected_forward.backward(grad)
forward_with_mathview.backward(
math_op_view(math_op_physical(grad))
)
self.assertEqual(tensor.grad, cloned1_tensor.grad)
@ops(ops_and_refs, allowed_dtypes=(torch.cfloat,))
def test_conj_view(self, device, dtype, op):
if not op.test_conjugated_samples:
self.skipTest("Operation doesn't support conjugated inputs.")
math_op_physical = torch.conj_physical
math_op_view = torch.conj
_requires_grad = torch.cfloat in op.supported_backward_dtypes(
torch.device(device).type
)
is_bit_set = torch.is_conj
samples = op.sample_inputs(device, dtype, requires_grad=_requires_grad)
self._test_math_view(
device,
dtype,
op,
samples,
math_op_physical,
math_op_view,
is_bit_set,
torch.is_complex,
)
@ops(ops_and_refs, allowed_dtypes=(torch.double,))
def test_neg_view(self, device, dtype, op):
if not op.test_neg_view:
self.skipTest("Operation not tested with tensors with negative bit.")
math_op_physical = torch.neg
math_op_view = torch._neg_view
is_bit_set = torch.is_neg
samples = op.sample_inputs(device, dtype, requires_grad=op.supports_autograd)
self._test_math_view(
device,
dtype,
op,
samples,
math_op_physical,
math_op_view,
is_bit_set,
lambda x: True,
)
@ops(ops_and_refs, allowed_dtypes=(torch.cdouble,))
def test_neg_conj_view(self, device, dtype, op):
if not op.test_neg_view:
self.skipTest("Operation not tested with tensors with negative bit.")
if not op.test_conjugated_samples:
self.skipTest("Operation doesn't support conjugated inputs.")
def math_op_physical(x):
return -x.conj_physical()
def math_op_view(x):
return torch._neg_view(x).conj()
def is_bit_set(x):
return torch.is_neg(x) and torch.is_conj(x)
_requires_grad = dtype in op.supported_backward_dtypes(
torch.device(device).type
)
samples = op.sample_inputs(device, dtype, requires_grad=_requires_grad)
# Only test one sample
samples = itertools.islice(samples, 1)
self._test_math_view(
device,
dtype,
op,
samples,
math_op_physical,
math_op_view,
is_bit_set,
torch.is_complex,
)
# input strides and size may have been altered due to the result of an inplace op
def check_inplace_view(func, input, rs, input_size, input_strides):
if func is None:
return
# TODO: extend this test to test ops with multiple outputs and ops like native_batch_norm(_legit).out
# which mutate not necessarily the first input.
if isinstance(rs, torch.Tensor) and rs is input:
unequal_size = rs.size() != input_size
unequal_strides = rs.stride() != input_strides
# resize_ should probably have inplace_view tag. Not adding the tag since it
# breaks some codegen logic
if unequal_size or unequal_strides:
if isinstance(func, torch._ops.OpOverloadPacket):
func = func.default
# Reference: https://github.com/pytorch/pytorch/issues/78759
if func is not torch.ops.aten.resize_.default:
# TODO: use self.assertIn when we have separate tests for each tag
assert torch.Tag.inplace_view in func.tags
# A mode that when enabled runs correctness checks to ensure
# that operators have expected tags based on their input and
# output tensor properties
| TestMathBits |
python | getsentry__sentry-python | sentry_sdk/integrations/huey.py | {
"start": 1151,
"end": 5443
} | class ____(Integration):
identifier = "huey"
origin = f"auto.queue.{identifier}"
@staticmethod
def setup_once():
# type: () -> None
patch_enqueue()
patch_execute()
def patch_enqueue():
# type: () -> None
old_enqueue = Huey.enqueue
@ensure_integration_enabled(HueyIntegration, old_enqueue)
def _sentry_enqueue(self, task):
# type: (Huey, Task) -> Optional[Union[Result, ResultGroup]]
with sentry_sdk.start_span(
op=OP.QUEUE_SUBMIT_HUEY,
name=task.name,
origin=HueyIntegration.origin,
):
if not isinstance(task, PeriodicTask):
# Attach trace propagation data to task kwargs. We do
# not do this for periodic tasks, as these don't
# really have an originating transaction.
task.kwargs["sentry_headers"] = {
BAGGAGE_HEADER_NAME: get_baggage(),
SENTRY_TRACE_HEADER_NAME: get_traceparent(),
}
return old_enqueue(self, task)
Huey.enqueue = _sentry_enqueue
def _make_event_processor(task):
# type: (Any) -> EventProcessor
def event_processor(event, hint):
# type: (Event, Hint) -> Optional[Event]
with capture_internal_exceptions():
tags = event.setdefault("tags", {})
tags["huey_task_id"] = task.id
tags["huey_task_retry"] = task.default_retries > task.retries
extra = event.setdefault("extra", {})
extra["huey-job"] = {
"task": task.name,
"args": (
task.args
if should_send_default_pii()
else SENSITIVE_DATA_SUBSTITUTE
),
"kwargs": (
task.kwargs
if should_send_default_pii()
else SENSITIVE_DATA_SUBSTITUTE
),
"retry": (task.default_retries or 0) - task.retries,
}
return event
return event_processor
def _capture_exception(exc_info):
# type: (ExcInfo) -> None
scope = sentry_sdk.get_current_scope()
if exc_info[0] in HUEY_CONTROL_FLOW_EXCEPTIONS:
scope.transaction.set_status(SPANSTATUS.ABORTED)
return
scope.transaction.set_status(SPANSTATUS.INTERNAL_ERROR)
event, hint = event_from_exception(
exc_info,
client_options=sentry_sdk.get_client().options,
mechanism={"type": HueyIntegration.identifier, "handled": False},
)
scope.capture_event(event, hint=hint)
def _wrap_task_execute(func):
# type: (F) -> F
@ensure_integration_enabled(HueyIntegration, func)
def _sentry_execute(*args, **kwargs):
# type: (*Any, **Any) -> Any
try:
result = func(*args, **kwargs)
except Exception:
exc_info = sys.exc_info()
_capture_exception(exc_info)
reraise(*exc_info)
return result
return _sentry_execute # type: ignore
def patch_execute():
# type: () -> None
old_execute = Huey._execute
@ensure_integration_enabled(HueyIntegration, old_execute)
def _sentry_execute(self, task, timestamp=None):
# type: (Huey, Task, Optional[datetime]) -> Any
with sentry_sdk.isolation_scope() as scope:
with capture_internal_exceptions():
scope._name = "huey"
scope.clear_breadcrumbs()
scope.add_event_processor(_make_event_processor(task))
sentry_headers = task.kwargs.pop("sentry_headers", None)
transaction = continue_trace(
sentry_headers or {},
name=task.name,
op=OP.QUEUE_TASK_HUEY,
source=TransactionSource.TASK,
origin=HueyIntegration.origin,
)
transaction.set_status(SPANSTATUS.OK)
if not getattr(task, "_sentry_is_patched", False):
task.execute = _wrap_task_execute(task.execute)
task._sentry_is_patched = True
with sentry_sdk.start_transaction(transaction):
return old_execute(self, task, timestamp)
Huey._execute = _sentry_execute
| HueyIntegration |
python | pypa__warehouse | warehouse/captcha/interfaces.py | {
"start": 199,
"end": 816
} | class ____(Interface):
def create_service(context, request):
"""
Create the service, given the context and request for which it is being
created for, passing a name for settings.
"""
def enabled() -> bool:
"""
Return whether the Captcha service is enabled.
"""
def csp_policy() -> dict[str, list[str]]:
"""
Return the CSP policy appropriate for the Captcha service.
"""
def verify_response(response) -> ChallengeResponse | None:
"""
Verify the response from the Captcha service.
"""
| ICaptchaService |
python | realpython__materials | python-built-in-functions/fibonacci.py | {
"start": 0,
"end": 421
} | class ____:
def __init__(self, initial_value=1):
self._cache = [0, initial_value]
def __call__(self, index):
if index < len(self._cache):
fib_number = self._cache[index]
print(f"{index} {fib_number} id = {id(fib_number)}")
else:
fib_number = self(index - 1) + self(index - 2)
self._cache.append(fib_number)
return fib_number
| Fibonaccish |
python | networkx__networkx | networkx/algorithms/tests/test_lowest_common_ancestors.py | {
"start": 5852,
"end": 11116
} | class ____:
@classmethod
def setup_class(cls):
cls.DG = nx.DiGraph()
nx.add_path(cls.DG, (0, 1, 2, 3))
nx.add_path(cls.DG, (0, 4, 3))
nx.add_path(cls.DG, (0, 5, 6, 8, 3))
nx.add_path(cls.DG, (5, 7, 8))
cls.DG.add_edge(6, 2)
cls.DG.add_edge(7, 2)
cls.root_distance = nx.shortest_path_length(cls.DG, source=0)
cls.gold = {
(1, 1): 1,
(1, 2): 1,
(1, 3): 1,
(1, 4): 0,
(1, 5): 0,
(1, 6): 0,
(1, 7): 0,
(1, 8): 0,
(2, 2): 2,
(2, 3): 2,
(2, 4): 0,
(2, 5): 5,
(2, 6): 6,
(2, 7): 7,
(2, 8): 7,
(3, 3): 3,
(3, 4): 4,
(3, 5): 5,
(3, 6): 6,
(3, 7): 7,
(3, 8): 8,
(4, 4): 4,
(4, 5): 0,
(4, 6): 0,
(4, 7): 0,
(4, 8): 0,
(5, 5): 5,
(5, 6): 5,
(5, 7): 5,
(5, 8): 5,
(6, 6): 6,
(6, 7): 5,
(6, 8): 6,
(7, 7): 7,
(7, 8): 7,
(8, 8): 8,
}
cls.gold.update(((0, n), 0) for n in cls.DG)
def assert_lca_dicts_same(self, d1, d2, G=None):
"""Checks if d1 and d2 contain the same pairs and
have a node at the same distance from root for each.
If G is None use self.DG."""
if G is None:
G = self.DG
root_distance = self.root_distance
else:
roots = [n for n, deg in G.in_degree if deg == 0]
assert len(roots) == 1
root_distance = nx.shortest_path_length(G, source=roots[0])
for a, b in ((min(pair), max(pair)) for pair in chain(d1, d2)):
assert (
root_distance[get_pair(d1, a, b)] == root_distance[get_pair(d2, a, b)]
)
def test_all_pairs_lca_gold_example(self):
self.assert_lca_dicts_same(dict(all_pairs_lca(self.DG)), self.gold)
def test_all_pairs_lca_all_pairs_given(self):
all_pairs = list(product(self.DG.nodes(), self.DG.nodes()))
ans = all_pairs_lca(self.DG, pairs=all_pairs)
self.assert_lca_dicts_same(dict(ans), self.gold)
def test_all_pairs_lca_generator(self):
all_pairs = product(self.DG.nodes(), self.DG.nodes())
ans = all_pairs_lca(self.DG, pairs=all_pairs)
self.assert_lca_dicts_same(dict(ans), self.gold)
def test_all_pairs_lca_input_graph_with_two_roots(self):
G = self.DG.copy()
G.add_edge(9, 10)
G.add_edge(9, 4)
gold = self.gold.copy()
gold[9, 9] = 9
gold[9, 10] = 9
gold[9, 4] = 9
gold[9, 3] = 9
gold[10, 4] = 9
gold[10, 3] = 9
gold[10, 10] = 10
testing = dict(all_pairs_lca(G))
G.add_edge(-1, 9)
G.add_edge(-1, 0)
self.assert_lca_dicts_same(testing, gold, G)
def test_all_pairs_lca_nonexisting_pairs_exception(self):
pytest.raises(nx.NodeNotFound, all_pairs_lca, self.DG, [(-1, -1)])
def test_all_pairs_lca_pairs_without_lca(self):
G = self.DG.copy()
G.add_node(-1)
gen = all_pairs_lca(G, [(-1, -1), (-1, 0)])
assert dict(gen) == {(-1, -1): -1}
def test_all_pairs_lca_null_graph(self):
pytest.raises(nx.NetworkXPointlessConcept, all_pairs_lca, nx.DiGraph())
def test_all_pairs_lca_non_dags(self):
pytest.raises(nx.NetworkXError, all_pairs_lca, nx.DiGraph([(3, 4), (4, 3)]))
def test_all_pairs_lca_nonempty_graph_without_lca(self):
G = nx.DiGraph()
G.add_node(3)
ans = list(all_pairs_lca(G))
assert ans == [((3, 3), 3)]
def test_all_pairs_lca_bug_gh4942(self):
G = nx.DiGraph([(0, 2), (1, 2), (2, 3)])
ans = list(all_pairs_lca(G))
assert len(ans) == 9
def test_all_pairs_lca_default_kwarg(self):
G = nx.DiGraph([(0, 1), (2, 1)])
sentinel = object()
assert nx.lowest_common_ancestor(G, 0, 2, default=sentinel) is sentinel
def test_all_pairs_lca_identity(self):
G = nx.DiGraph()
G.add_node(3)
assert nx.lowest_common_ancestor(G, 3, 3) == 3
def test_all_pairs_lca_issue_4574(self):
G = nx.DiGraph()
G.add_nodes_from(range(17))
G.add_edges_from(
[
(2, 0),
(1, 2),
(3, 2),
(5, 2),
(8, 2),
(11, 2),
(4, 5),
(6, 5),
(7, 8),
(10, 8),
(13, 11),
(14, 11),
(15, 11),
(9, 10),
(12, 13),
(16, 15),
]
)
assert nx.lowest_common_ancestor(G, 7, 9) is None
def test_all_pairs_lca_one_pair_gh4942(self):
G = nx.DiGraph()
# Note: order edge addition is critical to the test
G.add_edge(0, 1)
G.add_edge(2, 0)
G.add_edge(2, 3)
G.add_edge(4, 0)
G.add_edge(5, 2)
assert nx.lowest_common_ancestor(G, 1, 3) == 2
| TestDAGLCA |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataplex.py | {
"start": 59816,
"end": 62943
} | class ____(GoogleCloudBaseOperator):
"""
Gets a DataScan DataProfile resource.
:param project_id: Required. The ID of the Google Cloud project that the lake belongs to.
:param region: Required. The ID of the Google Cloud region that the lake belongs to.
:param data_scan_id: Required. Data Profile scan identifier.
:param api_version: The version of the api that will be requested for example 'v1'.
:param retry: A retry object used to retry requests. If `None` is specified, requests
will not be retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete.
Note that if `retry` is specified, the timeout applies to each individual attempt.
:param metadata: Additional metadata that is provided to the method.
:param gcp_conn_id: The connection ID to use when fetching connection info.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
:return: Dataplex data profile
"""
template_fields = ("project_id", "data_scan_id", "impersonation_chain")
def __init__(
self,
project_id: str,
region: str,
data_scan_id: str,
api_version: str = "v1",
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
*args,
**kwargs,
) -> None:
super().__init__(*args, **kwargs)
self.project_id = project_id
self.region = region
self.data_scan_id = data_scan_id
self.api_version = api_version
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
def execute(self, context: Context):
hook = DataplexHook(
gcp_conn_id=self.gcp_conn_id,
api_version=self.api_version,
impersonation_chain=self.impersonation_chain,
)
self.log.info("Retrieving the details of Dataplex Data Profile scan %s", self.data_scan_id)
data_profile_scan = hook.get_data_scan(
project_id=self.project_id,
region=self.region,
data_scan_id=self.data_scan_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
return DataScan.to_dict(data_profile_scan)
| DataplexGetDataProfileScanOperator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.