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 | Netflix__metaflow | metaflow/packaging_sys/distribution_support.py | {
"start": 3121,
"end": 4111
} | class ____(metadata.Distribution):
"""
A Python Package packaged within a MetaflowCodeContent. This allows users to use use importlib
as they would regularly and the packaged Python Package would be considered as a
distribution even if it really isn't (since it is just included in the PythonPath).
"""
def __init__(self, root: str, content: Dict[str, str]):
self._root = Path(root)
self._content = content
# Strongly inspired from PathDistribution in metadata.py
def read_text(self, filename: Union[str, os.PathLike]) -> Optional[str]:
if str(filename) in self._content:
return self._content[str(filename)]
return None
read_text.__doc__ = metadata.Distribution.read_text.__doc__
# Returns a metadata.SimplePath but not always present in importlib.metadata libs so
# skipping return type.
def locate_file(self, path: Union[str, os.PathLike]):
return self._root / path
| PackagedDistribution |
python | django__django | tests/template_tests/filter_tests/test_dictsort.py | {
"start": 113,
"end": 309
} | class ____:
password = "abc"
_private = "private"
@property
def test_property(self):
return "cde"
def test_method(self):
"""This is just a test method."""
| User |
python | django-import-export__django-import-export | tests/core/tests/test_instance_loaders.py | {
"start": 1802,
"end": 2760
} | class ____(TestCase):
"""Ensure that the cache is empty when the PK field is absent
in the inbound dataset.
"""
def setUp(self):
self.resource = resources.modelresource_factory(Book)()
self.dataset = tablib.Dataset(headers=["name", "author_email"])
self.book = Book.objects.create(name="Some book")
self.book2 = Book.objects.create(name="Some other book")
row = ["Some book", "test@example.com"]
self.dataset.append(row)
self.instance_loader = instance_loaders.CachedInstanceLoader(
self.resource, self.dataset
)
def test_all_instances(self):
self.assertEqual(self.instance_loader.all_instances, {})
self.assertEqual(len(self.instance_loader.all_instances), 0)
def test_get_instance(self):
obj = self.instance_loader.get_instance(self.dataset.dict[0])
self.assertEqual(obj, None)
| CachedInstanceLoaderWithAbsentImportIdFieldTest |
python | pikepdf__pikepdf | src/pikepdf/models/outlines.py | {
"start": 9337,
"end": 16200
} | class ____:
"""Maintains a intuitive interface for creating and editing PDF document outlines.
See {{ pdfrm }} section 12.3.
Arguments:
pdf: PDF document object.
max_depth: Maximum recursion depth to consider when reading the outline.
strict: If set to ``False`` (default) silently ignores structural errors.
Setting it to ``True`` raises a
:class:`pikepdf.OutlineStructureError`
if any object references re-occur while the outline is being read or
written.
See Also:
:meth:`pikepdf.Pdf.open_outline`
"""
def __init__(self, pdf: Pdf, max_depth: int = 15, strict: bool = False):
"""Initialize Outline."""
self._root: list[OutlineItem] | None = None
self._pdf = pdf
self._max_depth = max_depth
self._strict = strict
self._updating = False
def __str__(self):
return str(self.root)
def __repr__(self):
return f'<pikepdf.{self.__class__.__name__}: {len(self.root)} items>'
def _repr_pretty_(self, p, cycle):
if cycle:
p.text("...")
else:
with p.group(2, "pikepdf.models.outlines.Outline<\n", "\n>"):
for _, item in enumerate(self.root):
p.breakable()
p.pretty(str(item))
def __enter__(self):
self._updating = True
return self
def __exit__(self, exc_type, exc_val, exc_tb):
try:
if exc_type is not None:
return
self._save()
finally:
self._updating = False
def _save_level_outline(
self,
parent: Dictionary,
outline_items: Iterable[OutlineItem],
level: int,
visited_objs: set[tuple[int, int]],
):
count = 0
prev: Dictionary | None = None
first: Dictionary | None = None
for item in outline_items:
out_obj = item.to_dictionary_object(self._pdf)
objgen = out_obj.objgen
if objgen in visited_objs:
if self._strict:
raise OutlineStructureError(
f"Outline object {objgen} reoccurred in structure"
)
out_obj = item.to_dictionary_object(self._pdf, create_new=True)
else:
visited_objs.add(objgen)
out_obj.Parent = parent
count += 1
if prev is not None:
prev.Next = out_obj
out_obj.Prev = prev
else:
first = out_obj
if Name.Prev in out_obj:
del out_obj.Prev
prev = out_obj
if level < self._max_depth:
sub_items: Iterable[OutlineItem] = item.children
else:
sub_items = ()
self._save_level_outline(out_obj, sub_items, level + 1, visited_objs)
if item.is_closed:
out_obj.Count = -cast(int, out_obj.Count)
else:
count += cast(int, out_obj.Count)
if count:
assert prev is not None and first is not None
if Name.Next in prev:
del prev.Next
parent.First = first
parent.Last = prev
else:
if Name.First in parent:
del parent.First
if Name.Last in parent:
del parent.Last
parent.Count = count
def _load_level_outline(
self,
first_obj: Dictionary,
outline_items: list[Object],
level: int,
visited_objs: set[tuple[int, int]],
):
current_obj: Dictionary | None = first_obj
while current_obj:
objgen = current_obj.objgen
if objgen in visited_objs:
if self._strict:
raise OutlineStructureError(
f"Outline object {objgen} reoccurred in structure"
)
return
visited_objs.add(objgen)
item = OutlineItem.from_dictionary_object(current_obj)
first_child = current_obj.get(Name.First)
if isinstance(first_child, Dictionary) and level < self._max_depth:
self._load_level_outline(
first_child, item.children, level + 1, visited_objs
)
count = current_obj.get(Name.Count)
if isinstance(count, int) and count < 0:
item.is_closed = True
outline_items.append(item)
next_obj = current_obj.get(Name.Next)
if next_obj is None or isinstance(next_obj, Dictionary):
current_obj = next_obj
else:
raise OutlineStructureError(
f"Outline object {objgen} points to non-dictionary"
)
def _save(self):
if self._root is None:
return
if Name.Outlines in self._pdf.Root:
outlines = self._pdf.Root.Outlines
else:
self._pdf.Root.Outlines = outlines = self._pdf.make_indirect(
Dictionary(Type=Name.Outlines)
)
self._save_level_outline(outlines, self._root, 0, set())
def _load(self):
self._root = root = []
if Name.Outlines not in self._pdf.Root:
return
outlines = self._pdf.Root.Outlines or {}
first_obj = outlines.get(Name.First)
if first_obj:
self._load_level_outline(first_obj, root, 0, set())
def add(self, title: str, destination: Array | int | None) -> OutlineItem:
"""Add an item to the outline.
Arguments:
title: Title of the outline item.
destination: Destination to jump to when the item is selected.
Returns:
The newly created :class:`OutlineItem`.
"""
if self._root is None:
self._load()
item = OutlineItem(title, destination)
if self._root is None:
self._root = [item]
else:
self._root.append(item)
if not self._updating:
self._save()
return item
@property
def root(self) -> list[OutlineItem]:
"""Return the root node of the outline."""
if self._root is None:
self._load()
return cast(list[OutlineItem], self._root)
@root.setter
def root(self, new_root: list[OutlineItem]):
"""Set the root node of the outline."""
if not isinstance(new_root, list):
raise ValueError("Root must be a list of OutlineItem objects.")
for item in new_root:
if not isinstance(item, OutlineItem):
raise ValueError("Each item in root must be an OutlineItem.")
self._root = new_root
| Outline |
python | getsentry__sentry | src/sentry/web/frontend/debug/debug_note_email.py | {
"start": 243,
"end": 595
} | class ____(ActivityMailDebugView):
def get_activity(self, request: HttpRequest, event):
random = get_random(request)
return {
"type": ActivityType.NOTE.value,
"user_id": request.user.id,
"data": {"text": make_message(random, max(2, int(random.weibullvariate(12, 0.4))))},
}
| DebugNoteEmailView |
python | google__flatbuffers | python/flatbuffers/number_types.py | {
"start": 1116,
"end": 1259
} | class ____(object):
bytewidth = 1
min_val = 0
max_val = (2**8) - 1
py_type = int
name = "uint8"
packer_type = packer.uint8
| Uint8Flags |
python | getsentry__sentry | tests/sentry/rules/history/backends/test_postgres.py | {
"start": 10182,
"end": 13658
} | class ____(BasePostgresRuleHistoryBackendTest):
def test(self) -> None:
rule = Rule.objects.create(project=self.event.project)
rule_2 = Rule.objects.create(project=self.event.project)
history = []
for i in range(3):
for _ in range(i + 1):
history.append(
RuleFireHistory(
project=rule.project,
rule=rule,
group=self.group,
date_added=before_now(hours=i + 1),
)
)
for i in range(2):
history.append(
RuleFireHistory(
project=rule_2.project,
rule=rule_2,
group=self.group,
date_added=before_now(hours=i + 1),
)
)
RuleFireHistory.objects.bulk_create(history)
results = self.backend.fetch_rule_hourly_stats(rule, before_now(hours=24), before_now())
assert len(results) == 24
assert [r.count for r in results[-5:]] == [0, 3, 2, 1, 0]
results = self.backend.fetch_rule_hourly_stats(rule_2, before_now(hours=24), before_now())
assert len(results) == 24
assert [r.count for r in results[-5:]] == [0, 0, 1, 1, 0]
def test_combined_rule_and_workflow_history(self) -> None:
"""Test combining RuleFireHistory and WorkflowFireHistory for hourly stats when feature flag is enabled"""
rule = self.create_project_rule(project=self.event.project)
workflow = self.create_workflow(organization=self.event.project.organization)
AlertRuleWorkflow.objects.create(rule_id=rule.id, workflow=workflow)
rule_history = []
# Hour 1: 2 rule fire entries
for _ in range(2):
rule_history.append(
RuleFireHistory(
project=rule.project,
rule=rule,
group=self.group,
date_added=before_now(hours=1),
)
)
# Hour 2: 1 rule fire entry
rule_history.append(
RuleFireHistory(
project=rule.project,
rule=rule,
group=self.group,
date_added=before_now(hours=2),
)
)
# Hour 1: 1 workflow fire entry
wfh = WorkflowFireHistory.objects.create(
workflow=workflow,
group=self.group,
date_added=before_now(hours=1),
)
wfh.update(date_added=before_now(hours=1))
# Hour 3: 2 workflow fire entries
for _ in range(2):
wfh = WorkflowFireHistory.objects.create(
workflow=workflow,
group=self.group,
date_added=before_now(hours=3),
)
wfh.update(date_added=before_now(hours=3))
RuleFireHistory.objects.bulk_create(rule_history)
results = self.backend.fetch_rule_hourly_stats(rule, before_now(hours=24), before_now())
assert len(results) == 24
# Check the last 5 hours (from most recent to oldest)
# Hour 0: 0 total
# Hour 1: 2 (rule) + 1 (workflow) = 3 total
# Hour 2: 1 (rule) + 0 (workflow) = 1 total
# Hour 3: 0 (rule) + 2 (workflow) = 2 total
# Hour 4: 0 total
assert [r.count for r in results[-5:]] == [0, 2, 1, 3, 0]
| FetchRuleHourlyStatsPaginatedTest |
python | tensorflow__tensorflow | tensorflow/python/checkpoint/checkpoint_test.py | {
"start": 59472,
"end": 61667
} | class ____(parameterized.TestCase, test.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_trackable_save_restore_nested(self):
def _inner_template():
v = variable_scope.get_variable(
"v", shape=[1], initializer=init_ops.zeros_initializer())
return v
def _outer_template():
first_inner = template.make_template("i1", _inner_template)
second_inner = template.make_template("i2", _inner_template)
v1 = first_inner()
v2 = second_inner()
v3 = second_inner()
return (first_inner, second_inner), (v1, v2, v3)
with variable_scope.variable_scope("ignored"):
save_template = template.make_template("s1", _outer_template)
save_root = trackable_utils.Checkpoint(my_template=save_template)
(inner_template_one, inner_template_two), _ = save_template()
self.evaluate(inner_template_one.variables[0].assign([20.]))
self.evaluate(inner_template_two.variables[0].assign([25.]))
checkpoint_directory = self.get_temp_dir()
checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt")
save_path = save_root.save(checkpoint_prefix)
load_template = template.make_template("s2", _outer_template)
load_root = trackable_utils.Checkpoint(my_template=load_template)
status = load_root.restore(save_path)
(inner_template_one, inner_template_two), (v1, v2, v3) = load_template()
outer_template_dependencies = load_root.my_template._trackable_children()
self.assertLen(outer_template_dependencies, 2)
self.assertDictEqual({"i1": inner_template_one, "i2": inner_template_two},
outer_template_dependencies)
self.assertLen(inner_template_one._trackable_children(), 1)
self.assertIn("v", inner_template_one._trackable_children())
self.assertLen(inner_template_two._trackable_children(), 1)
self.assertIn("v", inner_template_two._trackable_children())
status.assert_consumed().run_restore_ops()
self.assertAllEqual([20.], self.evaluate(v1))
self.assertAllEqual([25.], self.evaluate(v2))
self.assertAllEqual([25.], self.evaluate(v3))
if __name__ == "__main__":
ops.enable_eager_execution()
test.main()
| TemplateTests |
python | dagster-io__dagster | python_modules/libraries/dagster-dbt/dagster_dbt/cloud_v2/types.py | {
"start": 281,
"end": 657
} | class ____:
"""Represents a dbt Cloud Account, based on data as returned from the API."""
id: int
name: Optional[str]
@classmethod
def from_account_details(cls, account_details: Mapping[str, Any]) -> "DbtCloudAccount":
return cls(
id=account_details["id"],
name=account_details.get("name"),
)
@record
| DbtCloudAccount |
python | pypa__warehouse | tests/unit/accounts/test_views.py | {
"start": 146844,
"end": 207594
} | class ____:
def test_initializes(self, metrics):
project_service = pretend.stub(check_project_name=lambda name: None)
def find_service(iface, name=None, context=None):
if iface is IMetricsService:
return metrics
if iface is IProjectService:
return project_service
pytest.fail(f"Unexpected service requested: {iface}")
request = pretend.stub(
find_service=pretend.call_recorder(find_service),
route_url=pretend.stub(),
POST=MultiDict(),
user=pretend.stub(id=pretend.stub()),
registry=pretend.stub(
settings={
"github.token": "fake-api-token",
}
),
)
view = views.ManageAccountPublishingViews(request)
assert view.request is request
assert view.metrics is metrics
assert view.project_service is project_service
assert view.request.find_service.calls == [
pretend.call(IMetricsService, context=None),
pretend.call(IProjectService, context=None),
]
@pytest.mark.parametrize(
("ip_exceeded", "user_exceeded"),
[
(False, False),
(False, True),
(True, False),
],
)
def test_ratelimiting(self, metrics, ip_exceeded, user_exceeded):
user_rate_limiter = pretend.stub(
hit=pretend.call_recorder(lambda *a, **kw: None),
test=pretend.call_recorder(lambda uid: not user_exceeded),
resets_in=pretend.call_recorder(lambda uid: pretend.stub()),
)
ip_rate_limiter = pretend.stub(
hit=pretend.call_recorder(lambda *a, **kw: None),
test=pretend.call_recorder(lambda ip: not ip_exceeded),
resets_in=pretend.call_recorder(lambda uid: pretend.stub()),
)
def find_service(iface, name=None, context=None):
if iface is IMetricsService:
return metrics
if iface is IProjectService:
return pretend.stub(check_project_name=lambda name: None)
if name == "user_oidc.publisher.register":
return user_rate_limiter
else:
return ip_rate_limiter
request = pretend.stub(
find_service=pretend.call_recorder(find_service),
user=pretend.stub(id=pretend.stub()),
remote_addr=pretend.stub(),
POST=MultiDict(),
registry=pretend.stub(
settings={
"github.token": "fake-api-token",
}
),
route_url=pretend.stub(),
)
view = views.ManageAccountPublishingViews(request)
assert view._ratelimiters == {
"user.oidc": user_rate_limiter,
"ip.oidc": ip_rate_limiter,
}
assert request.find_service.calls == [
pretend.call(IMetricsService, context=None),
pretend.call(IProjectService, context=None),
pretend.call(IRateLimiter, name="user_oidc.publisher.register"),
pretend.call(IRateLimiter, name="ip_oidc.publisher.register"),
]
view._hit_ratelimits()
assert user_rate_limiter.hit.calls == [
pretend.call(request.user.id),
]
assert ip_rate_limiter.hit.calls == [pretend.call(request.remote_addr)]
if user_exceeded or ip_exceeded:
with pytest.raises(TooManyOIDCRegistrations):
view._check_ratelimits()
else:
view._check_ratelimits()
def test_manage_publishing(self, metrics, monkeypatch):
route_url = pretend.stub()
request = pretend.stub(
user=pretend.stub(),
route_url=route_url,
registry=pretend.stub(
settings={
"github.token": "fake-api-token",
}
),
find_service=lambda svc, **kw: {
IMetricsService: metrics,
IProjectService: project_service,
}[svc],
flags=pretend.stub(
disallow_oidc=pretend.call_recorder(lambda f=None: False)
),
POST=pretend.stub(),
)
project_service = pretend.stub(check_project_name=lambda name: None)
pending_github_publisher_form_obj = pretend.stub()
pending_github_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_github_publisher_form_obj
)
monkeypatch.setattr(
views, "PendingGitHubPublisherForm", pending_github_publisher_form_cls
)
pending_gitlab_publisher_form_obj = pretend.stub()
pending_gitlab_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_gitlab_publisher_form_obj
)
monkeypatch.setattr(
views, "PendingGitLabPublisherForm", pending_gitlab_publisher_form_cls
)
pending_google_publisher_form_obj = pretend.stub()
pending_google_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_google_publisher_form_obj
)
monkeypatch.setattr(
views, "PendingGooglePublisherForm", pending_google_publisher_form_cls
)
pending_activestate_publisher_form_obj = pretend.stub()
pending_activestate_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_activestate_publisher_form_obj
)
monkeypatch.setattr(
views,
"PendingActiveStatePublisherForm",
pending_activestate_publisher_form_cls,
)
view = views.ManageAccountPublishingViews(request)
assert view.manage_publishing() == {
"disabled": {
"GitHub": False,
"GitLab": False,
"Google": False,
"ActiveState": False,
},
"pending_github_publisher_form": pending_github_publisher_form_obj,
"pending_gitlab_publisher_form": pending_gitlab_publisher_form_obj,
"pending_google_publisher_form": pending_google_publisher_form_obj,
"pending_activestate_publisher_form": pending_activestate_publisher_form_obj, # noqa: E501
}
assert request.flags.disallow_oidc.calls == [
pretend.call(),
pretend.call(AdminFlagValue.DISALLOW_GITHUB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GITLAB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GOOGLE_OIDC),
pretend.call(AdminFlagValue.DISALLOW_ACTIVESTATE_OIDC),
]
assert pending_github_publisher_form_cls.calls == [
pretend.call(
request.POST,
api_token="fake-api-token",
route_url=route_url,
check_project_name=project_service.check_project_name,
user=request.user,
)
]
assert pending_gitlab_publisher_form_cls.calls == [
pretend.call(
request.POST,
route_url=route_url,
check_project_name=project_service.check_project_name,
user=request.user,
)
]
def test_manage_publishing_admin_disabled(self, monkeypatch, pyramid_request):
project_service = pretend.stub(check_project_name=lambda name: None)
pyramid_request.find_service = lambda _, **kw: project_service
pyramid_request.user = pretend.stub()
pyramid_request.registry = pretend.stub(
settings={
"github.token": "fake-api-token",
}
)
pyramid_request.flags = pretend.stub(
disallow_oidc=pretend.call_recorder(lambda f=None: True)
)
pyramid_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
pending_github_publisher_form_obj = pretend.stub()
pending_github_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_github_publisher_form_obj
)
monkeypatch.setattr(
views, "PendingGitHubPublisherForm", pending_github_publisher_form_cls
)
pending_gitlab_publisher_form_obj = pretend.stub()
pending_gitlab_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_gitlab_publisher_form_obj
)
monkeypatch.setattr(
views, "PendingGitLabPublisherForm", pending_gitlab_publisher_form_cls
)
pending_google_publisher_form_obj = pretend.stub()
pending_google_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_google_publisher_form_obj
)
monkeypatch.setattr(
views, "PendingGooglePublisherForm", pending_google_publisher_form_cls
)
pending_activestate_publisher_form_obj = pretend.stub()
pending_activestate_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_activestate_publisher_form_obj
)
monkeypatch.setattr(
views,
"PendingActiveStatePublisherForm",
pending_activestate_publisher_form_cls,
)
view = views.ManageAccountPublishingViews(pyramid_request)
assert view.manage_publishing() == {
"disabled": {
"GitHub": True,
"GitLab": True,
"Google": True,
"ActiveState": True,
},
"pending_github_publisher_form": pending_github_publisher_form_obj,
"pending_gitlab_publisher_form": pending_gitlab_publisher_form_obj,
"pending_google_publisher_form": pending_google_publisher_form_obj,
"pending_activestate_publisher_form": pending_activestate_publisher_form_obj, # noqa: E501
}
assert pyramid_request.flags.disallow_oidc.calls == [
pretend.call(),
pretend.call(AdminFlagValue.DISALLOW_GITHUB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GITLAB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GOOGLE_OIDC),
pretend.call(AdminFlagValue.DISALLOW_ACTIVESTATE_OIDC),
]
assert pyramid_request.session.flash.calls == [
pretend.call(
(
"Trusted publishing is temporarily disabled. "
"See https://pypi.org/help#admin-intervention for details."
),
queue="error",
)
]
assert pending_github_publisher_form_cls.calls == [
pretend.call(
pyramid_request.POST,
api_token="fake-api-token",
route_url=pyramid_request.route_url,
check_project_name=project_service.check_project_name,
user=pyramid_request.user,
)
]
assert pending_gitlab_publisher_form_cls.calls == [
pretend.call(
pyramid_request.POST,
route_url=pyramid_request.route_url,
check_project_name=project_service.check_project_name,
user=pyramid_request.user,
)
]
@pytest.mark.parametrize(
("view_name", "flag", "publisher_name"),
[
(
"add_pending_github_oidc_publisher",
AdminFlagValue.DISALLOW_GITHUB_OIDC,
"GitHub",
),
(
"add_pending_gitlab_oidc_publisher",
AdminFlagValue.DISALLOW_GITLAB_OIDC,
"GitLab",
),
(
"add_pending_google_oidc_publisher",
AdminFlagValue.DISALLOW_GOOGLE_OIDC,
"Google",
),
(
"add_pending_activestate_oidc_publisher",
AdminFlagValue.DISALLOW_ACTIVESTATE_OIDC,
"ActiveState",
),
],
)
def test_add_pending_oidc_publisher_admin_disabled(
self, monkeypatch, pyramid_request, view_name, flag, publisher_name
):
project_service = pretend.stub(check_project_name=lambda name: None)
pyramid_request.find_service = lambda interface, **kwargs: {
IProjectService: project_service,
IMetricsService: pretend.stub(),
}[interface]
pyramid_request.user = pretend.stub()
pyramid_request.registry = pretend.stub(
settings={
"github.token": "fake-api-token",
}
)
pyramid_request.flags = pretend.stub(
disallow_oidc=pretend.call_recorder(lambda f=None: True),
)
pyramid_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
pending_github_publisher_form_obj = pretend.stub()
pending_github_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_github_publisher_form_obj
)
monkeypatch.setattr(
views,
"PendingGitHubPublisherForm",
pending_github_publisher_form_cls,
)
pending_activestate_publisher_form_obj = pretend.stub()
pending_activestate_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_activestate_publisher_form_obj
)
monkeypatch.setattr(
views,
"PendingActiveStatePublisherForm",
pending_activestate_publisher_form_cls,
)
pending_gitlab_publisher_form_obj = pretend.stub()
pending_gitlab_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_gitlab_publisher_form_obj
)
monkeypatch.setattr(
views, "PendingGitLabPublisherForm", pending_gitlab_publisher_form_cls
)
pending_google_publisher_form_obj = pretend.stub()
pending_google_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_google_publisher_form_obj
)
monkeypatch.setattr(
views, "PendingGooglePublisherForm", pending_google_publisher_form_cls
)
view = views.ManageAccountPublishingViews(pyramid_request)
assert getattr(view, view_name)() == {
"disabled": {
"GitHub": True,
"GitLab": True,
"Google": True,
"ActiveState": True,
},
"pending_github_publisher_form": pending_github_publisher_form_obj,
"pending_gitlab_publisher_form": pending_gitlab_publisher_form_obj,
"pending_google_publisher_form": pending_google_publisher_form_obj,
"pending_activestate_publisher_form": pending_activestate_publisher_form_obj, # noqa: E501
}
assert pyramid_request.flags.disallow_oidc.calls == [
pretend.call(AdminFlagValue.DISALLOW_GITHUB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GITLAB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GOOGLE_OIDC),
pretend.call(AdminFlagValue.DISALLOW_ACTIVESTATE_OIDC),
pretend.call(flag),
pretend.call(AdminFlagValue.DISALLOW_GITHUB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GITLAB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GOOGLE_OIDC),
pretend.call(AdminFlagValue.DISALLOW_ACTIVESTATE_OIDC),
]
assert pyramid_request.session.flash.calls == [
pretend.call(
(
f"{publisher_name}-based trusted publishing is temporarily "
"disabled. See https://pypi.org/help#admin-intervention for "
"details."
),
queue="error",
)
]
assert pending_github_publisher_form_cls.calls == [
pretend.call(
pyramid_request.POST,
api_token="fake-api-token",
route_url=pyramid_request.route_url,
check_project_name=project_service.check_project_name,
user=pyramid_request.user,
)
]
assert pending_gitlab_publisher_form_cls.calls == [
pretend.call(
pyramid_request.POST,
route_url=pyramid_request.route_url,
check_project_name=project_service.check_project_name,
user=pyramid_request.user,
)
]
@pytest.mark.parametrize(
("view_name", "flag", "publisher_name"),
[
(
"add_pending_github_oidc_publisher",
AdminFlagValue.DISALLOW_GITHUB_OIDC,
"GitHub",
),
(
"add_pending_gitlab_oidc_publisher",
AdminFlagValue.DISALLOW_GITLAB_OIDC,
"GitLab",
),
(
"add_pending_google_oidc_publisher",
AdminFlagValue.DISALLOW_GOOGLE_OIDC,
"Google",
),
(
"add_pending_activestate_oidc_publisher",
AdminFlagValue.DISALLOW_ACTIVESTATE_OIDC,
"ActiveState",
),
],
)
def test_add_pending_oidc_publisher_user_cannot_register(
self,
monkeypatch,
pyramid_request,
view_name,
flag,
publisher_name,
metrics,
):
project_service = pretend.stub(check_project_name=lambda name: None)
pyramid_request.find_service = lambda interface, **kwargs: {
IProjectService: project_service,
IMetricsService: metrics,
}[interface]
pyramid_request.registry = pretend.stub(
settings={
"github.token": "fake-api-token",
}
)
pyramid_request.user = pretend.stub(
has_primary_verified_email=False,
)
pyramid_request.flags = pretend.stub(
disallow_oidc=pretend.call_recorder(lambda f=None: False),
)
pyramid_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
pending_github_publisher_form_obj = pretend.stub()
pending_github_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_github_publisher_form_obj
)
monkeypatch.setattr(
views, "PendingGitHubPublisherForm", pending_github_publisher_form_cls
)
pending_gitlab_publisher_form_obj = pretend.stub()
pending_gitlab_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_gitlab_publisher_form_obj
)
monkeypatch.setattr(
views, "PendingGitLabPublisherForm", pending_gitlab_publisher_form_cls
)
pending_google_publisher_form_obj = pretend.stub()
pending_google_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_google_publisher_form_obj
)
monkeypatch.setattr(
views, "PendingGooglePublisherForm", pending_google_publisher_form_cls
)
pending_activestate_publisher_form_obj = pretend.stub()
pending_activestate_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_activestate_publisher_form_obj
)
monkeypatch.setattr(
views,
"PendingActiveStatePublisherForm",
pending_activestate_publisher_form_cls,
)
view = views.ManageAccountPublishingViews(pyramid_request)
assert getattr(view, view_name)() == {
"disabled": {
"GitHub": False,
"GitLab": False,
"Google": False,
"ActiveState": False,
},
"pending_github_publisher_form": pending_github_publisher_form_obj,
"pending_gitlab_publisher_form": pending_gitlab_publisher_form_obj,
"pending_google_publisher_form": pending_google_publisher_form_obj,
"pending_activestate_publisher_form": pending_activestate_publisher_form_obj, # noqa: E501
}
assert pyramid_request.flags.disallow_oidc.calls == [
pretend.call(AdminFlagValue.DISALLOW_GITHUB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GITLAB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GOOGLE_OIDC),
pretend.call(AdminFlagValue.DISALLOW_ACTIVESTATE_OIDC),
pretend.call(flag),
pretend.call(AdminFlagValue.DISALLOW_GITHUB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GITLAB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GOOGLE_OIDC),
pretend.call(AdminFlagValue.DISALLOW_ACTIVESTATE_OIDC),
]
assert view.metrics.increment.calls == [
pretend.call(
"warehouse.oidc.add_pending_publisher.attempt",
tags=[f"publisher:{publisher_name}"],
),
]
assert pyramid_request.session.flash.calls == [
pretend.call(
(
"You must have a verified email in order to register a "
"pending trusted publisher. "
"See https://pypi.org/help#openid-connect for details."
),
queue="error",
)
]
assert pending_github_publisher_form_cls.calls == [
pretend.call(
pyramid_request.POST,
api_token="fake-api-token",
route_url=pyramid_request.route_url,
check_project_name=project_service.check_project_name,
user=pyramid_request.user,
)
]
assert pending_gitlab_publisher_form_cls.calls == [
pretend.call(
pyramid_request.POST,
route_url=pyramid_request.route_url,
check_project_name=project_service.check_project_name,
user=pyramid_request.user,
)
]
@pytest.mark.parametrize(
("view_name", "flag", "publisher_name", "make_publisher", "publisher_class"),
[
(
"add_pending_github_oidc_publisher",
AdminFlagValue.DISALLOW_GITHUB_OIDC,
"GitHub",
lambda i, user_id: PendingGitHubPublisher(
project_name="some-project-name-" + str(i),
repository_name="some-repository" + str(i),
repository_owner="some-owner",
repository_owner_id="some-id",
workflow_filename="some-filename",
environment="",
added_by_id=user_id,
),
PendingGitHubPublisher,
),
(
"add_pending_gitlab_oidc_publisher",
AdminFlagValue.DISALLOW_GITLAB_OIDC,
"GitLab",
lambda i, user_id: PendingGitLabPublisher(
project_name="some-project-name-" + str(i),
project="some-repository" + str(i),
namespace="some-namespace",
workflow_filepath="some-filepath",
environment="",
issuer_url="https://gitlab.com",
added_by_id=user_id,
),
PendingGitLabPublisher,
),
(
"add_pending_google_oidc_publisher",
AdminFlagValue.DISALLOW_GOOGLE_OIDC,
"Google",
lambda i, user_id: PendingGooglePublisher(
project_name="some-project-name-" + str(i),
email="some-email-" + str(i) + "@example.com",
sub="some-sub",
added_by_id=user_id,
),
PendingGooglePublisher,
),
(
"add_pending_activestate_oidc_publisher",
AdminFlagValue.DISALLOW_ACTIVESTATE_OIDC,
"ActiveState",
lambda i, user_id: PendingActiveStatePublisher(
project_name="some-project-name-" + str(i),
added_by_id=user_id,
organization="some-org-" + str(i),
activestate_project_name="some-project-" + str(i),
actor="some-user-" + str(i),
actor_id="some-user-id-" + str(i),
),
PendingActiveStatePublisher,
),
],
)
def test_add_pending_github_oidc_publisher_too_many_already(
self,
monkeypatch,
db_request,
view_name,
flag,
publisher_name,
make_publisher,
publisher_class,
):
db_request.user = UserFactory.create()
EmailFactory(user=db_request.user, verified=True, primary=True)
for i in range(3):
pending_publisher = make_publisher(i, db_request.user.id)
db_request.db.add(pending_publisher)
db_request.registry = pretend.stub(
settings={
"github.token": "fake-api-token",
}
)
db_request.flags = pretend.stub(
disallow_oidc=pretend.call_recorder(lambda f=None: False)
)
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
db_request.POST = MultiDict(
{
"owner": "some-owner",
"repository": "some-repository",
"workflow_filename": "some-workflow-filename.yml",
"environment": "some-environment",
"project_name": "some-other-project-name",
}
)
view = views.ManageAccountPublishingViews(db_request)
assert getattr(view, view_name)() == view.default_response
assert db_request.flags.disallow_oidc.calls == [
pretend.call(AdminFlagValue.DISALLOW_GITHUB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GITLAB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GOOGLE_OIDC),
pretend.call(AdminFlagValue.DISALLOW_ACTIVESTATE_OIDC),
pretend.call(flag),
pretend.call(AdminFlagValue.DISALLOW_GITHUB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GITLAB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GOOGLE_OIDC),
pretend.call(AdminFlagValue.DISALLOW_ACTIVESTATE_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GITHUB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GITLAB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GOOGLE_OIDC),
pretend.call(AdminFlagValue.DISALLOW_ACTIVESTATE_OIDC),
]
assert view.metrics.increment.calls == [
pretend.call(
"warehouse.oidc.add_pending_publisher.attempt",
tags=[f"publisher:{publisher_name}"],
),
]
assert db_request.session.flash.calls == [
pretend.call(
"You can't register more than 3 pending trusted publishers at once.",
queue="error",
)
]
assert len(db_request.db.query(publisher_class).all()) == 3
@pytest.mark.parametrize(
("view_name", "publisher_name"),
[
(
"add_pending_github_oidc_publisher",
"GitHub",
),
(
"add_pending_gitlab_oidc_publisher",
"GitLab",
),
(
"add_pending_google_oidc_publisher",
"Google",
),
(
"add_pending_activestate_oidc_publisher",
"ActiveState",
),
],
)
def test_add_pending_oidc_publisher_ratelimited(
self, monkeypatch, pyramid_request, view_name, publisher_name
):
pyramid_request.user = pretend.stub(
has_primary_verified_email=True,
pending_oidc_publishers=[],
)
pyramid_request.registry = pretend.stub(
settings={
"github.token": "fake-api-token",
}
)
pyramid_request.flags = pretend.stub(
disallow_oidc=pretend.call_recorder(lambda f=None: False)
)
pyramid_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
pyramid_request.POST = MultiDict(
{
"owner": "some-owner",
"repository": "some-repository",
"workflow_filename": "some-workflow-filename.yml",
"environment": "some-environment",
"project_name": "some-other-project-name",
}
)
view = views.ManageAccountPublishingViews(pyramid_request)
monkeypatch.setattr(
view,
"_check_ratelimits",
pretend.call_recorder(
pretend.raiser(
TooManyOIDCRegistrations(
resets_in=pretend.stub(total_seconds=lambda: 60)
)
)
),
)
assert isinstance(getattr(view, view_name)(), HTTPTooManyRequests)
assert view.metrics.increment.calls == [
pretend.call(
"warehouse.oidc.add_pending_publisher.attempt",
tags=[f"publisher:{publisher_name}"],
),
pretend.call(
"warehouse.oidc.add_pending_publisher.ratelimited",
tags=[f"publisher:{publisher_name}"],
),
]
@pytest.mark.parametrize(
("view_name", "publisher_name"),
[
(
"add_pending_github_oidc_publisher",
"GitHub",
),
(
"add_pending_gitlab_oidc_publisher",
"GitLab",
),
(
"add_pending_google_oidc_publisher",
"Google",
),
(
"add_pending_activestate_oidc_publisher",
"ActiveState",
),
],
)
def test_add_pending_oidc_publisher_invalid_form(
self, monkeypatch, db_request, view_name, publisher_name
):
db_request.user = pretend.stub(
has_primary_verified_email=True,
pending_oidc_publishers=[],
)
db_request.registry = pretend.stub(
settings={
"github.token": "fake-api-token",
}
)
db_request.flags = pretend.stub(
disallow_oidc=pretend.call_recorder(lambda f=None: False)
)
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
db_request.POST = MultiDict(
{
"owner": "some-owner",
"repository": "some-repository",
"workflow_filename": "some-workflow-filename-without-extension", # Fail
"environment": "some-environment",
"project_name": "some-other-project-name",
}
)
view = views.ManageAccountPublishingViews(db_request)
monkeypatch.setattr(
views.ManageAccountPublishingViews,
"default_response",
view.default_response,
)
monkeypatch.setattr(
views.PendingGitHubPublisherForm,
"_lookup_owner",
lambda *a: {"login": "some-owner", "id": "some-owner-id"},
)
monkeypatch.setattr(
views.PendingGitHubPublisherForm,
"validate_project_name",
lambda *a: True,
)
monkeypatch.setattr(
views.PendingActiveStatePublisherForm,
"_lookup_organization",
lambda *a: None,
)
monkeypatch.setattr(
views.PendingActiveStatePublisherForm,
"_lookup_actor",
lambda *a: {"user_id": "some-user-id"},
)
monkeypatch.setattr(
view, "_check_ratelimits", pretend.call_recorder(lambda: None)
)
monkeypatch.setattr(
view, "_hit_ratelimits", pretend.call_recorder(lambda: None)
)
assert getattr(view, view_name)() == view.default_response
assert view.metrics.increment.calls == [
pretend.call(
"warehouse.oidc.add_pending_publisher.attempt",
tags=[f"publisher:{publisher_name}"],
),
]
assert view._hit_ratelimits.calls == [pretend.call()]
assert view._check_ratelimits.calls == [pretend.call()]
@pytest.mark.parametrize(
("view_name", "publisher_name", "make_publisher", "post_body"),
[
(
"add_pending_github_oidc_publisher",
"GitHub",
lambda user_id: PendingGitHubPublisher(
project_name="some-project-name",
repository_name="some-repository",
repository_owner="some-owner",
repository_owner_id="some-owner-id",
workflow_filename="some-workflow-filename.yml",
environment="some-environment",
added_by_id=user_id,
),
MultiDict(
{
"owner": "some-owner",
"repository": "some-repository",
"workflow_filename": "some-workflow-filename.yml",
"environment": "some-environment",
"project_name": "some-project-name",
}
),
),
(
"add_pending_gitlab_oidc_publisher",
"GitLab",
lambda user_id: PendingGitLabPublisher(
project_name="some-project-name",
namespace="some-owner",
project="some-repository",
workflow_filepath="subfolder/some-workflow-filename.yml",
environment="some-environment",
issuer_url="https://gitlab.com",
added_by_id=user_id,
),
MultiDict(
{
"namespace": "some-owner",
"project": "some-repository",
"workflow_filepath": "subfolder/some-workflow-filename.yml",
"environment": "some-environment",
"project_name": "some-project-name",
"issuer_url": "https://gitlab.com",
}
),
),
(
"add_pending_google_oidc_publisher",
"Google",
lambda user_id: PendingGooglePublisher(
project_name="some-project-name",
email="some-email@example.com",
sub="some-sub",
added_by_id=user_id,
),
MultiDict(
{
"email": "some-email@example.com",
"sub": "some-sub",
"project_name": "some-project-name",
}
),
),
(
"add_pending_activestate_oidc_publisher",
"ActiveState",
lambda user_id: PendingActiveStatePublisher(
project_name="some-project-name",
added_by_id=user_id,
organization="some-org",
activestate_project_name="some-project",
actor="some-user",
actor_id="some-user-id",
),
MultiDict(
{
"organization": "some-org",
"project": "some-project",
"actor": "some-user",
"project_name": "some-project-name",
}
),
),
],
)
def test_add_pending_oidc_publisher_already_exists(
self,
monkeypatch,
db_request,
view_name,
publisher_name,
make_publisher,
post_body,
):
db_request.user = UserFactory.create()
EmailFactory(user=db_request.user, verified=True, primary=True)
pending_publisher = make_publisher(db_request.user.id)
db_request.db.add(pending_publisher)
db_request.db.flush() # To get it into the DB
db_request.registry = pretend.stub(
settings={
"github.token": "fake-api-token",
}
)
db_request.flags = pretend.stub(
disallow_oidc=pretend.call_recorder(lambda f=None: False)
)
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
db_request.POST = post_body
view = views.ManageAccountPublishingViews(db_request)
monkeypatch.setattr(
views.ManageAccountPublishingViews,
"default_response",
view.default_response,
)
monkeypatch.setattr(
views.PendingGitHubPublisherForm,
"_lookup_owner",
lambda *a: {"login": "some-owner", "id": "some-owner-id"},
)
monkeypatch.setattr(
views.PendingActiveStatePublisherForm,
"_lookup_organization",
lambda *a: None,
)
monkeypatch.setattr(
views.PendingActiveStatePublisherForm,
"_lookup_actor",
lambda *a: {"user_id": "some-user-id"},
)
monkeypatch.setattr(
view, "_check_ratelimits", pretend.call_recorder(lambda: None)
)
monkeypatch.setattr(
view, "_hit_ratelimits", pretend.call_recorder(lambda: None)
)
assert getattr(view, view_name)() == view.default_response
assert view.metrics.increment.calls == [
pretend.call(
"warehouse.oidc.add_pending_publisher.attempt",
tags=[f"publisher:{publisher_name}"],
),
]
assert view._hit_ratelimits.calls == [pretend.call()]
assert view._check_ratelimits.calls == [pretend.call()]
assert db_request.session.flash.calls == [
pretend.call(
(
"This trusted publisher has already been registered. "
"Please contact PyPI's admins if this wasn't intentional."
),
queue="error",
)
]
def test_add_pending_oidc_publisher_uniqueviolation(self, monkeypatch, db_request):
db_request.user = UserFactory.create()
EmailFactory(user=db_request.user, verified=True, primary=True)
db_request.db.add = pretend.raiser(UniqueViolation("foo", "bar", "baz"))
db_request.registry = pretend.stub(
settings={
"github.token": "fake-api-token",
}
)
db_request.flags = pretend.stub(
disallow_oidc=pretend.call_recorder(lambda f=None: False)
)
db_request.POST = MultiDict(
{
"owner": "some-owner",
"repository": "some-repository",
"workflow_filename": "some-workflow-filename.yml",
"environment": "some-environment",
"project_name": "some-project-name",
}
)
view = views.ManageAccountPublishingViews(db_request)
monkeypatch.setattr(
views.PendingGitHubPublisherForm,
"_lookup_owner",
lambda *a: {"login": "some-owner", "id": "some-owner-id"},
)
monkeypatch.setattr(
view, "_check_ratelimits", pretend.call_recorder(lambda: None)
)
monkeypatch.setattr(
view, "_hit_ratelimits", pretend.call_recorder(lambda: None)
)
resp = view.add_pending_github_oidc_publisher()
assert isinstance(resp, HTTPSeeOther)
@pytest.mark.parametrize(
("view_name", "publisher_name", "post_body", "publisher_class"),
[
(
"add_pending_github_oidc_publisher",
"GitHub",
MultiDict(
{
"owner": "some-owner",
"repository": "some-repository",
"workflow_filename": "some-workflow-filename.yml",
"environment": "some-environment",
"project_name": "some-project-name",
}
),
PendingGitHubPublisher,
),
(
"add_pending_gitlab_oidc_publisher",
"GitLab",
MultiDict(
{
"namespace": "some-owner",
"project": "some-repository",
"workflow_filepath": "subfolder/some-workflow-filename.yml",
"environment": "some-environment",
"project_name": "some-project-name",
"issuer_url": "https://gitlab.com",
}
),
PendingGitLabPublisher,
),
(
"add_pending_google_oidc_publisher",
"Google",
MultiDict(
{
"email": "some-email@example.com",
"sub": "some-sub",
"project_name": "some-project-name",
}
),
PendingGooglePublisher,
),
(
"add_pending_activestate_oidc_publisher",
"ActiveState",
MultiDict(
{
"organization": "some-org",
"project": "some-project",
"actor": "some-user",
"project_name": "some-project-name",
}
),
PendingActiveStatePublisher,
),
],
)
def test_add_pending_oidc_publisher(
self,
monkeypatch,
db_request,
view_name,
publisher_name,
publisher_class,
post_body,
):
db_request.user = UserFactory()
db_request.user.record_event = pretend.call_recorder(lambda **kw: None)
EmailFactory(user=db_request.user, verified=True, primary=True)
db_request.registry = pretend.stub(
settings={
"github.token": "fake-api-token",
}
)
db_request.flags = pretend.stub(
disallow_oidc=pretend.call_recorder(lambda f=None: False)
)
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
db_request.POST = post_body
monkeypatch.setattr(
views.PendingGitHubPublisherForm,
"_lookup_owner",
lambda *a: {"login": "some-owner", "id": "some-owner-id"},
)
monkeypatch.setattr(
views.PendingActiveStatePublisherForm,
"_lookup_organization",
lambda *a: None,
)
monkeypatch.setattr(
views.PendingActiveStatePublisherForm,
"_lookup_actor",
lambda *a: {"user_id": "some-user-id"},
)
view = views.ManageAccountPublishingViews(db_request)
monkeypatch.setattr(
view, "_check_ratelimits", pretend.call_recorder(lambda: None)
)
monkeypatch.setattr(
view, "_hit_ratelimits", pretend.call_recorder(lambda: None)
)
resp = getattr(view, view_name)()
assert db_request.session.flash.calls == [
pretend.call(
"Registered a new pending publisher to create "
"the project 'some-project-name'.",
queue="success",
)
]
assert view.metrics.increment.calls == [
pretend.call(
"warehouse.oidc.add_pending_publisher.attempt",
tags=[f"publisher:{publisher_name}"],
),
pretend.call(
"warehouse.oidc.add_pending_publisher.ok",
tags=[f"publisher:{publisher_name}"],
),
]
assert view._hit_ratelimits.calls == [pretend.call()]
assert view._check_ratelimits.calls == [pretend.call()]
assert isinstance(resp, HTTPSeeOther)
pending_publisher = db_request.db.query(publisher_class).one()
assert pending_publisher.added_by_id == db_request.user.id
mapping = {"owner": "repository_owner", "repository": "repository_name"}
for k, v in post_body.items():
assert getattr(pending_publisher, mapping.get(k, k)) == v
assert db_request.user.record_event.calls == [
pretend.call(
tag=EventTag.Account.PendingOIDCPublisherAdded,
request=db_request,
additional={
"project": "some-project-name",
"publisher": pending_publisher.publisher_name,
"id": str(pending_publisher.id),
"specifier": str(pending_publisher),
"url": pending_publisher.publisher_url(),
"submitted_by": db_request.user.username,
},
)
]
def test_delete_pending_oidc_publisher_admin_disabled(
self, monkeypatch, pyramid_request
):
project_service = pretend.stub(check_project_name=lambda name: None)
pyramid_request.find_service = lambda interface, **kwargs: {
IProjectService: project_service,
IMetricsService: pretend.stub(),
}[interface]
pyramid_request.user = pretend.stub()
pyramid_request.registry = pretend.stub(
settings={
"github.token": "fake-api-token",
}
)
pyramid_request.flags = pretend.stub(
disallow_oidc=pretend.call_recorder(lambda f=None: True)
)
pyramid_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
pending_github_publisher_form_obj = pretend.stub()
pending_github_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_github_publisher_form_obj
)
monkeypatch.setattr(
views, "PendingGitHubPublisherForm", pending_github_publisher_form_cls
)
pending_gitlab_publisher_form_obj = pretend.stub()
pending_gitlab_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_gitlab_publisher_form_obj
)
monkeypatch.setattr(
views, "PendingGitLabPublisherForm", pending_gitlab_publisher_form_cls
)
pending_google_publisher_form_obj = pretend.stub()
pending_google_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_google_publisher_form_obj
)
monkeypatch.setattr(
views, "PendingGooglePublisherForm", pending_google_publisher_form_cls
)
pending_activestate_publisher_form_obj = pretend.stub()
pending_activestate_publisher_form_cls = pretend.call_recorder(
lambda *a, **kw: pending_activestate_publisher_form_obj
)
monkeypatch.setattr(
views,
"PendingActiveStatePublisherForm",
pending_activestate_publisher_form_cls,
)
view = views.ManageAccountPublishingViews(pyramid_request)
assert view.delete_pending_oidc_publisher() == {
"disabled": {
"GitHub": True,
"GitLab": True,
"Google": True,
"ActiveState": True,
},
"pending_github_publisher_form": pending_github_publisher_form_obj,
"pending_gitlab_publisher_form": pending_gitlab_publisher_form_obj,
"pending_google_publisher_form": pending_google_publisher_form_obj,
"pending_activestate_publisher_form": pending_activestate_publisher_form_obj, # noqa: E501
}
assert pyramid_request.flags.disallow_oidc.calls == [
pretend.call(),
pretend.call(AdminFlagValue.DISALLOW_GITHUB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GITLAB_OIDC),
pretend.call(AdminFlagValue.DISALLOW_GOOGLE_OIDC),
pretend.call(AdminFlagValue.DISALLOW_ACTIVESTATE_OIDC),
]
assert pyramid_request.session.flash.calls == [
pretend.call(
(
"Trusted publishing is temporarily disabled. "
"See https://pypi.org/help#admin-intervention for details."
),
queue="error",
)
]
assert pending_github_publisher_form_cls.calls == [
pretend.call(
pyramid_request.POST,
api_token="fake-api-token",
route_url=pyramid_request.route_url,
check_project_name=project_service.check_project_name,
user=pyramid_request.user,
)
]
assert pending_gitlab_publisher_form_cls.calls == [
pretend.call(
pyramid_request.POST,
route_url=pyramid_request.route_url,
check_project_name=project_service.check_project_name,
user=pyramid_request.user,
)
]
def test_delete_pending_oidc_publisher_invalid_form(
self, monkeypatch, pyramid_request
):
pyramid_request.user = pretend.stub()
pyramid_request.flags = pretend.stub(
disallow_oidc=pretend.call_recorder(lambda f=None: False)
)
pyramid_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
pyramid_request.POST = MultiDict({"publisher_id": None})
view = views.ManageAccountPublishingViews(pyramid_request)
monkeypatch.setattr(
views.ManageAccountPublishingViews, "default_response", pretend.stub()
)
assert view.delete_pending_oidc_publisher() == view.default_response
assert view.metrics.increment.calls == [
pretend.call(
"warehouse.oidc.delete_pending_publisher.attempt",
),
]
assert pyramid_request.session.flash.calls == [
pretend.call(
"Invalid publisher ID",
queue="error",
)
]
@pytest.mark.parametrize(
("make_publisher", "publisher_class"),
[
(
lambda user_id: PendingGitHubPublisher(
project_name="some-project-name",
repository_name="some-repository",
repository_owner="some-owner",
repository_owner_id="some-id",
workflow_filename="some-filename",
environment="",
added_by_id=user_id,
),
PendingGitHubPublisher,
),
(
lambda user_id: PendingGitLabPublisher(
project_name="some-project-name",
namespace="some-owner",
project="some-repository",
workflow_filepath="subfolder/some-filename",
environment="",
issuer_url="https://gitlab.com",
added_by_id=user_id,
),
PendingGitLabPublisher,
),
(
lambda user_id: PendingGooglePublisher(
project_name="some-project-name",
email="some-email@example.com",
sub="some-sub",
added_by_id=user_id,
),
PendingGooglePublisher,
),
(
lambda user_id: PendingActiveStatePublisher(
project_name="some-project-name",
added_by_id=user_id,
organization="some-org",
activestate_project_name="some-project",
actor="some-user",
actor_id="some-user-id",
),
PendingActiveStatePublisher,
),
],
)
def test_delete_pending_oidc_publisher_not_found(
self, monkeypatch, db_request, make_publisher, publisher_class
):
db_request.user = UserFactory.create()
pending_publisher = make_publisher(db_request.user.id)
db_request.db.add(pending_publisher)
db_request.flags = pretend.stub(
disallow_oidc=pretend.call_recorder(lambda f=None: False)
)
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
db_request.POST = MultiDict({"publisher_id": str(uuid.uuid4())})
view = views.ManageAccountPublishingViews(db_request)
monkeypatch.setattr(
views.ManageAccountPublishingViews, "default_response", pretend.stub()
)
assert view.delete_pending_oidc_publisher() == view.default_response
assert view.metrics.increment.calls == [
pretend.call(
"warehouse.oidc.delete_pending_publisher.attempt",
),
]
assert db_request.session.flash.calls == [
pretend.call(
"Invalid publisher ID",
queue="error",
)
]
assert db_request.db.query(publisher_class).all() == [pending_publisher]
@pytest.mark.parametrize(
("make_publisher", "publisher_class"),
[
(
lambda user_id: PendingGitHubPublisher(
project_name="some-project-name",
repository_name="some-repository",
repository_owner="some-owner",
repository_owner_id="some-id",
workflow_filename="some-filename",
environment="",
added_by_id=user_id,
),
PendingGitHubPublisher,
),
(
lambda user_id: PendingGitLabPublisher(
project_name="some-project-name",
namespace="some-owner",
project="some-repository",
workflow_filepath="subfolder/some-filename",
environment="",
issuer_url="https://gitlab.com",
added_by_id=user_id,
),
PendingGitLabPublisher,
),
(
lambda user_id: PendingGooglePublisher(
project_name="some-project-name",
email="some-email@example.com",
sub="some-sub",
added_by_id=user_id,
),
PendingGooglePublisher,
),
],
)
def test_delete_pending_oidc_publisher_no_access(
self, monkeypatch, db_request, make_publisher, publisher_class
):
db_request.user = UserFactory.create()
some_other_user = UserFactory.create()
pending_publisher = make_publisher(some_other_user.id)
db_request.db.add(pending_publisher)
db_request.db.flush() # To get the id
db_request.user = pretend.stub()
db_request.flags = pretend.stub(
disallow_oidc=pretend.call_recorder(lambda f=None: False)
)
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
db_request.POST = MultiDict({"publisher_id": str(pending_publisher.id)})
view = views.ManageAccountPublishingViews(db_request)
monkeypatch.setattr(
views.ManageAccountPublishingViews, "default_response", pretend.stub()
)
assert view.delete_pending_oidc_publisher() == view.default_response
assert view.metrics.increment.calls == [
pretend.call(
"warehouse.oidc.delete_pending_publisher.attempt",
),
]
assert db_request.session.flash.calls == [
pretend.call(
"Invalid publisher ID",
queue="error",
)
]
assert db_request.db.query(publisher_class).all() == [pending_publisher]
@pytest.mark.parametrize(
("publisher_name", "make_publisher", "publisher_class"),
[
(
"GitHub",
lambda user_id: PendingGitHubPublisher(
project_name="some-project-name",
repository_name="some-repository",
repository_owner="some-owner",
repository_owner_id="some-id",
workflow_filename="some-filename",
environment="",
added_by_id=user_id,
),
PendingGitHubPublisher,
),
(
"GitLab",
lambda user_id: PendingGitLabPublisher(
project_name="some-project-name",
namespace="some-owner",
project="some-owner",
workflow_filepath="subfolder/some-filename",
environment="",
issuer_url="https://gitlab.com",
added_by_id=user_id,
),
PendingGitLabPublisher,
),
(
"Google",
lambda user_id: PendingGooglePublisher(
project_name="some-project-name",
email="some-email@example.com",
sub="some-sub",
added_by_id=user_id,
),
PendingGooglePublisher,
),
],
)
def test_delete_pending_oidc_publisher(
self, monkeypatch, db_request, publisher_name, make_publisher, publisher_class
):
db_request.user = UserFactory.create()
pending_publisher = make_publisher(db_request.user.id)
db_request.db.add(pending_publisher)
db_request.db.flush() # To get the id
db_request.flags = pretend.stub(
disallow_oidc=pretend.call_recorder(lambda f=None: False)
)
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
db_request.user.record_event = pretend.call_recorder(lambda **kw: None)
db_request.POST = MultiDict({"publisher_id": str(pending_publisher.id)})
view = views.ManageAccountPublishingViews(db_request)
assert view.delete_pending_oidc_publisher().__class__ == HTTPSeeOther
assert view.metrics.increment.calls == [
pretend.call(
"warehouse.oidc.delete_pending_publisher.attempt",
),
pretend.call(
"warehouse.oidc.delete_pending_publisher.ok",
tags=[f"publisher:{publisher_name}"],
),
]
assert db_request.session.flash.calls == [
pretend.call(
"Removed trusted publisher for project 'some-project-name'",
queue="success",
)
]
assert db_request.user.record_event.calls == [
pretend.call(
tag=EventTag.Account.PendingOIDCPublisherRemoved,
request=db_request,
additional={
"project": "some-project-name",
"publisher": publisher_name,
"id": str(pending_publisher.id),
"specifier": str(pending_publisher),
"url": pending_publisher.publisher_url(),
"submitted_by": db_request.user.username,
},
)
]
assert db_request.db.query(publisher_class).all() == []
| TestManageAccountPublishingViews |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 111330,
"end": 113410
} | class ____(fixtures.MappedTest):
"""'viewonly' mappings that contain the same 'local' column twice"""
@classmethod
def define_tables(cls, metadata):
Table(
"foos",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data", String(50)),
)
Table(
"bars",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("fid1", Integer, ForeignKey("foos.id")),
Column("fid2", Integer, ForeignKey("foos.id")),
Column("data", String(50)),
)
def test_relationship_on_or(self):
bars, foos = self.tables.bars, self.tables.foos
class Foo(ComparableEntity):
pass
class Bar(ComparableEntity):
pass
self.mapper_registry.map_imperatively(
Foo,
foos,
properties={
"bars": relationship(
Bar,
primaryjoin=sa.or_(
bars.c.fid1 == foos.c.id, bars.c.fid2 == foos.c.id
),
viewonly=True,
)
},
)
self.mapper_registry.map_imperatively(Bar, bars)
sess = fixture_session()
f1 = Foo(id=1, data="f1")
f2 = Foo(id=2, data="f2")
b1 = Bar(fid1=1, data="b1")
b2 = Bar(fid2=1, data="b2")
b3 = Bar(fid1=2, data="b3")
b4 = Bar(fid1=1, fid2=2, data="b4")
sess.add_all((f1, f2))
sess.flush()
sess.add_all((b1, b2, b3, b4))
sess.flush()
sess.expunge_all()
eq_(
sess.query(Foo).filter_by(id=f1.id).one(),
Foo(bars=[Bar(data="b1"), Bar(data="b2"), Bar(data="b4")]),
)
eq_(
sess.query(Foo).filter_by(id=f2.id).one(),
Foo(bars=[Bar(data="b3"), Bar(data="b4")]),
)
| ViewOnlyRepeatedLocalColumn |
python | scipy__scipy | benchmarks/benchmarks/sparse.py | {
"start": 4142,
"end": 4570
} | class ____(Benchmark):
param_names = ['sparse_type', "format"]
params = [
['spmatrix', 'sparray'],
['dia', 'coo', 'csr', 'csc', 'bsr'],
]
def setup(self, sparse_type, format):
self.A = poisson2d(300, format=format, sparse_type=sparse_type)
self.x = np.ones((self.A.shape[1], 10), dtype=self.A.dtype)
def time_matvecs(self, sparse_type, format):
self.A @ self.x
| Matvecs |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 8394,
"end": 8634
} | class ____:
xlActionTypeDrillthrough = 256 # from enum XlActionType
xlActionTypeReport = 128 # from enum XlActionType
xlActionTypeRowset = 16 # from enum XlActionType
xlActionTypeUrl = 1 # from enum XlActionType
| ActionType |
python | getsentry__sentry | src/sentry/release_health/metrics.py | {
"start": 3398,
"end": 61716
} | class ____(ReleaseHealthBackend):
"""
Implementation of the ReleaseHealthBackend using the MetricsLayer API
"""
@staticmethod
def _get_org_id(project_ids: Sequence[int]) -> int:
return MetricsReleaseHealthBackend._get_projects_and_org_id(project_ids)[1]
@staticmethod
def _get_projects(project_ids: Sequence[int]) -> Sequence[Project]:
return MetricsReleaseHealthBackend._get_projects_and_org_id(project_ids)[0]
@staticmethod
def _get_projects_and_org_id(project_ids: Sequence[int]) -> tuple[Sequence[Project], int]:
projects = Project.objects.get_many_from_cache(project_ids)
org_ids: set[int] = {project.organization_id for project in projects}
if len(org_ids) != 1:
raise ValueError("Expected projects to be from the same organization")
return projects, org_ids.pop()
@staticmethod
def _extract_crash_free_rates_from_result_groups(
result_groups: Sequence[Any],
) -> dict[int, float | None]:
crash_free_rates: dict[int, float | None] = {}
for result_group in result_groups:
project_id = get_path(result_group, "by", "project_id")
if project_id is None:
continue
totals = get_path(result_group, "totals", "rate", should_log=True)
if totals is not None:
crash_free_rates[project_id] = totals * 100
else:
crash_free_rates[project_id] = None
return crash_free_rates
@staticmethod
def _get_crash_free_rate_data(
org_id: int,
projects: Sequence[Project],
start: datetime,
end: datetime,
rollup: int,
) -> dict[int, float | None]:
project_ids = [p.id for p in projects]
select = [
MetricField(metric_mri=SessionMRI.CRASH_FREE_RATE.value, alias="rate", op=None),
]
groupby = [
MetricGroupByField(field="project_id"),
]
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=end,
granularity=Granularity(rollup),
groupby=groupby,
include_series=False,
include_totals=True,
)
result = get_series(projects=projects, metrics_query=query, use_case_id=USE_CASE_ID)
result_groups = get_path(result, "groups", default=[])
return MetricsReleaseHealthBackend._extract_crash_free_rates_from_result_groups(
result_groups=result_groups
)
def get_current_and_previous_crash_free_rates(
self,
project_ids: Sequence[int],
current_start: datetime,
current_end: datetime,
previous_start: datetime,
previous_end: datetime,
rollup: int,
org_id: int | None = None,
) -> CurrentAndPreviousCrashFreeRates:
projects, proj_org_id = self._get_projects_and_org_id(project_ids)
if org_id is None:
org_id = proj_org_id
else:
if org_id != proj_org_id:
# the specified org_id is not the projects' organization
raise ValueError("Expected projects to be from the specified organization")
projects_crash_free_rate_dict: CurrentAndPreviousCrashFreeRates = {
prj: {"currentCrashFreeRate": None, "previousCrashFreeRate": None}
for prj in project_ids
}
previous = self._get_crash_free_rate_data(
org_id,
projects,
previous_start,
previous_end,
rollup,
)
current = self._get_crash_free_rate_data(
org_id,
projects,
current_start,
current_end,
rollup,
)
for project_id, project_data in projects_crash_free_rate_dict.items():
project_data["previousCrashFreeRate"] = previous.get(project_id)
project_data["currentCrashFreeRate"] = current.get(project_id)
return projects_crash_free_rate_dict
def get_release_adoption(
self,
project_releases: Sequence[ProjectRelease],
environments: Sequence[EnvironmentName] | None = None,
now: datetime | None = None,
org_id: OrganizationId | None = None,
) -> ReleasesAdoption:
project_ids = list({x[0] for x in project_releases})
if org_id is None:
org_id = self._get_org_id(project_ids)
if now is None:
now = datetime.now(timezone.utc)
return self._get_release_adoption_impl(now, org_id, project_releases, environments)
@staticmethod
def _get_release_adoption_impl(
now: datetime,
org_id: int,
project_releases: Sequence[ProjectRelease],
environments: Sequence[EnvironmentName] | None = None,
) -> ReleasesAdoption:
start = now - timedelta(days=1)
project_ids = [proj for proj, _rel in project_releases]
projects = MetricsReleaseHealthBackend._get_projects(project_ids)
def _get_common_where(total: bool) -> list[Condition]:
where_common: list[Condition] = [
filter_projects_by_project_release(project_releases),
]
if environments is not None:
where_common.append(
Condition(
lhs=Column("tags[environment]"),
op=Op.IN,
rhs=environments,
)
)
if not total:
where_common.append(filter_releases_by_project_release(project_releases))
return where_common
def _get_common_groupby(total: bool) -> list[MetricGroupByField]:
if total:
return [MetricGroupByField(field="project_id")]
else:
return [
MetricGroupByField(field="project_id"),
MetricGroupByField(field="release"),
]
def _convert_results(groups: Any, total: bool) -> dict[Any, int]:
"""
Converts the result groups into an array of values:
from [{ "by": {"project_id": 123, "release": "r1"}, "totals": {"init": 23.3}},...]
to:
{ 123: 23.3, ...} // for totals
{ (123, "r1"): 23.3, ...} // for details
"""
ret_val = {}
for group in groups:
if total:
idx = get_path(group, "by", "project_id")
else:
by = group.get("by", {})
idx = by.get("project_id"), by.get("release")
ret_val[idx] = get_path(group, "totals", "value")
return ret_val
def _count_sessions(
total: bool, project_ids: Sequence[int], referrer: str
) -> dict[Any, int]:
select = [
MetricField(metric_mri=SessionMRI.ALL.value, alias="value", op=None),
]
query = DeprecatingMetricsQuery(
org_id=org_id,
start=start,
end=now,
project_ids=project_ids,
select=select,
groupby=_get_common_groupby(total),
where=_get_common_where(total),
granularity=Granularity(LEGACY_SESSIONS_DEFAULT_ROLLUP),
include_series=False,
include_totals=True,
)
raw_result = get_series(projects=projects, metrics_query=query, use_case_id=USE_CASE_ID)
return _convert_results(raw_result["groups"], total=total)
def _count_users(total: bool, referrer: str) -> dict[Any, int]:
select = [
MetricField(metric_mri=SessionMRI.RAW_USER.value, alias="value", op="count_unique")
]
query = DeprecatingMetricsQuery(
org_id=org_id,
start=start,
end=now,
project_ids=project_ids,
select=select,
groupby=_get_common_groupby(total),
where=_get_common_where(total),
granularity=Granularity(LEGACY_SESSIONS_DEFAULT_ROLLUP),
include_series=False,
include_totals=True,
)
raw_result = get_series(projects=projects, metrics_query=query, use_case_id=USE_CASE_ID)
return _convert_results(raw_result["groups"], total)
# XXX(markus): Four queries are quite horrible for this... the old code
# sufficed with two. From what I understand, ClickHouse would have to
# gain a function uniqCombined64MergeIf, i.e. a conditional variant of
# what we already use.
#
# Alternatively we may want to use a threadpool here to send the
# queries in parallel.
# NOTE: referrers are spelled out as single static string literal so
# S&S folks can search for it more easily. No string formatting
# business please!
# Count of sessions/users for given list of environments and timerange, per-project
sessions_per_project: dict[int, int] = _count_sessions(
total=True,
project_ids=project_ids,
referrer=Referrer.RELEASE_HEALTH_METRICS_GET_RELEASE_ADOPTION_TOTAL_SESSIONS,
)
users_per_project: dict[int, int] = _count_users(
total=True, referrer=Referrer.RELEASE_HEALTH_METRICS_GET_RELEASE_ADOPTION_TOTAL_USERS
)
# Count of sessions/users for given list of environments and timerange AND GIVEN RELEASES, per-project
sessions_per_release: dict[tuple[int, str], int] = _count_sessions(
total=False,
project_ids=project_ids,
referrer=Referrer.RELEASE_HEALTH_METRICS_GET_RELEASE_ADOPTION_RELEASES_SESSIONS,
)
users_per_release: dict[tuple[int, str], int] = _count_users(
total=False,
referrer=Referrer.RELEASE_HEALTH_METRICS_GET_RELEASE_ADOPTION_RELEASES_USERS,
)
rv = {}
for project_id, release in project_releases:
release_tag_value = indexer.resolve(USE_CASE_ID, org_id, release)
if release_tag_value is None:
# Don't emit empty releases -- for exact compatibility with
# sessions table backend.
continue
release_sessions = sessions_per_release.get((project_id, release), 0.0)
release_users = users_per_release.get((project_id, release), 0.0)
total_sessions = sessions_per_project.get(project_id, 0.0)
total_users = users_per_project.get(project_id, 0.0)
adoption: ReleaseAdoption = {
"adoption": (
release_users / total_users * 100 if release_users and total_users else None
),
"sessions_adoption": (
release_sessions / total_sessions * 100
if release_sessions and total_sessions
else None
),
"users_24h": int(release_users),
"sessions_24h": int(release_sessions),
"project_users_24h": int(total_users),
"project_sessions_24h": int(total_sessions),
}
rv[project_id, release] = adoption
return rv
def sessions_query_config(self, organization: Any) -> SessionsQueryConfig:
return SessionsQueryConfig(
allowed_resolution=AllowedResolution.ten_seconds,
allow_session_status_query=True,
restrict_date_range=False,
)
def run_sessions_query(
self,
org_id: int,
query: QueryDefinition,
span_op: str,
) -> SessionsQueryResult:
return run_sessions_query(org_id, query, span_op)
def get_release_sessions_time_bounds(
self,
project_id: ProjectId,
release: ReleaseName,
org_id: OrganizationId,
environments: Iterable[str] | None = None,
) -> ReleaseSessionsTimeBounds:
projects, org_id = self._get_projects_and_org_id([project_id])
select = [
MetricField(
metric_mri=SessionMRI.RAW_SESSION.value,
alias="min_counter_date",
op="min_timestamp",
),
MetricField(
metric_mri=SessionMRI.RAW_SESSION.value,
alias="max_counter_date",
op="max_timestamp",
),
MetricField(
metric_mri=SessionMRI.RAW_DURATION.value, alias="min_dist_date", op="min_timestamp"
),
MetricField(
metric_mri=SessionMRI.RAW_DURATION.value, alias="max_dist_date", op="max_timestamp"
),
]
where = []
if release:
where.append(
Condition(
lhs=Column(name="tags[release]"),
op=Op.EQ,
rhs=release,
)
)
if environments:
where.append(
Condition(
lhs=Column(name="tags[environment]"),
op=Op.IN,
rhs=list(environments),
)
)
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=[project_id],
select=select,
start=SENTRY_FIRST_COMMIT_DATE,
end=datetime.now(timezone.utc) + timedelta(seconds=10),
where=where,
granularity=Granularity(LEGACY_SESSIONS_DEFAULT_ROLLUP),
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
def iso_format_snuba_datetime(date: str) -> str:
return datetime.strptime(date, "%Y-%m-%dT%H:%M:%S+00:00").isoformat()[:19] + "Z"
formatted_unix_start_time = datetime.fromtimestamp(0).strftime("%Y-%m-%dT%H:%M:%S+00:00")
def clean_date_string(d: str | None) -> str | None:
# This check is added because if there are no sessions found, then the
# aggregation queries return both the sessions_lower_bound and the
# sessions_upper_bound as `0` timestamp, and we do not want that behaviour
# by default
# P.S. To avoid confusion the `0` timestamp which is '1970-01-01 00:00:00'
# is rendered as '0000-00-00 00:00:00' in clickhouse shell
# sets and Unix start time dates to None
if d == formatted_unix_start_time:
return None
return d
min_date = None
max_date = None
if groups:
totals = groups[0]["totals"]
min_date = clean_date_string(totals.get("min_counter_date"))
max_date = clean_date_string(totals.get("max_counter_date"))
min_date2 = clean_date_string(totals.get("min_dist_date"))
max_date2 = clean_date_string(totals.get("max_dist_date"))
if min_date is None or (min_date2 is not None and min_date > min_date2):
min_date = min_date2
if max_date is None or (max_date2 is not None and max_date < max_date2):
max_date = max_date2
if min_date is not None and max_date is not None:
return {
"sessions_lower_bound": iso_format_snuba_datetime(min_date),
"sessions_upper_bound": iso_format_snuba_datetime(max_date),
}
else:
return {
"sessions_lower_bound": None,
"sessions_upper_bound": None,
}
def check_has_health_data(
self,
projects_list: Collection[ProjectOrRelease],
now: datetime | None = None,
) -> set[ProjectOrRelease]:
if now is None:
now = datetime.now(timezone.utc)
start = now - timedelta(days=90)
projects_list = list(projects_list)
if len(projects_list) == 0:
return set()
includes_releases = isinstance(projects_list[0], tuple)
if includes_releases:
project_ids: list[ProjectId] = [x[0] for x in projects_list] # type: ignore[index]
else:
project_ids = projects_list # type: ignore[assignment]
projects, org_id = self._get_projects_and_org_id(project_ids)
select = [MetricField(metric_mri=SessionMRI.RAW_SESSION.value, alias="value", op="sum")]
where_clause = []
groupby = [
MetricGroupByField(field="project_id"),
]
if includes_releases:
where_clause.append(filter_releases_by_project_release(projects_list)) # type: ignore[arg-type]
groupby.append(MetricGroupByField(field="release"))
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=now,
granularity=Granularity(DAY),
groupby=groupby,
where=where_clause,
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
ret_val = set()
for group in groups:
if includes_releases:
by = group.get("by", {})
idx = by.get("project_id"), by.get("release")
ret_val.add(idx)
else:
proj_id = get_path(group, "by", "project_id")
ret_val.add(proj_id)
return ret_val # type: ignore[return-value]
def check_releases_have_health_data(
self,
organization_id: OrganizationId,
project_ids: Sequence[ProjectId],
release_versions: Sequence[ReleaseName],
start: datetime,
end: datetime,
) -> set[ReleaseName]:
"""
Returns a set of all release versions that have health data within a given period of time.
"""
projects, org_id = self._get_projects_and_org_id(project_ids)
select = [MetricField(metric_mri=SessionMRI.RAW_SESSION.value, alias="value", op="sum")]
groupby = [MetricGroupByField(field="release")]
where_clause = [
Condition(
lhs=Column(name="tags[release]"),
op=Op.IN,
rhs=release_versions,
)
]
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=end,
granularity=Granularity(LEGACY_SESSIONS_DEFAULT_ROLLUP),
groupby=groupby,
where=where_clause,
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
ret_val = set()
for group in groups:
by = group.get("by", {})
release = by.get("release")
if release is not None:
ret_val.add(release)
return ret_val
@staticmethod
def _get_session_duration_data_for_overview(
projects: Sequence[Project],
where: list[Condition],
org_id: int,
granularity: int,
start: datetime,
end: datetime,
) -> Mapping[tuple[int, str], Any]:
"""
Percentiles of session duration
"""
project_ids = [p.id for p in projects]
select = [
MetricField(metric_mri=SessionMRI.DURATION.value, alias="p50", op="p50"),
MetricField(metric_mri=SessionMRI.DURATION.value, alias="p90", op="p90"),
]
session_status_cond = Condition(lhs=Column("tags[session.status]"), op=Op.EQ, rhs="exited")
where = [*where, session_status_cond]
groupby = [
MetricGroupByField(field="project_id"),
MetricGroupByField(field="release"),
]
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=end,
granularity=Granularity(granularity),
groupby=groupby,
where=where,
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
ret_val = {}
for group in groups:
by = group.get("by", {})
proj_id = by.get("project_id")
release = by.get("release")
totals = group.get("totals", {})
p50 = totals.get("p50")
p90 = totals.get("p90")
ret_val[(proj_id, release)] = {"duration_p50": p50, "duration_p90": p90}
return ret_val
@staticmethod
def _get_errored_sessions_for_overview(
projects: Sequence[Project],
where: list[Condition],
org_id: int,
granularity: int,
start: datetime,
end: datetime,
) -> Mapping[tuple[int, str], int]:
"""
Count of errored sessions, incl fatal (abnormal, unhandled, crashed) session
excl errored *preaggregated* sessions
"""
project_ids = [p.id for p in projects]
select = [
MetricField(metric_mri=SessionMRI.ERRORED_SET.value, alias="value", op=None),
]
groupby = [
MetricGroupByField(field="project_id"),
MetricGroupByField(field="release"),
]
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=end,
granularity=Granularity(granularity),
groupby=groupby,
where=where,
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
ret_val = {}
for group in groups:
by = group.get("by", {})
proj_id = by.get("project_id")
release = by.get("release")
value = get_path(group, "totals", "value")
ret_val[(proj_id, release)] = value
return ret_val
@staticmethod
def _get_session_by_status_for_overview(
projects: Sequence[Project],
where: list[Condition],
org_id: int,
granularity: int,
start: datetime,
end: datetime,
) -> Mapping[tuple[int, str, str], int]:
"""
Counts of init, abnormal, unhandled and crashed sessions, purpose-built for overview
"""
project_ids = [p.id for p in projects]
select = [
MetricField(metric_mri=SessionMRI.ABNORMAL.value, alias="abnormal", op=None),
MetricField(metric_mri=SessionMRI.UNHANDLED.value, alias="unhandled", op=None),
MetricField(metric_mri=SessionMRI.CRASHED.value, alias="crashed", op=None),
MetricField(metric_mri=SessionMRI.ALL.value, alias="init", op=None),
MetricField(
metric_mri=SessionMRI.ERRORED_PREAGGREGATED.value,
alias="errored_preaggr",
op=None,
),
]
groupby = [
MetricGroupByField(field="project_id"),
MetricGroupByField(field="release"),
]
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=end,
granularity=Granularity(granularity),
groupby=groupby,
where=where,
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
ret_val = {}
for group in groups:
by = group.get("by", {})
proj_id = by.get("project_id")
release = by.get("release")
totals = group.get("totals", {})
for status in [
"abnormal",
"unhandled",
"crashed",
"init",
"errored_preaggr",
]:
value = totals.get(status)
if value is not None and value != 0.0:
ret_val[(proj_id, release, status)] = value
return ret_val
@staticmethod
def _get_users_and_crashed_users_for_overview(
projects: Sequence[Project],
where: list[Condition],
org_id: int,
granularity: int,
start: datetime,
end: datetime,
) -> Mapping[tuple[int, str, str], int]:
project_ids = [p.id for p in projects]
select = [
MetricField(metric_mri=SessionMRI.ALL_USER.value, alias="all_users", op=None),
MetricField(metric_mri=SessionMRI.CRASHED_USER.value, alias="crashed_users", op=None),
MetricField(
metric_mri=SessionMRI.UNHANDLED_USER.value, alias="unhandled_users", op=None
),
]
groupby = [
MetricGroupByField(field="release"),
MetricGroupByField(field="project_id"),
]
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=end,
granularity=Granularity(granularity),
groupby=groupby,
where=where,
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
ret_val = {}
for group in groups:
by = group.get("by", {})
proj_id = by.get("project_id")
release = by.get("release")
totals = group.get("totals", {})
for status in ["all_users", "crashed_users"]:
value = totals.get(status)
if value is not None:
ret_val[(proj_id, release, status)] = value
return ret_val
@staticmethod
def _get_health_stats_for_overview(
projects: Sequence[Project],
where: list[Condition],
org_id: int,
stat: OverviewStat,
granularity: int,
start: datetime,
end: datetime,
buckets: int,
) -> Mapping[ProjectRelease, list[list[int]]]:
project_ids = [p.id for p in projects]
metric_field = {
"users": MetricField(metric_mri=SessionMRI.ALL_USER.value, alias="value", op=None),
"sessions": MetricField(metric_mri=SessionMRI.ALL.value, alias="value", op=None),
}[stat]
groupby = [
MetricGroupByField(field="release"),
MetricGroupByField(field="project_id"),
]
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=[metric_field],
start=start,
end=end,
granularity=Granularity(granularity),
groupby=groupby,
where=where,
include_series=True,
include_totals=False,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
ret_val: dict[ProjectRelease, list[list[int]]] = defaultdict(
lambda: _make_stats(start, granularity, buckets)
)
timestamps = [int(dt.timestamp()) for dt in raw_result["intervals"]]
for group in groups:
proj_id = get_path(group, "by", "project_id")
release = get_path(group, "by", "release")
series = get_path(group, "series", "value")
assert len(timestamps)
data = zip(timestamps, series)
as_array = [[ts, dt] for ts, dt in data]
ret_val[(proj_id, release)] = as_array
return ret_val
def get_release_health_data_overview(
self,
project_releases: Sequence[ProjectRelease],
environments: Sequence[EnvironmentName] | None = None,
summary_stats_period: StatsPeriod | None = None,
health_stats_period: StatsPeriod | None = None,
stat: Literal["users", "sessions"] | None = None,
now: datetime | None = None,
) -> Mapping[ProjectRelease, ReleaseHealthOverview]:
"""Checks quickly for which of the given project releases we have
health data available. The argument is a tuple of `(project_id, release_name)`
tuples. The return value is a set of all the project releases that have health
data.
"""
if stat is None:
stat = "sessions"
assert stat in ("sessions", "users")
if now is None:
now = datetime.now(timezone.utc)
project_ids = [proj_id for proj_id, _release in project_releases]
projects, org_id = self._get_projects_and_org_id(project_ids)
granularity, summary_start, stats_buckets = get_rollup_starts_and_buckets(
summary_stats_period or "24h", now=now
)
# NOTE: for backward compatibility with previous implementation some queries use the granularity calculated from
# stats_period and others use the legacy_session_rollup
rollup = LEGACY_SESSIONS_DEFAULT_ROLLUP
where = [filter_projects_by_project_release(project_releases)]
if health_stats_period:
health_stats_data = self._get_health_stats_for_overview(
projects=projects,
where=where,
org_id=org_id,
stat=stat,
granularity=granularity,
start=summary_start,
end=now,
buckets=stats_buckets,
)
else:
health_stats_data = {}
rv_durations = self._get_session_duration_data_for_overview(
projects, where, org_id, rollup, summary_start, now
)
rv_errored_sessions = self._get_errored_sessions_for_overview(
projects, where, org_id, rollup, summary_start, now
)
rv_sessions = self._get_session_by_status_for_overview(
projects, where, org_id, rollup, summary_start, now
)
rv_users = self._get_users_and_crashed_users_for_overview(
projects, where, org_id, rollup, summary_start, now
)
# XXX: In order to be able to dual-read and compare results from both
# old and new backend, this should really go back through the
# release_health service instead of directly calling `self`. For now
# that makes the entire backend too hard to test though.
release_adoption = self.get_release_adoption(project_releases, environments)
rv: dict[ProjectRelease, ReleaseHealthOverview] = {}
fetch_has_health_data_releases = set()
default_adoption_info: ReleaseAdoption = {
"adoption": None,
"sessions_adoption": None,
"users_24h": None,
"project_users_24h": None,
"sessions_24h": None,
"project_sessions_24h": None,
}
for project_id, release in project_releases:
adoption_info: ReleaseAdoption = (
release_adoption.get((project_id, release)) or default_adoption_info
)
total_sessions = rv_sessions.get((project_id, release, "init"))
total_users = rv_users.get((project_id, release, "all_users"))
has_health_data = bool(total_sessions)
# has_health_data is supposed to be irrespective of the currently
# selected rollup window. Therefore we need to run another query
# over 90d just to see if health data is available to compute
# has_health_data correctly.
if not has_health_data and summary_stats_period != "90d":
fetch_has_health_data_releases.add((project_id, release))
sessions_unhandled = rv_sessions.get((project_id, release, "unhandled"), 0)
sessions_crashed = rv_sessions.get((project_id, release, "crashed"), 0)
users_unhandled = rv_users.get((project_id, release, "unhandled_users"), 0)
users_crashed = rv_users.get((project_id, release, "crashed_users"), 0)
rv_row = rv[project_id, release] = {
"adoption": adoption_info.get("adoption"),
"sessions_adoption": adoption_info.get("sessions_adoption"),
"total_users_24h": adoption_info.get("users_24h"),
"total_project_users_24h": adoption_info.get("project_users_24h"),
"total_sessions_24h": adoption_info.get("sessions_24h"),
"total_project_sessions_24h": adoption_info.get("project_sessions_24h"),
"total_sessions": total_sessions,
"total_users": total_users,
# Users where the error was `unhandled`; possibly resulting in a crash
"unhandled_user_rate": (
(users_unhandled + users_crashed) / total_users * 100 if total_users else None
),
# Users where the error was not a crash (but may have been unhandled)
"crash_free_users": (
100 - users_crashed / total_users * 100 if total_users else None
),
"has_health_data": has_health_data,
# Sessions where the error was specifically `unhandled`; NOT resulting in a crash
"sessions_unhandled": sessions_unhandled,
# Sessions where the error was a crash
"sessions_crashed": sessions_crashed,
# Sessions where the error was `unhandled`; possibly resulting in a crash
"unhandled_session_rate": (
(sessions_unhandled + sessions_crashed) / total_sessions * 100
if total_sessions
else None
),
# Sessions where the error was not a crash (but may have been unhandled)
"crash_free_sessions": (
100 - sessions_crashed / float(total_sessions) * 100 if total_sessions else None
),
# Sessions where the error was handled
"sessions_errored": max(
0,
rv_errored_sessions.get((project_id, release), 0)
+ rv_sessions.get((project_id, release, "errored_preaggr"), 0)
- sessions_crashed
- sessions_unhandled
- rv_sessions.get((project_id, release, "abnormal"), 0),
),
"duration_p50": None,
"duration_p90": None,
}
durations = rv_durations.get((project_id, release))
if durations:
rv_row.update(durations)
if health_stats_period:
rv_row["stats"] = {health_stats_period: health_stats_data[project_id, release]}
if fetch_has_health_data_releases:
has_health_data = self.check_has_health_data(fetch_has_health_data_releases) # type: ignore[assignment]
for key in fetch_has_health_data_releases:
rv[key]["has_health_data"] = key in has_health_data # type: ignore[operator]
return rv
def _get_crash_free_breakdown_fn(
self,
org_id: int,
project_id: ProjectId,
release: ReleaseName,
start: datetime,
environments: Sequence[EnvironmentName] | None = None,
) -> Callable[[datetime], CrashFreeBreakdown]:
projects = self._get_projects([project_id])
where = [
Condition(
lhs=Column(name="tags[release]"),
op=Op.EQ,
rhs=release,
)
]
if environments:
environments = list(environments)
where.append(
Condition(
lhs=Column(name="tags[environment]"),
op=Op.IN,
rhs=environments,
)
)
def query_stats(end: datetime) -> CrashFreeBreakdown:
def _get_data(select: list[MetricField]) -> tuple[int, int]:
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=[project_id],
select=select,
start=start,
end=end,
where=where,
granularity=Granularity(LEGACY_SESSIONS_DEFAULT_ROLLUP),
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
assert len(groups) == 1
totals = groups[0]["totals"]
total = totals["total"]
crashed = totals["crashed"]
return total, crashed
session_select = [
MetricField(metric_mri=SessionMRI.ALL.value, alias="total", op=None),
MetricField(metric_mri=SessionMRI.CRASH_FREE_RATE.value, alias="crashed", op=None),
]
sessions_total, sessions_crashed_rate = _get_data(session_select)
users_select = [
MetricField(metric_mri=SessionMRI.ALL_USER.value, alias="total", op=None),
MetricField(
metric_mri=SessionMRI.CRASH_FREE_USER_RATE.value, alias="crashed", op=None
),
]
users_total, users_crashed_rate = _get_data(users_select)
return {
"date": end,
"total_users": users_total,
"crash_free_users": users_crashed_rate * 100 if users_total else None,
"total_sessions": sessions_total,
"crash_free_sessions": sessions_crashed_rate * 100 if sessions_total else None,
}
return query_stats
def get_crash_free_breakdown(
self,
project_id: ProjectId,
release: ReleaseName,
start: datetime,
environments: Sequence[EnvironmentName] | None = None,
now: datetime | None = None,
) -> Sequence[CrashFreeBreakdown]:
projects, org_id = self._get_projects_and_org_id([project_id])
if now is None:
now = datetime.now(timezone.utc)
query_fn = self._get_crash_free_breakdown_fn(
org_id, project_id, release, start, environments
)
last: datetime | None = None
rv = []
for offset in (
timedelta(days=1),
timedelta(days=2),
timedelta(days=7),
timedelta(days=14),
timedelta(days=30),
):
try:
end = start + offset
if end > now:
if last is None or (end - last).days > 1:
rv.append(query_fn(now))
break
rv.append(query_fn(end))
last = end
except QueryOutsideRetentionError:
# cannot query for these
pass
return rv
def get_changed_project_release_model_adoptions(
self,
project_ids: Iterable[int],
now: datetime | None = None,
) -> Sequence[ProjectRelease]:
if now is None:
now = datetime.now(timezone.utc)
start = now - timedelta(days=3)
project_ids = list(project_ids)
if len(project_ids) == 0:
return []
projects, org_id = self._get_projects_and_org_id(project_ids)
select = [MetricField(metric_mri=SessionMRI.ALL.value, alias="value", op=None)]
groupby = [
MetricGroupByField(field="release"),
MetricGroupByField(field="project_id"),
]
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=now,
groupby=groupby,
granularity=Granularity(LEGACY_SESSIONS_DEFAULT_ROLLUP),
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
ret_val = []
for group in groups:
by = group.get("by")
ret_val.append((by.get("project_id"), by.get("release")))
return ret_val
def get_oldest_health_data_for_releases(
self,
project_releases: Sequence[ProjectRelease],
now: datetime | None = None,
) -> Mapping[ProjectRelease, str]:
if now is None:
now = datetime.now(timezone.utc)
# TODO: assumption about retention?
start = now - timedelta(days=90)
project_ids = [proj_id for proj_id, _release in project_releases]
projects, org_id = self._get_projects_and_org_id(project_ids)
where = [filter_releases_by_project_release(project_releases)]
groupby = [
MetricGroupByField(field="release"),
MetricGroupByField(field="project_id"),
]
select = [
MetricField(
metric_mri=SessionMRI.RAW_SESSION.value, alias="oldest", op="min_timestamp"
),
]
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=now,
groupby=groupby,
where=where,
granularity=Granularity(LEGACY_SESSIONS_DEFAULT_ROLLUP),
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
ret_val = {}
groups = raw_result["groups"]
for group in groups:
by = group.get("by")
proj_id = by.get("project_id")
release = by.get("release")
totals = group.get("totals")
ret_val[(proj_id, release)] = totals["oldest"]
return ret_val
def get_project_releases_count(
self,
organization_id: OrganizationId,
project_ids: Sequence[ProjectId],
scope: str,
stats_period: str | None = None,
environments: Sequence[EnvironmentName] | None = None,
) -> int:
projects = self._get_projects(project_ids)
now = datetime.now(timezone.utc)
if stats_period is None:
stats_period = "24h"
# Special rule that we support sorting by the last 24h only.
if scope.endswith("_24h"):
stats_period = "24h"
granularity, stats_start, _ = get_rollup_starts_and_buckets(stats_period, now=now)
where = []
if environments is not None:
where.append(Condition(Column("tags[environment]"), Op.IN, environments))
if scope == "users":
select = [MetricField(metric_mri=SessionMRI.ALL_USER.value, alias="v", op=None)]
elif scope == "crash_free_users":
select = [MetricField(metric_mri=SessionMRI.CRASH_FREE_USER.value, alias="v", op=None)]
else: # sessions
select = [MetricField(metric_mri=SessionMRI.ALL.value, alias="v", op=None)]
groupby = [
MetricGroupByField(field="project_id"),
MetricGroupByField(field="release"),
]
query = DeprecatingMetricsQuery(
org_id=organization_id,
project_ids=project_ids,
select=select,
start=stats_start,
end=now,
where=where,
groupby=groupby,
granularity=Granularity(LEGACY_SESSIONS_DEFAULT_ROLLUP),
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
# since we are grouping by release & project the number of unique
# combination is the number of groups.
# NOTE: (RaduW) I don't know how to get a more direct query
# the way it was in the original implementation where we
# didn't use a group by but calculated in one go with
# a column uniqueExact(projectId, release)
ret_val = 0
for group in groups:
val = get_path(group, "totals", "v", default=0)
if val > 0:
ret_val += 1
return ret_val
def get_project_release_stats(
self,
project_id: ProjectId,
release: ReleaseName,
stat: OverviewStat,
rollup: int,
start: datetime,
end: datetime,
environments: Sequence[EnvironmentName] | None = None,
) -> ProjectReleaseUserStats | ProjectReleaseSessionStats:
assert stat in ("users", "sessions")
projects, org_id = self._get_projects_and_org_id([project_id])
start = to_datetime((start.timestamp() // rollup + 1) * rollup)
# since snuba end queries are exclusive of the time and we're bucketing to
# 10 seconds, we need to round to the next 10 seconds since snuba is
# exclusive on the end.
end = to_datetime(
(end.timestamp() // SMALLEST_METRICS_BUCKET + 1) * SMALLEST_METRICS_BUCKET
)
where = [
Condition(
lhs=Column(name="tags[release]"),
op=Op.EQ,
rhs=release,
)
]
if environments is not None:
where.append(Condition(Column("tags[environment]"), Op.IN, environments))
if stat == "users":
select = [
MetricField(metric_mri=SessionMRI.ALL_USER.value, alias="users", op=None),
MetricField(
metric_mri=SessionMRI.ABNORMAL_USER.value, alias="users_abnormal", op=None
),
MetricField(
metric_mri=SessionMRI.CRASHED_USER.value, alias="users_crashed", op=None
),
MetricField(
metric_mri=SessionMRI.UNHANDLED_USER.value, alias="users_unhandled", op=None
),
MetricField(
metric_mri=SessionMRI.ERRORED_USER.value, alias="users_errored", op=None
),
MetricField(
metric_mri=SessionMRI.HEALTHY_USER.value, alias="users_healthy", op=None
),
]
else:
select = [
MetricField(metric_mri=SessionMRI.ALL.value, alias="sessions", op=None),
MetricField(
metric_mri=SessionMRI.ABNORMAL.value, alias="sessions_abnormal", op=None
),
MetricField(
metric_mri=SessionMRI.UNHANDLED.value,
alias="sessions_unhandled",
op=None,
),
MetricField(metric_mri=SessionMRI.CRASHED.value, alias="sessions_crashed", op=None),
MetricField(metric_mri=SessionMRI.ERRORED.value, alias="sessions_errored", op=None),
MetricField(metric_mri=SessionMRI.HEALTHY.value, alias="sessions_healthy", op=None),
]
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=[project_id],
select=select,
start=start,
end=end,
where=where,
granularity=Granularity(rollup),
include_series=False,
include_totals=True,
)
raw_totals = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
totals = raw_totals["groups"][0]["totals"]
# we also need durations for series we also need durations p50 and p90
select += [
MetricField(metric_mri=SessionMRI.DURATION.value, alias="duration_p50", op="p50"),
MetricField(metric_mri=SessionMRI.DURATION.value, alias="duration_p90", op="p90"),
]
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=[project_id],
select=select,
start=start,
end=end,
where=where,
granularity=Granularity(rollup),
include_series=True,
include_totals=False,
)
raw_series = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_series["groups"]
intervals = raw_series["intervals"]
timestamps = [int(dt.timestamp()) for dt in intervals]
if not groups:
# no data create empty series
empty_entry = {
"duration_p50": None,
"duration_p90": None,
f"{stat}": 0,
f"{stat}_abnormal": 0,
f"{stat}_crashed": 0,
f"{stat}_unhandled": 0,
f"{stat}_errored": 0,
f"{stat}_healthy": 0,
}
# create [(timestamp_0, copy(empty_entry)),(timestamp_2, copy(empty_entry))...]
ret_series = [(ts, {**empty_entry}) for ts in timestamps]
else:
series = groups[0]["series"]
# massage series from { "healthy":[10,20], "errored":[1,2]}
# to : [(timestamp_0, {"healthy":10, "errored":1}),(timestamp_2, {..}) ]
ret_series = []
for idx, timestamp in enumerate(timestamps):
value = {}
for key in series.keys():
value[key] = series[key][idx]
ret_series.append((timestamp, value))
return ret_series, totals # type: ignore[return-value]
def get_project_sessions_count(
self,
project_id: ProjectId,
rollup: int, # rollup in seconds
start: datetime,
end: datetime,
environment_id: int | None = None,
) -> int:
"""
Returns the number of sessions in the specified period (optionally
filtered by environment)
"""
projects, org_id = self._get_projects_and_org_id([project_id])
select = [MetricField(metric_mri=SessionMRI.ALL.value, alias="value", op=None)]
where = []
if environment_id is not None:
# convert the PosgreSQL environmentID into the clickhouse string index
# for the environment name
env_names = _model_environment_ids_to_environment_names([environment_id])
env_name = env_names[environment_id]
where.append(Condition(Column("tags[environment]"), Op.EQ, env_name))
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=[project_id],
select=select,
start=start,
end=end,
where=where,
granularity=Granularity(rollup),
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
if len(groups) > 0:
return get_path(groups[0], "totals", "value", default=0)
else:
return 0
def get_num_sessions_per_project(
self,
project_ids: Sequence[ProjectId],
start: datetime | None,
end: datetime | None,
environment_ids: Sequence[int] | None = None,
) -> Sequence[ProjectWithCount]:
projects, org_id = self._get_projects_and_org_id(project_ids)
select = [MetricField(metric_mri=SessionMRI.ALL.value, alias="value", op=None)]
where = []
groupby = [
MetricGroupByField(field="project_id"),
]
if environment_ids is not None and len(environment_ids) > 0:
# convert the PosgreSQL environmentID into the clickhouse string index
# for the environment name
env_names_dict = _model_environment_ids_to_environment_names(environment_ids)
env_names = [value for value in env_names_dict.values() if value is not None]
where.append(
Condition(
lhs=Column(name="tags[environment]"),
op=Op.IN,
rhs=env_names,
)
)
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=end,
where=where,
groupby=groupby,
granularity=Granularity(LEGACY_SESSIONS_DEFAULT_ROLLUP),
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
ret_val = [
(get_path(group, "by", "project_id"), get_path(group, "totals", "value"))
for group in raw_result["groups"]
]
return ret_val
def get_project_releases_by_stability(
self,
project_ids: Sequence[ProjectId],
offset: int | None,
limit: int | None,
scope: str,
stats_period: str | None = None,
environments: Sequence[str] | None = None,
now: datetime | None = None,
) -> Sequence[ProjectRelease]:
if len(project_ids) == 0:
return []
projects, org_id = self._get_projects_and_org_id(project_ids)
where = []
if environments is not None:
where.append(Condition(Column("tags[environment]"), Op.IN, environments))
if stats_period is None:
stats_period = "24h"
# Special rule that we support sorting by the last 24h only.
if scope.endswith("_24h"):
scope = scope[:-4]
stats_period = "24h"
if now is None:
now = datetime.now(timezone.utc)
granularity, stats_start, _ = get_rollup_starts_and_buckets(stats_period, now=now)
groupby = [
MetricGroupByField(field="project_id"),
MetricGroupByField(field="release"),
]
if scope == "crash_free_sessions":
select = [
MetricField(metric_mri=SessionMRI.ALL.value, op=None),
MetricField(metric_mri=SessionMRI.CRASH_RATE.value, op=None),
]
orderby = [
MetricOrderByField(
MetricField(metric_mri=SessionMRI.CRASH_RATE.value, op=None),
direction=Direction.DESC,
)
]
elif scope == "sessions":
select = [MetricField(metric_mri=SessionMRI.ALL.value, op=None)]
orderby = [
MetricOrderByField(
MetricField(metric_mri=SessionMRI.ALL.value, op=None), direction=Direction.DESC
)
]
elif scope == "crash_free_users":
select = [
MetricField(metric_mri=SessionMRI.ALL_USER.value, op=None),
MetricField(metric_mri=SessionMRI.CRASH_USER_RATE.value, op=None),
]
orderby = [
MetricOrderByField(
MetricField(metric_mri=SessionMRI.CRASH_USER_RATE.value, op=None),
direction=Direction.DESC,
)
]
else: # users
assert scope == "users"
select = [MetricField(metric_mri=SessionMRI.ALL_USER.value, op=None)]
orderby = [
MetricOrderByField(
MetricField(metric_mri=SessionMRI.ALL_USER.value, op=None),
direction=Direction.DESC,
)
]
query = DeprecatingMetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=stats_start,
end=now,
where=where,
orderby=orderby,
groupby=groupby,
granularity=Granularity(LEGACY_SESSIONS_DEFAULT_ROLLUP),
offset=Offset(offset) if offset is not None else None,
limit=Limit(limit) if limit is not None else None,
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
ret_val = []
for group in groups:
by = group.get("by")
ret_val.append((by["project_id"], by["release"]))
return ret_val
| MetricsReleaseHealthBackend |
python | ansible__ansible | lib/ansible/modules/package_facts.py | {
"start": 10806,
"end": 12169
} | class ____(CLIMgr):
CLI = 'pkg'
atoms = ['name', 'version', 'origin', 'installed', 'automatic', 'arch', 'category', 'prefix', 'vital']
def list_installed(self):
rc, out, err = module.run_command([self._cli, 'query', "%%%s" % '\t%'.join(['n', 'v', 'R', 't', 'a', 'q', 'o', 'p', 'V'])])
if rc != 0 or err:
raise Exception("Unable to list packages rc=%s : %s" % (rc, err))
return out.splitlines()
def get_package_details(self, package):
pkg = dict(zip(self.atoms, package.split('\t')))
if 'arch' in pkg:
try:
pkg['arch'] = pkg['arch'].split(':')[2]
except IndexError:
pass
if 'automatic' in pkg:
pkg['automatic'] = bool(int(pkg['automatic']))
if 'category' in pkg:
pkg['category'] = pkg['category'].split('/', 1)[0]
if 'version' in pkg:
if ',' in pkg['version']:
pkg['version'], pkg['port_epoch'] = pkg['version'].split(',', 1)
else:
pkg['port_epoch'] = 0
if '_' in pkg['version']:
pkg['version'], pkg['revision'] = pkg['version'].split('_', 1)
else:
pkg['revision'] = '0'
if 'vital' in pkg:
pkg['vital'] = bool(int(pkg['vital']))
return pkg
| PKG |
python | keras-team__keras | keras/src/legacy/preprocessing/image.py | {
"start": 7172,
"end": 15036
} | class ____:
"""Adds methods related to getting batches from filenames.
It includes the logic to transform image files to batches.
"""
def set_processing_attrs(
self,
image_data_generator,
target_size,
color_mode,
data_format,
save_to_dir,
save_prefix,
save_format,
subset,
interpolation,
keep_aspect_ratio,
):
"""Sets attributes to use later for processing files into a batch.
Args:
image_data_generator: Instance of `ImageDataGenerator`
to use for random transformations and normalization.
target_size: tuple of integers, dimensions to resize input images
to.
color_mode: One of `"rgb"`, `"rgba"`, `"grayscale"`.
Color mode to read images.
data_format: String, one of `channels_first`, `channels_last`.
save_to_dir: Optional directory where to save the pictures
being yielded, in a viewable format. This is useful
for visualizing the random transformations being
applied, for debugging purposes.
save_prefix: String prefix to use for saving sample
images (if `save_to_dir` is set).
save_format: Format to use for saving sample images
(if `save_to_dir` is set).
subset: Subset of data (`"training"` or `"validation"`) if
validation_split is set in ImageDataGenerator.
interpolation: Interpolation method used to resample the image if
the target size is different from that of the loaded image.
Supported methods are "nearest", "bilinear", and "bicubic". If
PIL version 1.1.3 or newer is installed, "lanczos" is also
supported. If PIL version 3.4.0 or newer is installed, "box" and
"hamming" are also supported. By default, "nearest" is used.
keep_aspect_ratio: Boolean, whether to resize images to a target
size without aspect ratio distortion. The image is cropped in
the center with target aspect ratio before resizing.
"""
self.image_data_generator = image_data_generator
self.target_size = tuple(target_size)
self.keep_aspect_ratio = keep_aspect_ratio
if color_mode not in {"rgb", "rgba", "grayscale"}:
raise ValueError(
f"Invalid color mode: {color_mode}"
'; expected "rgb", "rgba", or "grayscale".'
)
self.color_mode = color_mode
self.data_format = data_format
if self.color_mode == "rgba":
if self.data_format == "channels_last":
self.image_shape = self.target_size + (4,)
else:
self.image_shape = (4,) + self.target_size
elif self.color_mode == "rgb":
if self.data_format == "channels_last":
self.image_shape = self.target_size + (3,)
else:
self.image_shape = (3,) + self.target_size
else:
if self.data_format == "channels_last":
self.image_shape = self.target_size + (1,)
else:
self.image_shape = (1,) + self.target_size
self.save_to_dir = save_to_dir
self.save_prefix = save_prefix
self.save_format = save_format
self.interpolation = interpolation
if subset is not None:
validation_split = self.image_data_generator._validation_split
if subset == "validation":
split = (0, validation_split)
elif subset == "training":
split = (validation_split, 1)
else:
raise ValueError(
f"Invalid subset name: {subset};"
'expected "training" or "validation"'
)
else:
split = None
self.split = split
self.subset = subset
def _get_batches_of_transformed_samples(self, index_array):
"""Gets a batch of transformed samples.
Args:
index_array: Array of sample indices to include in batch.
Returns:
A batch of transformed samples.
"""
batch_x = np.zeros(
(len(index_array),) + self.image_shape, dtype=self.dtype
)
# build batch of image data
# self.filepaths is dynamic, is better to call it once outside the loop
filepaths = self.filepaths
for i, j in enumerate(index_array):
img = image_utils.load_img(
filepaths[j],
color_mode=self.color_mode,
target_size=self.target_size,
interpolation=self.interpolation,
keep_aspect_ratio=self.keep_aspect_ratio,
)
x = image_utils.img_to_array(img, data_format=self.data_format)
# Pillow images should be closed after `load_img`,
# but not PIL images.
if hasattr(img, "close"):
img.close()
if self.image_data_generator:
params = self.image_data_generator.get_random_transform(x.shape)
x = self.image_data_generator.apply_transform(x, params)
x = self.image_data_generator.standardize(x)
batch_x[i] = x
# optionally save augmented images to disk for debugging purposes
if self.save_to_dir:
for i, j in enumerate(index_array):
img = image_utils.array_to_img(
batch_x[i], self.data_format, scale=True
)
fname = "{prefix}_{index}_{hash}.{format}".format(
prefix=self.save_prefix,
index=j,
hash=np.random.randint(1e7),
format=self.save_format,
)
img.save(os.path.join(self.save_to_dir, fname))
# build batch of labels
if self.class_mode == "input":
batch_y = batch_x.copy()
elif self.class_mode in {"binary", "sparse"}:
batch_y = np.empty(len(batch_x), dtype=self.dtype)
for i, n_observation in enumerate(index_array):
batch_y[i] = self.classes[n_observation]
elif self.class_mode == "categorical":
batch_y = np.zeros(
(len(batch_x), len(self.class_indices)), dtype=self.dtype
)
for i, n_observation in enumerate(index_array):
batch_y[i, self.classes[n_observation]] = 1.0
elif self.class_mode == "multi_output":
batch_y = [output[index_array] for output in self.labels]
elif self.class_mode == "raw":
batch_y = self.labels[index_array]
else:
return batch_x
if self.sample_weight is None:
return batch_x, batch_y
else:
return batch_x, batch_y, self.sample_weight[index_array]
@property
def filepaths(self):
"""List of absolute paths to image files."""
raise NotImplementedError(
"`filepaths` property method has not "
"been implemented in {}.".format(type(self).__name__)
)
@property
def labels(self):
"""Class labels of every observation."""
raise NotImplementedError(
"`labels` property method has not been implemented in {}.".format(
type(self).__name__
)
)
@property
def sample_weight(self):
raise NotImplementedError(
"`sample_weight` property method has not "
"been implemented in {}.".format(type(self).__name__)
)
@keras_export("keras._legacy.preprocessing.image.DirectoryIterator")
| BatchFromFilesMixin |
python | scikit-learn__scikit-learn | sklearn/model_selection/tests/test_validation.py | {
"start": 72199,
"end": 92981
} | class ____(BaseEstimator):
def __init__(self, max_x_value=None):
self.max_x_value = max_x_value
def fit(self, X, y=None):
num_values_too_high = (X > self.max_x_value).sum()
if num_values_too_high:
raise ValueError(
f"Classifier fit failed with {num_values_too_high} values too high"
)
def score(self, X=None, Y=None):
return 0.0
@pytest.mark.parametrize("error_score", [np.nan, 0])
def test_cross_validate_some_failing_fits_warning(error_score):
# Create a failing classifier to deliberately fail
failing_clf = DataDependentFailingClassifier(max_x_value=8)
# dummy X data
X = np.arange(1, 10)
y = np.ones(9)
# passing error score to trigger the warning message
cross_validate_args = [failing_clf, X, y]
cross_validate_kwargs = {"cv": 3, "error_score": error_score}
# check if the warning message type is as expected
individual_fit_error_message = (
"ValueError: Classifier fit failed with 1 values too high"
)
warning_message = re.compile(
(
"2 fits failed.+total of 3.+The score on these"
" train-test partitions for these parameters will be set to"
f" {cross_validate_kwargs['error_score']}.+{individual_fit_error_message}"
),
flags=re.DOTALL,
)
with pytest.warns(FitFailedWarning, match=warning_message):
cross_validate(*cross_validate_args, **cross_validate_kwargs)
@pytest.mark.parametrize("error_score", [np.nan, 0])
def test_cross_validate_all_failing_fits_error(error_score):
# Create a failing classifier to deliberately fail
failing_clf = FailingClassifier(FailingClassifier.FAILING_PARAMETER)
# dummy X data
X = np.arange(1, 10)
y = np.ones(9)
cross_validate_args = [failing_clf, X, y]
cross_validate_kwargs = {"cv": 7, "error_score": error_score}
individual_fit_error_message = "ValueError: Failing classifier failed as required"
error_message = re.compile(
(
"All the 7 fits failed.+your model is misconfigured.+"
f"{individual_fit_error_message}"
),
flags=re.DOTALL,
)
with pytest.raises(ValueError, match=error_message):
cross_validate(*cross_validate_args, **cross_validate_kwargs)
def _failing_scorer(estimator, X, y, error_msg):
raise ValueError(error_msg)
@pytest.mark.filterwarnings("ignore:lbfgs failed to converge")
@pytest.mark.parametrize("error_score", [np.nan, 0, "raise"])
def test_cross_val_score_failing_scorer(error_score):
# check that an estimator can fail during scoring in `cross_val_score` and
# that we can optionally replaced it with `error_score`
X, y = load_iris(return_X_y=True)
clf = LogisticRegression(max_iter=5).fit(X, y)
error_msg = "This scorer is supposed to fail!!!"
failing_scorer = partial(_failing_scorer, error_msg=error_msg)
if error_score == "raise":
with pytest.raises(ValueError, match=error_msg):
cross_val_score(
clf, X, y, cv=3, scoring=failing_scorer, error_score=error_score
)
else:
warning_msg = (
"Scoring failed. The score on this train-test partition for "
f"these parameters will be set to {error_score}"
)
with pytest.warns(UserWarning, match=warning_msg):
scores = cross_val_score(
clf, X, y, cv=3, scoring=failing_scorer, error_score=error_score
)
assert_allclose(scores, error_score)
@pytest.mark.filterwarnings("ignore:lbfgs failed to converge")
@pytest.mark.parametrize("error_score", [np.nan, 0, "raise"])
@pytest.mark.parametrize("return_train_score", [True, False])
@pytest.mark.parametrize("with_multimetric", [False, True])
def test_cross_validate_failing_scorer(
error_score, return_train_score, with_multimetric
):
# Check that an estimator can fail during scoring in `cross_validate` and
# that we can optionally replace it with `error_score`. In the multimetric
# case also check the result of a non-failing scorer where the other scorers
# are failing.
X, y = load_iris(return_X_y=True)
clf = LogisticRegression(max_iter=5).fit(X, y)
error_msg = "This scorer is supposed to fail!!!"
failing_scorer = partial(_failing_scorer, error_msg=error_msg)
if with_multimetric:
non_failing_scorer = make_scorer(mean_squared_error)
scoring = {
"score_1": failing_scorer,
"score_2": non_failing_scorer,
"score_3": failing_scorer,
}
else:
scoring = failing_scorer
if error_score == "raise":
with pytest.raises(ValueError, match=error_msg):
cross_validate(
clf,
X,
y,
cv=3,
scoring=scoring,
return_train_score=return_train_score,
error_score=error_score,
)
else:
warning_msg = (
"Scoring failed. The score on this train-test partition for "
f"these parameters will be set to {error_score}"
)
with pytest.warns(UserWarning, match=warning_msg):
results = cross_validate(
clf,
X,
y,
cv=3,
scoring=scoring,
return_train_score=return_train_score,
error_score=error_score,
)
for key in results:
if "_score" in key:
if "_score_2" in key:
# check the test (and optionally train) score for the
# scorer that should be non-failing
for i in results[key]:
assert isinstance(i, float)
else:
# check the test (and optionally train) score for all
# scorers that should be assigned to `error_score`.
assert_allclose(results[key], error_score)
def three_params_scorer(i, j, k):
return 3.4213
@pytest.mark.parametrize(
"train_score, scorer, verbose, split_prg, cdt_prg, expected",
[
(
False,
three_params_scorer,
2,
(1, 3),
(0, 1),
r"\[CV\] END ...................................................."
r" total time= 0.\ds",
),
(
True,
_MultimetricScorer(
scorers={"sc1": three_params_scorer, "sc2": three_params_scorer}
),
3,
(1, 3),
(0, 1),
r"\[CV 2/3\] END sc1: \(train=3.421, test=3.421\) sc2: "
r"\(train=3.421, test=3.421\) total time= 0.\ds",
),
(
False,
_MultimetricScorer(
scorers={"sc1": three_params_scorer, "sc2": three_params_scorer}
),
10,
(1, 3),
(0, 1),
r"\[CV 2/3; 1/1\] END ....... sc1: \(test=3.421\) sc2: \(test=3.421\)"
r" total time= 0.\ds",
),
],
)
def test_fit_and_score_verbosity(
capsys, train_score, scorer, verbose, split_prg, cdt_prg, expected
):
X, y = make_classification(n_samples=30, random_state=0)
clf = SVC(kernel="linear", random_state=0)
train, test = next(ShuffleSplit().split(X))
# test print without train score
fit_and_score_args = dict(
estimator=clf,
X=X,
y=y,
scorer=scorer,
train=train,
test=test,
verbose=verbose,
parameters=None,
fit_params=None,
score_params=None,
return_train_score=train_score,
split_progress=split_prg,
candidate_progress=cdt_prg,
)
_fit_and_score(**fit_and_score_args)
out, _ = capsys.readouterr()
outlines = out.split("\n")
if len(outlines) > 2:
assert re.match(expected, outlines[1])
else:
assert re.match(expected, outlines[0])
def test_score():
error_message = "scoring must return a number, got None"
def two_params_scorer(estimator, X_test):
return None
with pytest.raises(ValueError, match=error_message):
_score(
estimator=None,
X_test=None,
y_test=None,
scorer=two_params_scorer,
score_params=None,
error_score=np.nan,
)
def test_callable_multimetric_confusion_matrix_cross_validate():
def custom_scorer(clf, X, y):
y_pred = clf.predict(X)
cm = confusion_matrix(y, y_pred)
return {"tn": cm[0, 0], "fp": cm[0, 1], "fn": cm[1, 0], "tp": cm[1, 1]}
X, y = make_classification(n_samples=40, n_features=4, random_state=42)
est = LinearSVC(random_state=42)
est.fit(X, y)
cv_results = cross_validate(est, X, y, cv=5, scoring=custom_scorer)
score_names = ["tn", "fp", "fn", "tp"]
for name in score_names:
assert "test_{}".format(name) in cv_results
def test_learning_curve_partial_fit_regressors():
"""Check that regressors with partial_fit is supported.
Non-regression test for #22981.
"""
X, y = make_regression(random_state=42)
# Does not error
learning_curve(MLPRegressor(), X, y, exploit_incremental_learning=True, cv=2)
def test_learning_curve_some_failing_fits_warning(global_random_seed):
"""Checks for fit failures in `learning_curve` and raises the required warning"""
X, y = make_classification(
n_samples=30,
n_classes=3,
n_informative=6,
shuffle=False,
random_state=global_random_seed,
)
# sorting the target to trigger SVC error on the 2 first splits because a single
# class is present
sorted_idx = np.argsort(y)
X, y = X[sorted_idx], y[sorted_idx]
svc = SVC()
warning_message = "10 fits failed out of a total of 25"
with pytest.warns(FitFailedWarning, match=warning_message):
_, train_score, test_score, *_ = learning_curve(
svc, X, y, cv=5, error_score=np.nan
)
# the first 2 splits should lead to warnings and thus np.nan scores
for idx in range(2):
assert np.isnan(train_score[idx]).all()
assert np.isnan(test_score[idx]).all()
for idx in range(2, train_score.shape[0]):
assert not np.isnan(train_score[idx]).any()
assert not np.isnan(test_score[idx]).any()
def test_cross_validate_return_indices(global_random_seed):
"""Check the behaviour of `return_indices` in `cross_validate`."""
X, y = load_iris(return_X_y=True)
X = scale(X) # scale features for better convergence
estimator = LogisticRegression()
cv = KFold(n_splits=3, shuffle=True, random_state=global_random_seed)
cv_results = cross_validate(estimator, X, y, cv=cv, n_jobs=2, return_indices=False)
assert "indices" not in cv_results
cv_results = cross_validate(estimator, X, y, cv=cv, n_jobs=2, return_indices=True)
assert "indices" in cv_results
train_indices = cv_results["indices"]["train"]
test_indices = cv_results["indices"]["test"]
assert len(train_indices) == cv.n_splits
assert len(test_indices) == cv.n_splits
assert_array_equal([indices.size for indices in train_indices], 100)
assert_array_equal([indices.size for indices in test_indices], 50)
for split_idx, (expected_train_idx, expected_test_idx) in enumerate(cv.split(X, y)):
assert_array_equal(train_indices[split_idx], expected_train_idx)
assert_array_equal(test_indices[split_idx], expected_test_idx)
# Tests for metadata routing in cross_val* and in *curve
# ======================================================
@pytest.mark.parametrize(
"func, extra_args",
[
(cross_validate, {}),
(cross_val_score, {}),
(cross_val_predict, {}),
(learning_curve, {}),
(permutation_test_score, {}),
(validation_curve, {"param_name": "alpha", "param_range": np.array([1])}),
],
)
@config_context(enable_metadata_routing=True)
def test_groups_with_routing_validation(func, extra_args):
"""Check that we raise an error if `groups` are passed to the cv method instead
of `params` when metadata routing is enabled.
"""
with pytest.raises(ValueError, match="`groups` can only be passed if"):
func(
estimator=ConsumingClassifier(),
X=X,
y=y,
groups=[],
**extra_args,
)
@pytest.mark.parametrize(
"func, extra_args",
[
(cross_validate, {}),
(cross_val_score, {}),
(cross_val_predict, {}),
(learning_curve, {}),
(permutation_test_score, {}),
(validation_curve, {"param_name": "alpha", "param_range": np.array([1])}),
],
)
@config_context(enable_metadata_routing=True)
def test_cross_validate_params_none(func, extra_args):
"""Test that no errors are raised when passing `params=None`, which is the
default value.
Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/30447
"""
X, y = make_classification(n_samples=100, n_classes=2, random_state=0)
func(estimator=ConsumingClassifier(), X=X, y=y, **extra_args)
@pytest.mark.parametrize(
"func, extra_args",
[
(cross_validate, {}),
(cross_val_score, {}),
(cross_val_predict, {}),
(learning_curve, {}),
(permutation_test_score, {}),
(validation_curve, {"param_name": "alpha", "param_range": np.array([1])}),
],
)
@config_context(enable_metadata_routing=True)
def test_passed_unrequested_metadata(func, extra_args):
"""Check that we raise an error when passing metadata that is not
requested."""
err_msg = re.escape(
"[metadata] are passed but are not explicitly set as requested or not "
"requested for ConsumingClassifier.fit, which is used within"
)
with pytest.raises(UnsetMetadataPassedError, match=err_msg):
func(
estimator=ConsumingClassifier(),
X=X,
y=y2,
params=dict(metadata=[]),
**extra_args,
)
# cross_val_predict doesn't use scoring
if func == cross_val_predict:
return
err_msg = re.escape(
"[metadata] are passed but are not explicitly set as requested or not "
"requested for ConsumingClassifier.score, which is used within"
)
with pytest.raises(UnsetMetadataPassedError, match=err_msg):
func(
estimator=ConsumingClassifier()
.set_fit_request(metadata=True)
.set_partial_fit_request(metadata=True),
X=X,
y=y2,
params=dict(metadata=[]),
**extra_args,
)
@pytest.mark.parametrize(
"func, extra_args",
[
(cross_validate, {}),
(cross_val_score, {}),
(cross_val_predict, {}),
(learning_curve, {}),
(permutation_test_score, {}),
(validation_curve, {"param_name": "alpha", "param_range": np.array([1])}),
],
)
@config_context(enable_metadata_routing=True)
def test_validation_functions_routing(func, extra_args):
"""Check that the respective cv method is properly dispatching the metadata
to the consumer."""
scorer_registry = _Registry()
scorer = ConsumingScorer(registry=scorer_registry).set_score_request(
sample_weight="score_weights", metadata="score_metadata"
)
splitter_registry = _Registry()
splitter = ConsumingSplitter(registry=splitter_registry).set_split_request(
groups="split_groups", metadata="split_metadata"
)
estimator_registry = _Registry()
estimator = ConsumingClassifier(registry=estimator_registry).set_fit_request(
sample_weight="fit_sample_weight", metadata="fit_metadata"
)
n_samples = _num_samples(X)
rng = np.random.RandomState(0)
score_weights = rng.rand(n_samples)
score_metadata = rng.rand(n_samples)
split_groups = rng.randint(0, 3, n_samples)
split_metadata = rng.rand(n_samples)
fit_sample_weight = rng.rand(n_samples)
fit_metadata = rng.rand(n_samples)
scoring_args = {
cross_validate: dict(scoring=dict(my_scorer=scorer, accuracy="accuracy")),
cross_val_score: dict(scoring=scorer),
learning_curve: dict(scoring=scorer),
validation_curve: dict(scoring=scorer),
permutation_test_score: dict(scoring=scorer),
cross_val_predict: dict(),
}
params = dict(
split_groups=split_groups,
split_metadata=split_metadata,
fit_sample_weight=fit_sample_weight,
fit_metadata=fit_metadata,
)
if func is not cross_val_predict:
params.update(
score_weights=score_weights,
score_metadata=score_metadata,
)
func(
estimator,
X=X,
y=y,
cv=splitter,
**scoring_args[func],
**extra_args,
params=params,
)
if func is not cross_val_predict:
# cross_val_predict doesn't need a scorer
assert len(scorer_registry)
for _scorer in scorer_registry:
check_recorded_metadata(
obj=_scorer,
method="score",
parent=func.__name__,
split_params=("sample_weight", "metadata"),
sample_weight=score_weights,
metadata=score_metadata,
)
assert len(splitter_registry)
for _splitter in splitter_registry:
check_recorded_metadata(
obj=_splitter,
method="split",
parent=func.__name__,
groups=split_groups,
metadata=split_metadata,
)
assert len(estimator_registry)
for _estimator in estimator_registry:
check_recorded_metadata(
obj=_estimator,
method="fit",
parent=func.__name__,
split_params=("sample_weight", "metadata"),
sample_weight=fit_sample_weight,
metadata=fit_metadata,
)
@config_context(enable_metadata_routing=True)
def test_learning_curve_exploit_incremental_learning_routing():
"""Test that learning_curve routes metadata to the estimator correctly while
partial_fitting it with `exploit_incremental_learning=True`."""
n_samples = _num_samples(X)
rng = np.random.RandomState(0)
fit_sample_weight = rng.rand(n_samples)
fit_metadata = rng.rand(n_samples)
estimator_registry = _Registry()
estimator = ConsumingClassifier(
registry=estimator_registry
).set_partial_fit_request(
sample_weight="fit_sample_weight", metadata="fit_metadata"
)
learning_curve(
estimator,
X=X,
y=y,
cv=ConsumingSplitter(),
exploit_incremental_learning=True,
params=dict(fit_sample_weight=fit_sample_weight, fit_metadata=fit_metadata),
)
assert len(estimator_registry)
for _estimator in estimator_registry:
check_recorded_metadata(
obj=_estimator,
method="partial_fit",
parent="learning_curve",
split_params=("sample_weight", "metadata"),
sample_weight=fit_sample_weight,
metadata=fit_metadata,
)
# End of metadata routing tests
# =============================
@pytest.mark.parametrize(
"estimator",
[Ridge(), LinearDiscriminantAnalysis()],
ids=["Ridge", "LinearDiscriminantAnalysis"],
)
@pytest.mark.parametrize("cv", [None, 3, 5])
@pytest.mark.parametrize(
"namespace, device_, dtype_name",
yield_namespace_device_dtype_combinations(),
ids=_get_namespace_device_dtype_ids,
)
def test_cross_val_predict_array_api_compliance(
estimator, cv, namespace, device_, dtype_name
):
"""Test that `cross_val_predict` functions correctly with the array API
with both a classifier and a regressor."""
xp = _array_api_for_tests(namespace, device_)
if is_classifier(estimator):
X, y = make_classification(
n_samples=1000, n_features=5, n_classes=3, n_informative=3, random_state=42
)
else:
X, y = make_regression(
n_samples=1000, n_features=5, n_informative=3, random_state=42
)
X_np = X.astype(dtype_name)
y_np = y.astype(dtype_name)
X_xp = xp.asarray(X_np, device=device_)
y_xp = xp.asarray(y_np, device=device_)
with config_context(array_api_dispatch=True):
pred_xp = cross_val_predict(estimator, X_xp, y_xp, cv=cv)
pred_np = cross_val_predict(estimator, X_np, y_np, cv=cv)
assert_allclose(
_convert_to_numpy(pred_xp, xp), pred_np, atol=_atol_for_type(dtype_name)
)
| DataDependentFailingClassifier |
python | doocs__leetcode | solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.py | {
"start": 0,
"end": 309
} | class ____:
def makePrefSumNonNegative(self, nums: List[int]) -> int:
h = []
ans = s = 0
for x in nums:
s += x
if x < 0:
heappush(h, x)
while s < 0:
s -= heappop(h)
ans += 1
return ans
| Solution |
python | coleifer__peewee | tests/model_save.py | {
"start": 118,
"end": 188
} | class ____(TestModel):
pk = AutoField()
value = IntegerField()
| T1 |
python | viewflow__viewflow | viewflow/middleware.py | {
"start": 320,
"end": 2567
} | class ____(object):
"""
Set `site` and `app` attributes on request.resolver_match object.
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
return self.get_response(request)
def process_view(self, request, callback, callback_args, callback_kwargs):
if not hasattr(request, "user"):
raise ValueError(
"No `request.user` found. `django.contrib.auth.context_processors.auth` "
"missing or `material.middleware.site included before it.` "
"You need to add auth middleware or change middlewares order."
)
match = request.resolver_match
if match:
extra = getattr(match.url_name, "extra", {})
site, app = extra.get("site"), extra.get("app")
if site:
if not site.has_view_permission(request.user):
raise PermissionDenied
if app:
if not app.has_view_permission(request.user):
raise PermissionDenied
for name, value in extra.items():
setattr(request.resolver_match, name, value)
return None
def process_template_response(self, request, response):
app = getattr(request.resolver_match, "app", None)
if app:
app_context = app.get_context_data(request)
for key, value in app_context.items():
if key in response.context_data:
raise ValueError(
f"App context key {key} clashes with view response context"
)
else:
response.context_data[key] = value
return response
def HotwireTurboMiddleware(get_response):
def middleware(request):
response = get_response(request)
if (
request.method == "POST"
and request.META.get("HTTP_X_REQUEST_FRAMEWORK") == "Turbo"
):
if response.status_code == 200:
response.status_code = 422
elif response.status_code == 301:
response.status_code = 303
return response
return middleware
| SiteMiddleware |
python | astropy__astropy | astropy/utils/masked/tests/test_masked.py | {
"start": 26778,
"end": 26852
} | class ____(MaskedItemTests, QuantitySetup):
pass
| TestMaskedQuantityItems |
python | ApeWorX__ape | tests/functional/test_network_manager.py | {
"start": 17854,
"end": 18260
} | class ____:
def test_matches_provider(self, eth_tester_provider):
data = NodeProcessData(
network_choice=f"{eth_tester_provider.network.choice}:{eth_tester_provider.name}",
ipc_path="test.ipc",
)
assert not data.matches_provider(eth_tester_provider)
data.ipc_path = None
assert data.matches_provider(eth_tester_provider)
| TestNodeProcessData |
python | PrefectHQ__prefect | tests/utilities/schema_tools/test_validation.py | {
"start": 4057,
"end": 5348
} | class ____:
@pytest.fixture
def schema(self) -> dict:
return {
"title": "Parameters",
"type": "object",
"properties": {
"param": {"title": "param", "position": 0, "type": "boolean"}
},
"required": ["param"],
}
@pytest.mark.parametrize(
"obj, expected",
[
({"param": True}, True),
({"param": False}, True),
({"param": "not a boolean"}, False),
({}, False),
({"param": None}, False),
],
)
def test_is_valid(self, schema, obj, expected):
assert is_valid(obj, schema) == expected
@pytest.mark.parametrize(
"obj, expected_errors",
[
({"param": True}, []), # Valid boolean (True)
({"param": False}, []), # Valid boolean (False)
(
{"param": "not a boolean"},
["'not a boolean' is not of type 'boolean'"],
), # Invalid type
({}, ["'param' is a required property"]), # Missing required field
],
)
def test_validate(self, schema, obj, expected_errors):
errors = validate(obj, schema)
assert [e.message for e in errors] == expected_errors
| TestBoolean |
python | getsentry__sentry | tests/sentry/api/endpoints/test_broadcast_index.py | {
"start": 214,
"end": 3390
} | class ____(APITestCase):
def test_simple(self) -> None:
broadcast1 = Broadcast.objects.create(message="bar", is_active=True)
Broadcast.objects.create(message="foo", is_active=False)
self.add_user_permission(user=self.user, permission="broadcasts.admin")
self.login_as(user=self.user)
response = self.client.get("/api/0/broadcasts/")
assert response.status_code == 200
assert len(response.data) == 1
assert response.data[0]["id"] == str(broadcast1.id)
def test_superuser_with_all(self) -> None:
Broadcast.objects.create(message="bar", is_active=True)
Broadcast.objects.create(message="foo", is_active=False)
self.add_user_permission(user=self.user, permission="broadcasts.admin")
self.login_as(user=self.user, superuser=True)
response = self.client.get("/api/0/broadcasts/?show=all")
assert response.status_code == 200
assert len(response.data) == 2
response = self.client.get("/api/0/broadcasts/?show=all&query=status:active")
assert response.status_code == 200
assert len(response.data) == 1
response = self.client.get("/api/0/broadcasts/?show=all&query=status:inactive")
assert response.status_code == 200
assert len(response.data) == 1
response = self.client.get("/api/0/broadcasts/?show=all&query=status:zzz")
assert response.status_code == 200
assert len(response.data) == 0
response = self.client.get("/api/0/broadcasts/?show=all&query=foo")
assert response.status_code == 200
assert len(response.data) == 1
response = self.client.get("/api/0/broadcasts/?show=all&query=zzz")
assert response.status_code == 200
assert len(response.data) == 0
def test_basic_user_with_all(self) -> None:
broadcast1 = Broadcast.objects.create(message="bar", is_active=True)
Broadcast.objects.create(message="foo", is_active=False, created_by_id=self.user)
self.add_user_permission(user=self.user, permission="broadcasts.admin")
self.login_as(user=self.user, superuser=False)
response = self.client.get("/api/0/broadcasts/?show=all")
assert response.status_code == 200
assert len(response.data) == 1
assert response.data[0]["id"] == str(broadcast1.id)
assert "createdBy" not in response.data[0]
def test_organization_filtering(self) -> None:
broadcast1 = Broadcast.objects.create(message="foo", is_active=True)
broadcast2 = Broadcast.objects.create(message="bar", is_active=True)
self.add_user_permission(user=self.user, permission="broadcasts.admin")
self.login_as(user=self.user)
url = reverse("sentry-api-0-organization-broadcasts", args=[self.organization.slug])
response = self.client.get(url)
assert response.status_code == 200
assert len(response.data) == 2
assert str(broadcast1.id) in [str(broadcast["id"]) for broadcast in response.data]
assert str(broadcast2.id) in [str(broadcast["id"]) for broadcast in response.data]
@control_silo_test
| BroadcastListTest |
python | ansible__ansible | test/units/config/test_manager.py | {
"start": 7586,
"end": 11027
} | class ____:
@classmethod
def setup_class(cls):
cls.manager = ConfigManager(cfg_file, os.path.join(curdir, 'test.yml'))
@classmethod
def teardown_class(cls):
cls.manager = None
def test_resolve_path(self):
assert os.path.join(curdir, 'test.yml') == resolve_path('./test.yml', cfg_file)
def test_resolve_path_cwd(self):
assert os.path.join(os.getcwd(), 'test.yml') == resolve_path('{{CWD}}/test.yml')
assert os.path.join(os.getcwd(), 'test.yml') == resolve_path('./test.yml')
def test_value_and_origin_from_ini(self):
assert self.manager.get_config_value_and_origin('config_entry') == ('fromini', cfg_file)
def test_value_from_ini(self):
assert self.manager.get_config_value('config_entry') == 'fromini'
def test_value_and_origin_from_alt_ini(self):
assert self.manager.get_config_value_and_origin('config_entry', cfile=cfg_file2) == ('fromini2', cfg_file2)
def test_value_from_alt_ini(self):
assert self.manager.get_config_value('config_entry', cfile=cfg_file2) == 'fromini2'
def test_config_types(self):
assert get_config_type('/tmp/ansible.ini') == 'ini'
assert get_config_type('/tmp/ansible.cfg') == 'ini'
assert get_config_type('/tmp/ansible.yaml') == 'yaml'
assert get_config_type('/tmp/ansible.yml') == 'yaml'
def test_config_types_negative(self):
with pytest.raises(AnsibleOptionsError) as exec_info:
get_config_type('/tmp/ansible.txt')
assert "Unsupported configuration file extension for" in str(exec_info.value)
def test_read_config_yaml_file(self):
assert isinstance(self.manager._read_config_yaml_file(os.path.join(curdir, 'test.yml')), dict)
def test_read_config_yaml_file_negative(self):
with pytest.raises(AnsibleError) as exec_info:
self.manager._read_config_yaml_file(os.path.join(curdir, 'test_non_existent.yml'))
assert "Missing base YAML definition file (bad install?)" in str(exec_info.value)
@pytest.mark.parametrize(("key", "expected_value"), (
("COLOR_UNREACHABLE", "bright red"),
("COLOR_VERBOSE", "rgb013"),
("COLOR_DEBUG", "gray10")))
def test_256color_support(key, expected_value):
# GIVEN: a config file containing 256-color values with default definitions
manager = ConfigManager(cfg_file3)
# WHEN: get config values
actual_value = manager.get_config_value(key)
# THEN: no error
assert actual_value == expected_value
def test_config_trust_from_env(monkeypatch: pytest.MonkeyPatch) -> None:
expected = "from test"
monkeypatch.setenv("ANSIBLE_TEST_ENTRY", expected)
result = ConfigManager().get_config_value("_Z_TEST_ENTRY")
origin = Origin.get_tag(result)
assert result == expected
assert is_trusted_as_template(result)
assert origin and origin.description == '<Config env: ANSIBLE_TEST_ENTRY>'
def test_config_trust_from_file(tmp_path: pathlib.Path) -> None:
expected = "from test"
cfg_path = tmp_path / 'test.cfg'
cfg_path.write_text(f"[testing]\nvalid={expected}")
result = ConfigManager(str(cfg_path)).get_config_value("_Z_TEST_ENTRY")
origin = Origin.get_tag(result)
assert result == expected
assert is_trusted_as_template(result)
assert origin
assert origin.path == str(cfg_path)
assert origin.description == "section 'testing' option 'valid'"
| TestConfigManager |
python | pytorch__pytorch | test/package/package_a/__init__.py | {
"start": 23,
"end": 174
} | class ____:
__slots__ = ["obj"]
def __init__(self, obj):
self.obj = obj
def return_result(self):
return result
| PackageAObject |
python | milvus-io__pymilvus | pymilvus/bulk_writer/stage_bulk_writer.py | {
"start": 356,
"end": 4091
} | class ____(LocalBulkWriter):
"""StageBulkWriter handles writing local bulk files to a remote stage."""
def __init__(
self,
schema: CollectionSchema,
remote_path: str,
cloud_endpoint: str,
api_key: str,
stage_name: str,
chunk_size: int = 1024 * MB,
file_type: BulkFileType = BulkFileType.PARQUET,
config: Optional[dict] = None,
**kwargs,
):
local_path = Path(sys.argv[0]).resolve().parent / "bulk_writer"
super().__init__(schema, str(local_path), chunk_size, file_type, config, **kwargs)
remote_dir_path = Path(remote_path) / super().uuid
self._remote_path = str(remote_dir_path) + "/"
self._remote_files: List[List[str]] = []
self._stage_name = stage_name
self._stage_file_manager = StageFileManager(
cloud_endpoint=cloud_endpoint,
api_key=api_key,
stage_name=stage_name,
connect_type=ConnectType.AUTO,
)
logger.info(f"Remote buffer writer initialized, target path: {self._remote_path}")
def __enter__(self):
return self
def append_row(self, row: Dict[str, Any], **kwargs):
super().append_row(row, **kwargs)
def commit(self, **kwargs):
"""Commit local bulk files and upload to remote stage."""
super().commit(call_back=self._upload)
@property
def data_path(self) -> str:
return str(self._remote_path)
@property
def batch_files(self) -> List[List[str]]:
return self._remote_files
def get_stage_upload_result(self) -> Dict[str, str]:
return {"stage_name": self._stage_name, "path": str(self._remote_path)}
def __exit__(self, exc_type: object, exc_val: object, exc_tb: object):
super().__exit__(exc_type, exc_val, exc_tb)
parent_dir = Path(self._local_path).parent
if parent_dir.exists() and not any(parent_dir.iterdir()):
parent_dir.rmdir()
logger.info(f"Deleted empty directory '{parent_dir}'")
def _local_rm(self, file_path: str):
"""Delete local file and possibly its empty parent directory."""
try:
path = Path(file_path)
path.unlink()
parent_dir = path.parent
if parent_dir != Path(self._local_path) and not any(parent_dir.iterdir()):
parent_dir.rmdir()
logger.info(f"Deleted empty directory '{parent_dir}'")
except Exception:
logger.warning(f"Failed to delete local file: {file_path}")
def _upload(self, file_list: List[str]) -> List[str]:
"""Upload files to remote stage and remove local copies."""
uploaded_files: List[str] = []
for file_path in file_list:
path = Path(file_path)
relative_file_path = path.relative_to(super().data_path)
remote_file_path = self._remote_path / relative_file_path
try:
self._upload_object(file_path=str(path), object_name=str(remote_file_path))
uploaded_files.append(str(remote_file_path))
self._local_rm(str(path))
except Exception as e:
self._throw(f"Failed to upload file '{file_path}', error: {e}")
logger.info(f"Successfully uploaded files: {uploaded_files}")
self._remote_files.append(uploaded_files)
return uploaded_files
def _upload_object(self, file_path: str, object_name: str):
logger.info(f"Prepare to upload '{file_path}' to '{object_name}'")
self._stage_file_manager.upload_file_to_stage(file_path, self._remote_path)
logger.info(f"Uploaded file '{file_path}' to '{object_name}'")
| StageBulkWriter |
python | pytorch__pytorch | test/torch_np/test_reductions.py | {
"start": 1733,
"end": 2364
} | class ____(TestCase):
def test_basic(self):
y1 = [0, 1, 1, 0]
y2 = [0, 0, 0, 0]
y3 = [1, 1, 1, 1]
assert not np.all(y1)
assert np.all(y3)
assert not np.all(y2)
assert np.all(~np.array(y2))
def test_nd(self):
y1 = [[0, 0, 1], [0, 1, 1], [1, 1, 1]]
assert not np.all(y1)
assert_equal(np.all(y1, axis=0), [0, 0, 1])
assert_equal(np.all(y1, axis=1), [0, 0, 1])
assert_equal(np.all(y1), False)
def test_method_vs_function(self):
y = np.array([[0, 1, 0, 3], [1, 0, 2, 0]])
assert_equal(np.all(y), y.all())
| TestAll |
python | pypa__warehouse | warehouse/accounts/forms.py | {
"start": 23043,
"end": 23109
} | class ____(NewPasswordMixin, wtforms.Form):
pass
| ResetPasswordForm |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefault2.py | {
"start": 585,
"end": 632
} | class ____[T: list[Any] = list[int]]: ...
| ClassT4 |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 978508,
"end": 979796
} | class ____(sgqlc.types.Type, Node, UniformResourceLocatable):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"actor",
"created_at",
"database_id",
"dismissal_message",
"dismissal_message_html",
"previous_review_state",
"pull_request",
"pull_request_commit",
"review",
)
actor = sgqlc.types.Field(Actor, graphql_name="actor")
created_at = sgqlc.types.Field(
sgqlc.types.non_null(DateTime), graphql_name="createdAt"
)
database_id = sgqlc.types.Field(Int, graphql_name="databaseId")
dismissal_message = sgqlc.types.Field(String, graphql_name="dismissalMessage")
dismissal_message_html = sgqlc.types.Field(
String, graphql_name="dismissalMessageHTML"
)
previous_review_state = sgqlc.types.Field(
sgqlc.types.non_null(PullRequestReviewState), graphql_name="previousReviewState"
)
pull_request = sgqlc.types.Field(
sgqlc.types.non_null(PullRequest), graphql_name="pullRequest"
)
pull_request_commit = sgqlc.types.Field(
PullRequestCommit, graphql_name="pullRequestCommit"
)
review = sgqlc.types.Field(PullRequestReview, graphql_name="review")
| ReviewDismissedEvent |
python | django__django | tests/bulk_create/models.py | {
"start": 1526,
"end": 1686
} | class ____(models.Model):
number = models.IntegerField(unique=True)
rank = models.IntegerField()
name = models.CharField(max_length=15)
| UpsertConflict |
python | pytest-dev__pytest-cov | src/pytest_cov/engine.py | {
"start": 11238,
"end": 14516
} | class ____(CovController):
"""Implementation for distributed master."""
@_ensure_topdir
def start(self):
self.cov = coverage.Coverage(
source=self.cov_source,
branch=self.cov_branch,
data_suffix=True,
config_file=self.cov_config,
)
if self.cov.config.dynamic_context == 'test_function':
raise DistCovError(
'Detected dynamic_context=test_function in coverage configuration. '
'This is known to cause issues when using xdist, see: https://github.com/pytest-dev/pytest-cov/issues/604\n'
'It is recommended to use --cov-context instead.'
)
self.cov._warn_no_data = False
self.cov._warn_unimported_source = False
self.cov._warn_preimported_source = False
self.combining_cov = coverage.Coverage(
source=self.cov_source,
branch=self.cov_branch,
data_suffix=f'{filename_suffix(True)}.combine',
data_file=os.path.abspath(self.cov.config.data_file), # noqa: PTH100
config_file=self.cov_config,
)
if not self.cov_append:
self.cov.erase()
self.cov.start()
self.cov.config.paths['source'] = [self.topdir]
def configure_node(self, node):
"""Workers need to know if they are collocated and what files have moved."""
node.workerinput.update(
{
'cov_master_host': socket.gethostname(),
'cov_master_topdir': self.topdir,
'cov_master_rsync_roots': [str(root) for root in node.nodemanager.roots],
}
)
def testnodedown(self, node, error):
"""Collect data file name from worker."""
# If worker doesn't return any data then it is likely that this
# plugin didn't get activated on the worker side.
output = getattr(node, 'workeroutput', {})
if 'cov_worker_node_id' not in output:
self.failed_workers.append(node)
return
# If worker is not collocated then we must save the data file
# that it returns to us.
if 'cov_worker_data' in output:
data_suffix = '%s.%s.%06d.%s' % ( # noqa: UP031
socket.gethostname(),
os.getpid(),
random.randint(0, 999999), # noqa: S311
output['cov_worker_node_id'],
)
cov_data = CoverageData(
suffix=data_suffix,
)
cov_data.loads(output['cov_worker_data'])
path = output['cov_worker_path']
self.cov.config.paths['source'].append(path)
# Record the worker types that contribute to the data file.
rinfo = node.gateway._rinfo()
node_desc = self.get_node_desc(rinfo.platform, rinfo.version_info)
self.node_descs.add(node_desc)
@_ensure_topdir
def finish(self):
"""Combines coverage data and sets the list of coverage objects to report on."""
# Combine all the suffix files into the data file.
self.cov.stop()
self.cov.save()
self.cov = self.combining_cov
self.cov.load()
self.cov.combine()
self.cov.save()
| DistMaster |
python | wandb__wandb | wandb/vendor/pygments/lexers/html.py | {
"start": 7389,
"end": 8657
} | class ____(XmlLexer):
"""
A lexer for XSLT.
.. versionadded:: 0.10
"""
name = 'XSLT'
aliases = ['xslt']
filenames = ['*.xsl', '*.xslt', '*.xpl'] # xpl is XProc
mimetypes = ['application/xsl+xml', 'application/xslt+xml']
EXTRA_KEYWORDS = set((
'apply-imports', 'apply-templates', 'attribute',
'attribute-set', 'call-template', 'choose', 'comment',
'copy', 'copy-of', 'decimal-format', 'element', 'fallback',
'for-each', 'if', 'import', 'include', 'key', 'message',
'namespace-alias', 'number', 'otherwise', 'output', 'param',
'preserve-space', 'processing-instruction', 'sort',
'strip-space', 'stylesheet', 'template', 'text', 'transform',
'value-of', 'variable', 'when', 'with-param'
))
def get_tokens_unprocessed(self, text):
for index, token, value in XmlLexer.get_tokens_unprocessed(self, text):
m = re.match('</?xsl:([^>]*)/?>?', value)
if token is Name.Tag and m and m.group(1) in self.EXTRA_KEYWORDS:
yield index, Keyword, value
else:
yield index, token, value
def analyse_text(text):
if looks_like_xml(text) and '<xsl' in text:
return 0.8
| XsltLexer |
python | yaml__pyyaml | lib/yaml/events.py | {
"start": 1873,
"end": 2223
} | class ____(NodeEvent):
def __init__(self, anchor, tag, implicit, value,
start_mark=None, end_mark=None, style=None):
self.anchor = anchor
self.tag = tag
self.implicit = implicit
self.value = value
self.start_mark = start_mark
self.end_mark = end_mark
self.style = style
| ScalarEvent |
python | redis__redis-py | tests/test_command_parser.py | {
"start": 238,
"end": 9131
} | class ____:
def test_init_commands(self, r):
commands_parser = CommandsParser(r)
assert commands_parser.commands is not None
assert "get" in commands_parser.commands
def test_get_keys_predetermined_key_location(self, r):
commands_parser = CommandsParser(r)
args1 = ["GET", "foo"]
args2 = ["OBJECT", "encoding", "foo"]
args3 = ["MGET", "foo", "bar", "foobar"]
assert commands_parser.get_keys(r, *args1) == ["foo"]
assert commands_parser.get_keys(r, *args2) == ["foo"]
assert commands_parser.get_keys(r, *args3) == ["foo", "bar", "foobar"]
@pytest.mark.filterwarnings("ignore:ResponseError")
@skip_if_redis_enterprise()
def test_get_moveable_keys(self, r):
commands_parser = CommandsParser(r)
args1 = [
"EVAL",
"return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}",
2,
"key1",
"key2",
"first",
"second",
]
args2 = ["XREAD", "COUNT", 2, b"STREAMS", "mystream", "writers", 0, 0]
args3 = ["ZUNIONSTORE", "out", 2, "zset1", "zset2", "WEIGHTS", 2, 3]
args4 = ["GEORADIUS", "Sicily", 15, 37, 200, "km", "WITHCOORD", b"STORE", "out"]
args5 = ["MEMORY USAGE", "foo"]
args6 = [
"MIGRATE",
"192.168.1.34",
6379,
"",
0,
5000,
b"KEYS",
"key1",
"key2",
"key3",
]
args7 = ["MIGRATE", "192.168.1.34", 6379, "key1", 0, 5000]
assert_resp_response(
r,
sorted(commands_parser.get_keys(r, *args1)),
["key1", "key2"],
[b"key1", b"key2"],
)
assert_resp_response(
r,
sorted(commands_parser.get_keys(r, *args2)),
["mystream", "writers"],
[b"mystream", b"writers"],
)
assert_resp_response(
r,
sorted(commands_parser.get_keys(r, *args3)),
["out", "zset1", "zset2"],
[b"out", b"zset1", b"zset2"],
)
assert_resp_response(
r,
sorted(commands_parser.get_keys(r, *args4)),
["Sicily", "out"],
[b"Sicily", b"out"],
)
assert sorted(commands_parser.get_keys(r, *args5)) in [["foo"], [b"foo"]]
assert_resp_response(
r,
sorted(commands_parser.get_keys(r, *args6)),
["key1", "key2", "key3"],
[b"key1", b"key2", b"key3"],
)
assert_resp_response(
r, sorted(commands_parser.get_keys(r, *args7)), ["key1"], [b"key1"]
)
# A bug in redis<7.0 causes this to fail: https://github.com/redis/redis/issues/9493
@skip_if_server_version_lt("7.0.0")
def test_get_eval_keys_with_0_keys(self, r):
commands_parser = CommandsParser(r)
args = ["EVAL", "return {ARGV[1],ARGV[2]}", 0, "key1", "key2"]
assert commands_parser.get_keys(r, *args) == []
def test_get_pubsub_keys(self, r):
commands_parser = CommandsParser(r)
args1 = ["PUBLISH", "foo", "bar"]
args2 = ["PUBSUB NUMSUB", "foo1", "foo2", "foo3"]
args3 = ["PUBSUB channels", "*"]
args4 = ["SUBSCRIBE", "foo1", "foo2", "foo3"]
assert commands_parser.get_keys(r, *args1) == ["foo"]
assert commands_parser.get_keys(r, *args2) == ["foo1", "foo2", "foo3"]
assert commands_parser.get_keys(r, *args3) == ["*"]
assert commands_parser.get_keys(r, *args4) == ["foo1", "foo2", "foo3"]
@skip_if_server_version_lt("8.0.0")
@pytest.mark.onlycluster
def test_get_command_policies(self, r):
commands_parser = CommandsParser(r)
expected_command_policies = {
"core": {
"keys": [
"keys",
RequestPolicy.ALL_SHARDS,
ResponsePolicy.DEFAULT_KEYLESS,
],
"acl setuser": [
"acl setuser",
RequestPolicy.ALL_NODES,
ResponsePolicy.ALL_SUCCEEDED,
],
"exists": ["exists", RequestPolicy.MULTI_SHARD, ResponsePolicy.AGG_SUM],
"config resetstat": [
"config resetstat",
RequestPolicy.ALL_NODES,
ResponsePolicy.ALL_SUCCEEDED,
],
"slowlog len": [
"slowlog len",
RequestPolicy.ALL_NODES,
ResponsePolicy.AGG_SUM,
],
"scan": ["scan", RequestPolicy.SPECIAL, ResponsePolicy.SPECIAL],
"latency history": [
"latency history",
RequestPolicy.ALL_NODES,
ResponsePolicy.SPECIAL,
],
"memory doctor": [
"memory doctor",
RequestPolicy.ALL_SHARDS,
ResponsePolicy.SPECIAL,
],
"randomkey": [
"randomkey",
RequestPolicy.ALL_SHARDS,
ResponsePolicy.SPECIAL,
],
"mget": [
"mget",
RequestPolicy.MULTI_SHARD,
ResponsePolicy.DEFAULT_KEYED,
],
"function restore": [
"function restore",
RequestPolicy.ALL_SHARDS,
ResponsePolicy.ALL_SUCCEEDED,
],
},
"json": {
"debug": [
"debug",
RequestPolicy.DEFAULT_KEYED,
ResponsePolicy.DEFAULT_KEYED,
],
"get": [
"get",
RequestPolicy.DEFAULT_KEYED,
ResponsePolicy.DEFAULT_KEYED,
],
},
"ft": {
"search": [
"search",
RequestPolicy.DEFAULT_KEYLESS,
ResponsePolicy.DEFAULT_KEYLESS,
],
"create": [
"create",
RequestPolicy.DEFAULT_KEYLESS,
ResponsePolicy.DEFAULT_KEYLESS,
],
},
"bf": {
"add": [
"add",
RequestPolicy.DEFAULT_KEYED,
ResponsePolicy.DEFAULT_KEYED,
],
"madd": [
"madd",
RequestPolicy.DEFAULT_KEYED,
ResponsePolicy.DEFAULT_KEYED,
],
},
"cf": {
"add": [
"add",
RequestPolicy.DEFAULT_KEYED,
ResponsePolicy.DEFAULT_KEYED,
],
"mexists": [
"mexists",
RequestPolicy.DEFAULT_KEYED,
ResponsePolicy.DEFAULT_KEYED,
],
},
"tdigest": {
"add": [
"add",
RequestPolicy.DEFAULT_KEYED,
ResponsePolicy.DEFAULT_KEYED,
],
"min": [
"min",
RequestPolicy.DEFAULT_KEYED,
ResponsePolicy.DEFAULT_KEYED,
],
},
"ts": {
"create": [
"create",
RequestPolicy.DEFAULT_KEYED,
ResponsePolicy.DEFAULT_KEYED,
],
"info": [
"info",
RequestPolicy.DEFAULT_KEYED,
ResponsePolicy.DEFAULT_KEYED,
],
},
"topk": {
"list": [
"list",
RequestPolicy.DEFAULT_KEYED,
ResponsePolicy.DEFAULT_KEYED,
],
"query": [
"query",
RequestPolicy.DEFAULT_KEYED,
ResponsePolicy.DEFAULT_KEYED,
],
},
}
actual_policies = commands_parser.get_command_policies()
assert len(actual_policies) > 0
for module_name, commands in expected_command_policies.items():
for command, command_policies in commands.items():
assert command in actual_policies[module_name]
assert command_policies == [
command,
actual_policies[module_name][command].request_policy,
actual_policies[module_name][command].response_policy,
]
| TestCommandsParser |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events_stats_span_indexed.py | {
"start": 498,
"end": 98270
} | class ____(OrganizationEventsEndpointTestBase):
endpoint = "sentry-api-0-organization-events-stats"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
self.two_days_ago = self.day_ago - timedelta(days=1)
self.url = reverse(
self.endpoint,
kwargs={"organization_id_or_slug": self.project.organization.slug},
)
def _do_request(self, data, url=None, features=None):
if features is None:
features = {"organizations:discover-basic": True}
features.update(self.features)
with self.feature(features):
return self.client.get(self.url if url is None else url, data=data, format="json")
def test_count(self) -> None:
event_counts = [6, 0, 6, 3, 0, 3]
spans = []
for hour, count in enumerate(event_counts):
spans.extend(
[
self.create_span(
{"description": "foo", "sentry_tags": {"status": "success"}},
start_ts=self.day_ago + timedelta(hours=hour, minutes=minute),
)
for minute in range(count)
],
)
self.store_spans(spans, is_eap=True)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
"transformAliasToInputFormat": 1,
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 6
assert response.data["meta"]["dataset"] == "spans"
assert response.data["meta"]["fields"]["count()"] == "integer"
rows = data[0:6]
for test in zip(event_counts, rows):
assert test[1][1][0]["count"] == test[0]
def test_handle_nans_from_snuba(self) -> None:
self.store_spans(
[self.create_span({"description": "foo"}, start_ts=self.day_ago)],
is_eap=True,
)
response = self._do_request(
data={
"yAxis": "avg(measurements.lcp)",
"project": self.project.id,
"dataset": "spans",
"transformAliasToInputFormat": 1,
},
)
assert response.status_code == 200, response.content
def test_handle_nans_from_snuba_top_n(self) -> None:
self.store_spans(
[
self.create_span(
{
"description": "foo",
"measurements": {"lcp": {"value": 1}},
},
start_ts=self.day_ago,
),
self.create_span({"description": "foo"}, start_ts=self.day_ago),
self.create_span({"description": "foo"}, start_ts=self.two_days_ago),
self.create_span(
{
"description": "bar",
"measurements": {"lcp": {"value": 2}},
},
start_ts=self.day_ago,
),
self.create_span({"description": "bar"}, start_ts=self.day_ago),
self.create_span({"description": "bar"}, start_ts=self.two_days_ago),
],
is_eap=True,
)
response = self._do_request(
data={
"field": ["span.description", "p50(measurements.lcp)", "avg(measurements.lcp)"],
"yAxis": ["p50(measurements.lcp)", "avg(measurements.lcp)"],
"project": self.project.id,
"dataset": "spans",
"excludeOther": 0,
"topEvents": 1,
"partial": 1,
"per_page": 50,
"interval": "1d",
"statsPeriod": "7d",
"orderby": "-avg_measurements_lcp",
"sort": "-avg_measurements_lcp",
"transformAliasToInputFormat": 1,
},
)
assert response.status_code == 200, response.content
# We cannot actually assert the value because the `spans_indexed` is
# producing the wrong result and treating missing values as 0s which
# skews the final aggregation.
# This is also the reason it never errored because snuba never returns
# nans in this situation.
#
# for k in response.data:
# for agg in ["p50(measurements.lcp)", "avg(measurements.lcp)"]:
# for row in response.data[k][agg]["data"]:
# assert row[1][0]["count"] in {0, 1, 2}
# assert response.data["Other"]
def test_count_unique(self) -> None:
event_counts = [6, 0, 6, 3, 0, 3]
spans = []
for hour, count in enumerate(event_counts):
spans.extend(
[
self.create_span(
{
"description": "foo",
"sentry_tags": {"status": "success"},
"tags": {"foo": f"foo-{minute}"},
},
start_ts=self.day_ago + timedelta(hours=hour, minutes=minute),
)
for minute in range(count)
],
)
self.store_spans(spans, is_eap=True)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": "count_unique(foo)",
"project": self.project.id,
"dataset": "spans",
"transformAliasToInputFormat": 1,
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 6
assert response.data["meta"]["dataset"] == "spans"
assert response.data["meta"]["fields"]["count_unique(foo)"] == "integer"
rows = data[0:6]
for test in zip(event_counts, rows):
assert test[1][1][0]["count"] == test[0]
def test_p95(self) -> None:
event_durations = [6, 0, 6, 3, 0, 3]
self.store_spans(
[
self.create_span(
{"description": "foo", "sentry_tags": {"status": "success"}},
duration=duration,
start_ts=self.day_ago + timedelta(hours=hour, minutes=1),
)
for hour, duration in enumerate(event_durations)
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": "p95()",
"project": self.project.id,
"dataset": "spans",
"transformAliasToInputFormat": 1,
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 6
assert response.data["meta"]["dataset"] == "spans"
rows = data[0:6]
for test in zip(event_durations, rows):
assert test[1][1][0]["count"] == test[0]
def test_multiaxis(self) -> None:
event_counts = [6, 0, 6, 3, 0, 3]
spans = []
for hour, count in enumerate(event_counts):
spans.extend(
[
self.create_span(
{
"description": "foo",
"sentry_tags": {"status": "success"},
},
duration=count,
start_ts=self.day_ago + timedelta(hours=hour, minutes=minute),
)
for minute in range(count)
],
)
self.store_spans(spans, is_eap=True)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": ["count()", "p95()"],
"project": self.project.id,
"dataset": "spans",
"transformAliasToInputFormat": 1,
},
)
assert response.status_code == 200, response.content
count_data = response.data["count()"]["data"]
p95_data = response.data["p95()"]["data"]
assert len(count_data) == len(p95_data) == 6
count_rows = count_data[0:6]
for test in zip(event_counts, count_rows):
assert test[1][1][0]["count"] == test[0]
p95_rows = p95_data[0:6]
for test in zip(event_counts, p95_rows):
assert test[1][1][0]["count"] == test[0]
assert response.data["count()"]["meta"]["fields"]["count()"] == "integer"
assert response.data["p95()"]["meta"]["fields"]["p95()"] == "duration"
# These throughput tests should roughly match the ones in OrganizationEventsStatsEndpointTest
@pytest.mark.querybuilder
def test_throughput_epm_hour_rollup(self) -> None:
# Each of these denotes how many events to create in each hour
event_counts = [6, 0, 6, 3, 0, 3]
spans = []
for hour, count in enumerate(event_counts):
spans.extend(
[
self.create_span(
{"description": "foo", "sentry_tags": {"status": "success"}},
start_ts=self.day_ago + timedelta(hours=hour, minutes=minute),
)
for minute in range(count)
]
)
self.store_spans(spans, is_eap=True)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": "epm()",
"project": self.project.id,
"dataset": "spans",
"transformAliasToInputFormat": 1,
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 6
assert response.data["meta"]["dataset"] == "spans"
rows = data[:6]
for test in zip(event_counts, rows):
self.assertAlmostEqual(test[1][1][0]["count"], test[0] / (3600.0 / 60.0))
def test_throughput_epm_day_rollup(self) -> None:
# Each of these denotes how many events to create in each minute
event_counts = [6, 0, 6, 3, 0, 3]
spans = []
for hour, count in enumerate(event_counts):
spans.extend(
[
self.create_span(
{"description": "foo", "sentry_tags": {"status": "success"}},
start_ts=self.two_days_ago + timedelta(hours=hour, minutes=minute),
)
for minute in range(count)
]
)
self.store_spans(spans, is_eap=True)
response = self._do_request(
data={
"start": self.two_days_ago,
"end": self.day_ago,
"interval": "24h",
"yAxis": "epm()",
"project": self.project.id,
"dataset": "spans",
"transformAliasToInputFormat": 1,
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert response.data["meta"]["dataset"] == "spans"
self.assertAlmostEqual(data[0][1][0]["count"], sum(event_counts) / (86400.0 / 60.0))
def test_throughput_epm_hour_rollup_offset_of_hour(self) -> None:
# Each of these denotes how many events to create in each hour
event_counts = [6, 0, 6, 3, 0, 3]
spans = []
for hour, count in enumerate(event_counts):
spans.extend(
[
self.create_span(
{"description": "foo", "sentry_tags": {"status": "success"}},
start_ts=self.day_ago + timedelta(hours=hour, minutes=minute + 30),
)
for minute in range(count)
],
)
self.store_spans(spans, is_eap=True)
response = self._do_request(
data={
"start": self.day_ago + timedelta(minutes=30),
"end": self.day_ago + timedelta(hours=6, minutes=30),
"interval": "1h",
"yAxis": "epm()",
"project": self.project.id,
"dataset": "spans",
"transformAliasToInputFormat": 1,
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
meta = response.data["meta"]
assert len(data) == 7
assert meta["dataset"] == "spans"
rows = data[0:6]
for test in zip(event_counts, rows):
self.assertAlmostEqual(test[1][1][0]["count"], test[0] / (3600.0 / 60.0))
assert meta["units"] == {"epm()": "1/minute"}
assert meta["fields"] == {"epm()": "rate"}
@pytest.mark.xfail(reason="epm not implemented yet")
def test_throughput_eps_minute_rollup(self) -> None:
# Each of these denotes how many events to create in each minute
event_counts = [6, 0, 6, 3, 0, 3]
spans = []
for minute, count in enumerate(event_counts):
spans.extend(
[
self.create_span(
{"description": "foo", "sentry_tags": {"status": "success"}},
start_ts=self.day_ago + timedelta(minutes=minute, seconds=second),
)
for second in range(count)
],
)
self.store_spans(spans, is_eap=True)
for axis in ["eps()", "sps()"]:
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=6),
"interval": "1m",
"yAxis": axis,
"project": self.project.id,
"dataset": "spans",
"transformAliasToInputFormat": 1,
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 6
assert response.data["meta"]["dataset"] == "spans"
rows = data[0:6]
for test in zip(event_counts, rows):
assert test[1][1][0]["count"] == test[0] / 60.0
def test_top_events(self) -> None:
self.store_spans(
[
self.create_span(
{"sentry_tags": {"transaction": "foo", "status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
duration=2000,
),
self.create_span(
{"sentry_tags": {"transaction": "bar", "status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
duration=2000,
),
self.create_span(
{"sentry_tags": {"transaction": "baz", "status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"sentry_tags": {"transaction": "qux", "status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=6),
"interval": "1m",
"yAxis": "count()",
"field": ["transaction", "sum(span.self_time)"],
"orderby": ["-sum_span_self_time"],
"project": self.project.id,
"dataset": "spans",
"excludeOther": 0,
"topEvents": 2,
},
)
assert response.status_code == 200, response.content
assert "Other" in response.data
assert "foo" in response.data
assert "bar" in response.data
assert len(response.data["Other"]["data"]) == 6
for key in ["foo", "bar"]:
rows = response.data[key]["data"][0:6]
for expected, result in zip([0, 1, 0, 0, 0, 0], rows):
assert result[1][0]["count"] == expected, key
rows = response.data["Other"]["data"][0:6]
for expected, result in zip([0, 2, 0, 0, 0, 0], rows):
assert result[1][0]["count"] == expected, "Other"
assert response.data["Other"]["meta"]["dataset"] == "spans"
def test_top_events_empty_other(self) -> None:
self.store_spans(
[
self.create_span(
{"sentry_tags": {"transaction": transaction, "status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
duration=2000,
)
for transaction in ["foo", "bar"]
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=6),
"interval": "1m",
"yAxis": "count()",
"field": ["transaction", "sum(span.self_time)"],
"orderby": ["-sum_span_self_time"],
"project": self.project.id,
"dataset": "spans",
"excludeOther": 0,
"topEvents": 2,
},
)
assert response.status_code == 200, response.content
assert "Other" not in response.data
assert "foo" in response.data
assert "bar" in response.data
for key in ["foo", "bar"]:
rows = response.data[key]["data"][0:6]
for expected, result in zip([0, 1, 0, 0, 0, 0], rows):
assert result[1][0]["count"] == expected, key
assert response.data["foo"]["meta"]["dataset"] == "spans"
def test_top_events_exclude_other(self) -> None:
self.store_spans(
[
self.create_span(
{"sentry_tags": {"transaction": transaction, "status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
duration=2000 if transaction in ["foo", "bar"] else 100,
)
for transaction in ["foo", "bar", "qux"]
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=6),
"interval": "1m",
"yAxis": "count()",
"field": ["transaction", "sum(span.self_time)"],
"orderby": ["-sum_span_self_time"],
"project": self.project.id,
"dataset": "spans",
"excludeOther": 1,
"topEvents": 2,
},
)
assert response.status_code == 200, response.content
assert "Other" not in response.data
assert "foo" in response.data
assert "bar" in response.data
for key in ["foo", "bar"]:
rows = response.data[key]["data"][0:6]
for expected, result in zip([0, 1, 0, 0, 0, 0], rows):
assert result[1][0]["count"] == expected, key
assert response.data[key]["meta"]["dataset"] == "spans"
def test_top_events_multi_y_axis(self) -> None:
self.store_spans(
[
self.create_span(
{"sentry_tags": {"transaction": transaction, "status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
duration=2000,
)
for transaction in ["foo", "bar", "baz"]
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=6),
"interval": "1m",
"yAxis": ["count()", "p50(span.duration)"],
"field": ["transaction", "count()", "p50(span.duration)"],
"orderby": ["transaction"],
"project": self.project.id,
"dataset": "spans",
"excludeOther": 0,
"topEvents": 2,
},
)
assert response.status_code == 200, response.content
for key in ["Other", "bar", "baz"]:
assert key in response.data
for y_axis in ["count()", "p50(span.duration)"]:
assert y_axis in response.data[key]
assert response.data[key][y_axis]["meta"]["dataset"] == "spans"
counts = response.data[key]["count()"]["data"][0:6]
for expected, result in zip([0, 1, 0, 0, 0, 0], counts):
assert result[1][0]["count"] == expected, key
p50s = response.data[key]["p50(span.duration)"]["data"][0:6]
for expected, result in zip([0, 2000, 0, 0, 0, 0], p50s):
assert result[1][0]["count"] == expected, key
def test_top_events_with_project(self) -> None:
projects = [self.create_project(), self.create_project()]
self.store_spans(
[
self.create_span(
{"sentry_tags": {"status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
project=project,
duration=2000,
)
for project in projects
],
is_eap=True,
)
self.store_spans(
[
self.create_span(
{"segment_name": "baz", "sentry_tags": {"status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=6),
"interval": "1m",
"yAxis": "count()",
"field": ["project", "sum(span.self_time)"],
"orderby": ["-sum_span_self_time"],
"dataset": "spans",
"excludeOther": 0,
"topEvents": 2,
},
)
assert response.status_code == 200, response.content
assert "Other" in response.data
assert projects[0].slug in response.data
assert projects[1].slug in response.data
assert len(response.data["Other"]["data"]) == 6
for key in ["Other", projects[0].slug, projects[1].slug]:
rows = response.data[key]["data"][0:6]
for expected, result in zip([0, 1, 0, 0, 0, 0], rows):
assert result[1][0]["count"] == expected, key
assert response.data["Other"]["meta"]["dataset"] == "spans"
def test_top_events_with_project_and_project_id(self) -> None:
projects = [self.create_project(), self.create_project()]
self.store_spans(
[
self.create_span(
{"sentry_tags": {"status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
project=project,
duration=2000,
)
for project in projects
],
is_eap=True,
)
self.store_spans(
[
self.create_span(
{"segment_name": "baz", "sentry_tags": {"status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=6),
"interval": "1m",
"yAxis": "count()",
"field": ["project", "project.id", "sum(span.self_time)"],
"orderby": ["-sum_span_self_time"],
"dataset": "spans",
"excludeOther": 0,
"topEvents": 2,
},
)
assert response.status_code == 200, response.content
assert "Other" in response.data
key1 = f"{projects[0].slug},{projects[0].id}"
key2 = f"{projects[1].slug},{projects[1].id}"
assert key1 in response.data
assert key2 in response.data
assert len(response.data["Other"]["data"]) == 6
for key in ["Other", key1, key2]:
rows = response.data[key]["data"][0:6]
for expected, result in zip([0, 1, 0, 0, 0, 0], rows):
assert result[1][0]["count"] == expected, key
assert response.data["Other"]["meta"]["dataset"] == "spans"
def test_top_events_with_no_data(self) -> None:
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=6),
"interval": "1m",
"yAxis": "count()",
"field": ["project", "project.id", "sum(span.self_time)"],
"orderby": ["-sum_span_self_time"],
"dataset": "spans",
"excludeOther": 0,
"topEvents": 2,
},
)
assert response.status_code == 200, response.content
def test_count_unique_nans(self) -> None:
self.store_span(
self.create_span(start_ts=self.two_days_ago + timedelta(minutes=1)),
is_eap=True,
)
response = self._do_request(
data={
"field": ["count_unique(foo)"],
"yAxis": ["count_unique(foo)"],
"project": self.project.id,
"dataset": "spans",
"excludeOther": 1,
"partial": 1,
"per_page": 50,
"interval": "1d",
"statsPeriod": "7d",
"transformAliasToInputFormat": 1,
},
)
assert response.status_code == 200, response.content
def test_count_extrapolation(self) -> None:
event_counts = [6, 0, 6, 3, 0, 3]
spans = []
for hour, count in enumerate(event_counts):
spans.extend(
[
self.create_span(
{
"description": "foo",
"sentry_tags": {"status": "success"},
"measurements": {"client_sample_rate": {"value": 0.1}},
},
start_ts=self.day_ago + timedelta(hours=hour, minutes=minute),
)
for minute in range(count)
],
)
self.store_spans(spans, is_eap=True)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 6
assert response.data["meta"]["dataset"] == "spans"
rows = data[0:6]
for test in zip(event_counts, rows):
assert test[1][1][0]["count"] == test[0] * 10
def test_extrapolation_count(self) -> None:
event_counts = [6, 0, 6, 3, 0, 3]
spans = []
for hour, count in enumerate(event_counts):
spans.extend(
[
self.create_span(
{
"description": "foo",
"sentry_tags": {"status": "success"},
"measurements": {"client_sample_rate": {"value": 0.1}},
},
start_ts=self.day_ago + timedelta(hours=hour, minutes=minute),
)
for minute in range(count)
],
)
self.store_spans(spans, is_eap=True)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
meta = response.data["meta"]
assert len(data) == 6
assert response.data["meta"]["dataset"] == "spans"
for expected, actual in zip(event_counts, data[0:6]):
assert actual[1][0]["count"] == expected * 10
accuracy = meta["accuracy"]
confidence = accuracy["confidence"]
sample_count = accuracy["sampleCount"]
sample_rate = accuracy["samplingRate"]
for expected, actual in zip(event_counts, confidence[0:6]):
if expected != 0:
assert actual["value"] == "low"
else:
assert actual["value"] is None
# Check old confidence format, TODO: remove this once frontend is updated
old_confidence = response.data["confidence"]
for expected, actual in zip(event_counts, old_confidence[0:6]):
if expected != 0:
assert actual[1][0]["count()"] == "low"
else:
assert actual[1][0]["count()"] is None
for expected, actual in zip(event_counts, sample_count[0:6]):
assert actual["value"] == expected
for expected, actual in zip(event_counts, sample_rate[0:6]):
if expected != 0:
assert actual["value"] == pytest.approx(0.1)
else:
assert actual["value"] is None
def test_confidence_is_set(self) -> None:
event_counts = [6, 0, 6, 3, 0, 3]
spans = []
for hour, count in enumerate(event_counts):
spans.extend(
[
self.create_span(
{
"description": "foo",
"sentry_tags": {"status": "success"},
"measurements": {"client_sample_rate": {"value": 0.1}},
},
start_ts=self.day_ago + timedelta(hours=hour, minutes=minute),
)
for minute in range(count)
],
)
self.store_spans(spans, is_eap=True)
y_axes = [
"count()",
"count(span.duration)",
"sum(span.duration)",
"avg(span.duration)",
"p50(span.duration)",
"p75(span.duration)",
"p90(span.duration)",
"p95(span.duration)",
"p99(span.duration)",
# "p100(span.duration)",
# "min(span.duration)",
# "max(span.duration)",
]
for y_axis in y_axes:
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": y_axis,
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, (y_axis, response.content)
data = response.data["data"]
meta = response.data["meta"]
assert len(data) == len(event_counts), y_axis
for count, row in zip(event_counts, data):
if count == 0:
assert row[1][0]["count"] == 0, y_axis
else:
assert isinstance(row[1][0]["count"], (float, int)), y_axis
accuracy = meta["accuracy"]
confidence = accuracy["confidence"]
sample_count = accuracy["sampleCount"]
sample_rate = accuracy["samplingRate"]
for expected, actual in zip(event_counts, confidence[0:6]):
if expected != 0:
assert actual["value"] in ("high", "low")
else:
assert actual["value"] is None
old_confidence = response.data["confidence"]
for expected, actual in zip(event_counts, old_confidence[0:6]):
if expected != 0:
assert actual[1][0][y_axis] in ("high", "low")
else:
assert actual[1][0][y_axis] is None
for expected, actual in zip(event_counts, sample_count[0:6]):
assert actual["value"] == expected
for expected, actual in zip(event_counts, sample_rate[0:6]):
if expected != 0:
assert actual["value"] == pytest.approx(0.1)
else:
assert actual["value"] is None
def test_extrapolation_with_multiaxis(self) -> None:
event_counts = [6, 0, 6, 3, 0, 3]
p95_counts = [0, 0, 6, 3, 0, 0]
spans = []
for hour, count in enumerate(event_counts):
measurements = {"client_sample_rate": {"value": 0.1}}
if hour in [2, 3]:
measurements["lcp"] = {"value": count}
spans.extend(
[
self.create_span(
{
"description": "foo",
"sentry_tags": {"status": "success"},
"measurements": measurements,
},
duration=count,
start_ts=self.day_ago + timedelta(hours=hour, minutes=minute),
)
for minute in range(count)
],
)
self.store_spans(spans, is_eap=True)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": ["count()", "p95(measurements.lcp)"],
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
count_data = response.data["count()"]["data"]
p95_data = response.data["p95(measurements.lcp)"]["data"]
assert len(count_data) == len(p95_data) == 6
count_rows = count_data[0:6]
for test in zip(event_counts, count_rows):
assert test[1][1][0]["count"] == test[0] * 10
for column in ["count()", "p95(measurements.lcp)"]:
if column == "p95(measurements.lcp)":
counts = p95_counts
else:
counts = event_counts
accuracy = response.data[column]["meta"]["accuracy"]
confidence = accuracy["confidence"]
sample_count = accuracy["sampleCount"]
sample_rate = accuracy["samplingRate"]
for expected, actual in zip(counts, confidence[0:6]):
if expected != 0:
assert actual["value"] in ("high", "low")
else:
assert actual["value"] is None
old_confidence = response.data[column]["confidence"]
for expected, actual in zip(counts, old_confidence[0:6]):
if expected != 0:
assert actual[1][0]["count"] in ("high", "low")
else:
assert actual[1][0]["count"] is None
for expected, actual in zip(counts, sample_count[0:6]):
assert actual["value"] == expected
for expected, actual in zip(counts, sample_rate[0:6]):
if expected != 0:
assert actual["value"] == pytest.approx(0.1)
else:
assert actual["value"] is None
p95_rows = p95_data[0:6]
for test in zip(p95_counts, p95_rows):
assert test[1][1][0]["count"] == test[0]
def test_top_events_with_extrapolation(self) -> None:
self.store_spans(
[
self.create_span(
{
"sentry_tags": {"transaction": "foo", "status": "success"},
"measurements": {"client_sample_rate": {"value": 0.1}},
},
start_ts=self.day_ago + timedelta(minutes=1),
duration=2000,
),
self.create_span(
{
"sentry_tags": {"transaction": "bar", "status": "success"},
"measurements": {"client_sample_rate": {"value": 0.1}},
},
start_ts=self.day_ago + timedelta(minutes=1),
duration=2000,
),
self.create_span(
{
"segment_name": "baz",
"sentry_tags": {"status": "success"},
"measurements": {"client_sample_rate": {"value": 0.1}},
},
start_ts=self.day_ago + timedelta(minutes=1),
),
],
is_eap=True,
)
event_counts = [0, 1, 0, 0, 0, 0]
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=6),
"interval": "1m",
"yAxis": "count()",
"field": ["transaction", "sum(span.self_time)"],
"orderby": ["-sum_span_self_time"],
"project": self.project.id,
"dataset": "spans",
"excludeOther": 0,
"topEvents": 2,
},
)
assert response.status_code == 200, response.content
assert "Other" in response.data
assert "foo" in response.data
assert "bar" in response.data
assert len(response.data["Other"]["data"]) == 6
for key in ["Other", "foo", "bar"]:
rows = response.data[key]["data"][0:6]
for expected, result in zip(event_counts, rows):
assert result[1][0]["count"] == expected * 10, key
meta = response.data[key]["meta"]
accuracy = meta["accuracy"]
confidence = accuracy["confidence"]
sample_count = accuracy["sampleCount"]
sample_rate = accuracy["samplingRate"]
for expected, actual in zip(event_counts, confidence[0:6]):
if expected != 0:
assert actual["value"] == "low"
else:
assert actual["value"] is None
for expected, actual in zip(event_counts, sample_count[0:6]):
assert actual["value"] == expected
for expected, actual in zip(event_counts, sample_rate[0:6]):
if expected != 0:
assert actual["value"] == pytest.approx(0.1)
else:
assert actual["value"] is None
assert response.data["Other"]["meta"]["dataset"] == "spans"
def test_comparison_delta(self) -> None:
event_counts = [6, 0, 6, 4, 0, 4]
spans = []
for current_period in [True, False]:
for hour, count in enumerate(event_counts):
count = count if current_period else int(count / 2)
spans.extend(
[
self.create_span(
{"description": "foo", "sentry_tags": {"status": "success"}},
start_ts=(
self.day_ago + timedelta(hours=hour, minutes=minute)
if current_period
else self.two_days_ago + timedelta(hours=hour, minutes=minute)
),
)
for minute in range(count)
],
)
self.store_spans(spans, is_eap=True)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(days=1),
"interval": "1h",
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
"comparisonDelta": 24 * 60 * 60,
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 24
assert response.data["meta"]["dataset"] == "spans"
rows = data[0:6]
for expected, actual in zip(event_counts, rows):
assert actual[1][0]["count"] == expected
assert actual[1][0]["comparisonCount"] == expected / 2
def test_comparison_delta_with_empty_comparison_values(self) -> None:
event_counts = [6, 0, 6, 4, 0, 4]
spans = []
for hour, count in enumerate(event_counts):
spans.extend(
[
self.create_span(
{"description": "foo", "sentry_tags": {"status": "success"}},
start_ts=self.day_ago + timedelta(hours=hour, minutes=minute),
)
for minute in range(count)
],
)
self.store_spans(spans, is_eap=True)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(days=1),
"interval": "1h",
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
"comparisonDelta": 24 * 60 * 60,
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 24
assert response.data["meta"]["dataset"] == "spans"
rows = data[0:6]
for test in zip(event_counts, rows):
assert test[1][1][0]["count"] == test[0]
assert test[1][1][0]["comparisonCount"] == 0
def test_invalid_intervals(self) -> None:
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=6),
"interval": "1m",
"yAxis": "count()",
"field": ["transaction", "sum(span.self_time)"],
"orderby": ["-sum_span_self_time"],
"project": self.project.id,
"dataset": "spans",
"excludeOther": 0,
"topEvents": 2,
},
)
assert response.status_code == 200, response.content
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=6),
"interval": "20s",
"yAxis": "count()",
"field": ["transaction", "sum(span.self_time)"],
"orderby": ["-sum_span_self_time"],
"project": self.project.id,
"dataset": "spans",
"excludeOther": 0,
"topEvents": 2,
},
)
assert response.status_code == 400, response.content
def test_project_filters(self) -> None:
event_counts = [6, 0, 6, 3, 0, 3]
spans = []
for hour, count in enumerate(event_counts):
spans.extend(
[
self.create_span(
{"description": "foo", "sentry_tags": {"status": "success"}},
start_ts=self.day_ago + timedelta(hours=hour, minutes=minute),
)
for minute in range(count)
],
)
self.store_spans(spans, is_eap=True)
for querystring in [f"project:{self.project.slug}", f"project:[{self.project.slug}]"]:
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": "count()",
"query": querystring,
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 6
assert response.data["meta"]["dataset"] == "spans"
rows = data[0:6]
for test in zip(event_counts, rows):
assert test[1][1][0]["count"] == test[0]
def test_nonexistent_project_filter(self) -> None:
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": "count()",
"query": "project:foobar",
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 400, response.content
assert "Unknown value foobar" in response.data["detail"]
def test_device_class_filter(self) -> None:
event_counts = [6, 0, 6, 3, 0, 3]
spans = []
for hour, count in enumerate(event_counts):
spans.extend(
[
self.create_span(
{
"description": "foo",
"sentry_tags": {"status": "success", "device.class": "1"},
},
start_ts=self.day_ago + timedelta(hours=hour, minutes=minute),
)
for minute in range(count)
],
)
self.store_spans(spans, is_eap=True)
for querystring in ["device.class:low", "device.class:[low,medium]"]:
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": "count()",
"query": querystring,
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 6
assert response.data["meta"]["dataset"] == "spans"
rows = data[0:6]
for test in zip(event_counts, rows):
assert test[1][1][0]["count"] == test[0]
def test_device_class_filter_empty(self):
event_counts = [
("low", 1),
("", 2),
("low", 3),
("", 4),
("low", 5),
("", 6),
]
spans = []
for hour, [device_class, count] in enumerate(event_counts):
spans.extend(
[
self.create_span(
{
"description": "foo",
"sentry_tags": {
"status": "success",
**(
{"device.class": list(DEVICE_CLASS["low"])[0]}
if device_class == "low"
else {}
),
},
},
start_ts=self.day_ago + timedelta(hours=hour, minutes=minute),
)
for minute in range(count)
],
)
self.store_spans(spans, is_eap=True)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": "count()",
"query": 'device.class:""',
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
for (device_class, count), row in zip(event_counts, response.data["data"]):
test_count = count if device_class == "" else 0
assert row[1][0]["count"] == test_count
def test_device_class_top_events(self) -> None:
event_counts = [
("low", 6),
("medium", 0),
("low", 6),
("medium", 6),
("low", 0),
("medium", 3),
]
spans = []
for hour, count in enumerate(event_counts):
spans.extend(
[
self.create_span(
{
"description": "foo",
"sentry_tags": {
"status": "success",
"device.class": (
list(DEVICE_CLASS["low"])[0]
if count[0] == "low"
else list(DEVICE_CLASS["medium"])[0]
),
},
},
start_ts=self.day_ago + timedelta(hours=hour, minutes=minute),
)
for minute in range(count[1])
],
)
self.store_spans(spans, is_eap=True)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": "count()",
"field": ["device.class", "count()"],
"topEvents": 5,
"query": "",
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
low = response.data["low"]["data"]
assert len(low) == 6
rows = low[0:6]
for i, test in enumerate(zip(event_counts, rows)):
test_data, row = test
test_count = test_data[1] if test_data[0] == "low" else 0.0
assert row[1][0]["count"] == test_count
medium = response.data["medium"]["data"]
assert len(medium) == 6
rows = medium[0:6]
for i, test in enumerate(zip(event_counts, rows)):
test_data, row = test
test_count = test_data[1] if test_data[0] == "medium" else 0.0
assert row[1][0]["count"] == test_count
def test_top_events_filters_out_groupby_even_when_its_just_one_row(self) -> None:
self.store_spans(
[
self.create_span(
{"sentry_tags": {"transaction": "foo", "status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
duration=2000,
),
self.create_span(
{"sentry_tags": {"transaction": "foo", "status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
duration=2000,
),
self.create_span(
{"sentry_tags": {"transaction": "foo", "status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"sentry_tags": {"transaction": "foo", "status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=6),
"interval": "1m",
"yAxis": "count(span.self_time)",
"field": ["transaction", "count(span.self_time)"],
"query": "count(span.self_time):>4",
"orderby": ["-count_span_self_time"],
"project": self.project.id,
"dataset": "spans",
"excludeOther": 0,
"topEvents": 5,
},
)
assert response.status_code == 200, response.content
assert len(response.data) == 0
def test_cache_miss_rate(self) -> None:
self.store_spans(
[
self.create_span(
{
"data": {"cache.hit": False},
},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{
"data": {"cache.hit": True},
},
start_ts=self.day_ago + timedelta(minutes=2),
),
self.create_span(
{
"data": {"cache.hit": False},
},
start_ts=self.day_ago + timedelta(minutes=2),
),
self.create_span(
{
"data": {"cache.hit": True},
},
start_ts=self.day_ago + timedelta(minutes=2),
),
self.create_span(
{
"data": {"cache.hit": True},
},
start_ts=self.day_ago + timedelta(minutes=2),
),
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"yAxis": "cache_miss_rate()",
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 3
assert data[0][1][0]["count"] == 0.0
assert data[1][1][0]["count"] == 1.0
assert data[2][1][0]["count"] == 0.25
assert response.data["meta"]["dataset"] == "spans"
def test_trace_status_rate(self) -> None:
self.store_spans(
[
self.create_span(
{"sentry_tags": {"trace.status": "ok"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"sentry_tags": {"trace.status": "unauthenticated"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"sentry_tags": {"trace.status": "ok"}},
start_ts=self.day_ago + timedelta(minutes=2),
),
self.create_span(
{"sentry_tags": {"trace.status": "ok"}},
start_ts=self.day_ago + timedelta(minutes=2),
),
self.create_span(
{"sentry_tags": {"trace.status": "unknown"}},
start_ts=self.day_ago + timedelta(minutes=2),
),
self.create_span(
{"sentry_tags": {"trace.status": "ok"}},
start_ts=self.day_ago + timedelta(minutes=2),
),
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"yAxis": "trace_status_rate(ok)",
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 3
assert data[0][1][0]["count"] == 0.0
assert data[1][1][0]["count"] == 0.5
assert data[2][1][0]["count"] == 0.75
assert response.data["meta"]["dataset"] == "spans"
def test_count_op(self) -> None:
self.store_spans(
[
self.create_span(
{"op": "queue.process", "sentry_tags": {"op": "queue.publish"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"op": "queue.process", "sentry_tags": {"op": "queue.publish"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"op": "queue.publish", "sentry_tags": {"op": "queue.publish"}},
start_ts=self.day_ago + timedelta(minutes=2),
),
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"yAxis": "count_op(queue.publish)",
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 3
assert data[0][1][0]["count"] == 0.0
assert data[1][1][0]["count"] == 2.0
assert data[2][1][0]["count"] == 1.0
assert response.data["meta"]["dataset"] == "spans"
def test_top_events_with_escape_characters(self) -> None:
key = "test\\n*"
key2 = "test\\n\\*"
self.store_spans(
[
self.create_span(
{
"sentry_tags": {"transaction": key, "status": "success"},
"tags": {"foo": key},
},
start_ts=self.day_ago + timedelta(minutes=1),
duration=2000,
),
self.create_span(
{
"sentry_tags": {"transaction": key, "status": "success"},
"tags": {"foo": key2},
},
start_ts=self.day_ago + timedelta(minutes=1),
duration=2000,
),
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=6),
"interval": "1m",
"yAxis": "count()",
"field": ["foo", "sum(span.self_time)"],
"orderby": ["-sum_span_self_time"],
"project": self.project.id,
"dataset": "spans",
"excludeOther": 0,
"topEvents": 2,
},
)
assert response.status_code == 200, response.content
for response_key in [key, key2]:
assert response_key in response.data
assert len(response.data[response_key]["data"]) == 6, response_key
rows = response.data[response_key]["data"][0:6]
for expected, result in zip([0, 1, 0, 0, 0, 0], rows):
assert result[1][0]["count"] == expected, response_key
def test_time_spent_percentage_timeseries_fails(self) -> None:
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"yAxis": "time_spent_percentage(span.self_time)",
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 400, response.content
assert (
"The Function Time_Spent_Percentage Is Not Allowed For This Query"
in response.data["detail"].title()
)
def test_module_alias(self) -> None:
self.store_spans(
[
self.create_span(
{
"op": "http.client",
"description": "GET /app/index",
"sentry_tags": {
"description": "GET /app/index",
"category": "http",
"op": "http.client",
"transaction": "my-transaction",
},
},
start_ts=self.day_ago + timedelta(minutes=1),
),
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"query": "span.module:http",
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 3
assert data[0][1][0]["count"] == 0.0
assert data[1][1][0]["count"] == 1.0
assert data[2][1][0]["count"] == 0.0
assert response.data["meta"]["dataset"] == "spans"
def test_module_alias_multi_value(self) -> None:
self.store_spans(
[
self.create_span(
{
"op": "http.client",
"description": "GET /app/index",
"sentry_tags": {
"description": "GET /app/index",
"category": "http",
"op": "http.client",
"transaction": "my-transaction",
},
},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{
"op": "cache.get",
"description": "get user cache",
"sentry_tags": {
"description": "get user cache",
"category": "cache",
"op": "cache.get",
"transaction": "my-transaction",
},
},
start_ts=self.day_ago + timedelta(minutes=1),
),
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"query": "span.module:[http,cache]",
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 3
assert data[0][1][0]["count"] == 0.0
assert data[1][1][0]["count"] == 2.0
assert data[2][1][0]["count"] == 0.0
assert response.data["meta"]["dataset"] == "spans"
def test_http_response_rate(self) -> None:
self.store_spans(
[
self.create_span(
{"description": "description 1", "sentry_tags": {"status_code": "500"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"description": "description 1", "sentry_tags": {"status_code": "400"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"description": "description 2", "sentry_tags": {"status_code": "500"}},
start_ts=self.day_ago + timedelta(minutes=2),
),
self.create_span(
{"description": "description 2", "sentry_tags": {"status_code": "500"}},
start_ts=self.day_ago + timedelta(minutes=2),
),
self.create_span(
{"description": "description 2", "sentry_tags": {"status_code": "500"}},
start_ts=self.day_ago + timedelta(minutes=2),
),
self.create_span(
{"description": "description 2", "sentry_tags": {"status_code": "400"}},
start_ts=self.day_ago + timedelta(minutes=2),
),
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=4),
"interval": "1m",
"query": "",
"yAxis": ["http_response_rate(5)"],
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
data = response.data
assert data["data"][0][1][0]["count"] == 0.0
assert data["data"][1][1][0]["count"] == 0.5
assert data["data"][2][1][0]["count"] == 0.75
def test_http_response_rate_multiple_series(self) -> None:
self.store_spans(
[
self.create_span(
{"description": "description 1", "sentry_tags": {"status_code": "500"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"description": "description 1", "sentry_tags": {"status_code": "400"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"description": "description 2", "sentry_tags": {"status_code": "500"}},
start_ts=self.day_ago + timedelta(minutes=2),
),
self.create_span(
{"description": "description 2", "sentry_tags": {"status_code": "500"}},
start_ts=self.day_ago + timedelta(minutes=2),
),
self.create_span(
{"description": "description 2", "sentry_tags": {"status_code": "500"}},
start_ts=self.day_ago + timedelta(minutes=2),
),
self.create_span(
{"description": "description 2", "sentry_tags": {"status_code": "400"}},
start_ts=self.day_ago + timedelta(minutes=2),
),
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=4),
"interval": "1m",
"query": "",
"yAxis": ["http_response_rate(4)", "http_response_rate(5)"],
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
data = response.data
assert data["http_response_rate(4)"]["data"][0][1][0]["count"] == 0.0
assert data["http_response_rate(4)"]["data"][1][1][0]["count"] == 0.5
assert data["http_response_rate(4)"]["data"][2][1][0]["count"] == 0.25
assert data["http_response_rate(5)"]["data"][0][1][0]["count"] == 0.0
assert data["http_response_rate(5)"]["data"][1][1][0]["count"] == 0.5
assert data["http_response_rate(5)"]["data"][2][1][0]["count"] == 0.75
@pytest.mark.xfail(reason="https://github.com/getsentry/snuba/pull/7067")
def test_downsampling_single_series(self) -> None:
span = self.create_span(
{"description": "foo", "sentry_tags": {"status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
)
span["span_id"] = KNOWN_PREFLIGHT_ID
span2 = self.create_span(
{"description": "zoo", "sentry_tags": {"status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
)
span2["span_id"] = "b" * 16
self.store_spans(
[span, span2],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
"sampling": "PREFLIGHT",
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 3
assert data[0][1][0]["count"] == 0
assert data[1][1][0]["count"] == 512 # The preflight table is 1/512 of the full table
assert data[2][1][0]["count"] == 0
assert response.data["meta"]["dataset"] == "spans"
assert response.data["meta"]["dataScanned"] == "partial"
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
"sampling": "BEST_EFFORT",
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 3
assert data[0][1][0]["count"] == 0
assert data[1][1][0]["count"] == 2
assert data[2][1][0]["count"] == 0
assert response.data["meta"]["dataset"] == "spans"
assert response.data["meta"]["dataScanned"] == "full"
@pytest.mark.xfail(reason="https://github.com/getsentry/snuba/pull/7067")
def test_downsampling_top_events(self) -> None:
span = self.create_span(
{"description": "foo", "sentry_tags": {"status": "success"}},
duration=100,
start_ts=self.day_ago + timedelta(minutes=1),
)
span["span_id"] = KNOWN_PREFLIGHT_ID
span2 = self.create_span(
{"description": "zoo", "sentry_tags": {"status": "failure"}},
duration=10,
start_ts=self.day_ago + timedelta(minutes=1),
)
span2["span_id"] = "b" * 16
self.store_spans(
[span, span2],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"field": ["span.description", "sum(span.self_time)"],
"orderby": ["-sum(span.self_time)"],
"topEvents": 1,
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
"sampling": "PREFLIGHT",
},
)
assert "foo" in response.data
assert "Other" not in response.data
rows = response.data["foo"]["data"][0:6]
for expected, result in zip([0, 512, 0], rows):
assert result[1][0]["count"] == expected
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"field": ["span.description", "sum(span.self_time)"],
"orderby": ["-sum(span.self_time)"],
"topEvents": 1,
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
"sampling": "BEST_EFFORT",
},
)
assert "foo" in response.data
assert "Other" in response.data
rows = response.data["foo"]["data"][0:6]
for expected, result in zip([0, 1, 0], rows):
assert result[1][0]["count"] == expected
def test_interval_larger_than_period_uses_default_period(self) -> None:
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(seconds=10),
"interval": "15s",
"query": "",
"yAxis": ["count()"],
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 400, response.content
assert "for periods of at least" in response.data["detail"]
def test_small_valid_timerange(self) -> None:
# Each of these denotes how many events to create in each bucket
event_counts = [6, 3]
spans = []
for offset, count in enumerate(event_counts):
spans.extend(
[
self.create_span(
{"description": "foo", "sentry_tags": {"status": "success"}},
start_ts=self.day_ago + timedelta(seconds=offset * 15 + 1),
)
for _ in range(count)
]
)
self.store_spans(spans, is_eap=True)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(seconds=30),
"interval": "15s",
"query": "",
"yAxis": ["count()"],
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 2
count_rows = response.data["data"]
for test in zip(event_counts, count_rows):
assert test[1][1][0]["count"] == test[0]
@pytest.mark.xfail(
reason="https://github.com/getsentry/snuba/actions/runs/14717943981/job/41305773190"
)
def test_downsampling_can_go_to_higher_accuracy_tier(self) -> None:
span = self.create_span(
{"description": "foo", "sentry_tags": {"status": "success"}},
duration=100,
start_ts=self.day_ago + timedelta(minutes=1),
)
span["span_id"] = KNOWN_PREFLIGHT_ID
span2 = self.create_span(
{"description": "zoo", "sentry_tags": {"status": "failure"}},
duration=10,
start_ts=self.day_ago + timedelta(minutes=1),
)
span2["span_id"] = "b" * 16
self.store_spans(
[span, span2],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
"sampling": "NORMAL",
},
)
assert response.data["meta"]["dataScanned"] == "full"
# Use preflight to test that we can go to a higher accuracy tier
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
"sampling": "PREFLIGHT",
},
)
assert response.data["meta"]["dataScanned"] == "partial"
def test_request_without_sampling_mode_defaults_to_highest_accuracy(self) -> None:
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
},
)
assert response.data["meta"]["dataScanned"] == "full"
def test_request_to_highest_accuracy_mode(self) -> None:
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
"sampling": "HIGHEST_ACCURACY",
},
)
assert response.data["meta"]["dataScanned"] == "full"
def test_top_n_is_transaction(self) -> None:
self.store_spans(
[
self.create_span(
{"is_segment": True},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"is_segment": False},
start_ts=self.day_ago + timedelta(minutes=1),
),
],
is_eap=True,
)
response = self._do_request(
data={
"field": ["is_transaction", "count(span.duration)"],
"yAxis": ["count(span.duration)"],
"project": self.project.id,
"dataset": "spans",
"excludeOther": 1,
"topEvents": 2,
"partial": 1,
"per_page": 50,
"interval": "1d",
"statsPeriod": "7d",
"orderby": "-count_span_duration",
"sort": "-count_span_duration",
"transformAliasToInputFormat": 1,
},
)
assert response.status_code == 200, response.content
assert set(response.data.keys()) == {"True", "False"}
def test_datetime_unaligned_with_regular_buckets(self) -> None:
"""When querying from 10:12-22:12 with 1 hour intervals
the returned buckets should be every hour; ie 10am, 11am, 12pm
but the data should still be constrained from 22:12-22:12"""
spans = []
# Create a span at 10:05, this should not be in the result
spans.append(
self.create_span(
{
"description": "foo",
"sentry_tags": {"status": "success"},
},
start_ts=self.day_ago + timedelta(minutes=5),
)
)
# Create a span at 10:30, this should be in the result
spans.append(
self.create_span(
{
"description": "foo",
"sentry_tags": {"status": "success"},
},
start_ts=self.day_ago + timedelta(minutes=30),
)
)
# Create a span at 22:05, this should be in the result
spans.append(
self.create_span(
{
"description": "foo",
"sentry_tags": {"status": "success"},
},
start_ts=self.day_ago + timedelta(hours=12, minutes=5),
)
)
self.store_spans(spans, is_eap=True)
# This should be set to 10:00 the previous day
query_start = self.day_ago + timedelta(minutes=12)
query_end = self.day_ago + timedelta(hours=12, minutes=12)
response = self._do_request(
data={
"start": query_start,
"end": query_end,
"interval": "1h",
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 13
assert response.data["meta"]["dataset"] == "spans"
# The timestamp of the first event should be 10:00, and there should only be 1 event
assert data[0] == (self.day_ago.timestamp(), [{"count": 1}])
# The timestamp of the last event should be 22:00 and there should also only be 1 event
assert data[-1] == ((self.day_ago + timedelta(hours=12)).timestamp(), [{"count": 1}])
def test_top_events_with_timestamp(self) -> None:
"""Users shouldn't groupby timestamp for top events"""
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=6),
"interval": "1m",
"yAxis": "count()",
"field": ["timestamp", "sum(span.self_time)"],
"orderby": ["-sum_span_self_time"],
"project": self.project.id,
"dataset": "spans",
"excludeOther": 0,
"topEvents": 2,
},
)
assert response.status_code == 400, response.content
def test_simple_equation(self) -> None:
self.store_spans(
[
self.create_span(
{"op": "queue.process", "sentry_tags": {"op": "queue.publish"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"op": "queue.process", "sentry_tags": {"op": "queue.publish"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"op": "queue.publish", "sentry_tags": {"op": "queue.publish"}},
start_ts=self.day_ago + timedelta(minutes=2),
),
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"yAxis": "equation|count() * 2",
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 3
assert data[0][1][0]["count"] == 0.0
assert data[1][1][0]["count"] == 4.0
assert data[2][1][0]["count"] == 2.0
assert response.data["meta"]["dataset"] == "spans"
def test_equation_all_symbols(self) -> None:
self.store_spans(
[
self.create_span(
{"op": "queue.process", "sentry_tags": {"op": "queue.publish"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"op": "queue.process", "sentry_tags": {"op": "queue.publish"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"op": "queue.publish", "sentry_tags": {"op": "queue.publish"}},
start_ts=self.day_ago + timedelta(minutes=2),
),
],
is_eap=True,
)
equation = "equation|count() * 2 + 2 - 2 / 2"
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"yAxis": equation,
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 3
assert data[0][1][0]["count"] == 0.0
assert data[1][1][0]["count"] == 5.0
assert data[2][1][0]["count"] == 3.0
assert response.data["meta"]["dataset"] == "spans"
def test_simple_equation_with_multi_axis(self) -> None:
self.store_spans(
[
self.create_span(
{"op": "queue.process", "sentry_tags": {"op": "queue.publish"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"op": "queue.process", "sentry_tags": {"op": "queue.publish"}},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{"op": "queue.publish", "sentry_tags": {"op": "queue.publish"}},
start_ts=self.day_ago + timedelta(minutes=2),
),
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"yAxis": ["equation|count() * 2", "equation|count() - 2"],
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
data = response.data["equation|count() * 2"]["data"]
assert len(data) == 3
assert data[0][1][0]["count"] == 0.0
assert data[1][1][0]["count"] == 4.0
assert data[2][1][0]["count"] == 2.0
data = response.data["equation|count() - 2"]["data"]
assert len(data) == 3
assert data[0][1][0]["count"] == 0.0
assert data[1][1][0]["count"] == 0.0
assert data[2][1][0]["count"] == -1.0
def test_simple_equation_with_top_events(self) -> None:
self.store_spans(
[
self.create_span(
{
"description": "foo",
},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{
"description": "foo",
},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{
"description": "baz",
},
start_ts=self.day_ago + timedelta(minutes=1),
),
self.create_span(
{
"description": "bar",
},
start_ts=self.day_ago + timedelta(minutes=2),
),
self.create_span(
{
"description": "bar",
},
start_ts=self.day_ago + timedelta(minutes=2),
),
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=3),
"interval": "1m",
"yAxis": "equation|count() * 2",
"topEvents": 2,
"field": ["description", "equation|count() * 2"],
"orderby": "-equation|count() * 2",
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200, response.content
data = response.data["foo"]["data"]
assert len(data) == 3
assert data[0][1][0]["count"] == 0.0
assert data[1][1][0]["count"] == 4.0
assert data[2][1][0]["count"] == 0.0
data = response.data["bar"]["data"]
assert len(data) == 3
assert data[0][1][0]["count"] == 0.0
assert data[1][1][0]["count"] == 0.0
assert data[2][1][0]["count"] == 4.0
def test_disable_extrapolation(self) -> None:
event_counts = [6, 0, 6, 3, 0, 3]
spans = []
for hour, count in enumerate(event_counts):
spans.extend(
[
self.create_span(
{
"description": "foo",
"sentry_tags": {"status": "success"},
"measurements": {"client_sample_rate": {"value": 0.1}},
},
start_ts=self.day_ago + timedelta(hours=hour, minutes=minute),
)
for minute in range(count)
],
)
self.store_spans(spans, is_eap=True)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": "count()",
"project": self.project.id,
"dataset": "spans",
"disableAggregateExtrapolation": 1,
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 6
assert response.data["meta"]["dataset"] == "spans"
rows = data[0:6]
for test in zip(event_counts, rows):
assert test[1][1][0]["count"] == test[0]
def test_debug_param(self) -> None:
self.user = self.create_user("user@example.com", is_superuser=False)
self.create_team(organization=self.organization, members=[self.user])
self.login_as(user=self.user)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=4),
"interval": "1m",
"query": "",
"yAxis": ["count()"],
"project": self.project.id,
"dataset": "spans",
"debug": True,
},
)
assert response.status_code == 200, response.content
# Debug should be ignored without superuser
assert "debug_info" not in response.data["meta"]
self.user = self.create_user("superuser@example.com", is_superuser=True)
self.create_team(organization=self.organization, members=[self.user])
self.login_as(user=self.user)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=4),
"interval": "1m",
"query": "",
"yAxis": ["count()"],
"project": self.project.id,
"dataset": "spans",
"debug": True,
},
)
assert response.status_code == 200, response.content
assert "debug_info" in response.data["meta"]
assert (
"FUNCTION_COUNT"
== response.data["meta"]["debug_info"]["query"]["expressions"][0]["aggregation"][
"aggregate"
]
)
def test_debug_with_top_events(self) -> None:
self.store_spans(
[
self.create_span(
{"sentry_tags": {"transaction": "foo", "status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
duration=2000,
),
self.create_span(
{"sentry_tags": {"transaction": "bar", "status": "success"}},
start_ts=self.day_ago + timedelta(minutes=1),
duration=2000,
),
],
is_eap=True,
)
self.user = self.create_user("superuser@example.com", is_superuser=True)
self.create_team(organization=self.organization, members=[self.user])
self.login_as(user=self.user)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=4),
"interval": "1m",
"query": "",
"yAxis": ["count()"],
"field": ["transaction"],
"project": self.project.id,
"dataset": "spans",
"topEvents": 2,
"debug": True,
},
)
assert response.status_code == 200, response.content
assert (
"FUNCTION_COUNT"
== response.data["bar"]["meta"]["debug_info"]["query"]["expressions"][0]["aggregation"][
"aggregate"
]
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=4),
"interval": "1m",
"query": "",
"yAxis": ["count()"],
"field": ["transaction"],
"project": self.project.id,
"dataset": "spans",
"topEvents": 2,
},
)
assert response.status_code == 200, response.content
assert "debug_info" not in response.data["bar"]["meta"]
@patch("sentry.utils.snuba_rpc.timeseries_rpc")
def test_debug_param_with_error(self, mock_query) -> None:
self.user = self.create_user("superuser@example.com", is_superuser=True)
self.create_team(organization=self.organization, members=[self.user])
self.login_as(user=self.user)
mock_query.side_effect = SnubaRPCError("test")
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=4),
"interval": "1m",
"query": "",
"yAxis": ["count()"],
"project": self.project.id,
"dataset": "spans",
"debug": True,
},
)
assert response.status_code == 500, response.content
assert response.data["detail"] == "Internal error. Please try again."
assert "meta" in response.data
assert "debug_info" in response.data["meta"]
assert (
"FUNCTION_COUNT"
== response.data["meta"]["debug_info"]["query"]["expressions"][0]["aggregation"][
"aggregate"
]
)
# Need to reset the mock, otherwise previous query is still attached
mock_query.side_effect = SnubaRPCError("test")
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=4),
"interval": "1m",
"query": "",
"yAxis": ["count()"],
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 500, response.content
assert response.data["detail"] == "Internal error. Please try again."
assert "meta" not in response.data
assert "debug_info" not in response.data
def test_groupby_non_existent_attribute(self):
self.store_spans(
[
self.create_span({"description": "span"}, start_ts=self.day_ago),
self.create_span({"description": "span"}, start_ts=self.day_ago),
self.create_span(
{
"description": "span",
"tags": {"foo": "foo"},
"measurements": {"bar": {"value": 1}},
},
start_ts=self.day_ago,
),
],
is_eap=True,
)
response = self._do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=6),
"interval": "1m",
"yAxis": "count(span.duration)",
"field": ["foo", "tags[bar,number]", "count(span.duration)"],
"orderby": ["-count(span.duration)"],
"project": self.project.id,
"dataset": "spans",
"excludeOther": 0,
"topEvents": 2,
},
)
assert response.status_code == 200, response.content
count_none = sum(entry[1][0]["count"] for entry in response.data["None,None"]["data"])
assert count_none == 2
count_foo_1 = sum(entry[1][0]["count"] for entry in response.data["foo,1.0"]["data"])
assert count_foo_1 == 1
| OrganizationEventsStatsSpansEndpointTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 421644,
"end": 422391
} | class ____(sgqlc.types.Interface):
"""Metadata for an audit entry with action repo.*"""
__schema__ = github_schema
__field_names__ = ("repository", "repository_name", "repository_resource_path", "repository_url")
repository = sgqlc.types.Field("Repository", graphql_name="repository")
"""The repository associated with the action"""
repository_name = sgqlc.types.Field(String, graphql_name="repositoryName")
"""The name of the repository"""
repository_resource_path = sgqlc.types.Field(URI, graphql_name="repositoryResourcePath")
"""The HTTP path for the repository"""
repository_url = sgqlc.types.Field(URI, graphql_name="repositoryUrl")
"""The HTTP URL for the repository"""
| RepositoryAuditEntryData |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 24510,
"end": 24829
} | class ____(NotFoundError):
"""
UMFPACK sparse solver (https://www.cise.ufl.edu/research/sparse/umfpack/)
not found. Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [umfpack]) or by setting
the UMFPACK environment variable."""
| UmfpackNotFoundError |
python | kamyu104__LeetCode-Solutions | Python/check-if-a-number-is-majority-element-in-a-sorted-array.py | {
"start": 48,
"end": 578
} | class ____(object):
def isMajorityElement(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
if len(nums) % 2:
if nums[len(nums)//2] != target:
return False
else:
if not (nums[len(nums)//2-1] == nums[len(nums)//2] == target):
return False
left = bisect.bisect_left(nums, target)
right= bisect.bisect_right(nums, target)
return (right-left)*2 > len(nums)
| Solution |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/zip_test.py | {
"start": 1748,
"end": 2141
} | class ____:
mask: bool
value1: np.ndarray
value2: np.ndarray
def __tf_flatten__(self):
metadata = (self.mask,)
components = (self.value1, self.value2)
return metadata, components
def __tf_unflatten__(self, metadata, components):
mask = metadata[0]
value1, value2 = components
return MaskedNdarrayPair(mask=mask, value1=value1, value2=value2)
| MaskedNdarrayPair |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_textbox24.py | {
"start": 315,
"end": 899
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("textbox24.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with textbox(s)."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.insert_textbox(
"E9", "This\nis\n\nsome long text", {"font": {"color": "red"}}
)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | getsentry__sentry | tests/sentry/core/endpoints/test_team_unresolved_issue_age.py | {
"start": 292,
"end": 4567
} | class ____(APITestCase):
endpoint = "sentry-api-0-team-unresolved-issue-age"
def test_simple(self) -> None:
other_user = self.create_user()
other_team = self.create_team()
project1 = self.create_project(teams=[self.team], slug="foo")
project2 = self.create_project(teams=[self.team], slug="bar")
group1 = self.create_group(project=project1)
group2 = self.create_group(project=project2, first_seen=before_now(days=20))
group3 = self.create_group(project=project2, first_seen=before_now(weeks=100))
group4 = self.create_group(project=project2, first_seen=before_now(weeks=60))
# Not assigned, shouldn't count
self.create_group(project=project2, first_seen=before_now(weeks=60))
# Assigned but resolved, shouldn't count
resolved_group = self.create_group(
project=project2, status=GroupStatus.RESOLVED, first_seen=before_now(weeks=60)
)
# Assigned to another user, shouldn't count
assigned_other_user = self.create_group(
project=project2, status=GroupStatus.RESOLVED, first_seen=before_now(weeks=60)
)
# Assigned to another team, shouldn't count
assigned_other_team = self.create_group(
project=project2, status=GroupStatus.RESOLVED, first_seen=before_now(weeks=60)
)
# This group shouldn't be counted since it hasn't been seen for more than 90 days
last_seen_too_old_group = self.create_group(project=project1, last_seen=before_now(days=91))
GroupAssignee.objects.assign(group1, self.user)
GroupAssignee.objects.assign(group2, self.user)
GroupAssignee.objects.assign(group3, self.team)
GroupAssignee.objects.assign(group4, self.user)
GroupAssignee.objects.assign(last_seen_too_old_group, self.user)
GroupAssignee.objects.assign(resolved_group, self.user)
GroupAssignee.objects.assign(assigned_other_user, other_user)
GroupAssignee.objects.assign(assigned_other_team, other_team)
self.login_as(user=self.user)
response = self.get_success_response(self.team.organization.slug, self.team.slug)
assert response.data == {
"< 1 hour": 1,
"< 4 hour": 0,
"< 12 hour": 0,
"< 1 day": 0,
"< 1 week": 0,
"< 4 week": 1,
"< 24 week": 0,
"< 1 year": 0,
"> 1 year": 2,
}
def test_environment_filter(self) -> None:
project1 = self.create_project(teams=[self.team], slug="foo")
env1 = self.create_environment(project=project1, name="prod")
self.create_environment(project=project1, name="dev")
group1 = self.create_group(project=project1)
GroupEnvironment.objects.create(group_id=group1.id, environment_id=env1.id)
GroupAssignee.objects.assign(group1, self.user)
self.login_as(user=self.user)
response = self.get_success_response(
self.team.organization.slug, self.team.slug, environment="prod"
)
assert response.data == {
"< 1 hour": 1,
"< 4 hour": 0,
"< 12 hour": 0,
"< 1 day": 0,
"< 1 week": 0,
"< 4 week": 0,
"< 24 week": 0,
"< 1 year": 0,
"> 1 year": 0,
}
response = self.get_success_response(
self.team.organization.slug, self.team.slug, environment="dev"
)
assert response.data == {
"< 1 hour": 0,
"< 4 hour": 0,
"< 12 hour": 0,
"< 1 day": 0,
"< 1 week": 0,
"< 4 week": 0,
"< 24 week": 0,
"< 1 year": 0,
"> 1 year": 0,
}
def test_empty(self) -> None:
self.login_as(user=self.user)
response = self.get_success_response(self.team.organization.slug, self.team.slug)
assert response.data == {
"< 1 hour": 0,
"< 4 hour": 0,
"< 12 hour": 0,
"< 1 day": 0,
"< 1 week": 0,
"< 4 week": 0,
"< 24 week": 0,
"< 1 year": 0,
"> 1 year": 0,
}
| TeamUnresolvedIssueAgeEndpointTest |
python | agronholm__apscheduler | src/apscheduler/abc.py | {
"start": 2565,
"end": 3064
} | class ____(metaclass=ABCMeta):
"""
Represents a subscription with an event source.
If used as a context manager, unsubscribes on exit.
"""
def __enter__(self) -> Subscription:
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
self.unsubscribe()
@abstractmethod
def unsubscribe(self) -> None:
"""
Cancel this subscription.
Does nothing if the subscription has already been cancelled.
"""
| Subscription |
python | run-llama__llama_index | llama-index-core/llama_index/core/query_engine/router_query_engine.py | {
"start": 10441,
"end": 12408
} | class ____(BaseQueryEngine):
"""
Retriever-based router query engine.
NOTE: this is deprecated, please use our new ToolRetrieverRouterQueryEngine
Use a retriever to select a set of Nodes. Each node will be converted
into a ToolMetadata object, and also used to retrieve a query engine, to form
a QueryEngineTool.
NOTE: this is a beta feature. We are figuring out the right interface
between the retriever and query engine.
Args:
selector (BaseSelector): A selector that chooses one out of many options based
on each candidate's metadata and query.
query_engine_tools (Sequence[QueryEngineTool]): A sequence of candidate
query engines. They must be wrapped as tools to expose metadata to
the selector.
callback_manager (Optional[CallbackManager]): A callback manager.
"""
def __init__(
self,
retriever: BaseRetriever,
node_to_query_engine_fn: Callable,
callback_manager: Optional[CallbackManager] = None,
) -> None:
self._retriever = retriever
self._node_to_query_engine_fn = node_to_query_engine_fn
super().__init__(callback_manager)
def _get_prompt_modules(self) -> PromptMixinType:
"""Get prompt sub-modules."""
# NOTE: don't include tools for now
return {"retriever": self._retriever}
def _query(self, query_bundle: QueryBundle) -> RESPONSE_TYPE:
nodes_with_score = self._retriever.retrieve(query_bundle)
# TODO: for now we only support retrieving one node
if len(nodes_with_score) > 1:
raise ValueError("Retrieved more than one node.")
node = nodes_with_score[0].node
query_engine = self._node_to_query_engine_fn(node)
return query_engine.query(query_bundle)
async def _aquery(self, query_bundle: QueryBundle) -> RESPONSE_TYPE:
return self._query(query_bundle)
| RetrieverRouterQueryEngine |
python | getsentry__sentry | src/sentry/sentry_apps/api/endpoints/installation_external_issue_actions.py | {
"start": 1593,
"end": 3170
} | class ____(SentryAppInstallationBaseEndpoint):
owner = ApiOwner.INTEGRATIONS
publish_status = {
"POST": ApiPublishStatus.PRIVATE,
}
def post(self, request: Request, installation) -> Response:
data = request.data.copy()
external_issue_action_serializer = SentryAppInstallationExternalIssueActionsSerializer(
data=data
)
if not external_issue_action_serializer.is_valid():
return Response(external_issue_action_serializer.errors, status=400)
group_id = data.get("groupId")
del data["groupId"]
try:
group = Group.objects.get(
id=group_id,
project_id__in=Project.objects.filter(organization_id=installation.organization_id),
)
except Group.DoesNotExist:
raise SentryAppError(
message="Could not find the corresponding issue for the given groupId",
status_code=404,
)
action = data.pop("action")
uri = data.pop("uri")
user = _extract_lazy_object(request.user)
if isinstance(user, User):
user = serialize_rpc_user(user)
external_issue = IssueLinkCreator(
install=installation,
group=group,
action=action,
fields=data,
uri=uri,
user=user,
).run()
return Response(
serialize(objects=external_issue, serializer=PlatformExternalIssueSerializer())
)
| SentryAppInstallationExternalIssueActionsEndpoint |
python | ray-project__ray | python/ray/data/tests/conftest.py | {
"start": 17511,
"end": 24350
} | class ____(CoreExecutionMetrics):
"""Generated from a snapshot of the metrics collected by Ray Core during
the physical execution.
NOTE(swang): Currently object store stats only include objects stored in
plasma shared memory.
"""
def __init__(self, last_snapshot=None):
self.task_metrics = ray.util.state.list_tasks(detail=True, limit=10_000)
self.last_snapshot = last_snapshot
memory_info = get_memory_info_reply(
get_state_from_address(ray.get_runtime_context().gcs_address)
)
self.object_store_stats = {
"spilled_bytes_total": memory_info.store_stats.spilled_bytes_total,
"restored_bytes_total": memory_info.store_stats.restored_bytes_total,
"cumulative_created_plasma_bytes": (
memory_info.store_stats.cumulative_created_bytes
),
"cumulative_created_plasma_objects": (
memory_info.store_stats.cumulative_created_objects
),
}
self.actor_metrics = list_actors(limit=10_000)
def clear_task_count(self):
self.task_metrics = []
def clear_object_store_stats(self):
self.object_store_stats = {}
def clear_actor_count(self):
self.actor_metrics = []
def get_task_count(self):
task_count = defaultdict(int)
tasks = self.task_metrics
tasks = [t for t in tasks if t.name != "barrier"]
for task in tasks:
task_count[task.name] += 1
# Filter out previous and dummy tasks.
if self.last_snapshot is not None:
prev_task_count = self.last_snapshot.get_task_count()
if prev_task_count is not None:
for name, count in prev_task_count.items():
task_count[name] -= count
if task_count[name] < 0:
task_count[name] = 0
return task_count
def get_actor_count(self):
actor_count = defaultdict(int)
for actor in self.actor_metrics:
actor_count[actor.class_name] += 1
if self.last_snapshot is not None:
prev_actor_count = self.last_snapshot.get_actor_count()
if prev_actor_count is not None:
for name, count in prev_actor_count.items():
actor_count[name] -= count
if actor_count[name] < 0:
actor_count[name] = 0
return actor_count
def get_object_store_stats(self):
object_store_stats = self.object_store_stats.copy()
if self.last_snapshot is not None:
prev_object_store_stats = self.last_snapshot.get_object_store_stats()
if prev_object_store_stats is not None:
for key, val in prev_object_store_stats.items():
object_store_stats[key] -= val
return object_store_stats
# Dummy task used to make sure that we wait until (most) stats are available.
@ray.remote
def barrier():
time.sleep(1)
return
@ray.remote
def warmup():
time.sleep(1)
return np.zeros(1024 * 1024, dtype=np.uint8)
def task_metrics_flushed(refs):
task_ids = [t.task_id for t in ray.util.state.list_tasks(limit=10_000)]
# All tasks appear in the metrics.
return all(ref.task_id().hex() in task_ids for ref in refs)
def get_initial_core_execution_metrics_snapshot():
# Warmup plasma store and workers.
refs = [warmup.remote() for _ in range(int(ray.cluster_resources()["CPU"]))]
ray.get(refs)
wait_for_condition(lambda: task_metrics_flushed(refs))
last_snapshot = assert_core_execution_metrics_equals(
CoreExecutionMetrics(
task_count={"warmup": lambda count: True}, object_store_stats={}
),
last_snapshot=None,
)
return last_snapshot
def assert_core_execution_metrics_equals(
expected_metrics: CoreExecutionMetrics,
last_snapshot=None,
):
# Wait for one task per CPU to finish to prevent a race condition where not
# all of the task metrics have been collected yet.
if expected_metrics.get_task_count() is not None:
refs = [barrier.remote() for _ in range(int(ray.cluster_resources()["CPU"]))]
ray.get(refs)
wait_for_condition(lambda: task_metrics_flushed(refs))
metrics = PhysicalCoreExecutionMetrics(last_snapshot)
metrics.assert_task_metrics(expected_metrics)
metrics.assert_object_store_metrics(expected_metrics)
metrics.assert_actor_metrics(expected_metrics)
# Return a last_snapshot to the current snapshot of metrics to make subsequent
# queries easier. Don't return a last_snapshot for metrics that weren't asserted.
last_snapshot = PhysicalCoreExecutionMetrics()
if expected_metrics.get_task_count() is None:
last_snapshot.clear_task_count()
elif expected_metrics.get_object_store_stats() is None:
last_snapshot.clear_object_store_stats()
elif expected_metrics.get_actor_count() is None:
last_snapshot.clear_actor_count()
return last_snapshot
def assert_blocks_expected_in_plasma(
last_snapshot,
num_blocks_expected,
block_size_expected=None,
):
total_bytes_expected = None
if block_size_expected is not None:
total_bytes_expected = num_blocks_expected * block_size_expected
print(f"Expecting {total_bytes_expected} bytes, {num_blocks_expected} blocks")
def _assert(last_snapshot):
assert_core_execution_metrics_equals(
CoreExecutionMetrics(
object_store_stats={
"cumulative_created_plasma_objects": (
lambda count: num_blocks_expected * 0.5
<= count
<= 1.5 * num_blocks_expected
),
"cumulative_created_plasma_bytes": (
lambda count: total_bytes_expected is None
or total_bytes_expected * 0.5
<= count
<= 1.5 * total_bytes_expected
),
},
),
last_snapshot,
)
return True
wait_for_condition(lambda: _assert(last_snapshot))
# Get the latest last_snapshot.
last_snapshot = assert_core_execution_metrics_equals(
CoreExecutionMetrics(
object_store_stats={
"cumulative_created_plasma_objects": lambda count: True,
"cumulative_created_plasma_bytes": lambda count: True,
}
),
last_snapshot,
)
return last_snapshot
@pytest.fixture(autouse=True, scope="function")
def log_internal_stack_trace_to_stdout(restore_data_context):
ray.data.context.DataContext.get_current().log_internal_stack_trace_to_stdout = True
| PhysicalCoreExecutionMetrics |
python | coleifer__peewee | tests/pwiz_integration.py | {
"start": 1095,
"end": 1172
} | class ____(TestModel):
data = TextField()
status = IntegerField()
| Event |
python | neetcode-gh__leetcode | python/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.py | {
"start": 0,
"end": 759
} | class ____:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
edges = {(a,b) for a, b in connections}
neighbors = defaultdict(list)
visit = set()
changes = 0
for a, b in connections:
neighbors[a].append(b)
neighbors[b].append(a)
def dfs(city):
nonlocal changes
for neighbor in neighbors[city]:
if neighbor in visit:
continue
# check if this neighbor can reach city 0
if (neighbor, city) not in edges:
changes += 1
visit.add(neighbor)
dfs(neighbor)
visit.add(0)
dfs(0)
return changes
| Solution |
python | wandb__wandb | wandb/vendor/pygments/lexers/d.py | {
"start": 6980,
"end": 9289
} | class ____(RegexLexer):
"""
For `Croc <http://jfbillingsley.com/croc>`_ source.
"""
name = 'Croc'
filenames = ['*.croc']
aliases = ['croc']
mimetypes = ['text/x-crocsrc']
tokens = {
'root': [
(r'\n', Text),
(r'\s+', Text),
# Comments
(r'//(.*?)\n', Comment.Single),
(r'/\*', Comment.Multiline, 'nestedcomment'),
# Keywords
(words((
'as', 'assert', 'break', 'case', 'catch', 'class', 'continue',
'default', 'do', 'else', 'finally', 'for', 'foreach', 'function',
'global', 'namespace', 'if', 'import', 'in', 'is', 'local',
'module', 'return', 'scope', 'super', 'switch', 'this', 'throw',
'try', 'vararg', 'while', 'with', 'yield'), suffix=r'\b'),
Keyword),
(r'(false|true|null)\b', Keyword.Constant),
# FloatLiteral
(r'([0-9][0-9_]*)(?=[.eE])(\.[0-9][0-9_]*)?([eE][+\-]?[0-9_]+)?',
Number.Float),
# IntegerLiteral
# -- Binary
(r'0[bB][01][01_]*', Number.Bin),
# -- Hexadecimal
(r'0[xX][0-9a-fA-F][0-9a-fA-F_]*', Number.Hex),
# -- Decimal
(r'([0-9][0-9_]*)(?![.eE])', Number.Integer),
# CharacterLiteral
(r"""'(\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\[0-9]{1,3}"""
r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|.)'""",
String.Char),
# StringLiteral
# -- WysiwygString
(r'@"(""|[^"])*"', String),
(r'@`(``|[^`])*`', String),
(r"@'(''|[^'])*'", String),
# -- DoubleQuotedString
(r'"(\\\\|\\"|[^"])*"', String),
# Tokens
(r'(~=|\^=|%=|\*=|==|!=|>>>=|>>>|>>=|>>|>=|<=>|\?=|-\>'
r'|<<=|<<|<=|\+\+|\+=|--|-=|\|\||\|=|&&|&=|\.\.|/=)'
r'|[-/.&$@|\+<>!()\[\]{}?,;:=*%^~#\\]', Punctuation),
# Identifier
(r'[a-zA-Z_]\w*', Name),
],
'nestedcomment': [
(r'[^*/]+', Comment.Multiline),
(r'/\*', Comment.Multiline, '#push'),
(r'\*/', Comment.Multiline, '#pop'),
(r'[*/]', Comment.Multiline),
],
}
| CrocLexer |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/validators/actions/test_sentry_app.py | {
"start": 571,
"end": 6312
} | class ____(BaseWorkflowTest):
def setUp(self) -> None:
super().setUp()
self.sentry_app, self.sentry_app_installation = self.create_sentry_app_with_schema()
self.sentry_app_settings = [
{"name": "alert_prefix", "value": "[Not Good]"},
{"name": "channel", "value": "#ignored-errors"},
{"name": "best_emoji", "value": ":fire:"},
{"name": "teamId", "value": "1"},
{"name": "assigneeId", "value": "3"},
]
self.valid_data = {
"type": Action.Type.SENTRY_APP,
"config": {
"sentryAppIdentifier": SentryAppIdentifier.SENTRY_APP_INSTALLATION_UUID,
"targetType": ActionType.SENTRY_APP,
"targetIdentifier": self.sentry_app_installation.uuid,
},
"data": {"settings": self.sentry_app_settings},
}
group_event = self.event.for_group(self.group)
self.event_data = WorkflowEventData(
event=group_event,
group=self.group,
)
self.rule = self.create_project_rule(project=self.project)
self.detector = self.create_detector(project=self.project)
self.workflow = self.create_workflow()
self.create_alert_rule_workflow(rule_id=self.rule.id, workflow_id=self.workflow.id)
@mock.patch(
"sentry.rules.actions.sentry_apps.utils.app_service.trigger_sentry_app_action_creators"
)
def test_validate(self, mock_trigger_sentry_app_action_creators: mock.MagicMock) -> None:
mock_trigger_sentry_app_action_creators.return_value = RpcAlertRuleActionResult(
success=True, message="success"
)
validator = BaseActionValidator(
data=self.valid_data,
context={"organization": self.organization},
)
result = validator.is_valid()
assert result is True
validator.save()
@mock.patch(
"sentry.rules.actions.sentry_apps.utils.app_service.trigger_sentry_app_action_creators"
)
def test_validate_sentry_app_id(
self, mock_trigger_sentry_app_action_creators: mock.MagicMock
) -> None:
mock_trigger_sentry_app_action_creators.return_value = RpcAlertRuleActionResult(
success=True, message="success"
)
valid_data = {
"type": Action.Type.SENTRY_APP,
"config": {
"sentryAppIdentifier": SentryAppIdentifier.SENTRY_APP_ID,
"targetType": ActionType.SENTRY_APP,
"targetIdentifier": str(self.sentry_app.id),
},
"data": {"settings": self.sentry_app_settings},
}
validator = BaseActionValidator(
data=valid_data,
context={"organization": self.organization},
)
result = validator.is_valid()
assert result is True
validator.save()
@mock.patch(
"sentry.rules.actions.sentry_apps.utils.app_service.trigger_sentry_app_action_creators"
)
def test_validate__rpc_failure(
self, mock_trigger_sentry_app_action_creators: mock.MagicMock
) -> None:
mock_trigger_sentry_app_action_creators.return_value = RpcAlertRuleActionResult(
success=False,
message="Could not create sentry app action",
error_type=SentryAppErrorType.SENTRY,
)
validator = BaseActionValidator(
data=self.valid_data,
context={"organization": self.organization},
)
result = validator.is_valid()
assert result is False
assert validator.errors == {
"nonFieldErrors": [
ErrorDetail(
string="Something went wrong during the alert rule action process!",
code="invalid",
)
]
}
@mock.patch(
"sentry.rules.actions.sentry_apps.utils.app_service.trigger_sentry_app_action_creators"
)
def test_validate_settings_action_trigger(
self, mock_trigger_sentry_app_action_creators: mock.MagicMock
) -> None:
self.create_sentry_app(
organization=self.organization,
name="Test Application",
is_alertable=True,
)
install = self.create_sentry_app_installation(
slug="test-application", organization=self.organization
)
self.valid_data = {
"type": Action.Type.SENTRY_APP,
"config": {
"sentry_app_identifier": SentryAppIdentifier.SENTRY_APP_INSTALLATION_UUID,
"targetType": ActionType.SENTRY_APP,
"target_identifier": install.uuid,
},
"data": {
"settings": [
{
"name": "asdf",
"label": None,
"value": [{"id": "1dedabd2-059d-457b-ac17-df39031d4593", "type": "team"}],
},
{
"name": "fdsa",
"label": "label",
"value": "string",
},
]
},
}
mock_trigger_sentry_app_action_creators.return_value = RpcAlertRuleActionResult(
success=True, message="success"
)
validator = BaseActionValidator(
data=self.valid_data,
context={"organization": self.organization},
)
result = validator.is_valid()
assert result is True
action = validator.save()
setattr(action, "workflow_id", self.workflow.id)
action.trigger(self.event_data) # action should be triggerable
| TestSentryAppActionValidator |
python | pydantic__pydantic | pydantic/v1/color.py | {
"start": 897,
"end": 2355
} | class ____:
"""
Internal use only as a representation of a color.
"""
__slots__ = 'r', 'g', 'b', 'alpha', '_tuple'
def __init__(self, r: float, g: float, b: float, alpha: Optional[float]):
self.r = r
self.g = g
self.b = b
self.alpha = alpha
self._tuple: Tuple[float, float, float, Optional[float]] = (r, g, b, alpha)
def __getitem__(self, item: Any) -> Any:
return self._tuple[item]
# these are not compiled here to avoid import slowdown, they'll be compiled the first time they're used, then cached
r_hex_short = r'\s*(?:#|0x)?([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?\s*'
r_hex_long = r'\s*(?:#|0x)?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?\s*'
_r_255 = r'(\d{1,3}(?:\.\d+)?)'
_r_comma = r'\s*,\s*'
r_rgb = fr'\s*rgb\(\s*{_r_255}{_r_comma}{_r_255}{_r_comma}{_r_255}\)\s*'
_r_alpha = r'(\d(?:\.\d+)?|\.\d+|\d{1,2}%)'
r_rgba = fr'\s*rgba\(\s*{_r_255}{_r_comma}{_r_255}{_r_comma}{_r_255}{_r_comma}{_r_alpha}\s*\)\s*'
_r_h = r'(-?\d+(?:\.\d+)?|-?\.\d+)(deg|rad|turn)?'
_r_sl = r'(\d{1,3}(?:\.\d+)?)%'
r_hsl = fr'\s*hsl\(\s*{_r_h}{_r_comma}{_r_sl}{_r_comma}{_r_sl}\s*\)\s*'
r_hsla = fr'\s*hsl\(\s*{_r_h}{_r_comma}{_r_sl}{_r_comma}{_r_sl}{_r_comma}{_r_alpha}\s*\)\s*'
# colors where the two hex characters are the same, if all colors match this the short version of hex colors can be used
repeat_colors = {int(c * 2, 16) for c in '0123456789abcdef'}
rads = 2 * math.pi
| RGBA |
python | sqlalchemy__sqlalchemy | test/aaa_profiling/test_orm.py | {
"start": 27415,
"end": 32262
} | class ____(NoCache, fixtures.MappedTest):
__requires__ = ("python_profiling_backend",)
__backend__ = True
@classmethod
def define_tables(cls, metadata):
def make_some_columns():
return [Column("c%d" % i, Integer) for i in range(2)]
Table(
"a",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
*make_some_columns(),
)
Table(
"b",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("a_id", ForeignKey("a.id")),
*make_some_columns(),
)
Table(
"c",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("b_id", ForeignKey("b.id")),
*make_some_columns(),
)
Table(
"d",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("b_id", ForeignKey("b.id")),
*make_some_columns(),
)
Table(
"e",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("b_id", ForeignKey("b.id")),
*make_some_columns(),
)
Table(
"f",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("b_id", ForeignKey("b.id")),
*make_some_columns(),
)
Table(
"g",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("a_id", ForeignKey("a.id")),
*make_some_columns(),
)
@classmethod
def setup_classes(cls):
class A(cls.Basic):
pass
class B(cls.Basic):
pass
class C(cls.Basic):
pass
class D(cls.Basic):
pass
class E(cls.Basic):
pass
class F(cls.Basic):
pass
class G(cls.Basic):
pass
@classmethod
def setup_mappers(cls):
A, B, C, D, E, F, G = cls.classes("A", "B", "C", "D", "E", "F", "G")
a, b, c, d, e, f, g = cls.tables("a", "b", "c", "d", "e", "f", "g")
cls.mapper_registry.map_imperatively(
A, a, properties={"bs": relationship(B), "gs": relationship(G)}
)
cls.mapper_registry.map_imperatively(
B,
b,
properties={
"cs": relationship(C),
"ds": relationship(D),
"es": relationship(E),
"fs": relationship(F),
},
)
cls.mapper_registry.map_imperatively(C, c)
cls.mapper_registry.map_imperatively(D, d)
cls.mapper_registry.map_imperatively(E, e)
cls.mapper_registry.map_imperatively(F, f)
cls.mapper_registry.map_imperatively(G, g)
configure_mappers()
def test_query_opts_unbound_branching(self):
A, B, C, D, E, F, G = self.classes("A", "B", "C", "D", "E", "F", "G")
base = joinedload(A.bs)
opts = [
base.joinedload(B.cs),
base.joinedload(B.ds),
base.joinedload(B.es),
base.joinedload(B.fs),
]
q = fixture_session().query(A)
context = q._compile_state()
@profiling.function_call_count(warmup=1)
def go():
q2 = q.options(opts)
context.query = q2
context.attributes = q2._attributes = {
"_unbound_load_dedupes": set()
}
for opt in q2._with_options:
opt.process_compile_state(context)
go()
def test_query_opts_key_bound_branching(self):
A, B, C, D, E, F, G = self.classes("A", "B", "C", "D", "E", "F", "G")
base = Load(A).joinedload(A.bs)
opts = [
base.joinedload(B.cs),
base.joinedload(B.ds),
base.joinedload(B.es),
base.joinedload(B.fs),
]
q = fixture_session().query(A)
context = q._compile_state()
@profiling.function_call_count(warmup=1)
def go():
q2 = q.options(opts)
context.query = q2
context.attributes = q2._attributes = {
"_unbound_load_dedupes": set()
}
for opt in q2._with_options:
opt.process_compile_state(context)
go()
| BranchedOptionTest |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/instigation.py | {
"start": 3865,
"end": 4046
} | class ____(graphene.Union):
class Meta:
types = (GrapheneSensorData, GrapheneScheduleData)
name = "InstigationTypeSpecificData"
| GrapheneInstigationTypeSpecificData |
python | sympy__sympy | sympy/physics/secondquant.py | {
"start": 4130,
"end": 7327
} | class ____(TensorSymbol):
"""Stores upper and lower indices in separate Tuple's.
Each group of indices is assumed to be antisymmetric.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.secondquant import AntiSymmetricTensor
>>> i, j = symbols('i j', below_fermi=True)
>>> a, b = symbols('a b', above_fermi=True)
>>> AntiSymmetricTensor('v', (a, i), (b, j))
AntiSymmetricTensor(v, (a, i), (b, j))
>>> AntiSymmetricTensor('v', (i, a), (b, j))
-AntiSymmetricTensor(v, (a, i), (b, j))
As you can see, the indices are automatically sorted to a canonical form.
"""
def __new__(cls, symbol, upper, lower):
try:
upper, signu = _sort_anticommuting_fermions(
upper, key=_sqkey_index)
lower, signl = _sort_anticommuting_fermions(
lower, key=_sqkey_index)
except ViolationOfPauliPrinciple:
return S.Zero
symbol = sympify(symbol)
upper = Tuple(*upper)
lower = Tuple(*lower)
if (signu + signl) % 2:
return -TensorSymbol.__new__(cls, symbol, upper, lower)
else:
return TensorSymbol.__new__(cls, symbol, upper, lower)
def _latex(self, printer):
return "{%s^{%s}_{%s}}" % (
self.symbol,
"".join([ printer._print(i) for i in self.args[1]]),
"".join([ printer._print(i) for i in self.args[2]])
)
@property
def symbol(self):
"""
Returns the symbol of the tensor.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.secondquant import AntiSymmetricTensor
>>> i, j = symbols('i,j', below_fermi=True)
>>> a, b = symbols('a,b', above_fermi=True)
>>> AntiSymmetricTensor('v', (a, i), (b, j))
AntiSymmetricTensor(v, (a, i), (b, j))
>>> AntiSymmetricTensor('v', (a, i), (b, j)).symbol
v
"""
return self.args[0]
@property
def upper(self):
"""
Returns the upper indices.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.secondquant import AntiSymmetricTensor
>>> i, j = symbols('i,j', below_fermi=True)
>>> a, b = symbols('a,b', above_fermi=True)
>>> AntiSymmetricTensor('v', (a, i), (b, j))
AntiSymmetricTensor(v, (a, i), (b, j))
>>> AntiSymmetricTensor('v', (a, i), (b, j)).upper
(a, i)
"""
return self.args[1]
@property
def lower(self):
"""
Returns the lower indices.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.secondquant import AntiSymmetricTensor
>>> i, j = symbols('i,j', below_fermi=True)
>>> a, b = symbols('a,b', above_fermi=True)
>>> AntiSymmetricTensor('v', (a, i), (b, j))
AntiSymmetricTensor(v, (a, i), (b, j))
>>> AntiSymmetricTensor('v', (a, i), (b, j)).lower
(b, j)
"""
return self.args[2]
def __str__(self):
return "%s(%s,%s)" % self.args
| AntiSymmetricTensor |
python | Textualize__textual | docs/examples/guide/dom3.py | {
"start": 211,
"end": 667
} | class ____(App):
def compose(self) -> ComposeResult:
yield Header()
yield Footer()
yield Container(
Static(QUESTION, classes="question"),
Horizontal(
Button("Yes", variant="success"),
Button("No", variant="error"),
classes="buttons",
),
id="dialog",
)
if __name__ == "__main__":
app = ExampleApp()
app.run()
| ExampleApp |
python | ansible__ansible | test/lib/ansible_test/_internal/core_ci.py | {
"start": 1435,
"end": 2558
} | class ____(Resource):
"""Details needed to request a VM from Ansible Core CI."""
platform: str
version: str
architecture: str
provider: str
tag: str
def as_tuple(self) -> tuple[str, str, str, str]:
"""Return the resource as a tuple of platform, version, architecture and provider."""
return self.platform, self.version, self.architecture, self.provider
def get_label(self) -> str:
"""Return a user-friendly label for this resource."""
return f'{self.platform} {self.version} ({self.architecture}) [{self.tag}] @{self.provider}'
@property
def persist(self) -> bool:
"""True if the resource is persistent, otherwise false."""
return True
def get_config(self, core_ci: AnsibleCoreCI) -> dict[str, object]:
"""Return the configuration for this resource."""
return dict(
type="vm",
platform=self.platform,
version=self.version,
architecture=self.architecture,
public_key=core_ci.ssh_key.pub_contents,
)
@dataclasses.dataclass(frozen=True)
| VmResource |
python | huggingface__transformers | tests/models/reformer/test_modeling_reformer.py | {
"start": 39316,
"end": 57795
} | class ____(unittest.TestCase):
"""
These integration tests test the current layer activations and gradients against the output of the Hugging Face Reformer model at time of integration: 29/06/2020. During integration, the model was tested against the output of the official Trax ReformerLM model for various cases ("lsh" only, "lsh" only, masked / non-masked, different chunk length, ....). In order to recover the original trax integration tests, one should use patrickvonplaten's fork of trax and the code that lives on the branch `reformer_trax_tests`.
"""
def _get_basic_config_and_input(self):
config = {
"vocab_size": 320,
"attention_head_size": 8,
"hidden_size": 16,
"num_attention_heads": 2,
"num_buckets": 2,
"num_hashes": 4,
"lsh_attn_chunk_length": 4,
"local_attn_chunk_length": 4,
"lsh_num_chunks_before": 1,
"lsh_num_chunks_after": 0,
"local_num_chunks_before": 1,
"local_num_chunks_after": 0,
"chunk_size_lm_head": 0,
"chunk_size_feed_forward": 0,
"feed_forward_size": 32,
"hidden_act": "gelu",
"hidden_dropout_prob": 0.0,
"lsh_attention_probs_dropout_prob": 0.0,
"local_attention_probs_dropout_prob": 0.0,
"max_position_embeddings": 32,
"initializer_range": 0.02,
"axial_norm_std": 1.0,
"layer_norm_eps": 1e-12,
"sinusoidal_pos_embds": False,
"axial_pos_embds": True,
"axial_pos_shape": [4, 8],
"axial_pos_embds_dim": [8, 8],
"hash_seed": 0,
"is_decoder": True,
}
return config
def _get_hidden_states(self):
return torch.tensor(
[
[
[
1.90826353e00,
-1.45999730e00,
-6.20405462e-01,
1.52503433e00,
-3.64464232e-01,
-8.27359235e-01,
8.39670803e-01,
2.44492178e-01,
4.98332758e-01,
2.69175139e00,
-7.08081422e-03,
1.04915401e00,
-1.83476661e00,
7.67220476e-01,
2.98580543e-01,
2.84803992e-02,
],
[
-2.66374286e-02,
4.33497576e-01,
3.10386309e-01,
5.46039944e-01,
-2.47292666e-04,
-7.52305019e-01,
2.39162103e-01,
7.25216186e-01,
-7.58357372e-01,
4.20635998e-01,
-4.04739919e-02,
1.59924145e-01,
2.05135748e00,
-1.15997978e00,
5.37166397e-01,
2.62873606e-01,
],
[
1.85247482e-01,
7.07046037e-01,
-6.77089715e-01,
-2.24209655e00,
-3.75307980e-02,
-8.59380874e-01,
-2.81027884e00,
1.01276376e00,
-1.69438001e00,
4.17574660e-01,
-1.49196962e00,
-1.76483717e00,
-1.94566312e-01,
-1.71183858e00,
7.72903565e-01,
-1.11557056e00,
],
[
9.46069193e-01,
1.53417623e-01,
-9.58686996e-01,
1.18126669e-01,
1.75967724e00,
1.62194590e00,
-5.74108159e-01,
6.79920443e-01,
5.44028163e-01,
2.05466114e-01,
-3.63045868e-01,
2.41865062e-01,
3.20348382e-01,
-9.05611176e-01,
-1.92690727e-01,
-1.19917547e00,
],
]
],
dtype=torch.float32,
device=torch_device,
)
def _get_attn_mask(self):
return torch.tensor([[0, 1, 0, 0]], dtype=torch.long, device=torch_device)
def _get_input_ids_and_mask(self):
mask = torch.tensor(
[
[1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0],
],
dtype=torch.long,
device=torch_device,
)
input_ids = torch.tensor(
[
[
89,
279,
286,
84,
194,
316,
182,
28,
283,
37,
169,
7,
253,
267,
107,
250,
44,
7,
102,
62,
3,
243,
171,
265,
302,
48,
164,
264,
148,
229,
280,
150,
],
[
9,
192,
66,
112,
163,
83,
135,
70,
224,
96,
31,
80,
196,
80,
63,
22,
85,
100,
47,
283,
0,
163,
126,
143,
195,
82,
53,
82,
18,
27,
182,
52,
],
],
dtype=torch.long,
device=torch_device,
)
return input_ids, mask
def test_lsh_layer_forward(self):
config = self._get_basic_config_and_input()
config["lsh_num_chunks_before"] = 0
config["attn_layers"] = ["lsh"]
config["is_decoder"] = False
hidden_states = self._get_hidden_states()
torch.manual_seed(0)
layer = ReformerLayer(ReformerConfig(**config)).to(torch_device)
layer.eval()
reformer_output = layer(prev_attn_output=hidden_states.clone(), hidden_states=hidden_states)
output_slice = reformer_output.hidden_states[0, 0, :5]
expected_output_slice = torch.tensor(
[1.6879, -1.3083, -0.4708, 1.3555, -0.6292],
dtype=torch.float,
device=torch_device,
)
torch.testing.assert_close(output_slice, expected_output_slice, rtol=1e-3, atol=1e-3)
def test_lsh_layer_forward_complex(self):
config = self._get_basic_config_and_input()
config["lsh_num_chunks_before"] = 0
config["attn_layers"] = ["lsh"]
config["num_buckets"] = [2, 4]
attn_mask = self._get_attn_mask()
hidden_states = self._get_hidden_states()
torch.manual_seed(0)
layer = ReformerLayer(ReformerConfig(**config)).to(torch_device)
layer.eval()
reformer_output = layer(
prev_attn_output=hidden_states.clone(),
hidden_states=hidden_states,
attention_mask=attn_mask,
)
output_slice = reformer_output.hidden_states[0, 0, :5]
expected_output_slice = torch.tensor(
[1.6439, -1.2306, -0.5108, 1.3006, -0.6537],
dtype=torch.float,
device=torch_device,
)
torch.testing.assert_close(output_slice, expected_output_slice, rtol=1e-3, atol=1e-3)
def test_local_layer_forward(self):
config = self._get_basic_config_and_input()
config["local_num_chunks_before"] = 0
config["attn_layers"] = ["local"]
config["is_decoder"] = False
hidden_states = self._get_hidden_states()
torch.manual_seed(0)
layer = ReformerLayer(ReformerConfig(**config)).to(torch_device)
layer.eval()
reformer_output = layer(prev_attn_output=hidden_states, hidden_states=hidden_states)
output_slice = reformer_output.hidden_states[0, 0, :5]
expected_output_slice = torch.tensor(
[1.4212, -2.0576, -0.9688, 1.4599, -0.1344],
dtype=torch.float,
device=torch_device,
)
torch.testing.assert_close(output_slice, expected_output_slice, rtol=1e-3, atol=1e-3)
def test_local_layer_forward_complex(self):
config = self._get_basic_config_and_input()
config["local_num_chunks_before"] = 0
config["attn_layers"] = ["local"]
attn_mask = self._get_attn_mask()
hidden_states = self._get_hidden_states()
torch.manual_seed(0)
layer = ReformerLayer(ReformerConfig(**config)).to(torch_device)
layer.eval()
reformer_output = layer(
prev_attn_output=hidden_states,
hidden_states=hidden_states,
attention_mask=attn_mask,
)
output_slice = reformer_output.hidden_states[0, 0, :5]
expected_output_slice = torch.tensor(
[1.4750, -2.0235, -0.9743, 1.4463, -0.1269],
dtype=torch.float,
device=torch_device,
)
torch.testing.assert_close(output_slice, expected_output_slice, rtol=1e-3, atol=1e-3)
def test_lsh_model_forward(self):
config = self._get_basic_config_and_input()
config["attn_layers"] = ["lsh", "lsh", "lsh", "lsh"]
config["num_buckets"] = [2, 4]
torch.manual_seed(0)
model = ReformerModel(ReformerConfig(**config)).to(torch_device)
model.eval()
input_ids, attn_mask = self._get_input_ids_and_mask()
hidden_states = model(input_ids=input_ids, attention_mask=attn_mask)[0]
output_slice = hidden_states[0, 0, :5]
expected_output_slice = torch.tensor(
[-0.9896, -0.9396, -1.0831, -0.0597, 0.2456],
dtype=torch.float,
device=torch_device,
)
torch.testing.assert_close(output_slice, expected_output_slice, rtol=1e-3, atol=1e-3)
def test_local_model_forward(self):
config = self._get_basic_config_and_input()
config["attn_layers"] = ["local", "local", "local", "local"]
torch.manual_seed(0)
model = ReformerModel(ReformerConfig(**config)).to(torch_device)
model.eval()
input_ids, attn_mask = self._get_input_ids_and_mask()
hidden_states = model(input_ids=input_ids, attention_mask=attn_mask)[0]
output_slice = hidden_states[0, 0, :5]
expected_output_slice = torch.tensor(
[-1.6791, 0.7171, 0.1594, 0.4063, 1.2584],
dtype=torch.float,
device=torch_device,
)
torch.testing.assert_close(output_slice, expected_output_slice, rtol=1e-3, atol=1e-3)
def test_lm_model_forward(self):
config = self._get_basic_config_and_input()
config["attn_layers"] = ["local", "lsh", "local", "lsh", "local", "lsh"]
config["num_buckets"] = [2, 4]
config["is_decoder"] = False
torch.manual_seed(0)
model = ReformerForMaskedLM(ReformerConfig(**config)).to(torch_device)
model.eval()
input_ids, attn_mask = self._get_input_ids_and_mask()
hidden_states = model(input_ids=input_ids, attention_mask=attn_mask)[0]
output_slice = hidden_states[1, -1, :5]
expected_output_slice = torch.tensor(
[0.1018, -0.2026, 0.2116, 0.0270, -0.1233],
dtype=torch.float,
device=torch_device,
)
torch.testing.assert_close(output_slice, expected_output_slice, rtol=1e-3, atol=1e-3)
def test_local_lm_model_grad(self):
config = self._get_basic_config_and_input()
config["attn_layers"] = ["local", "local", "local", "local"]
config["hidden_dropout_prob"] = 0.0
config["local_attention_probs_dropout_prob"] = 0.0
torch.manual_seed(0)
model = ReformerModelWithLMHead(ReformerConfig(**config)).to(torch_device)
model.train()
model.zero_grad()
input_ids, _ = self._get_input_ids_and_mask()
loss = model(input_ids=input_ids, labels=input_ids)[0]
torch.testing.assert_close(
loss, torch.tensor(5.8019, dtype=torch.float, device=torch_device), rtol=1e-3, atol=1e-3
)
loss.backward()
# check last grads to cover all probable errors
grad_slice_word = model.reformer.embeddings.word_embeddings.weight.grad[0, :5]
expected_grad_slice_word = torch.tensor(
[-0.0005, -0.0001, -0.0002, -0.0006, -0.0006],
dtype=torch.float,
device=torch_device,
)
grad_slice_position_factor_1 = model.reformer.embeddings.position_embeddings.weights[0][1, 0, -5:]
expected_grad_slice_pos_fac_1 = torch.tensor(
[-0.5235, 0.5704, 0.0922, -0.3140, 0.9928],
dtype=torch.float,
device=torch_device,
)
grad_slice_position_factor_2 = model.reformer.embeddings.position_embeddings.weights[1][0, 1, :5]
expected_grad_slice_pos_fac_2 = torch.tensor(
[1.7960, 1.7668, 0.5593, 0.0907, 1.8342],
dtype=torch.float,
device=torch_device,
)
torch.testing.assert_close(grad_slice_word, expected_grad_slice_word, rtol=1e-3, atol=1e-3)
torch.testing.assert_close(grad_slice_position_factor_1, expected_grad_slice_pos_fac_1, rtol=1e-3, atol=1e-3)
torch.testing.assert_close(grad_slice_position_factor_2, expected_grad_slice_pos_fac_2, rtol=1e-3, atol=1e-3)
def test_lsh_lm_model_grad(self):
config = self._get_basic_config_and_input()
config["attn_layers"] = ["lsh", "lsh", "lsh", "lsh"]
config["hidden_dropout_prob"] = 0.0
config["lsh_attention_probs_dropout_prob"] = 0.0
config["num_buckets"] = [2, 4]
config["num_hashes"] = 6
torch.manual_seed(0)
model = ReformerModelWithLMHead(ReformerConfig(**config)).to(torch_device)
model.train()
model.zero_grad()
input_ids, _ = self._get_input_ids_and_mask()
loss = model(input_ids=input_ids, labels=input_ids)[0]
torch.testing.assert_close(
loss, torch.tensor(5.7854, dtype=torch.float, device=torch_device), rtol=1e-3, atol=1e-3
)
loss.backward()
# check last grads to cover all probable errors
grad_slice_word = model.reformer.embeddings.word_embeddings.weight.grad[0, :5]
expected_grad_slice_word = torch.tensor(
[0.0004, 0.0003, 0.0006, -0.0004, 0.0002],
dtype=torch.float,
device=torch_device,
)
grad_slice_position_factor_1 = model.reformer.embeddings.position_embeddings.weights[0][1, 0, -5:]
expected_grad_slice_pos_fac_1 = torch.tensor(
[-0.3792, 0.5593, -1.6993, 0.2033, 0.4131],
dtype=torch.float,
device=torch_device,
)
grad_slice_position_factor_2 = model.reformer.embeddings.position_embeddings.weights[1][0, 1, :5]
expected_grad_slice_pos_fac_2 = torch.tensor(
[-1.4212, -0.3201, -1.1944, 0.1258, 0.2856],
dtype=torch.float,
device=torch_device,
)
torch.testing.assert_close(grad_slice_word, expected_grad_slice_word, rtol=1e-3, atol=1e-3)
torch.testing.assert_close(grad_slice_position_factor_1, expected_grad_slice_pos_fac_1, rtol=1e-3, atol=1e-3)
torch.testing.assert_close(grad_slice_position_factor_2, expected_grad_slice_pos_fac_2, rtol=1e-3, atol=1e-3)
@slow
def test_pretrained_generate_crime_and_punish(self):
model = ReformerModelWithLMHead.from_pretrained("google/reformer-crime-and-punishment").to(torch_device)
tokenizer = ReformerTokenizer.from_pretrained("google/reformer-crime-and-punishment")
model.eval()
input_ids = tokenizer.encode("A few months later", return_tensors="pt").to(torch_device)
output_ids = model.generate(
input_ids, max_length=50, num_beams=4, early_stopping=True, do_sample=False, num_hashes=8
)
output = tokenizer.decode(output_ids[0])
self.assertEqual(
output,
"A few months later state expression in his ideas, at the first entrance. He was positively for an inst",
)
@slow
def test_pretrained_generate_use_cache_equality(self):
model = ReformerModelWithLMHead.from_pretrained("google/reformer-crime-and-punishment").to(torch_device)
tokenizer = ReformerTokenizer.from_pretrained("google/reformer-crime-and-punishment")
model.eval()
input_ids = tokenizer.encode("A few months later", return_tensors="pt").to(torch_device)
output_ids_with_cache = model.generate(input_ids, max_length=130, num_hashes=8, use_cache=False)
output_ids_without_cache = model.generate(input_ids, max_length=130, num_hashes=8, use_cache=True)
output_with_cache = tokenizer.decode(output_ids_with_cache[0])
output_without_cache = tokenizer.decode(output_ids_without_cache[0])
self.assertEqual(output_with_cache, output_without_cache)
| ReformerIntegrationTests |
python | getsentry__sentry | src/sentry/uptime/endpoints/serializers.py | {
"start": 7224,
"end": 7693
} | class ____(Serializer):
@override
def serialize(
self, obj: UptimeSummary, attrs: Any, user: Any, **kwargs: Any
) -> UptimeSummarySerializerResponse:
return {
"totalChecks": obj.total_checks,
"failedChecks": obj.failed_checks,
"downtimeChecks": obj.downtime_checks,
"missedWindowChecks": obj.missed_window_checks,
"avgDurationUs": obj.avg_duration_us,
}
| UptimeSummarySerializer |
python | matplotlib__matplotlib | lib/matplotlib/dates.py | {
"start": 18238,
"end": 19226
} | class ____(ticker.Formatter):
"""
Format a tick (in days since the epoch) with a
`~datetime.datetime.strftime` format string.
"""
def __init__(self, fmt, tz=None, *, usetex=None):
"""
Parameters
----------
fmt : str
`~datetime.datetime.strftime` format string
tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
usetex : bool, default: :rc:`text.usetex`
To enable/disable the use of TeX's math mode for rendering the
results of the formatter.
"""
self.tz = _get_tzinfo(tz)
self.fmt = fmt
self._usetex = mpl._val_or_rc(usetex, 'text.usetex')
def __call__(self, x, pos=0):
result = num2date(x, self.tz).strftime(self.fmt)
return _wrap_in_tex(result) if self._usetex else result
def set_tzinfo(self, tz):
self.tz = _get_tzinfo(tz)
| DateFormatter |
python | astropy__astropy | astropy/modeling/tests/test_constraints.py | {
"start": 3849,
"end": 9875
} | class ____:
def setup_class(self):
A = -2.0
B = 0.5
self.x = np.linspace(-1.0, 1.0, 100)
self.y = A * self.x + B + np.random.normal(scale=0.1, size=100)
# fmt: off
data = np.array(
[
505.0, 556.0, 630.0, 595.0, 561.0, 553.0, 543.0, 496.0, 460.0, 469.0,
426.0, 518.0, 684.0, 798.0, 830.0, 794.0, 649.0, 706.0, 671.0, 545.0,
479.0, 454.0, 505.0, 700.0, 1058.0, 1231.0, 1325.0, 997.0, 1036.0, 884.0,
610.0, 487.0, 453.0, 527.0, 780.0, 1094.0, 1983.0, 1993.0, 1809.0, 1525.0,
1056.0, 895.0, 604.0, 466.0, 510.0, 678.0, 1130.0, 1986.0, 2670.0, 2535.0,
1878.0, 1450.0, 1200.0, 663.0, 511.0, 474.0, 569.0, 848.0, 1670.0, 2611.0,
3129.0, 2507.0, 1782.0, 1211.0, 723.0, 541.0, 511.0, 518.0, 597.0, 1137.0,
1993.0, 2925.0, 2438.0, 1910.0, 1230.0, 738.0, 506.0, 461.0, 486.0, 597.0,
733.0, 1262.0, 1896.0, 2342.0, 1792.0, 1180.0, 667.0, 482.0, 454.0, 482.0,
504.0, 566.0, 789.0, 1194.0, 1545.0, 1361.0, 933.0, 562.0, 418.0, 463.0,
435.0, 466.0, 528.0, 487.0, 664.0, 799.0, 746.0, 550.0, 478.0, 535.0,
443.0, 416.0, 439.0, 472.0, 472.0, 492.0, 523.0, 569.0, 487.0, 441.0,
428.0
]
)
# fmt: on
self.data = data.reshape(11, 11)
@pytest.mark.parametrize("fitter", fitters)
def test_bounds_lsq(self, fitter):
fitter = fitter()
guess_slope = 1.1
guess_intercept = 0.0
bounds = {"slope": (-1.5, 5.0), "intercept": (-1.0, 1.0)}
line_model = models.Linear1D(guess_slope, guess_intercept, bounds=bounds)
with pytest.warns(AstropyUserWarning, match=r"Model is linear in parameters"):
model = fitter(line_model, self.x, self.y)
slope = model.slope.value
intercept = model.intercept.value
assert slope + 10**-5 >= bounds["slope"][0]
assert slope - 10**-5 <= bounds["slope"][1]
assert intercept + 10**-5 >= bounds["intercept"][0]
assert intercept - 10**-5 <= bounds["intercept"][1]
def test_bounds_slsqp(self):
guess_slope = 1.1
guess_intercept = 0.0
bounds = {"slope": (-1.5, 5.0), "intercept": (-1.0, 1.0)}
line_model = models.Linear1D(guess_slope, guess_intercept, bounds=bounds)
fitter = fitting.SLSQPLSQFitter()
with pytest.warns(
AstropyUserWarning, match="consider using linear fitting methods"
):
model = fitter(line_model, self.x, self.y)
slope = model.slope.value
intercept = model.intercept.value
assert slope + 10**-5 >= bounds["slope"][0]
assert slope - 10**-5 <= bounds["slope"][1]
assert intercept + 10**-5 >= bounds["intercept"][0]
assert intercept - 10**-5 <= bounds["intercept"][1]
@pytest.mark.filterwarnings("ignore:The fit may be unsuccessful")
@pytest.mark.parametrize("fitter", fitters)
def test_bounds_gauss2d_lsq(self, fitter):
fitter = fitter()
X, Y = np.meshgrid(np.arange(11), np.arange(11))
bounds = {
"x_mean": [0.0, 11.0],
"y_mean": [0.0, 11.0],
"x_stddev": [1.0, 4],
"y_stddev": [1.0, 4],
}
gauss = models.Gaussian2D(
amplitude=10.0,
x_mean=5.0,
y_mean=5.0,
x_stddev=4.0,
y_stddev=4.0,
theta=0.5,
bounds=bounds,
)
if isinstance(fitter, fitting.TRFLSQFitter):
ctx = np.errstate(invalid="ignore", divide="ignore")
else:
ctx = nullcontext()
with ctx:
model = fitter(gauss, X, Y, self.data)
x_mean = model.x_mean.value
y_mean = model.y_mean.value
x_stddev = model.x_stddev.value
y_stddev = model.y_stddev.value
assert x_mean + 10**-5 >= bounds["x_mean"][0]
assert x_mean - 10**-5 <= bounds["x_mean"][1]
assert y_mean + 10**-5 >= bounds["y_mean"][0]
assert y_mean - 10**-5 <= bounds["y_mean"][1]
assert x_stddev + 10**-5 >= bounds["x_stddev"][0]
assert x_stddev - 10**-5 <= bounds["x_stddev"][1]
assert y_stddev + 10**-5 >= bounds["y_stddev"][0]
assert y_stddev - 10**-5 <= bounds["y_stddev"][1]
def test_bounds_gauss2d_slsqp(self):
X, Y = np.meshgrid(np.arange(11), np.arange(11))
bounds = {
"x_mean": [0.0, 11.0],
"y_mean": [0.0, 11.0],
"x_stddev": [1.0, 4],
"y_stddev": [1.0, 4],
}
gauss = models.Gaussian2D(
amplitude=10.0,
x_mean=5.0,
y_mean=5.0,
x_stddev=4.0,
y_stddev=4.0,
theta=0.5,
bounds=bounds,
)
gauss_fit = fitting.SLSQPLSQFitter()
# Warning does not appear in all the CI jobs.
# TODO: Rewrite the test for more consistent warning behavior.
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
message=r".*The fit may be unsuccessful.*",
category=AstropyUserWarning,
)
model = gauss_fit(gauss, X, Y, self.data)
x_mean = model.x_mean.value
y_mean = model.y_mean.value
x_stddev = model.x_stddev.value
y_stddev = model.y_stddev.value
assert x_mean + 10**-5 >= bounds["x_mean"][0]
assert x_mean - 10**-5 <= bounds["x_mean"][1]
assert y_mean + 10**-5 >= bounds["y_mean"][0]
assert y_mean - 10**-5 <= bounds["y_mean"][1]
assert x_stddev + 10**-5 >= bounds["x_stddev"][0]
assert x_stddev - 10**-5 <= bounds["x_stddev"][1]
assert y_stddev + 10**-5 >= bounds["y_stddev"][0]
assert y_stddev - 10**-5 <= bounds["y_stddev"][1]
| TestBounds |
python | numpy__numpy | numpy/_core/tests/test_scalar_ctors.py | {
"start": 2807,
"end": 6693
} | class ____:
""" gh-15467 and gh-19125 """
def _do_test(self, t1, t2, arg=2):
if arg is None:
x = t1()
elif isinstance(arg, tuple):
if t1 is np.clongdouble:
pytest.xfail("creating a clongdouble from real and "
"imaginary parts isn't supported")
x = t1(*arg)
else:
x = t1(arg)
arr = np.array(x, dtype=t2)
# type should be preserved exactly
if t2 is None:
assert arr.dtype.type is t1
else:
assert arr.dtype.type is t2
@pytest.mark.parametrize('t1', int_types + uint_types)
@pytest.mark.parametrize('t2', int_types + uint_types + [None])
def test_integers(self, t1, t2):
return self._do_test(t1, t2)
@pytest.mark.parametrize('t1', float_types)
@pytest.mark.parametrize('t2', float_types + [None])
def test_reals(self, t1, t2):
return self._do_test(t1, t2)
@pytest.mark.parametrize('t1', cfloat_types)
@pytest.mark.parametrize('t2', cfloat_types + [None])
@pytest.mark.parametrize('arg', [2, 1 + 3j, (1, 2), None])
def test_complex(self, t1, t2, arg):
self._do_test(t1, t2, arg)
@pytest.mark.parametrize('t', cfloat_types)
def test_complex_errors(self, t):
with pytest.raises(TypeError):
t(1j, 1j)
with pytest.raises(TypeError):
t(1, None)
with pytest.raises(TypeError):
t(None, 1)
@pytest.mark.parametrize("length",
[5, np.int8(5), np.array(5, dtype=np.uint16)])
def test_void_via_length(length):
res = np.void(length)
assert type(res) is np.void
assert res.item() == b"\0" * 5
assert res.dtype == "V5"
@pytest.mark.parametrize("bytes_",
[b"spam", np.array(567.)])
def test_void_from_byteslike(bytes_):
res = np.void(bytes_)
expected = bytes(bytes_)
assert type(res) is np.void
assert res.item() == expected
# Passing dtype can extend it (this is how filling works)
res = np.void(bytes_, dtype="V100")
assert type(res) is np.void
assert res.item()[:len(expected)] == expected
assert res.item()[len(expected):] == b"\0" * (res.nbytes - len(expected))
# As well as shorten:
res = np.void(bytes_, dtype="V4")
assert type(res) is np.void
assert res.item() == expected[:4]
def test_void_arraylike_trumps_byteslike():
# The memoryview is converted as an array-like of shape (18,)
# rather than a single bytes-like of that length.
m = memoryview(b"just one mintleaf?")
res = np.void(m)
assert type(res) is np.ndarray
assert res.dtype == "V1"
assert res.shape == (18,)
def test_void_dtype_arg():
# Basic test for the dtype argument (positional and keyword)
res = np.void((1, 2), dtype="i,i")
assert res.item() == (1, 2)
res = np.void((2, 3), "i,i")
assert res.item() == (2, 3)
@pytest.mark.parametrize("data",
[5, np.int8(5), np.array(5, dtype=np.uint16)])
def test_void_from_integer_with_dtype(data):
# The "length" meaning is ignored, rather data is used:
res = np.void(data, dtype="i,i")
assert type(res) is np.void
assert res.dtype == "i,i"
assert res["f0"] == 5 and res["f1"] == 5
def test_void_from_structure():
dtype = np.dtype([('s', [('f', 'f8'), ('u', 'U1')]), ('i', 'i2')])
data = np.array(((1., 'a'), 2), dtype=dtype)
res = np.void(data[()], dtype=dtype)
assert type(res) is np.void
assert res.dtype == dtype
assert res == data[()]
def test_void_bad_dtype():
with pytest.raises(TypeError,
match="void: descr must be a `void.*int64"):
np.void(4, dtype="i8")
# Subarray dtype (with shape `(4,)` is rejected):
with pytest.raises(TypeError,
match=r"void: descr must be a `void.*\(4,\)"):
np.void(4, dtype="4i")
| TestArrayFromScalar |
python | kamyu104__LeetCode-Solutions | Python/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows.py | {
"start": 966,
"end": 2022
} | class ____(object):
def kthSmallest(self, mat, k):
"""
:type mat: List[List[int]]
:type k: int
:rtype: int
"""
def countArraysHaveSumLessOrEqual(mat, k, r, target): # Time: O(k + m) ~ O(k * m)
if target < 0:
return 0
if r == len(mat):
return 1
result = 0
for c in xrange(len(mat[0])):
cnt = countArraysHaveSumLessOrEqual(mat, k-result, r+1, target-mat[r][c])
if not cnt:
break
result += cnt
if result > k:
break
return result
max_num = max(x for row in mat for x in row)
left, right = len(mat), len(mat)*max_num
while left <= right:
mid = left + (right-left)//2
cnt = countArraysHaveSumLessOrEqual(mat, k, 0, mid)
if cnt >= k:
right = mid-1
else:
left = mid+1
return left
| Solution2 |
python | getsentry__sentry | src/sentry/workflow_engine/types.py | {
"start": 12139,
"end": 12343
} | class ____(TypedDict):
id: int | None
comparison: int
type: Condition
condition_result: DetectorPriorityLevel
condition_group_id: int
# TODO - Move this to snuba module
| DataConditionType |
python | pandas-dev__pandas | scripts/tests/test_validate_docstrings.py | {
"start": 95,
"end": 2121
} | class ____:
"""Everything here has a bad docstring"""
def private_classes(self) -> None:
"""
This mentions NDFrame, which is not correct.
"""
def prefix_pandas(self) -> None:
"""
Have `pandas` prefix in See Also section.
See Also
--------
pandas.Series.rename : Alter Series index labels or name.
DataFrame.head : The first `n` rows of the caller object.
"""
def redundant_import(self, paramx=None, paramy=None) -> None:
"""
A sample DataFrame method.
Should not import numpy and pandas.
Examples
--------
>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame(np.ones((3, 3)),
... columns=('a', 'b', 'c'))
>>> df.all(axis=1)
0 True
1 True
2 True
dtype: bool
>>> df.all(bool_only=True)
Series([], dtype: bool)
"""
def unused_import(self) -> None:
"""
Examples
--------
>>> import pandas as pdf
>>> df = pd.DataFrame(np.ones((3, 3)), columns=('a', 'b', 'c'))
"""
def missing_whitespace_around_arithmetic_operator(self) -> None:
"""
Examples
--------
>>> 2+5
7
"""
def indentation_is_not_a_multiple_of_four(self) -> None:
"""
Examples
--------
>>> if 2 + 5:
... pass
"""
def missing_whitespace_after_comma(self) -> None:
"""
Examples
--------
>>> df = pd.DataFrame(np.ones((3,3)),columns=('a','b', 'c'))
"""
def write_array_like_with_hyphen_not_underscore(self) -> None:
"""
In docstrings, use array-like over array_like
"""
def leftover_files(self) -> None:
"""
Examples
--------
>>> import pathlib
>>> pathlib.Path("foo.txt").touch()
"""
# fmt: on
| BadDocstrings |
python | numpy__numpy | benchmarks/benchmarks/bench_function_base.py | {
"start": 7687,
"end": 8165
} | class ____(Benchmark):
def setup(self):
# quicksort median of 3 worst case
self.worst = np.arange(1000000)
x = self.worst
while x.size > 3:
mid = x.size // 2
x[mid], x[-2] = x[-2], x[mid]
x = x[:-2]
def time_sort_worst(self):
np.sort(self.worst)
# Retain old benchmark name for backward compatibility
time_sort_worst.benchmark_name = "bench_function_base.Sort.time_sort_worst"
| SortWorst |
python | encode__django-rest-framework | tests/test_validators.py | {
"start": 5014,
"end": 5216
} | class ____(models.Model):
race_name = models.CharField(max_length=100)
position = models.IntegerField()
class Meta:
unique_together = ('race_name', 'position')
| UniquenessTogetherModel |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py | {
"start": 12784,
"end": 13492
} | class ____(Value):
__slots__ = ('loc', 'value',)
_fields = ('value',)
def __init__(self, value, loc=None):
self.loc = loc
self.value = value
def __eq__(self, other):
return (
self is other or (
isinstance(other, StringValue) and
# self.loc == other.loc and
self.value == other.value
)
)
def __repr__(self):
return ('StringValue('
'value={self.value!r}'
')').format(self=self)
def __copy__(self):
return type(self)(
self.value,
self.loc
)
def __hash__(self):
return id(self)
| StringValue |
python | scipy__scipy | scipy/signal/tests/test_windows.py | {
"start": 7987,
"end": 8889
} | class ____:
def test_basic(self, xp):
xp_assert_close(windows.bohman(6, xp=xp),
xp.asarray([0, 0.1791238937062839, 0.8343114522576858,
0.8343114522576858, 0.1791238937062838, 0],
dtype=xp.float64))
xp_assert_close(windows.bohman(7, sym=True, xp=xp),
xp.asarray([0, 0.1089977810442293, 0.6089977810442293, 1.0,
0.6089977810442295, 0.1089977810442293, 0],
dtype=xp.float64))
xp_assert_close(windows.bohman(6, False, xp=xp),
xp.asarray([0, 0.1089977810442293, 0.6089977810442293, 1.0,
0.6089977810442295, 0.1089977810442293],
dtype=xp.float64))
@make_xp_test_case(windows.boxcar)
| TestBohman |
python | openai__openai-python | src/openai/resources/beta/realtime/realtime.py | {
"start": 31415,
"end": 32186
} | class ____(BaseRealtimeConnectionResource):
def clear(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None:
"""**WebRTC Only:** Emit to cut off the current audio response.
This will trigger the server to
stop generating audio and emit a `output_audio_buffer.cleared` event. This
event should be preceded by a `response.cancel` client event to stop the
generation of the current response.
[Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc).
"""
self._connection.send(
cast(RealtimeClientEventParam, strip_not_given({"type": "output_audio_buffer.clear", "event_id": event_id}))
)
| RealtimeOutputAudioBufferResource |
python | django-import-export__django-import-export | tests/core/tests/test_fields.py | {
"start": 363,
"end": 7050
} | class ____(TestCase):
def setUp(self):
self.field = fields.Field(column_name="name", attribute="name")
self.row = {
"name": "Foo",
}
self.obj = Obj(name="Foo", date=date(2012, 8, 13))
def test_clean(self):
self.assertEqual(self.field.clean(self.row), self.row["name"])
def test_clean_raises_KeyError(self):
self.field.column_name = "x"
with self.assertRaisesRegex(
KeyError,
"Column 'x' not found in dataset. Available columns are: \\['name'\\]",
):
self.field.clean(self.row)
def test_export(self):
self.assertEqual(self.field.export(self.obj), self.row["name"])
def test_export_none(self):
# 1872
instance = Obj(name=None)
self.assertEqual("", self.field.export(instance))
def test_save(self):
self.row["name"] = "foo"
self.field.save(self.obj, self.row)
self.assertEqual(self.obj.name, "foo")
def test_save_follow(self):
class Test:
class name:
class follow:
me = "bar"
test = Test()
field = fields.Field(column_name="name", attribute="name__follow__me")
row = {"name": "foo"}
field.save(test, row)
self.assertEqual(test.name.follow.me, "foo")
def test_following_attribute(self):
field = fields.Field(attribute="other_obj__name")
obj2 = Obj(name="bar")
self.obj.other_obj = obj2
self.assertEqual(field.export(self.obj), "bar")
def test_default(self):
field = fields.Field(default=1, column_name="name")
self.assertEqual(field.clean({"name": None}), 1)
def test_default_falsy_values(self):
field = fields.Field(default=1, column_name="name")
self.assertEqual(field.clean({"name": 0}), 0)
def test_default_falsy_values_without_default(self):
field = fields.Field(column_name="name")
self.assertEqual(field.clean({"name": 0}), 0)
def test_saves_null_values(self):
field = fields.Field(
column_name="name", attribute="name", saves_null_values=False
)
row = {
"name": None,
}
field.save(self.obj, row)
self.assertEqual(self.obj.name, "Foo")
self.field.save(self.obj, row)
self.assertIsNone(self.obj.name)
def test_repr(self):
self.assertEqual(repr(self.field), "<import_export.fields.Field: name>")
self.field.column_name = None
self.assertEqual(repr(self.field), "<import_export.fields.Field>")
def testget_dehydrate_method_default(self):
field = fields.Field(attribute="foo", column_name="bar")
# `field_name` is the variable name defined in `Resource`
resource_field_name = "field"
method_name = field.get_dehydrate_method(resource_field_name)
self.assertEqual(f"dehydrate_{resource_field_name}", method_name)
def testget_dehydrate_method_with_custom_method_name(self):
custom_dehydrate_method = "custom_method_name"
field = fields.Field(
attribute="foo", column_name="bar", dehydrate_method=custom_dehydrate_method
)
resource_field_name = "field"
method_name = field.get_dehydrate_method(resource_field_name)
self.assertEqual(method_name, custom_dehydrate_method)
def test_get_dehydrate_method_with_callable(self):
field = fields.Field(
attribute="foo", column_name="bar", dehydrate_method=lambda x: x
)
resource_field_name = "field"
method = field.get_dehydrate_method(resource_field_name)
self.assertTrue(callable(method))
def testget_dehydrate_method_without_params_raises_attribute_error(self):
field = fields.Field(attribute="foo", column_name="bar")
self.assertRaises(FieldError, field.get_dehydrate_method)
def test_m2m_add_true(self):
m2m_related_manager = mock.Mock(spec=["add", "set", "all"])
m2m_related_manager.all.return_value = []
self.obj.aliases = m2m_related_manager
field = fields.Field(column_name="aliases", attribute="aliases", m2m_add=True)
row = {
"aliases": ["Foo", "Bar"],
}
field.save(self.obj, row, is_m2m=True)
self.assertEqual(m2m_related_manager.add.call_count, 1)
self.assertEqual(m2m_related_manager.set.call_count, 0)
m2m_related_manager.add.assert_called_once_with("Foo", "Bar")
row = {
"aliases": ["apple"],
}
field.save(self.obj, row, is_m2m=True)
m2m_related_manager.add.assert_called_with("apple")
def test_m2m_add_False(self):
m2m_related_manager = mock.Mock(spec=["add", "set", "all"])
self.obj.aliases = m2m_related_manager
field = fields.Field(column_name="aliases", attribute="aliases")
row = {
"aliases": ["Foo", "Bar"],
}
field.save(self.obj, row, is_m2m=True)
self.assertEqual(m2m_related_manager.add.call_count, 0)
self.assertEqual(m2m_related_manager.set.call_count, 1)
m2m_related_manager.set.assert_called_once_with(["Foo", "Bar"])
def test_get_value_with_callable(self):
class CallableValue:
def __call__(self):
return "some val"
self.obj.name = CallableValue()
val = self.field.get_value(self.obj)
self.assertEqual("some val", val)
def test_get_value_with_no_attribute(self):
self.field.attribute = None
self.assertIsNone(self.field.get_value(self.obj))
def test_import_null_django_CharField_saved_as_empty_string(self):
# issue 1485
resource = BookResource()
self.assertTrue(resource._meta.model.author_email.field.blank)
self.assertFalse(resource._meta.model.author_email.field.null)
headers = ["id", "author_email"]
row = [1, None]
dataset = tablib.Dataset(row, headers=headers)
resource.import_data(dataset, raise_errors=True)
book = Book.objects.get(id=1)
self.assertEqual("", book.author_email)
def test_import_empty_django_CharField_saved_as_empty_string(self):
resource = BookResource()
self.assertTrue(resource._meta.model.author_email.field.blank)
self.assertFalse(resource._meta.model.author_email.field.null)
headers = ["id", "author_email"]
row = [1, ""]
dataset = tablib.Dataset(row, headers=headers)
resource.import_data(dataset, raise_errors=True)
book = Book.objects.get(id=1)
self.assertEqual("", book.author_email)
| FieldTest |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_lookup.py | {
"start": 20360,
"end": 21043
} | class ____:
def __init__(self, nxt: typing.Optional["A_with_default"] = None):
self.nxt = nxt
def __repr__(self):
return f"B_with_default({self.nxt})"
@given(nxt=st.from_type(A_with_default))
def test_resolving_mutually_recursive_types_with_defaults(nxt):
# This test is required to cover the raise/except part of the recursion
# check in from_type, see
# https://github.com/HypothesisWorks/hypothesis/issues/3655. If the
# skip-nondefaulted-args check is removed, this test becomes redundant.
i = 0
while nxt:
assert isinstance(nxt, [A_with_default, B_with_default][i % 2])
nxt = nxt.nxt
i += 1
| B_with_default |
python | ray-project__ray | python/ray/air/tests/execution/test_e2e_tune_flow.py | {
"start": 1473,
"end": 6969
} | class ____:
"""This is a Ray Tune-like execution flow.
- We want to run 10 actors in total ("trials")
- Each actor collects 11 results sequentially
- We schedule up to 6 actors at the same time
- Every step, we see if we should add any new actors
- Otherwise, we just yield control to the event manager and process events one
by one
- When an actor is started, start training flow
- When a result comes in, schedule next future
- If this is the 11th result, stop actor
- When the last actor is stopped, set state to finished
- When an actor fails, restart
- When a task fails, stop actor, and restart
"""
def __init__(
self, actor_manager: RayActorManager, errors: Optional[List[str]] = None
):
self._actor_manager = actor_manager
self._finished = False
self._actors_to_run = 10
self._actors_started = 0
self._actors_stopped = 0
self._max_pending = 6
self._actor_to_id = {}
self._results = defaultdict(list)
self._errors = errors
def maybe_add_actors(self):
if self._actors_started >= self._actors_to_run:
return
if self._actor_manager.num_pending_actors >= self._max_pending:
return
error_kwargs = {}
if self._errors:
error = random.choice(self._errors)
error_kwargs[error] = True
actor_id = self._actors_started
print("Actor", actor_id, "will be failing with", error_kwargs)
tracked_actor = self._actor_manager.add_actor(
cls=Actor,
kwargs={"id": actor_id, **error_kwargs},
resource_request=ResourceRequest([{"CPU": 1}]),
on_start=self.actor_started,
on_stop=self.actor_stopped,
on_error=self.actor_error,
)
self._actor_to_id[tracked_actor] = actor_id
self._actors_started += 1
def actor_started(self, tracked_actor: TrackedActor):
self._actor_manager.schedule_actor_task(
tracked_actor,
"run",
kwargs={"value": 0},
on_error=self.task_error,
on_result=self.task_result,
)
def actor_stopped(self, tracked_actor: TrackedActor):
self._actors_stopped += 1
self._finished = self._actors_stopped >= self._actors_to_run
def actor_error(self, tracked_actor: TrackedActor, exception: Exception):
actor_id = self._actor_to_id.pop(tracked_actor)
replacement_actor = self._actor_manager.add_actor(
cls=Actor,
kwargs={
"id": actor_id,
"actor_error_init": False,
"actor_error_task": False,
"task_error": False,
},
resource_request=ResourceRequest([{"CPU": 1}]),
on_start=self.actor_started,
on_stop=self.actor_stopped,
on_error=self.actor_error,
)
self._actor_to_id[replacement_actor] = actor_id
def task_result(self, tracked_actor: TrackedActor, result: float):
actor_id = self._actor_to_id[tracked_actor]
self._results[actor_id].append(result)
if result == 10:
self._actor_manager.remove_actor(tracked_actor)
else:
self._actor_manager.schedule_actor_task(
tracked_actor,
"run",
kwargs={"value": result + 1},
on_result=self.task_result,
on_error=self.task_error,
)
def task_error(self, tracked_actor: TrackedActor, exception: Exception):
if isinstance(exception, RayActorError):
return
self._actors_stopped -= 1 # account for extra stop
self._actor_manager.remove_actor(tracked_actor)
actor_id = self._actor_to_id.pop(tracked_actor)
replacement_actor = self._actor_manager.add_actor(
cls=Actor,
kwargs={
"id": actor_id,
"actor_error_init": False,
"actor_error_task": False,
"task_error": False,
},
resource_request=ResourceRequest([{"CPU": 1}]),
on_start=self.actor_started,
on_stop=self.actor_stopped,
on_error=self.actor_error,
)
self._actor_to_id[replacement_actor] = actor_id
def run(self):
while not self._finished:
self.maybe_add_actors()
self._actor_manager.next(timeout=1)
def get_results(self) -> Dict[int, List[float]]:
return self._results
@pytest.mark.parametrize(
"resource_manager_cls", [FixedResourceManager, PlacementGroupResourceManager]
)
@pytest.mark.parametrize(
"errors",
[
None,
"actor_error_init",
"actor_error_task",
"task_error",
# Chaos - every actor fails somehow, but in different ways
["actor_error_init", "actor_error_task", "task_error"],
],
)
def test_e2e(ray_start_4_cpus, resource_manager_cls, errors):
actor_manager = RayActorManager(resource_manager=resource_manager_cls())
if errors and isinstance(errors, str):
errors = [errors]
flow = TuneFlow(actor_manager=actor_manager, errors=errors)
flow.run()
results = flow.get_results()
assert all(res[-1] == 10 for res in results.values()), results
if __name__ == "__main__":
import sys
sys.exit(pytest.main(["-v", __file__]))
| TuneFlow |
python | apache__airflow | airflow-core/tests/unit/utils/log/test_file_processor_handler.py | {
"start": 1023,
"end": 4413
} | class ____:
def setup_method(self):
self.base_log_folder = "/tmp/log_test"
self.filename = "{filename}"
self.filename_template = "{{ filename }}.log"
self.dag_dir = "/dags"
def test_non_template(self):
date = timezone.utcnow().strftime("%Y-%m-%d")
handler = FileProcessorHandler(base_log_folder=self.base_log_folder, filename_template=self.filename)
handler.dag_dir = self.dag_dir
path = os.path.join(self.base_log_folder, "latest")
assert os.path.islink(path)
assert os.path.basename(os.readlink(path)) == date
handler.set_context(filename=os.path.join(self.dag_dir, "logfile"))
assert os.path.exists(os.path.join(path, "logfile"))
def test_template(self):
date = timezone.utcnow().strftime("%Y-%m-%d")
handler = FileProcessorHandler(
base_log_folder=self.base_log_folder, filename_template=self.filename_template
)
handler.dag_dir = self.dag_dir
path = os.path.join(self.base_log_folder, "latest")
assert os.path.islink(path)
assert os.path.basename(os.readlink(path)) == date
handler.set_context(filename=os.path.join(self.dag_dir, "logfile"))
assert os.path.exists(os.path.join(path, "logfile.log"))
def test_symlink_latest_log_directory(self):
handler = FileProcessorHandler(base_log_folder=self.base_log_folder, filename_template=self.filename)
handler.dag_dir = self.dag_dir
date1 = (timezone.utcnow() + timedelta(days=1)).strftime("%Y-%m-%d")
date2 = (timezone.utcnow() + timedelta(days=2)).strftime("%Y-%m-%d")
path1 = os.path.join(self.base_log_folder, date1, "log1")
path2 = os.path.join(self.base_log_folder, date1, "log2")
if os.path.exists(path1):
os.remove(path1)
if os.path.exists(path2):
os.remove(path2)
link = os.path.join(self.base_log_folder, "latest")
with time_machine.travel(date1, tick=False):
handler.set_context(filename=os.path.join(self.dag_dir, "log1"))
assert os.path.islink(link)
assert os.path.basename(os.path.realpath(link)) == date1
assert os.path.exists(os.path.join(link, "log1"))
with time_machine.travel(date2, tick=False):
handler.set_context(filename=os.path.join(self.dag_dir, "log2"))
assert os.path.islink(link)
assert os.path.basename(os.path.realpath(link)) == date2
assert os.path.exists(os.path.join(link, "log2"))
def test_symlink_latest_log_directory_exists(self):
handler = FileProcessorHandler(base_log_folder=self.base_log_folder, filename_template=self.filename)
handler.dag_dir = self.dag_dir
date1 = (timezone.utcnow() + timedelta(days=1)).strftime("%Y-%m-%d")
path1 = os.path.join(self.base_log_folder, date1, "log1")
if os.path.exists(path1):
os.remove(path1)
link = os.path.join(self.base_log_folder, "latest")
if os.path.exists(link):
os.remove(link)
os.makedirs(link)
with time_machine.travel(date1, tick=False):
handler.set_context(filename=os.path.join(self.dag_dir, "log1"))
def teardown_method(self):
shutil.rmtree(self.base_log_folder, ignore_errors=True)
| TestFileProcessorHandler |
python | plotly__plotly.py | plotly/graph_objs/layout/mapbox/layer/_line.py | {
"start": 235,
"end": 3897
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.mapbox.layer"
_path_str = "layout.mapbox.layer.line"
_valid_props = {"dash", "dashsrc", "width"}
@property
def dash(self):
"""
Sets the length of dashes and gaps (mapbox.layer.paint.line-
dasharray). Has an effect only when `type` is set to "line".
The 'dash' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["dash"]
@dash.setter
def dash(self, val):
self["dash"] = val
@property
def dashsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `dash`.
The 'dashsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["dashsrc"]
@dashsrc.setter
def dashsrc(self, val):
self["dashsrc"] = val
@property
def width(self):
"""
Sets the line width (mapbox.layer.paint.line-width). Has an
effect only when `type` is set to "line".
The 'width' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["width"]
@width.setter
def width(self, val):
self["width"] = val
@property
def _prop_descriptions(self):
return """\
dash
Sets the length of dashes and gaps
(mapbox.layer.paint.line-dasharray). Has an effect only
when `type` is set to "line".
dashsrc
Sets the source reference on Chart Studio Cloud for
`dash`.
width
Sets the line width (mapbox.layer.paint.line-width).
Has an effect only when `type` is set to "line".
"""
def __init__(self, arg=None, dash=None, dashsrc=None, width=None, **kwargs):
"""
Construct a new Line object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.mapbox.layer.Line`
dash
Sets the length of dashes and gaps
(mapbox.layer.paint.line-dasharray). Has an effect only
when `type` is set to "line".
dashsrc
Sets the source reference on Chart Studio Cloud for
`dash`.
width
Sets the line width (mapbox.layer.paint.line-width).
Has an effect only when `type` is set to "line".
Returns
-------
Line
"""
super().__init__("line")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.layout.mapbox.layer.Line
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.mapbox.layer.Line`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("dash", arg, dash)
self._set_property("dashsrc", arg, dashsrc)
self._set_property("width", arg, width)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Line |
python | ipython__ipython | IPython/lib/pretty.py | {
"start": 22842,
"end": 30722
} | class ____:
def __init__(self, value):
self.value = value
def _repr_pretty_(self, p, cycle):
done_one = False
for flag in (
"IGNORECASE",
"LOCALE",
"MULTILINE",
"DOTALL",
"UNICODE",
"VERBOSE",
"DEBUG",
):
if self.value & getattr(re, flag):
if done_one:
p.text('|')
p.text('re.' + flag)
done_one = True
def _re_pattern_pprint(obj, p, cycle):
"""The pprint function for regular expression patterns."""
re_compile = CallExpression.factory('re.compile')
if obj.flags:
p.pretty(re_compile(RawStringLiteral(obj.pattern), _ReFlags(obj.flags)))
else:
p.pretty(re_compile(RawStringLiteral(obj.pattern)))
def _types_simplenamespace_pprint(obj, p, cycle):
"""The pprint function for types.SimpleNamespace."""
namespace = CallExpression.factory('namespace')
if cycle:
p.pretty(namespace(RawText("...")))
else:
p.pretty(namespace(**obj.__dict__))
def _type_pprint(obj, p, cycle):
"""The pprint for classes and types."""
# Heap allocated types might not have the module attribute,
# and others may set it to None.
# Checks for a __repr__ override in the metaclass. Can't compare the
# type(obj).__repr__ directly because in PyPy the representation function
# inherited from type isn't the same type.__repr__
if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
_repr_pprint(obj, p, cycle)
return
mod = _safe_getattr(obj, '__module__', None)
try:
name = obj.__qualname__
if not isinstance(name, str):
# This can happen if the type implements __qualname__ as a property
# or other descriptor in Python 2.
raise Exception("Try __name__")
except Exception:
name = obj.__name__
if not isinstance(name, str):
name = '<unknown type>'
if mod in (None, '__builtin__', 'builtins', 'exceptions'):
p.text(name)
else:
p.text(mod + '.' + name)
def _repr_pprint(obj, p, cycle):
"""A pprint that just redirects to the normal repr function."""
# Find newlines and replace them with p.break_()
output = repr(obj)
lines = output.splitlines()
with p.group():
for idx, output_line in enumerate(lines):
if idx:
p.break_()
p.text(output_line)
def _function_pprint(obj, p, cycle):
"""Base pprint for all functions and builtin functions."""
name = _safe_getattr(obj, '__qualname__', obj.__name__)
mod = obj.__module__
if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
name = mod + '.' + name
try:
func_def = name + str(signature(obj))
except ValueError:
func_def = name
p.text('<function %s>' % func_def)
def _exception_pprint(obj, p, cycle):
"""Base pprint for all exceptions."""
name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
if obj.__class__.__module__ not in ('exceptions', 'builtins'):
name = '%s.%s' % (obj.__class__.__module__, name)
p.pretty(CallExpression(name, *getattr(obj, 'args', ())))
#: the exception base
_exception_base: type
try:
_exception_base = BaseException
except NameError:
_exception_base = Exception
#: printers for builtin types
_type_pprinters = {
int: _repr_pprint,
float: _repr_pprint,
str: _repr_pprint,
tuple: _seq_pprinter_factory('(', ')'),
list: _seq_pprinter_factory('[', ']'),
dict: _dict_pprinter_factory('{', '}'),
set: _set_pprinter_factory('{', '}'),
frozenset: _set_pprinter_factory('frozenset({', '})'),
super: _super_pprint,
_re_pattern_type: _re_pattern_pprint,
type: _type_pprint,
types.FunctionType: _function_pprint,
types.BuiltinFunctionType: _function_pprint,
types.MethodType: _repr_pprint,
types.SimpleNamespace: _types_simplenamespace_pprint,
datetime.datetime: _repr_pprint,
datetime.timedelta: _repr_pprint,
_exception_base: _exception_pprint
}
# render os.environ like a dict
_env_type = type(os.environ)
# future-proof in case os.environ becomes a plain dict?
if _env_type is not dict:
_type_pprinters[_env_type] = _dict_pprinter_factory('environ{', '}')
_type_pprinters[types.MappingProxyType] = _dict_pprinter_factory("mappingproxy({", "})")
_type_pprinters[slice] = _repr_pprint
_type_pprinters[range] = _repr_pprint
_type_pprinters[bytes] = _repr_pprint
#: printers for types specified by name
_deferred_type_pprinters: Dict = {}
def for_type(typ, func):
"""
Add a pretty printer for a given type.
"""
oldfunc = _type_pprinters.get(typ, None)
if func is not None:
# To support easy restoration of old pprinters, we need to ignore Nones.
_type_pprinters[typ] = func
return oldfunc
def for_type_by_name(type_module, type_name, func):
"""
Add a pretty printer for a type specified by the module and name of a type
rather than the type object itself.
"""
key = (type_module, type_name)
oldfunc = _deferred_type_pprinters.get(key, None)
if func is not None:
# To support easy restoration of old pprinters, we need to ignore Nones.
_deferred_type_pprinters[key] = func
return oldfunc
#: printers for the default singletons
_singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
NotImplemented]), _repr_pprint)
def _defaultdict_pprint(obj, p, cycle):
cls_ctor = CallExpression.factory(obj.__class__.__name__)
if cycle:
p.pretty(cls_ctor(RawText("...")))
else:
p.pretty(cls_ctor(obj.default_factory, dict(obj)))
def _ordereddict_pprint(obj, p, cycle):
cls_ctor = CallExpression.factory(obj.__class__.__name__)
if cycle:
p.pretty(cls_ctor(RawText("...")))
elif len(obj):
p.pretty(cls_ctor(list(obj.items())))
else:
p.pretty(cls_ctor())
def _deque_pprint(obj, p, cycle):
cls_ctor = CallExpression.factory(obj.__class__.__name__)
if cycle:
p.pretty(cls_ctor(RawText("...")))
elif obj.maxlen is not None:
p.pretty(cls_ctor(list(obj), maxlen=obj.maxlen))
else:
p.pretty(cls_ctor(list(obj)))
def _counter_pprint(obj, p, cycle):
cls_ctor = CallExpression.factory(obj.__class__.__name__)
if cycle:
p.pretty(cls_ctor(RawText("...")))
elif len(obj):
p.pretty(cls_ctor(dict(obj.most_common())))
else:
p.pretty(cls_ctor())
def _userlist_pprint(obj, p, cycle):
cls_ctor = CallExpression.factory(obj.__class__.__name__)
if cycle:
p.pretty(cls_ctor(RawText("...")))
else:
p.pretty(cls_ctor(obj.data))
for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
for_type_by_name('collections', 'deque', _deque_pprint)
for_type_by_name('collections', 'Counter', _counter_pprint)
for_type_by_name("collections", "UserList", _userlist_pprint)
if __name__ == '__main__':
from random import randrange
class Foo:
def __init__(self):
self.foo = 1
self.bar = re.compile(r'\s+')
self.blub = dict.fromkeys(range(30), randrange(1, 40))
self.hehe = 23424.234234
self.list = ["blub", "blah", self]
def get_foo(self):
print("foo")
pprint(Foo(), verbose=True)
| _ReFlags |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/callbackProtocol10.py | {
"start": 628,
"end": 737
} | class ____(Protocol[T_contra]):
def __call__(self, *args: T_contra, **kwargs: T_contra) -> None: ...
| Proto5 |
python | pallets__markupsafe | src/markupsafe/__init__.py | {
"start": 2255,
"end": 11088
} | class ____(str):
"""A string that is ready to be safely inserted into an HTML or XML
document, either because it was escaped or because it was marked
safe.
Passing an object to the constructor converts it to text and wraps
it to mark it safe without escaping. To escape the text, use the
:meth:`escape` class method instead.
>>> Markup("Hello, <em>World</em>!")
Markup('Hello, <em>World</em>!')
>>> Markup(42)
Markup('42')
>>> Markup.escape("Hello, <em>World</em>!")
Markup('Hello <em>World</em>!')
This implements the ``__html__()`` interface that some frameworks
use. Passing an object that implements ``__html__()`` will wrap the
output of that method, marking it safe.
>>> class Foo:
... def __html__(self):
... return '<a href="/foo">foo</a>'
...
>>> Markup(Foo())
Markup('<a href="/foo">foo</a>')
This is a subclass of :class:`str`. It has the same methods, but
escapes their arguments and returns a ``Markup`` instance.
>>> Markup("<em>%s</em>") % ("foo & bar",)
Markup('<em>foo & bar</em>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup('<em>Hello</em> <foo>')
"""
__slots__ = ()
def __new__(
cls, object: t.Any = "", encoding: str | None = None, errors: str = "strict"
) -> te.Self:
if hasattr(object, "__html__"):
object = object.__html__()
if encoding is None:
return super().__new__(cls, object)
return super().__new__(cls, object, encoding, errors)
def __html__(self, /) -> te.Self:
return self
def __add__(self, value: str | _HasHTML, /) -> te.Self:
if isinstance(value, str) or hasattr(value, "__html__"):
return self.__class__(super().__add__(self.escape(value)))
return NotImplemented
def __radd__(self, value: str | _HasHTML, /) -> te.Self:
if isinstance(value, str) or hasattr(value, "__html__"):
return self.escape(value).__add__(self)
return NotImplemented
def __mul__(self, value: t.SupportsIndex, /) -> te.Self:
return self.__class__(super().__mul__(value))
def __rmul__(self, value: t.SupportsIndex, /) -> te.Self:
return self.__class__(super().__mul__(value))
def __mod__(self, value: t.Any, /) -> te.Self:
if isinstance(value, tuple):
# a tuple of arguments, each wrapped
value = tuple(_MarkupEscapeHelper(x, self.escape) for x in value)
elif hasattr(type(value), "__getitem__") and not isinstance(value, str):
# a mapping of arguments, wrapped
value = _MarkupEscapeHelper(value, self.escape)
else:
# a single argument, wrapped with the helper and a tuple
value = (_MarkupEscapeHelper(value, self.escape),)
return self.__class__(super().__mod__(value))
def __repr__(self, /) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
def join(self, iterable: cabc.Iterable[str | _HasHTML], /) -> te.Self:
return self.__class__(super().join(map(self.escape, iterable)))
def split( # type: ignore[override]
self, /, sep: str | None = None, maxsplit: t.SupportsIndex = -1
) -> list[te.Self]:
return [self.__class__(v) for v in super().split(sep, maxsplit)]
def rsplit( # type: ignore[override]
self, /, sep: str | None = None, maxsplit: t.SupportsIndex = -1
) -> list[te.Self]:
return [self.__class__(v) for v in super().rsplit(sep, maxsplit)]
def splitlines( # type: ignore[override]
self, /, keepends: bool = False
) -> list[te.Self]:
return [self.__class__(v) for v in super().splitlines(keepends)]
def unescape(self, /) -> str:
"""Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
>>> Markup("Main » <em>About</em>").unescape()
'Main » <em>About</em>'
"""
from html import unescape
return unescape(str(self))
def striptags(self, /) -> str:
""":meth:`unescape` the markup, remove tags, and normalize
whitespace to single spaces.
>>> Markup("Main »\t<em>About</em>").striptags()
'Main » About'
"""
value = str(self)
# Look for comments then tags separately. Otherwise, a comment that
# contains a tag would end early, leaving some of the comment behind.
# keep finding comment start marks
while (start := value.find("<!--")) != -1:
# find a comment end mark beyond the start, otherwise stop
if (end := value.find("-->", start)) == -1:
break
value = f"{value[:start]}{value[end + 3 :]}"
# remove tags using the same method
while (start := value.find("<")) != -1:
if (end := value.find(">", start)) == -1:
break
value = f"{value[:start]}{value[end + 1 :]}"
# collapse spaces
value = " ".join(value.split())
return self.__class__(value).unescape()
@classmethod
def escape(cls, s: t.Any, /) -> te.Self:
"""Escape a string. Calls :func:`escape` and ensures that for
subclasses the correct type is returned.
"""
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv # type: ignore[return-value]
def __getitem__(self, key: t.SupportsIndex | slice, /) -> te.Self:
return self.__class__(super().__getitem__(key))
def capitalize(self, /) -> te.Self:
return self.__class__(super().capitalize())
def title(self, /) -> te.Self:
return self.__class__(super().title())
def lower(self, /) -> te.Self:
return self.__class__(super().lower())
def upper(self, /) -> te.Self:
return self.__class__(super().upper())
def replace(self, old: str, new: str, count: t.SupportsIndex = -1, /) -> te.Self:
return self.__class__(super().replace(old, self.escape(new), count))
def ljust(self, width: t.SupportsIndex, fillchar: str = " ", /) -> te.Self:
return self.__class__(super().ljust(width, self.escape(fillchar)))
def rjust(self, width: t.SupportsIndex, fillchar: str = " ", /) -> te.Self:
return self.__class__(super().rjust(width, self.escape(fillchar)))
def lstrip(self, chars: str | None = None, /) -> te.Self:
return self.__class__(super().lstrip(chars))
def rstrip(self, chars: str | None = None, /) -> te.Self:
return self.__class__(super().rstrip(chars))
def center(self, width: t.SupportsIndex, fillchar: str = " ", /) -> te.Self:
return self.__class__(super().center(width, self.escape(fillchar)))
def strip(self, chars: str | None = None, /) -> te.Self:
return self.__class__(super().strip(chars))
def translate(
self,
table: cabc.Mapping[int, str | int | None], # type: ignore[override]
/,
) -> str:
return self.__class__(super().translate(table))
def expandtabs(self, /, tabsize: t.SupportsIndex = 8) -> te.Self:
return self.__class__(super().expandtabs(tabsize))
def swapcase(self, /) -> te.Self:
return self.__class__(super().swapcase())
def zfill(self, width: t.SupportsIndex, /) -> te.Self:
return self.__class__(super().zfill(width))
def casefold(self, /) -> te.Self:
return self.__class__(super().casefold())
def removeprefix(self, prefix: str, /) -> te.Self:
return self.__class__(super().removeprefix(prefix))
def removesuffix(self, suffix: str) -> te.Self:
return self.__class__(super().removesuffix(suffix))
def partition(self, sep: str, /) -> tuple[te.Self, te.Self, te.Self]:
left, sep, right = super().partition(sep)
cls = self.__class__
return cls(left), cls(sep), cls(right)
def rpartition(self, sep: str, /) -> tuple[te.Self, te.Self, te.Self]:
left, sep, right = super().rpartition(sep)
cls = self.__class__
return cls(left), cls(sep), cls(right)
def format(self, *args: t.Any, **kwargs: t.Any) -> te.Self:
formatter = EscapeFormatter(self.escape)
return self.__class__(formatter.vformat(self, args, kwargs))
def format_map(
self,
mapping: cabc.Mapping[str, t.Any], # type: ignore[override]
/,
) -> te.Self:
formatter = EscapeFormatter(self.escape)
return self.__class__(formatter.vformat(self, (), mapping))
def __html_format__(self, format_spec: str, /) -> te.Self:
if format_spec:
raise ValueError("Unsupported format specification for Markup.")
return self
| Markup |
python | realpython__materials | web-scraping-with-scrapy-and-mongodb/books/books/items.py | {
"start": 16,
"end": 150
} | class ____(scrapy.Item):
_id = scrapy.Field()
url = scrapy.Field()
title = scrapy.Field()
price = scrapy.Field()
| BooksItem |
python | kamyu104__LeetCode-Solutions | Python/minimum-money-required-before-transactions.py | {
"start": 63,
"end": 347
} | class ____(object):
def minimumMoney(self, transactions):
"""
:type transactions: List[List[int]]
:rtype: int
"""
return sum(max(a-b, 0) for a, b in transactions)+max(a-max(a-b, 0) for a, b in transactions) # a-max(a-b, 0) = min(a, b)
| Solution |
python | scipy__scipy | scipy/stats/_mannwhitneyu.py | {
"start": 379,
"end": 19573
} | class ____:
'''Distribution of MWU statistic under the null hypothesis'''
def __init__(self, n1, n2):
self._reset(n1, n2)
def set_shapes(self, n1, n2):
n1, n2 = min(n1, n2), max(n1, n2)
if (n1, n2) == (self.n1, self.n2):
return
self.n1 = n1
self.n2 = n2
self.s_array = np.zeros(0, dtype=int)
self.configurations = np.zeros(0, dtype=np.uint64)
def reset(self):
self._reset(self.n1, self.n2)
def _reset(self, n1, n2):
self.n1 = None
self.n2 = None
self.set_shapes(n1, n2)
def pmf(self, k):
# In practice, `pmf` is never called with k > m*n/2.
# If it were, we'd exploit symmetry here:
# k = np.array(k, copy=True)
# k2 = m*n - k
# i = k2 < k
# k[i] = k2[i]
pmfs = self.build_u_freqs_array(np.max(k))
return pmfs[k]
def cdf(self, k):
'''Cumulative distribution function'''
# In practice, `cdf` is never called with k > m*n/2.
# If it were, we'd exploit symmetry here rather than in `sf`
pmfs = self.build_u_freqs_array(np.max(k))
cdfs = np.cumsum(pmfs)
return cdfs[k]
def sf(self, k):
'''Survival function'''
# Note that both CDF and SF include the PMF at k. The p-value is
# calculated from the SF and should include the mass at k, so this
# is desirable
# Use the fact that the distribution is symmetric and sum from the left
kc = np.asarray(self.n1*self.n2 - k) # complement of k
i = k < kc
if np.any(i):
kc[i] = k[i]
cdfs = np.asarray(self.cdf(kc))
cdfs[i] = 1. - cdfs[i] + self.pmf(kc[i])
else:
cdfs = np.asarray(self.cdf(kc))
return cdfs[()]
# build_sigma_array and build_u_freqs_array adapted from code
# by @toobaz with permission. Thanks to @andreasloe for the suggestion.
# See https://github.com/scipy/scipy/pull/4933#issuecomment-1898082691
def build_sigma_array(self, a):
n1, n2 = self.n1, self.n2
if a + 1 <= self.s_array.size:
return self.s_array[1:a+1]
s_array = np.zeros(a + 1, dtype=int)
for d in np.arange(1, n1 + 1):
# All multiples of d, except 0:
indices = np.arange(d, a + 1, d)
# \epsilon_d = 1:
s_array[indices] += d
for d in np.arange(n2 + 1, n2 + n1 + 1):
# All multiples of d, except 0:
indices = np.arange(d, a + 1, d)
# \epsilon_d = -1:
s_array[indices] -= d
# We don't need 0:
self.s_array = s_array
return s_array[1:]
def build_u_freqs_array(self, maxu):
"""
Build all the array of frequencies for u from 0 to maxu.
Assumptions:
n1 <= n2
maxu <= n1 * n2 / 2
"""
n1, n2 = self.n1, self.n2
total = special.binom(n1 + n2, n1)
if maxu + 1 <= self.configurations.size:
return self.configurations[:maxu + 1] / total
s_array = self.build_sigma_array(maxu)
# Start working with ints, for maximum precision and efficiency:
configurations = np.zeros(maxu + 1, dtype=np.uint64)
configurations_is_uint = True
uint_max = np.iinfo(np.uint64).max
# How many ways to have U=0? 1
configurations[0] = 1
for u in np.arange(1, maxu + 1):
coeffs = s_array[u - 1::-1]
new_val = np.dot(configurations[:u], coeffs) / u
if new_val > uint_max and configurations_is_uint:
# OK, we got into numbers too big for uint64.
# So now we start working with floats.
# By doing this since the beginning, we would have lost precision.
# (And working on python long ints would be unbearably slow)
configurations = configurations.astype(float)
configurations_is_uint = False
configurations[u] = new_val
self.configurations = configurations
return configurations / total
# Maintain state for faster repeat calls to `mannwhitneyu`.
# _MWU() is calculated once per thread and stored as an attribute on
# this thread-local variable inside mannwhitneyu().
_mwu_state = threading.local()
def _get_mwu_z(U, n1, n2, t, continuity=True, *, xp):
'''Standardized MWU statistic'''
# Follows mannwhitneyu [2]
mu = n1 * n2 / 2
n = n1 + n2
# Tie correction according to [2], "Normal approximation and tie correction"
# "A more computationally-efficient form..."
tie_term = xp.sum(t**3 - t, axis=-1)
s = xp.sqrt(n1*n2/12 * ((n + 1) - tie_term/(n*(n-1))))
numerator = U - mu
# Continuity correction.
# Because SF is always used to calculate the p-value, we can always
# _subtract_ 0.5 for the continuity correction. This always increases the
# p-value to account for the rest of the probability mass _at_ q = U.
if continuity:
numerator -= 0.5
# no problem evaluating the norm SF at an infinity
with np.errstate(divide='ignore', invalid='ignore'):
z = numerator / s
return z
def _mwu_input_validation(x, y, use_continuity, alternative, axis, method):
''' Input validation and standardization for mannwhitneyu '''
xp = array_namespace(x, y)
x, y = xpx.atleast_nd(x, ndim=1), xpx.atleast_nd(y, ndim=1)
if xp.any(xp.isnan(x)) or xp.any(xp.isnan(y)):
raise ValueError('`x` and `y` must not contain NaNs.')
if xp_size(x) == 0 or xp_size(y) == 0:
raise ValueError('`x` and `y` must be of nonzero size.')
x, y = xp_promote(x, y, force_floating=True, xp=xp)
bools = {True, False}
if use_continuity not in bools:
raise ValueError(f'`use_continuity` must be one of {bools}.')
alternatives = {"two-sided", "less", "greater"}
alternative = alternative.lower()
if alternative not in alternatives:
raise ValueError(f'`alternative` must be one of {alternatives}.')
axis_int = int(axis)
if axis != axis_int:
raise ValueError('`axis` must be an integer.')
if not isinstance(method, stats.PermutationMethod):
methods = {"asymptotic", "exact", "auto"}
method = method.lower()
if method not in methods:
raise ValueError(f'`method` must be one of {methods}.')
return x, y, use_continuity, alternative, axis_int, method, xp
def _mwu_choose_method(n1, n2, ties):
"""Choose method 'asymptotic' or 'exact' depending on input size, ties"""
# if both inputs are large, asymptotic is OK
if n1 > 8 and n2 > 8:
return "asymptotic"
# if there are any ties, asymptotic is preferred
if ties:
return "asymptotic"
return "exact"
MannwhitneyuResult = namedtuple('MannwhitneyuResult', ('statistic', 'pvalue'))
@xp_capabilities(cpu_only=True, # exact calculation only implemented in NumPy
skip_backends=[('cupy', 'needs rankdata'),
('dask.array', 'needs rankdata')],
jax_jit=False)
@_axis_nan_policy_factory(MannwhitneyuResult, n_samples=2)
def mannwhitneyu(x, y, use_continuity=True, alternative="two-sided",
axis=0, method="auto"):
r'''Perform the Mann-Whitney U rank test on two independent samples.
The Mann-Whitney U test is a nonparametric test of the null hypothesis
that the distribution underlying sample `x` is the same as the
distribution underlying sample `y`. It is often used as a test of
difference in location between distributions.
Parameters
----------
x, y : array-like
N-d arrays of samples. The arrays must be broadcastable except along
the dimension given by `axis`.
use_continuity : bool, optional
Whether a continuity correction (1/2) should be applied.
Default is True when `method` is ``'asymptotic'``; has no effect
otherwise.
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis. Default is 'two-sided'.
Let *SX(u)* and *SY(u)* be the survival functions of the
distributions underlying `x` and `y`, respectively. Then the following
alternative hypotheses are available:
* 'two-sided': the distributions are not equal, i.e. *SX(u) ≠ SY(u)* for
at least one *u*.
* 'less': the distribution underlying `x` is stochastically less
than the distribution underlying `y`, i.e. *SX(u) < SY(u)* for all *u*.
* 'greater': the distribution underlying `x` is stochastically greater
than the distribution underlying `y`, i.e. *SX(u) > SY(u)* for all *u*.
Under a more restrictive set of assumptions, the alternative hypotheses
can be expressed in terms of the locations of the distributions;
see [5]_ section 5.1.
axis : int, optional
Axis along which to perform the test. Default is 0.
method : {'auto', 'asymptotic', 'exact'} or `PermutationMethod` instance, optional
Selects the method used to calculate the *p*-value.
Default is 'auto'. The following options are available.
* ``'asymptotic'``: compares the standardized test statistic
against the normal distribution, correcting for ties.
* ``'exact'``: computes the exact *p*-value by comparing the observed
:math:`U` statistic against the exact distribution of the :math:`U`
statistic under the null hypothesis. No correction is made for ties.
* ``'auto'``: chooses ``'exact'`` when the size of one of the samples
is less than or equal to 8 and there are no ties;
chooses ``'asymptotic'`` otherwise.
* `PermutationMethod` instance. In this case, the p-value
is computed using `permutation_test` with the provided
configuration options and other appropriate settings.
Returns
-------
res : MannwhitneyuResult
An object containing attributes:
statistic : float
The Mann-Whitney U statistic corresponding with sample `x`. See
Notes for the test statistic corresponding with sample `y`.
pvalue : float
The associated *p*-value for the chosen `alternative`.
Notes
-----
If ``U1`` is the statistic corresponding with sample `x`, then the
statistic corresponding with sample `y` is
``U2 = x.shape[axis] * y.shape[axis] - U1``.
`mannwhitneyu` is for independent samples. For related / paired samples,
consider `scipy.stats.wilcoxon`.
`method` ``'exact'`` is recommended when there are no ties and when either
sample size is less than 8 [1]_. The implementation follows the algorithm
reported in [3]_.
Note that the exact method is *not* corrected for ties, but
`mannwhitneyu` will not raise errors or warnings if there are ties in the
data. If there are ties and either samples is small (fewer than ~10
observations), consider passing an instance of `PermutationMethod`
as the `method` to perform a permutation test.
The Mann-Whitney U test is a non-parametric version of the t-test for
independent samples. When the means of samples from the populations
are normally distributed, consider `scipy.stats.ttest_ind`.
See Also
--------
scipy.stats.wilcoxon, scipy.stats.ranksums, scipy.stats.ttest_ind
References
----------
.. [1] H.B. Mann and D.R. Whitney, "On a test of whether one of two random
variables is stochastically larger than the other", The Annals of
Mathematical Statistics, Vol. 18, pp. 50-60, 1947.
.. [2] Mann-Whitney U Test, Wikipedia,
http://en.wikipedia.org/wiki/Mann-Whitney_U_test
.. [3] Andreas Löffler,
"Über eine Partition der nat. Zahlen und ihr Anwendung beim U-Test",
Wiss. Z. Univ. Halle, XXXII'83 pp. 87-89.
.. [4] Rosie Shier, "Statistics: 2.3 The Mann-Whitney U Test", Mathematics
Learning Support Centre, 2004.
.. [5] Michael P. Fay and Michael A. Proschan. "Wilcoxon-Mann-Whitney
or t-test? On assumptions for hypothesis tests and multiple \
interpretations of decision rules." Statistics surveys, Vol. 4, pp.
1-39, 2010. https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2857732/
Examples
--------
We follow the example from [4]_: nine randomly sampled young adults were
diagnosed with type II diabetes at the ages below.
>>> males = [19, 22, 16, 29, 24]
>>> females = [20, 11, 17, 12]
We use the Mann-Whitney U test to assess whether there is a statistically
significant difference in the diagnosis age of males and females.
The null hypothesis is that the distribution of male diagnosis ages is
the same as the distribution of female diagnosis ages. We decide
that a confidence level of 95% is required to reject the null hypothesis
in favor of the alternative that the distributions are different.
Since the number of samples is very small and there are no ties in the
data, we can compare the observed test statistic against the *exact*
distribution of the test statistic under the null hypothesis.
>>> from scipy.stats import mannwhitneyu
>>> U1, p = mannwhitneyu(males, females, method="exact")
>>> print(U1)
17.0
`mannwhitneyu` always reports the statistic associated with the first
sample, which, in this case, is males. This agrees with :math:`U_M = 17`
reported in [4]_. The statistic associated with the second statistic
can be calculated:
>>> nx, ny = len(males), len(females)
>>> U2 = nx*ny - U1
>>> print(U2)
3.0
This agrees with :math:`U_F = 3` reported in [4]_. The two-sided
*p*-value can be calculated from either statistic, and the value produced
by `mannwhitneyu` agrees with :math:`p = 0.11` reported in [4]_.
>>> print(p)
0.1111111111111111
The exact distribution of the test statistic is asymptotically normal, so
the example continues by comparing the exact *p*-value against the
*p*-value produced using the normal approximation.
>>> _, pnorm = mannwhitneyu(males, females, method="asymptotic")
>>> print(pnorm)
0.11134688653314041
Here `mannwhitneyu`'s reported *p*-value appears to conflict with the
value :math:`p = 0.09` given in [4]_. The reason is that [4]_
does not apply the continuity correction performed by `mannwhitneyu`;
`mannwhitneyu` reduces the distance between the test statistic and the
mean :math:`\mu = n_x n_y / 2` by 0.5 to correct for the fact that the
discrete statistic is being compared against a continuous distribution.
Here, the :math:`U` statistic used is less than the mean, so we reduce
the distance by adding 0.5 in the numerator.
>>> import numpy as np
>>> from scipy.stats import norm
>>> U = min(U1, U2)
>>> N = nx + ny
>>> z = (U - nx*ny/2 + 0.5) / np.sqrt(nx*ny * (N + 1)/ 12)
>>> p = 2 * norm.cdf(z) # use CDF to get p-value from smaller statistic
>>> print(p)
0.11134688653314041
If desired, we can disable the continuity correction to get a result
that agrees with that reported in [4]_.
>>> _, pnorm = mannwhitneyu(males, females, use_continuity=False,
... method="asymptotic")
>>> print(pnorm)
0.0864107329737
Regardless of whether we perform an exact or asymptotic test, the
probability of the test statistic being as extreme or more extreme by
chance exceeds 5%, so we do not consider the results statistically
significant.
Suppose that, before seeing the data, we had hypothesized that females
would tend to be diagnosed at a younger age than males.
In that case, it would be natural to provide the female ages as the
first input, and we would have performed a one-sided test using
``alternative = 'less'``: females are diagnosed at an age that is
stochastically less than that of males.
>>> res = mannwhitneyu(females, males, alternative="less", method="exact")
>>> print(res)
MannwhitneyuResult(statistic=3.0, pvalue=0.05555555555555555)
Again, the probability of getting a sufficiently low value of the
test statistic by chance under the null hypothesis is greater than 5%,
so we do not reject the null hypothesis in favor of our alternative.
If it is reasonable to assume that the means of samples from the
populations are normally distributed, we could have used a t-test to
perform the analysis.
>>> from scipy.stats import ttest_ind
>>> res = ttest_ind(females, males, alternative="less")
>>> print(res)
TtestResult(statistic=-2.239334696520584,
pvalue=0.030068441095757924,
df=7.0)
Under this assumption, the *p*-value would be low enough to reject the
null hypothesis in favor of the alternative.
'''
x, y, use_continuity, alternative, axis_int, method, xp = (
_mwu_input_validation(x, y, use_continuity, alternative, axis, method))
xy = _broadcast_concatenate((x, y), axis)
n1, n2 = x.shape[-1], y.shape[-1] # _axis_nan_policy decorator ensures axis=-1
# Follows [2]
ranks, t = _rankdata(xy, 'average', return_ties=True) # method 2, step 1
ranks = xp.astype(ranks, x.dtype, copy=False)
t = xp.astype(t, x.dtype, copy=False)
R1 = xp.sum(ranks[..., :n1], axis=-1) # method 2, step 2
U1 = R1 - n1*(n1+1)/2 # method 2, step 3
U2 = n1 * n2 - U1 # as U1 + U2 = n1 * n2
if alternative == "greater":
U, f = U1, 1 # U is the statistic to use for p-value, f is a factor
elif alternative == "less":
U, f = U2, 1 # Due to symmetry, use SF of U2 rather than CDF of U1
else:
U, f = xp.maximum(U1, U2), 2 # multiply SF by two for two-sided test
if method == "auto":
method = _mwu_choose_method(n1, n2, xp.any(t > 1))
if method == "exact":
if not hasattr(_mwu_state, 's'):
_mwu_state.s = _MWU(0, 0)
_mwu_state.s.set_shapes(n1, n2)
p = xp.asarray(_mwu_state.s.sf(np.asarray(U, np.int64)), dtype=x.dtype)
elif method == "asymptotic":
z = _get_mwu_z(U, n1, n2, t, continuity=use_continuity, xp=xp)
p = special.ndtr(-z)
else: # `PermutationMethod` instance (already validated)
def statistic(x, y, axis):
return mannwhitneyu(x, y, use_continuity=use_continuity,
alternative=alternative, axis=axis,
method="asymptotic").statistic
res = stats.permutation_test((x, y), statistic, axis=axis,
**method._asdict(), alternative=alternative)
p = res.pvalue
f = 1
p *= f
# Ensure that test statistic is not greater than 1
# This could happen for exact test when U = m*n/2
p = xp.clip(p, 0., 1.)
return MannwhitneyuResult(U1, p)
| _MWU |
python | apache__airflow | helm-tests/tests/helm_tests/redis/test_labels_statefulset.py | {
"start": 900,
"end": 5020
} | class ____:
"""Tests redis statefulset labels."""
AIRFLOW_EXECUTOR = "CeleryExecutor"
TEMPLATE_FILE = "templates/redis/redis-statefulset.yaml"
def test_should_add_global_labels_to_metadata(self):
"""Test adding only .Values.labels to metadata.labels."""
docs = render_chart(
values={
"executor": self.AIRFLOW_EXECUTOR,
"redis": {"enabled": True},
"labels": {"test_global_label": "test_global_label_value"},
},
show_only=[self.TEMPLATE_FILE],
)
assert "test_global_label" in jmespath.search("metadata.labels", docs[0])
assert jmespath.search("metadata.labels", docs[0])["test_global_label"] == "test_global_label_value"
def test_should_add_global_labels_to_pod_template(self):
"""Test adding only .Values.labels to spec.template.metadata.labels."""
docs = render_chart(
values={
"executor": self.AIRFLOW_EXECUTOR,
"redis": {"enabled": True},
"labels": {"test_global_label": "test_global_label_value"},
},
show_only=[self.TEMPLATE_FILE],
)
assert "test_global_label" in jmespath.search("spec.template.metadata.labels", docs[0])
assert (
jmespath.search("spec.template.metadata.labels", docs[0])["test_global_label"]
== "test_global_label_value"
)
def test_should_add_component_specific_labels_to_pod_template(self):
"""Test adding only .Values.redis.labels to spec.template.metadata.labels."""
docs = render_chart(
values={
"executor": self.AIRFLOW_EXECUTOR,
"redis": {
"enabled": True,
"labels": {"test_component_label": "test_component_label_value"},
},
},
show_only=[self.TEMPLATE_FILE],
)
assert "test_component_label" in jmespath.search("spec.template.metadata.labels", docs[0])
assert (
jmespath.search("spec.template.metadata.labels", docs[0])["test_component_label"]
== "test_component_label_value"
)
def test_should_merge_global_and_component_specific_labels_in_pod_template(self):
"""Test adding both .Values.labels and .Values.redis.labels to spec.template.metadata.labels."""
docs = render_chart(
values={
"executor": self.AIRFLOW_EXECUTOR,
"redis": {
"enabled": True,
"labels": {"test_component_label": "test_component_label_value"},
},
"labels": {"test_global_label": "test_global_label_value"},
},
show_only=[self.TEMPLATE_FILE],
)
assert "test_global_label" in jmespath.search("spec.template.metadata.labels", docs[0])
assert (
jmespath.search("spec.template.metadata.labels", docs[0])["test_global_label"]
== "test_global_label_value"
)
assert "test_component_label" in jmespath.search("spec.template.metadata.labels", docs[0])
assert (
jmespath.search("spec.template.metadata.labels", docs[0])["test_component_label"]
== "test_component_label_value"
)
def test_component_specific_labels_should_override_global_labels(self):
"""Test that component-specific labels take precedence over global labels with the same key."""
docs = render_chart(
values={
"executor": self.AIRFLOW_EXECUTOR,
"redis": {
"enabled": True,
"labels": {"common_label": "component_value"},
},
"labels": {"common_label": "global_value"},
},
show_only=[self.TEMPLATE_FILE],
)
assert "common_label" in jmespath.search("spec.template.metadata.labels", docs[0])
assert jmespath.search("spec.template.metadata.labels", docs[0])["common_label"] == "component_value"
| TestRedisStatefulSet |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/result.py | {
"start": 77691,
"end": 78875
} | class ____(IteratorResult[Unpack[_Ts]]):
"""A :class:`_engine.Result` that is merged from any number of
:class:`_engine.Result` objects.
Returned by the :meth:`_engine.Result.merge` method.
.. versionadded:: 1.4
"""
closed = False
rowcount: Optional[int]
def __init__(
self,
cursor_metadata: ResultMetaData,
results: Sequence[Result[Unpack[_Ts]]],
):
self._results = results
super().__init__(
cursor_metadata,
itertools.chain.from_iterable(
r._raw_row_iterator() for r in results
),
)
self._unique_filter_state = results[0]._unique_filter_state
self._yield_per = results[0]._yield_per
# going to try something w/ this in next rev
self._source_supports_scalars = results[0]._source_supports_scalars
self._attributes = self._attributes.merge_with(
*[r._attributes for r in results]
)
def _soft_close(self, hard: bool = False, **kw: Any) -> None:
for r in self._results:
r._soft_close(hard=hard, **kw)
if hard:
self.closed = True
| MergedResult |
python | miyuchina__mistletoe | test/test_block_token.py | {
"start": 4854,
"end": 5364
} | class ____(TestToken):
def test_parse_indented_code(self):
lines = [' rm dir\n', ' mkdir test\n']
arg = 'rm dir\nmkdir test\n'
self._test_match(block_token.BlockCode, lines, arg, language='')
def test_parse_indented_code_with_blank_lines(self):
lines = [' chunk1\n', '\n', ' chunk2\n', ' \n', ' \n', ' \n', ' chunk3\n']
arg = 'chunk1\n\nchunk2\n\n\n\nchunk3\n'
self._test_match(block_token.BlockCode, lines, arg, language='')
| TestBlockCode |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/step.py | {
"start": 6529,
"end": 12167
} | class ____( # pyright: ignore[reportIncompatibleVariableOverride]
NamedTuple(
"_UnresolvedMappedExecutionStep",
[
("handle", UnresolvedStepHandle),
("job_name", str),
("step_input_dict", Mapping[str, Union[StepInput, UnresolvedMappedStepInput]]),
("step_output_dict", Mapping[str, StepOutput]),
("tags", Mapping[str, str]),
("pool", Optional[str]),
],
),
IExecutionStep,
):
"""A placeholder step that will become N ExecutionSteps once the upstream dynamic output resolves in to N mapping keys."""
def __new__(
cls,
handle: UnresolvedStepHandle,
job_name: str,
step_inputs: Sequence[Union[StepInput, UnresolvedMappedStepInput]],
step_outputs: Sequence[StepOutput],
tags: Optional[Mapping[str, str]],
pool: Optional[str],
):
return super().__new__(
cls,
handle=check.inst_param(handle, "handle", UnresolvedStepHandle),
job_name=check.str_param(job_name, "job_name"),
step_input_dict={
si.name: si
for si in check.sequence_param(
step_inputs, "step_inputs", of_type=(StepInput, UnresolvedMappedStepInput)
)
},
step_output_dict={
so.name: so
for so in check.sequence_param(step_outputs, "step_outputs", of_type=StepOutput)
},
tags=check.opt_mapping_param(tags, "tags", key_type=str),
pool=check.opt_str_param(pool, "pool"),
)
@property
def node_handle(self) -> "NodeHandle":
return self.handle.node_handle
@property
def key(self) -> str:
return self.handle.to_key()
@property
def kind(self) -> StepKind:
return StepKind.UNRESOLVED_MAPPED
@property
def step_outputs(self) -> Sequence[StepOutput]:
return list(self.step_output_dict.values())
@property
def step_inputs(self) -> Sequence[Union[StepInput, UnresolvedMappedStepInput]]:
return list(self.step_input_dict.values())
def step_input_named(self, name: str) -> Union[StepInput, UnresolvedMappedStepInput]:
check.str_param(name, "name")
return self.step_input_dict[name]
def step_output_named(self, name: str) -> StepOutput:
check.str_param(name, "name")
return self.step_output_dict[name]
def get_all_dependency_keys(self) -> set[str]:
deps = set()
for inp in self.step_inputs:
if isinstance(inp, StepInput):
deps.update(
[handle.step_key for handle in inp.get_step_output_handle_dependencies()]
)
elif isinstance(inp, UnresolvedMappedStepInput):
deps.update(
[
handle.step_key
for handle in inp.get_step_output_handle_deps_with_placeholders()
]
)
else:
check.failed(f"Unexpected step input type {inp}")
return deps
@property
def resolved_by_step_key(self) -> str:
# this function will be removed in moving to supporting being downstream of multiple dynamic outputs
keys = self.resolved_by_step_keys
check.invariant(len(keys) == 1, "Unresolved step expects one and only one dynamic step key")
return next(iter(keys))
@property
def resolved_by_output_name(self) -> str:
# this function will be removed in moving to supporting being downstream of multiple dynamic outputs
keys = set()
for inp in self.step_inputs:
if isinstance(inp, UnresolvedMappedStepInput):
keys.add(inp.resolved_by_output_name)
check.invariant(
len(keys) == 1, "Unresolved step expects one and only one dynamic output name"
)
return next(iter(keys))
@property
def resolved_by_step_keys(self) -> frozenset[str]:
keys = set()
for inp in self.step_inputs:
if isinstance(inp, UnresolvedMappedStepInput):
keys.add(inp.resolved_by_step_key)
return frozenset(keys)
def resolve(
self, mappings: Mapping[str, Mapping[str, Optional[Sequence[str]]]]
) -> Sequence[ExecutionStep]:
check.invariant(
all(key in mappings for key in self.resolved_by_step_keys),
"resolving with mappings that do not contain all required step keys",
)
execution_steps: list[ExecutionStep] = []
mapping_keys = mappings[self.resolved_by_step_key][self.resolved_by_output_name]
# dynamic output skipped
if mapping_keys is None:
return execution_steps
for mapped_key in mapping_keys:
resolved_inputs = [_resolved_input(inp, mapped_key) for inp in self.step_inputs]
execution_steps.append(
ExecutionStep(
handle=ResolvedFromDynamicStepHandle(self.handle.node_handle, mapped_key),
job_name=self.job_name,
step_inputs=resolved_inputs,
step_outputs=self.step_outputs,
tags=self.tags,
pool=self.pool,
)
)
return execution_steps
def _resolved_input(
step_input: Union[StepInput, UnresolvedMappedStepInput],
map_key: str,
):
if isinstance(step_input, StepInput):
return step_input
return step_input.resolve(map_key)
| UnresolvedMappedExecutionStep |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 481827,
"end": 482625
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for BypassPullRequestAllowance."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("BypassPullRequestAllowanceEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.types.Field(sgqlc.types.list_of("BypassPullRequestAllowance"), graphql_name="nodes")
"""A list of nodes."""
page_info = sgqlc.types.Field(sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo")
"""Information to aid in pagination."""
total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount")
"""Identifies the total count of items in the connection."""
| BypassPullRequestAllowanceConnection |
python | doocs__leetcode | solution/0300-0399/0318.Maximum Product of Word Lengths/Solution.py | {
"start": 0,
"end": 391
} | class ____:
def maxProduct(self, words: List[str]) -> int:
mask = [0] * len(words)
ans = 0
for i, s in enumerate(words):
for c in s:
mask[i] |= 1 << (ord(c) - ord("a"))
for j, t in enumerate(words[:i]):
if (mask[i] & mask[j]) == 0:
ans = max(ans, len(s) * len(t))
return ans
| Solution |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/batchtospace_op_test.py | {
"start": 4650,
"end": 8929
} | class ____(test.TestCase):
def _testStaticShape(self, input_shape, block_shape, paddings, error):
block_shape = np.array(block_shape)
paddings = np.array(paddings)
# Try with sizes known at graph construction time.
with self.assertRaises(error):
_ = array_ops.batch_to_space_nd(
np.zeros(input_shape, np.float32), block_shape, paddings)
def _testDynamicShape(self, input_shape, block_shape, paddings):
block_shape = np.array(block_shape)
paddings = np.array(paddings)
# Try with sizes unknown at graph construction time.
input_placeholder = array_ops.placeholder(dtypes.float32)
block_shape_placeholder = array_ops.placeholder(
dtypes.int32, shape=block_shape.shape)
paddings_placeholder = array_ops.placeholder(dtypes.int32)
t = array_ops.batch_to_space_nd(input_placeholder, block_shape_placeholder,
paddings_placeholder)
with self.assertRaises(ValueError):
_ = t.eval({
input_placeholder: np.zeros(input_shape, np.float32),
block_shape_placeholder: block_shape,
paddings_placeholder: paddings
})
def _testShape(self, input_shape, block_shape, paddings, error):
self._testStaticShape(input_shape, block_shape, paddings, error)
self._testDynamicShape(input_shape, block_shape, paddings)
@test_util.run_deprecated_v1
def testInputWrongDimMissingBatch(self):
self._testShape([2, 2], [2, 2], [[0, 0], [0, 0]], ValueError)
self._testShape([2, 2, 3], [2, 2, 3], [[0, 0], [0, 0]], ValueError)
@test_util.run_deprecated_v1
def testBlockSize0(self):
# The block size is 0.
self._testShape([1, 2, 2, 1], [0, 1], [[0, 0], [0, 0]], ValueError)
@test_util.run_deprecated_v1
def testBlockSizeNegative(self):
self._testShape([1, 2, 2, 1], [-1, 1], [[0, 0], [0, 0]], ValueError)
@test_util.run_deprecated_v1
def testNegativePadding(self):
self._testShape([1, 2, 2], [1, 1], [[0, -1], [0, 0]], ValueError)
@test_util.run_deprecated_v1
def testCropTooLarge(self):
# The amount to crop exceeds the padded size.
self._testShape([1 * 2 * 2, 2, 3, 1], [2, 2], [[3, 2], [0, 0]], ValueError)
@test_util.run_deprecated_v1
def testBlockSizeSquaredNotDivisibleBatch(self):
# The batch dimension is not divisible by the product of the block_shape.
self._testShape([3, 1, 1, 1], [2, 3], [[0, 0], [0, 0]], ValueError)
@test_util.run_deprecated_v1
def testUnknownShape(self):
# Verify that input shape and paddings shape can be unknown.
_ = array_ops.batch_to_space_nd(
array_ops.placeholder(dtypes.float32),
array_ops.placeholder(
dtypes.int32, shape=(2,)),
array_ops.placeholder(dtypes.int32))
# Only number of input dimensions is known.
t = array_ops.batch_to_space_nd(
array_ops.placeholder(
dtypes.float32, shape=(None, None, None, None)),
array_ops.placeholder(
dtypes.int32, shape=(2,)),
array_ops.placeholder(dtypes.int32))
self.assertEqual(4, t.get_shape().ndims)
# Dimensions are partially known.
t = array_ops.batch_to_space_nd(
array_ops.placeholder(
dtypes.float32, shape=(None, None, None, 2)),
array_ops.placeholder(
dtypes.int32, shape=(2,)),
array_ops.placeholder(dtypes.int32))
self.assertEqual([None, None, None, 2], t.get_shape().as_list())
# Dimensions are partially known.
t = array_ops.batch_to_space_nd(
array_ops.placeholder(
dtypes.float32, shape=(3 * 2 * 3, None, None, 2)), [2, 3],
array_ops.placeholder(dtypes.int32))
self.assertEqual([3, None, None, 2], t.get_shape().as_list())
# Dimensions are partially known.
t = array_ops.batch_to_space_nd(
array_ops.placeholder(
dtypes.float32, shape=(3 * 2 * 3, None, 2, 2)), [2, 3],
[[1, 1], [0, 1]])
self.assertEqual([3, None, 5, 2], t.get_shape().as_list())
# Dimensions are fully known.
t = array_ops.batch_to_space_nd(
array_ops.placeholder(
dtypes.float32, shape=(3 * 2 * 3, 2, 1, 2)), [2, 3],
[[1, 1], [0, 0]])
self.assertEqual([3, 2, 3, 2], t.get_shape().as_list())
| BatchToSpaceNDErrorHandlingTest |
python | huggingface__transformers | src/transformers/models/deberta/modeling_deberta.py | {
"start": 32462,
"end": 32864
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.lm_head = DebertaLMPredictionHead(config)
# note that the input embeddings must be passed as an argument
def forward(self, sequence_output, word_embeddings):
prediction_scores = self.lm_head(sequence_output, word_embeddings)
return prediction_scores
@auto_docstring
| DebertaOnlyMLMHead |
python | pypa__warehouse | tests/unit/test_views.py | {
"start": 11341,
"end": 11651
} | class ____:
def test_forbidden_include(self):
exc = pretend.stub()
request = pretend.stub()
resp = forbidden_include(exc, request)
assert resp.status_code == 403
assert resp.content_type == "text/html"
assert resp.content_length == 0
| TestForbiddenIncludeView |
python | PyCQA__pylint | doc/data/messages/a/abstract-method/bad/abstract_method.py | {
"start": 96,
"end": 153
} | class ____(WildAnimal): # [abstract-method]
pass
| Panther |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/assets/graph/remote_asset_graph.py | {
"start": 5788,
"end": 8587
} | class ____(RemoteAssetNode):
"""Asset nodes from a single RemoteRepository."""
repository_handle: RepositoryHandle
asset_node_snap: Annotated[
"AssetNodeSnap",
ImportFrom("dagster._core.remote_representation.external_data"),
]
parent_keys: AbstractSet[AssetKey]
child_keys: AbstractSet[AssetKey]
check_keys: AbstractSet[AssetCheckKey] # pyright: ignore[reportIncompatibleMethodOverride]
execution_set_entity_keys: AbstractSet[EntityKey] # pyright: ignore[reportIncompatibleMethodOverride]
def __hash__(self):
# we create sets of these objects in the context of asset graphs but don't want to
# enforce that all recursively contained types are hashable so use object hash instead
return object.__hash__(self)
def resolve_to_repo_scoped_node(
self, repository_selector: "RepositorySelector"
) -> Optional["RemoteRepositoryAssetNode"]:
return (
self
if self.repository_handle.get_remote_origin().get_selector() == repository_selector
else None
)
def resolve_to_singular_repo_scoped_node(self) -> "RemoteRepositoryAssetNode":
return self
@property
def key(self) -> AssetKey: # pyright: ignore[reportIncompatibleVariableOverride]
return self.asset_node_snap.asset_key
@property
def is_materializable(self) -> bool:
return self.asset_node_snap.is_materializable
@property
def is_observable(self) -> bool:
return self.asset_node_snap.is_observable
@property
def is_external(self) -> bool:
return self.asset_node_snap.is_external
@property
def is_executable(self) -> bool:
return self.asset_node_snap.is_executable
@property
def partition_mappings(self) -> Mapping[AssetKey, PartitionMapping]: # pyright: ignore[reportIncompatibleMethodOverride]
return {
dep.parent_asset_key: dep.partition_mapping
for dep in self.asset_node_snap.parent_edges
if dep.partition_mapping is not None
}
@property
def backfill_policy(self) -> Optional[BackfillPolicy]:
return self.asset_node_snap.backfill_policy
@property
def automation_condition(self) -> Optional[AutomationCondition]:
return self.asset_node_snap.automation_condition
@property
def auto_materialize_policy(self) -> Optional[AutoMaterializePolicy]:
return self.asset_node_snap.auto_materialize_policy
@property
def auto_observe_interval_minutes(self) -> Optional[float]:
return self.asset_node_snap.auto_observe_interval_minutes
@property
def pools(self) -> Optional[set[str]]:
return self.asset_node_snap.pools
@whitelist_for_serdes
@record
| RemoteRepositoryAssetNode |
python | doocs__leetcode | solution/2500-2599/2518.Number of Great Partitions/Solution.py | {
"start": 0,
"end": 552
} | class ____:
def countPartitions(self, nums: List[int], k: int) -> int:
if sum(nums) < k * 2:
return 0
mod = 10**9 + 7
n = len(nums)
f = [[0] * k for _ in range(n + 1)]
f[0][0] = 1
ans = 1
for i in range(1, n + 1):
ans = ans * 2 % mod
for j in range(k):
f[i][j] = f[i - 1][j]
if j >= nums[i - 1]:
f[i][j] = (f[i][j] + f[i - 1][j - nums[i - 1]]) % mod
return (ans - sum(f[-1]) * 2 + mod) % mod
| Solution |
python | huggingface__transformers | tests/models/trocr/test_processing_trocr.py | {
"start": 390,
"end": 1337
} | class ____(ProcessorTesterMixin, unittest.TestCase):
text_input_name = "labels"
processor_class = TrOCRProcessor
@classmethod
def _setup_image_processor(cls):
image_processor_class = cls._get_component_class_from_processor("image_processor")
return image_processor_class()
@classmethod
def _setup_tokenizer(cls):
tokenizer_class = cls._get_component_class_from_processor("tokenizer")
return tokenizer_class.from_pretrained("FacebookAI/xlm-roberta-base")
def test_processor_text(self):
processor = self.get_processor()
input_str = "lower newer"
image_input = self.prepare_image_inputs()
inputs = processor(text=input_str, images=image_input)
self.assertListEqual(list(inputs.keys()), ["pixel_values", "labels"])
# test if it raises when no input is passed
with pytest.raises(ValueError):
processor()
| TrOCRProcessorTest |
python | apache__airflow | task-sdk/tests/task_sdk/api/test_client.py | {
"start": 10116,
"end": 23507
} | class ____:
"""
Test that the TestTaskInstanceOperations class works as expected. While the operations are simple, it
still catches the basic functionality of the client for task instances including endpoint and
response parsing.
"""
def test_task_instance_start(self, make_ti_context):
with time_machine.travel("2023-01-01T00:00:00Z", tick=False):
# Simulate a successful response from the server that starts a task
ti_id = uuid6.uuid7()
start_date = "2024-10-31T12:00:00Z"
ti_context = make_ti_context(
start_date=start_date,
logical_date="2024-10-31T12:00:00Z",
run_type="manual",
)
# ...including a validation that retry really works
call_count = 0
def handle_request(request: httpx.Request) -> httpx.Response:
nonlocal call_count
call_count += 1
if call_count < 3:
return httpx.Response(status_code=500, json={"detail": "Internal Server Error"})
if request.url.path == f"/task-instances/{ti_id}/run":
actual_body = json.loads(request.read())
assert actual_body["pid"] == 100
assert actual_body["start_date"] == start_date
assert actual_body["state"] == "running"
return httpx.Response(
status_code=200,
json=ti_context.model_dump(mode="json"),
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
resp = client.task_instances.start(ti_id, 100, start_date)
assert resp == ti_context
assert call_count == 3
@pytest.mark.parametrize(
"state", [state for state in TerminalTIState if state != TerminalTIState.SUCCESS]
)
def test_task_instance_finish(self, state):
# Simulate a successful response from the server that finishes (moved to terminal state) a task
ti_id = uuid6.uuid7()
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/task-instances/{ti_id}/state":
actual_body = json.loads(request.read())
assert actual_body["end_date"] == "2024-10-31T12:00:00Z"
assert actual_body["state"] == state
assert actual_body["rendered_map_index"] == "test"
return httpx.Response(
status_code=204,
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
client.task_instances.finish(
ti_id, state=state, when="2024-10-31T12:00:00Z", rendered_map_index="test"
)
def test_task_instance_heartbeat(self):
# Simulate a successful response from the server that sends a heartbeat for a ti
ti_id = uuid6.uuid7()
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/task-instances/{ti_id}/heartbeat":
actual_body = json.loads(request.read())
assert actual_body["pid"] == 100
return httpx.Response(
status_code=204,
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
client.task_instances.heartbeat(ti_id, 100)
def test_task_instance_defer(self):
# Simulate a successful response from the server that defers a task
ti_id = uuid6.uuid7()
msg = DeferTask(
classpath="airflow.providers.standard.triggers.temporal.DateTimeTrigger",
next_method="execute_complete",
trigger_kwargs={
"__type": "dict",
"__var": {
"moment": {"__type": "datetime", "__var": 1730982899.0},
"end_from_trigger": False,
},
},
next_kwargs={"__type": "dict", "__var": {}},
)
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/task-instances/{ti_id}/state":
actual_body = json.loads(request.read())
assert actual_body["state"] == "deferred"
assert actual_body["trigger_kwargs"] == msg.trigger_kwargs
assert (
actual_body["classpath"] == "airflow.providers.standard.triggers.temporal.DateTimeTrigger"
)
assert actual_body["next_method"] == "execute_complete"
return httpx.Response(
status_code=204,
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
client.task_instances.defer(ti_id, msg)
def test_task_instance_reschedule(self):
# Simulate a successful response from the server that reschedules a task
ti_id = uuid6.uuid7()
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/task-instances/{ti_id}/state":
actual_body = json.loads(request.read())
assert actual_body["state"] == "up_for_reschedule"
assert actual_body["reschedule_date"] == "2024-10-31T12:00:00Z"
assert actual_body["end_date"] == "2024-10-31T12:00:00Z"
return httpx.Response(
status_code=204,
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
msg = RescheduleTask(
reschedule_date=timezone.parse("2024-10-31T12:00:00Z"),
end_date=timezone.parse("2024-10-31T12:00:00Z"),
)
client.task_instances.reschedule(ti_id, msg)
def test_task_instance_up_for_retry(self):
ti_id = uuid6.uuid7()
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/task-instances/{ti_id}/state":
actual_body = json.loads(request.read())
assert actual_body["state"] == "up_for_retry"
assert actual_body["end_date"] == "2024-10-31T12:00:00Z"
assert actual_body["rendered_map_index"] == "test"
return httpx.Response(
status_code=204,
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
client.task_instances.retry(
ti_id, end_date=timezone.parse("2024-10-31T12:00:00Z"), rendered_map_index="test"
)
@pytest.mark.parametrize(
"rendered_fields",
[
pytest.param({"field1": "rendered_value1", "field2": "rendered_value2"}, id="simple-rendering"),
pytest.param(
{
"field1": "ClassWithCustomAttributes({'nested1': ClassWithCustomAttributes("
"{'att1': 'test', 'att2': 'test2'), "
"'nested2': ClassWithCustomAttributes("
"{'att3': 'test3', 'att4': 'test4')"
},
id="complex-rendering",
),
],
)
def test_taskinstance_set_rtif_success(self, rendered_fields):
TI_ID = uuid6.uuid7()
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/task-instances/{TI_ID}/rtif":
return httpx.Response(
status_code=201,
json={"message": "Rendered task instance fields successfully set"},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.task_instances.set_rtif(id=TI_ID, body=rendered_fields)
assert result == OKResponse(ok=True)
def test_taskinstance_set_rendered_map_index_success(self):
TI_ID = uuid6.uuid7()
rendered_map_index = "Label: task_1"
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/task-instances/{TI_ID}/rendered-map-index":
actual_body = json.loads(request.read())
assert request.method == "PATCH"
# Body should be the string directly, not wrapped in JSON
assert actual_body == rendered_map_index
return httpx.Response(status_code=204)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.task_instances.set_rendered_map_index(id=TI_ID, rendered_map_index=rendered_map_index)
assert result == OKResponse(ok=True)
def test_get_count_basic(self):
"""Test basic get_count functionality with just dag_id."""
def handle_request(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/task-instances/count"
assert request.url.params.get("dag_id") == "test_dag"
return httpx.Response(200, json=5)
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.task_instances.get_count(dag_id="test_dag")
assert result.count == 5
def test_get_count_with_all_params(self):
"""Test get_count with all optional parameters."""
logical_dates_str = ["2024-01-01T00:00:00+00:00", "2024-01-02T00:00:00+00:00"]
logical_dates = [timezone.parse(d) for d in logical_dates_str]
task_ids = ["task1", "task2"]
states = ["success", "failed"]
def handle_request(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/task-instances/count"
assert request.method == "GET"
params = request.url.params
assert params["dag_id"] == "test_dag"
assert params.get_list("task_ids") == task_ids
assert params["task_group_id"] == "group1"
assert params.get_list("logical_dates") == logical_dates_str
assert params.get_list("run_ids") == []
assert params.get_list("states") == states
assert params["map_index"] == "0"
return httpx.Response(200, json=10)
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.task_instances.get_count(
dag_id="test_dag",
map_index=0,
task_ids=task_ids,
task_group_id="group1",
logical_dates=logical_dates,
states=states,
)
assert result.count == 10
def test_get_task_states_basic(self):
"""Test basic get_task_states functionality with just dag_id."""
def handle_request(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/task-instances/states"
assert request.url.params.get("dag_id") == "test_dag"
assert request.url.params.get("task_group_id") == "group1"
return httpx.Response(
200, json={"task_states": {"run_id": {"group1.task1": "success", "group1.task2": "failed"}}}
)
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.task_instances.get_task_states(dag_id="test_dag", task_group_id="group1")
assert result.task_states == {"run_id": {"group1.task1": "success", "group1.task2": "failed"}}
def test_get_task_states_with_all_params(self):
"""Test get_task_states with all optional parameters."""
logical_dates_str = ["2024-01-01T00:00:00+00:00", "2024-01-02T00:00:00+00:00"]
logical_dates = [timezone.parse(d) for d in logical_dates_str]
def handle_request(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/task-instances/states"
assert request.method == "GET"
params = request.url.params
assert params["dag_id"] == "test_dag"
assert params["task_group_id"] == "group1"
assert params.get_list("logical_dates") == logical_dates_str
assert params.get_list("task_ids") == []
assert params.get_list("run_ids") == []
assert params.get("map_index") == "0"
return httpx.Response(
200, json={"task_states": {"run_id": {"group1.task1": "success", "group1.task2": "failed"}}}
)
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.task_instances.get_task_states(
dag_id="test_dag",
map_index=0,
task_group_id="group1",
logical_dates=logical_dates,
)
assert result.task_states == {"run_id": {"group1.task1": "success", "group1.task2": "failed"}}
| TestTaskInstanceOperations |
python | huggingface__transformers | src/transformers/models/got_ocr2/modeling_got_ocr2.py | {
"start": 16832,
"end": 17734
} | class ____(nn.Module):
def __init__(self, config: GotOcr2VisionConfig):
super().__init__()
self.config = config
self.conv1 = nn.Conv2d(config.hidden_size, config.output_channels, kernel_size=1, bias=False)
self.layer_norm1 = GotOcr2LayerNorm(config.output_channels, data_format="channels_first")
self.conv2 = nn.Conv2d(config.output_channels, config.output_channels, kernel_size=3, padding=1, bias=False)
self.layer_norm2 = GotOcr2LayerNorm(config.output_channels, data_format="channels_first")
def forward(self, hidden_states):
hidden_states = hidden_states.permute(0, 3, 1, 2)
hidden_states = self.conv1(hidden_states)
hidden_states = self.layer_norm1(hidden_states)
hidden_states = self.conv2(hidden_states)
hidden_states = self.layer_norm2(hidden_states)
return hidden_states
| GotOcr2VisionNeck |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/autoVariance3.py | {
"start": 2290,
"end": 2776
} | class ____(Generic[T]):
def __init__(self, value: T) -> None:
self._value = value
@property
def value(self):
return self._value
@value.setter
def value(self, value: T):
self._value = value
# This should generate an error based on variance.
vinv1_1: ShouldBeInvariant1[float] = ShouldBeInvariant1[int](1)
# This should generate an error based on variance.
vinv1_2: ShouldBeInvariant1[int] = ShouldBeInvariant1[float](1.1)
| ShouldBeInvariant1 |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/asset_defs.py | {
"start": 35228,
"end": 51909
} | class ____(AirbyteCoreCacheableAssetsDefinition):
def __init__(
self,
project_dir: str,
workspace_id: Optional[str],
key_prefix: Sequence[str],
create_assets_for_normalization_tables: bool,
connection_meta_to_group_fn: Optional[Callable[[AirbyteConnectionMetadata], Optional[str]]],
connection_to_io_manager_key_fn: Optional[Callable[[str], Optional[str]]],
connection_filter: Optional[Callable[[AirbyteConnectionMetadata], bool]],
connection_directories: Optional[Sequence[str]],
connection_to_asset_key_fn: Optional[Callable[[AirbyteConnectionMetadata, str], AssetKey]],
connection_to_freshness_policy_fn: Optional[
Callable[[AirbyteConnectionMetadata], Optional[LegacyFreshnessPolicy]]
],
connection_to_auto_materialize_policy_fn: Optional[
Callable[[AirbyteConnectionMetadata], Optional[AutoMaterializePolicy]]
] = None,
):
super().__init__(
key_prefix=key_prefix,
create_assets_for_normalization_tables=create_assets_for_normalization_tables,
connection_meta_to_group_fn=connection_meta_to_group_fn,
connection_to_io_manager_key_fn=connection_to_io_manager_key_fn,
connection_filter=connection_filter,
connection_to_asset_key_fn=connection_to_asset_key_fn,
connection_to_freshness_policy_fn=connection_to_freshness_policy_fn,
connection_to_auto_materialize_policy_fn=connection_to_auto_materialize_policy_fn,
)
self._workspace_id = workspace_id
self._project_dir = project_dir
self._connection_directories = connection_directories
def _get_connections(self) -> Sequence[tuple[str, AirbyteConnectionMetadata]]:
connections_dir = os.path.join(self._project_dir, "connections")
output_connections: list[tuple[str, AirbyteConnectionMetadata]] = []
connection_directories = self._connection_directories or os.listdir(connections_dir)
for connection_name in connection_directories:
connection_dir = os.path.join(connections_dir, connection_name)
with open(os.path.join(connection_dir, "configuration.yaml"), encoding="utf-8") as f:
connection_data = yaml.safe_load(f.read())
destination_configuration_path = cast(
"str", connection_data.get("destination_configuration_path")
)
with open(
os.path.join(self._project_dir, destination_configuration_path), encoding="utf-8"
) as f:
destination_data = yaml.safe_load(f.read())
connection = AirbyteConnectionMetadata.from_config(connection_data, destination_data)
# Filter out connections that don't match the filter function
if self._connection_filter and not self._connection_filter(connection):
continue
if self._workspace_id:
state_file = f"state_{self._workspace_id}.yaml"
check.invariant(
state_file in os.listdir(connection_dir),
f"Workspace state file {state_file} not found",
)
else:
state_files = [
filename
for filename in os.listdir(connection_dir)
if filename.startswith("state_")
]
check.invariant(
len(state_files) > 0,
f"No state files found for connection {connection_name} in {connection_dir}",
)
check.invariant(
len(state_files) <= 1,
f"More than one state file found for connection {connection_name} in {connection_dir}, specify a workspace_id"
" to disambiguate",
)
state_file = state_files[0]
with open(os.path.join(connection_dir, cast("str", state_file)), encoding="utf-8") as f:
state = yaml.safe_load(f.read())
connection_id = state.get("resource_id")
output_connections.append((connection_id, connection))
return output_connections
@superseded(
additional_warn_text=(
"If you are using Airbyte 1.6.0 or higher, please see the migration guide: https://docs.dagster.io/integrations/libraries/airbyte/migration-guide"
)
)
def load_assets_from_airbyte_instance(
airbyte: Union[AirbyteResource, ResourceDefinition],
workspace_id: Optional[str] = None,
key_prefix: Optional[CoercibleToAssetKeyPrefix] = None,
create_assets_for_normalization_tables: bool = True,
connection_to_group_fn: Optional[Callable[[str], Optional[str]]] = clean_name,
connection_meta_to_group_fn: Optional[
Callable[[AirbyteConnectionMetadata], Optional[str]]
] = None,
io_manager_key: Optional[str] = None,
connection_to_io_manager_key_fn: Optional[Callable[[str], Optional[str]]] = None,
connection_filter: Optional[Callable[[AirbyteConnectionMetadata], bool]] = None,
connection_to_asset_key_fn: Optional[
Callable[[AirbyteConnectionMetadata, str], AssetKey]
] = None,
connection_to_freshness_policy_fn: Optional[
Callable[[AirbyteConnectionMetadata], Optional[LegacyFreshnessPolicy]]
] = None,
connection_to_auto_materialize_policy_fn: Optional[
Callable[[AirbyteConnectionMetadata], Optional[AutoMaterializePolicy]]
] = None,
) -> CacheableAssetsDefinition:
"""Loads Airbyte connection assets from a configured AirbyteResource instance. This fetches information
about defined connections at initialization time, and will error on workspace load if the Airbyte
instance is not reachable.
Args:
airbyte (ResourceDefinition): An AirbyteResource configured with the appropriate connection
details.
workspace_id (Optional[str]): The ID of the Airbyte workspace to load connections from. Only
required if multiple workspaces exist in your instance.
key_prefix (Optional[CoercibleToAssetKeyPrefix]): A prefix for the asset keys created.
create_assets_for_normalization_tables (bool): If True, assets will be created for tables
created by Airbyte's normalization feature. If False, only the destination tables
will be created. Defaults to True.
connection_to_group_fn (Optional[Callable[[str], Optional[str]]]): Function which returns an asset
group name for a given Airbyte connection name. If None, no groups will be created. Defaults
to a basic sanitization function.
connection_meta_to_group_fn (Optional[Callable[[AirbyteConnectionMetadata], Optional[str]]]): Function which
returns an asset group name for a given Airbyte connection metadata. If None and connection_to_group_fn
is None, no groups will be created
io_manager_key (Optional[str]): The I/O manager key to use for all assets. Defaults to "io_manager".
Use this if all assets should be loaded from the same source, otherwise use connection_to_io_manager_key_fn.
connection_to_io_manager_key_fn (Optional[Callable[[str], Optional[str]]]): Function which returns an
I/O manager key for a given Airbyte connection name. When other ops are downstream of the loaded assets,
the IOManager specified determines how the inputs to those ops are loaded. Defaults to "io_manager".
connection_filter (Optional[Callable[[AirbyteConnectionMetadata], bool]]): Optional function which takes
in connection metadata and returns False if the connection should be excluded from the output assets.
connection_to_asset_key_fn (Optional[Callable[[AirbyteConnectionMetadata, str], AssetKey]]): Optional function which
takes in connection metadata and table name and returns an asset key for the table. If None, the default asset
key is based on the table name. Any asset key prefix will be applied to the output of this function.
connection_to_freshness_policy_fn (Optional[Callable[[AirbyteConnectionMetadata], Optional[FreshnessPolicy]]]): Optional function
which takes in connection metadata and returns a freshness policy for the connection's assets. If None, no freshness policies
will be applied to the assets.
connection_to_auto_materialize_policy_fn (Optional[Callable[[AirbyteConnectionMetadata], Optional[AutoMaterializePolicy]]]): Optional
function which takes in connection metadata and returns an auto materialization policy for the connection's assets. If None, no
auto materialization policies will be applied to the assets.
**Examples:**
Loading all Airbyte connections as assets:
.. code-block:: python
from dagster_airbyte import airbyte_resource, load_assets_from_airbyte_instance
airbyte_instance = airbyte_resource.configured(
{
"host": "localhost",
"port": "8000",
}
)
airbyte_assets = load_assets_from_airbyte_instance(airbyte_instance)
Filtering the set of loaded connections:
.. code-block:: python
from dagster_airbyte import airbyte_resource, load_assets_from_airbyte_instance
airbyte_instance = airbyte_resource.configured(
{
"host": "localhost",
"port": "8000",
}
)
airbyte_assets = load_assets_from_airbyte_instance(
airbyte_instance,
connection_filter=lambda meta: "snowflake" in meta.name,
)
"""
if isinstance(airbyte, AirbyteCloudResource):
raise DagsterInvalidInvocationError(
"load_assets_from_airbyte_instance is not yet supported for AirbyteCloudResource"
)
if isinstance(key_prefix, str):
key_prefix = [key_prefix]
key_prefix = check.list_param(key_prefix or [], "key_prefix", of_type=str)
check.invariant(
not io_manager_key or not connection_to_io_manager_key_fn,
"Cannot specify both io_manager_key and connection_to_io_manager_key_fn",
)
if not connection_to_io_manager_key_fn:
connection_to_io_manager_key_fn = lambda _: io_manager_key
check.invariant(
not connection_meta_to_group_fn
or not connection_to_group_fn
or connection_to_group_fn == clean_name,
"Cannot specify both connection_meta_to_group_fn and connection_to_group_fn",
)
if not connection_meta_to_group_fn and connection_to_group_fn:
connection_meta_to_group_fn = lambda meta: connection_to_group_fn(meta.name)
return AirbyteInstanceCacheableAssetsDefinition(
airbyte_resource_def=airbyte,
workspace_id=workspace_id,
key_prefix=key_prefix,
create_assets_for_normalization_tables=create_assets_for_normalization_tables,
connection_meta_to_group_fn=connection_meta_to_group_fn,
connection_to_io_manager_key_fn=connection_to_io_manager_key_fn,
connection_filter=connection_filter,
connection_to_asset_key_fn=connection_to_asset_key_fn,
connection_to_freshness_policy_fn=connection_to_freshness_policy_fn,
connection_to_auto_materialize_policy_fn=connection_to_auto_materialize_policy_fn,
)
# -----------------------
# Reworked assets factory
# -----------------------
@beta
def build_airbyte_assets_definitions(
*,
workspace: Union[AirbyteWorkspace, AirbyteCloudWorkspace],
dagster_airbyte_translator: Optional[DagsterAirbyteTranslator] = None,
connection_selector_fn: Optional[Callable[[AirbyteConnection], bool]] = None,
) -> Sequence[AssetsDefinition]:
"""The list of AssetsDefinition for all connections in the Airbyte workspace.
Args:
workspace (Union[AirbyteWorkspace, AirbyteCloudWorkspace]): The Airbyte workspace to fetch assets from.
dagster_airbyte_translator (Optional[DagsterAirbyteTranslator], optional): The translator to use
to convert Airbyte content into :py:class:`dagster.AssetSpec`.
Defaults to :py:class:`DagsterAirbyteTranslator`.
connection_selector_fn (Optional[Callable[[AirbyteConnection], bool]]): A function that allows for filtering
which Airbyte connection assets are created for.
Returns:
List[AssetsDefinition]: The list of AssetsDefinition for all connections in the Airbyte workspace.
Examples:
Sync the tables of a Airbyte connection:
.. code-block:: python
from dagster_airbyte import AirbyteCloudWorkspace, build_airbyte_assets_definitions
import dagster as dg
airbyte_workspace = AirbyteCloudWorkspace(
workspace_id=dg.EnvVar("AIRBYTE_CLOUD_WORKSPACE_ID"),
client_id=dg.EnvVar("AIRBYTE_CLOUD_CLIENT_ID"),
client_secret=dg.EnvVar("AIRBYTE_CLOUD_CLIENT_SECRET"),
)
airbyte_assets = build_airbyte_assets_definitions(workspace=workspace)
defs = dg.Definitions(
assets=airbyte_assets,
resources={"airbyte": airbyte_workspace},
)
Sync the tables of a Airbyte connection with a custom translator:
.. code-block:: python
from dagster_airbyte import (
DagsterAirbyteTranslator,
AirbyteConnectionTableProps,
AirbyteCloudWorkspace,
build_airbyte_assets_definitions
)
import dagster as dg
class CustomDagsterAirbyteTranslator(DagsterAirbyteTranslator):
def get_asset_spec(self, props: AirbyteConnectionTableProps) -> dg.AssetSpec:
default_spec = super().get_asset_spec(props)
return default_spec.merge_attributes(
metadata={"custom": "metadata"},
)
airbyte_workspace = AirbyteCloudWorkspace(
workspace_id=dg.EnvVar("AIRBYTE_CLOUD_WORKSPACE_ID"),
client_id=dg.EnvVar("AIRBYTE_CLOUD_CLIENT_ID"),
client_secret=dg.EnvVar("AIRBYTE_CLOUD_CLIENT_SECRET"),
)
airbyte_assets = build_airbyte_assets_definitions(
workspace=workspace,
dagster_airbyte_translator=CustomDagsterAirbyteTranslator()
)
defs = dg.Definitions(
assets=airbyte_assets,
resources={"airbyte": airbyte_workspace},
)
Filter connections by name:
.. code-block:: python
from dagster_airbyte import AirbyteCloudWorkspace, build_airbyte_assets_definitions
import dagster as dg
airbyte_workspace = AirbyteCloudWorkspace(
workspace_id=dg.EnvVar("AIRBYTE_CLOUD_WORKSPACE_ID"),
client_id=dg.EnvVar("AIRBYTE_CLOUD_CLIENT_ID"),
client_secret=dg.EnvVar("AIRBYTE_CLOUD_CLIENT_SECRET"),
)
airbyte_assets = build_airbyte_assets_definitions(
workspace=workspace,
connection_selector_fn=lambda connection: connection.name in ["connection1", "connection2"]
)
defs = dg.Definitions(
assets=airbyte_assets,
resources={"airbyte": airbyte_workspace},
)
"""
dagster_airbyte_translator = dagster_airbyte_translator or DagsterAirbyteTranslator()
connection_selector_fn = connection_selector_fn or (lambda connection: True)
all_asset_specs = workspace.load_asset_specs(
dagster_airbyte_translator=dagster_airbyte_translator,
connection_selector_fn=connection_selector_fn,
)
connections = {
(
check.not_none(AirbyteMetadataSet.extract(spec.metadata).connection_id),
check.not_none(AirbyteMetadataSet.extract(spec.metadata).connection_name),
)
for spec in all_asset_specs
}
_asset_fns = []
for connection_id, connection_name in connections:
@airbyte_assets(
connection_id=connection_id,
workspace=workspace,
name=f"airbyte_{clean_name(connection_name)}",
dagster_airbyte_translator=dagster_airbyte_translator,
)
def _asset_fn(context: AssetExecutionContext, airbyte: BaseAirbyteWorkspace):
yield from airbyte.sync_and_poll(context=context)
_asset_fns.append(_asset_fn)
return _asset_fns
| AirbyteYAMLCacheableAssetsDefinition |
python | catalyst-team__catalyst | catalyst/callbacks/criterion.py | {
"start": 220,
"end": 1896
} | class ____(FunctionalMetricCallback, ICriterionCallback):
"""Criterion callback, abstraction over criterion step.
Args:
input_key: input key to use for metric calculation, specifies our `y_pred`
target_key: output key to use for metric calculation, specifies our `y_true`
metric_key: key to store computed metric in ``runner.batch_metrics`` dictionary
criterion_key: A key to take a criterion in case
there are several of them, and they are in a dictionary format.
.. note::
Please follow the `minimal examples`_ sections for more use cases.
.. _`minimal examples`: https://github.com/catalyst-team/catalyst#minimal-examples # noqa: E501, W505
"""
def __init__(
self,
input_key: str,
target_key: str,
metric_key: str,
criterion_key: str = None,
prefix: str = None,
suffix: str = None,
):
"""Init."""
super().__init__(
input_key=input_key,
target_key=target_key,
metric_fn=self._metric_fn,
metric_key=metric_key,
compute_on_call=True,
log_on_batch=True,
prefix=prefix,
suffix=suffix,
)
self.criterion_key = criterion_key
self.criterion = None
def _metric_fn(self, *args, **kwargs):
return self.criterion(*args, **kwargs)
def on_experiment_start(self, runner: "IRunner"):
"""Event handler."""
self.criterion = get_attr(runner, key="criterion", inner_key=self.criterion_key)
assert self.criterion is not None
__all__ = ["CriterionCallback"]
| CriterionCallback |
python | has2k1__plotnine | plotnine/_mpl/patches.py | {
"start": 3347,
"end": 3838
} | class ____(Rectangle):
"""
A rectangle whose stroked is fully contained within it
"""
@artist.allow_rasterization
def draw(self, renderer):
"""
Draw with the bounds of the rectangle adjusted to contain the stroke
"""
x, y = self.xy
w, h = self.get_width(), self.get_height()
lw = self.get_linewidth()
self.set_bounds((x + lw / 2), (y + lw / 2), (w - lw), (h - lw))
super().draw(renderer)
| InsideStrokedRectangle |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.