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
|
getsentry__sentry
|
tests/sentry/issues/auto_source_code_config/test_code_mapping.py
|
{
"start": 3280,
"end": 13680
}
|
class ____(TestCase):
@pytest.fixture(autouse=True)
def inject_fixtures(self, caplog: pytest.LogCaptureFixture) -> None:
self._caplog = caplog
def setUp(self) -> None:
super().setUp()
self.foo_repo = RepoAndBranch("Test-Organization/foo", "master")
self.bar_repo = RepoAndBranch("Test-Organization/bar", "main")
self.code_mapping_helper = CodeMappingTreesHelper(
{
self.foo_repo.name: RepoTree(self.foo_repo, files=SENTRY_FILES),
self.bar_repo.name: RepoTree(self.bar_repo, files=["sentry/web/urls.py"]),
}
)
self.expected_code_mappings = [
CodeMapping(repo=self.foo_repo, stacktrace_root="sentry/", source_path="src/sentry/"),
CodeMapping(
repo=self.foo_repo,
stacktrace_root="sentry_plugins/",
source_path="src/sentry_plugins/",
),
]
def test_package_also_matches(self) -> None:
repo_tree = RepoTree(self.foo_repo, files=["apostello/views/base.py"])
# We create a new tree helper in order to improve the understability of this test
cmh = CodeMappingTreesHelper({self.foo_repo.name: repo_tree})
cm = cmh._generate_code_mapping_from_tree(
repo_tree=repo_tree, frame_filename=create_frame_info({"filename": "raven/base.py"})
)
# We should not derive a code mapping since the package name does not match
assert cm == []
def test_no_matches(self) -> None:
frames = [
{"filename": "getsentry/billing/tax/manager.py"},
{"filename": "requests/models.py"},
{"filename": "urllib3/connectionpool.py"},
{"filename": "ssl.py"},
]
code_mappings = self.code_mapping_helper.generate_code_mappings(frames)
assert code_mappings == []
@patch("sentry.issues.auto_source_code_config.code_mapping.logger")
def test_matches_top_src_file(self, logger: Any) -> None:
frames = [{"filename": "setup.py"}]
code_mappings = self.code_mapping_helper.generate_code_mappings(frames)
assert code_mappings == []
def test_no_dir_depth_match(self) -> None:
frames = [{"filename": "sentry/wsgi.py"}]
code_mappings = self.code_mapping_helper.generate_code_mappings(frames)
assert code_mappings == [
CodeMapping(
repo=RepoAndBranch(name="Test-Organization/foo", branch="master"),
stacktrace_root="sentry/",
source_path="src/sentry/",
)
]
def test_more_than_one_match_does_derive(self) -> None:
frames = [
# More than one file matches for this, however, the package name is taken into account
# - "src/sentry_plugins/slack/client.py",
# - "src/sentry/integrations/slack/client.py",
{"filename": "sentry_plugins/slack/client.py"},
]
code_mappings = self.code_mapping_helper.generate_code_mappings(frames)
assert code_mappings == [
CodeMapping(
repo=self.foo_repo,
stacktrace_root="sentry_plugins/",
source_path="src/sentry_plugins/",
)
]
def test_no_stacktraces_to_process(self) -> None:
code_mappings = self.code_mapping_helper.generate_code_mappings([])
assert code_mappings == []
def test_more_than_one_match_works_when_code_mapping_excludes_other_match(self) -> None:
frames = [
{"filename": "sentry/identity/oauth2.py"},
{"filename": "sentry_plugins/slack/client.py"},
]
code_mappings = self.code_mapping_helper.generate_code_mappings(frames)
assert code_mappings == self.expected_code_mappings
def test_more_than_one_match_works_with_different_order(self) -> None:
frames = [
# This file matches twice files in the repo, however, the reprocessing
# feature allows deriving both code mappings
{"filename": "sentry_plugins/slack/client.py"},
{"filename": "sentry/identity/oauth2.py"},
]
code_mappings = self.code_mapping_helper.generate_code_mappings(frames)
assert sorted(code_mappings) == sorted(self.expected_code_mappings)
@patch("sentry.issues.auto_source_code_config.code_mapping.logger")
def test_more_than_one_repo_match(self, logger: Any) -> None:
# XXX: There's a chance that we could infer package names but that is risky
# repo 1: src/sentry/web/urls.py
# repo 2: sentry/web/urls.py
frames = [{"filename": "sentry/web/urls.py"}]
code_mappings = self.code_mapping_helper.generate_code_mappings(frames)
# The file appears in more than one repo, thus, we are unable to determine the code mapping
assert code_mappings == []
logger.warning.assert_called_with("More than one repo matched %s", "sentry/web/urls.py")
def test_get_file_and_repo_matches_single(self) -> None:
frame_filename = create_frame_info({"filename": "sentry_plugins/slack/client.py"})
matches = self.code_mapping_helper.get_file_and_repo_matches(frame_filename)
expected_matches = [
{
"filename": "src/sentry_plugins/slack/client.py",
"repo_name": "Test-Organization/foo",
"repo_branch": "master",
"stacktrace_root": "sentry_plugins/",
"source_path": "src/sentry_plugins/",
}
]
assert matches == expected_matches
def test_get_file_and_repo_matches_multiple(self) -> None:
frame_filename = create_frame_info({"filename": "sentry/web/urls.py"})
matches = self.code_mapping_helper.get_file_and_repo_matches(frame_filename)
expected_matches = [
{
"filename": "src/sentry/web/urls.py",
"repo_name": "Test-Organization/foo",
"repo_branch": "master",
"stacktrace_root": "sentry/",
"source_path": "src/sentry/",
},
{
"filename": "sentry/web/urls.py",
"repo_name": "Test-Organization/bar",
"repo_branch": "main",
"stacktrace_root": "",
"source_path": "",
},
]
assert matches == expected_matches
def test_find_roots_starts_with_period_slash(self) -> None:
stacktrace_root, source_path = find_roots(
create_frame_info({"filename": "./app/foo.tsx"}), "static/app/foo.tsx"
)
assert stacktrace_root == "./"
assert source_path == "static/"
def test_find_roots_starts_with_period_slash_no_containing_directory(self) -> None:
stacktrace_root, source_path = find_roots(
create_frame_info({"filename": "./app/foo.tsx"}), "app/foo.tsx"
)
assert stacktrace_root == "./"
assert source_path == ""
def test_find_roots_not_matching(self) -> None:
stacktrace_root, source_path = find_roots(
create_frame_info({"filename": "sentry/foo.py"}), "src/sentry/foo.py"
)
assert stacktrace_root == "sentry/"
assert source_path == "src/sentry/"
def test_find_roots_equal(self) -> None:
stacktrace_root, source_path = find_roots(
create_frame_info({"filename": "source/foo.py"}), "source/foo.py"
)
assert stacktrace_root == ""
assert source_path == ""
def test_find_roots_starts_with_period_slash_two_levels(self) -> None:
stacktrace_root, source_path = find_roots(
create_frame_info({"filename": "./app/foo.tsx"}), "app/foo/app/foo.tsx"
)
assert stacktrace_root == "./"
assert source_path == "app/foo/"
def test_find_roots_starts_with_app(self) -> None:
stacktrace_root, source_path = find_roots(
create_frame_info({"filename": "app:///utils/foo.tsx"}), "utils/foo.tsx"
)
assert stacktrace_root == "app:///"
assert source_path == ""
def test_find_roots_starts_with_multiple_dot_dot_slash(self) -> None:
stacktrace_root, source_path = find_roots(
create_frame_info({"filename": "../../../../../../packages/foo.tsx"}),
"packages/foo.tsx",
)
assert stacktrace_root == "../../../../../../"
assert source_path == ""
def test_find_roots_starts_with_app_dot_dot_slash(self) -> None:
stacktrace_root, source_path = find_roots(
create_frame_info({"filename": "app:///../services/foo.tsx"}),
"services/foo.tsx",
)
assert stacktrace_root == "app:///../"
assert source_path == ""
def test_find_roots_bad_stack_path(self) -> None:
with pytest.raises(UnsupportedFrameInfo):
create_frame_info({"filename": "https://yrurlsinyourstackpath.com/"})
def test_find_roots_bad_source_path(self) -> None:
with pytest.raises(UnexpectedPathException):
find_roots(
create_frame_info({"filename": "sentry/random.py"}),
"nothing/something.js",
)
def test_find_roots_windows_path_with_spaces(self) -> None:
stacktrace_root, source_path = find_roots(
create_frame_info({"filename": "C:\\Program Files\\MyApp\\src\\file.py"}), "src/file.py"
)
assert stacktrace_root == "C:\\Program Files\\MyApp\\"
assert source_path == ""
def test_find_roots_windows_path_with_spaces_nested(self) -> None:
stacktrace_root, source_path = find_roots(
create_frame_info(
{"filename": "C:\\Program Files\\My Company\\My App\\src\\main\\file.py"}
),
"src/main/file.py",
)
assert stacktrace_root == "C:\\Program Files\\My Company\\My App\\"
assert source_path == ""
def test_find_roots_windows_path_with_spaces_source_match(self) -> None:
stacktrace_root, source_path = find_roots(
create_frame_info({"filename": "C:\\Program Files\\MyApp\\src\\components\\file.py"}),
"frontend/src/components/file.py",
)
assert stacktrace_root == "C:\\Program Files\\MyApp\\"
assert source_path == "frontend/"
|
TestDerivedCodeMappings
|
python
|
ray-project__ray
|
doc/source/serve/doc_code/object_detection.py
|
{
"start": 312,
"end": 955
}
|
class ____:
def __init__(self, object_detection_handle: DeploymentHandle):
self.handle = object_detection_handle
@app.get(
"/detect",
responses={200: {"content": {"image/jpeg": {}}}},
response_class=Response,
)
async def detect(self, image_url: str):
image = await self.handle.detect.remote(image_url)
file_stream = BytesIO()
image.save(file_stream, "jpeg")
return Response(content=file_stream.getvalue(), media_type="image/jpeg")
@serve.deployment(
ray_actor_options={"num_gpus": 1},
autoscaling_config={"min_replicas": 1, "max_replicas": 2},
)
|
APIIngress
|
python
|
walkccc__LeetCode
|
solutions/2598. Smallest Missing Non-negative Integer After Operations/2598.py
|
{
"start": 0,
"end": 279
}
|
class ____:
def findSmallestInteger(self, nums: list[int], value: int) -> int:
count = collections.Counter([num % value for num in nums])
for i in range(len(nums)):
if count[i % value] == 0:
return i
count[i % value] -= 1
return len(nums)
|
Solution
|
python
|
kamyu104__LeetCode-Solutions
|
Python/longest-happy-string.py
|
{
"start": 44,
"end": 1144
}
|
class ____(object):
def longestDiverseString(self, a, b, c):
"""
:type a: int
:type b: int
:type c: int
:rtype: str
"""
max_heap = []
if a:
heapq.heappush(max_heap, (-a, 'a'))
if b:
heapq.heappush(max_heap, (-b, 'b'))
if c:
heapq.heappush(max_heap, (-c, 'c'))
result = []
while max_heap:
count1, c1 = heapq.heappop(max_heap)
if len(result) >= 2 and result[-1] == result[-2] == c1:
if not max_heap:
return "".join(result)
count2, c2 = heapq.heappop(max_heap)
result.append(c2)
count2 += 1
if count2:
heapq.heappush(max_heap, (count2, c2))
heapq.heappush(max_heap, (count1, c1))
continue
result.append(c1)
count1 += 1
if count1 != 0:
heapq.heappush(max_heap, (count1, c1))
return "".join(result)
# Time: O(n)
# Space: O(1)
|
Solution
|
python
|
pytorch__pytorch
|
test/dynamo/cpython/3_13/test_collections.py
|
{
"start": 32152,
"end": 34375
}
|
class ____(__TestCase):
def validate_abstract_methods(self, abc, *names):
methodstubs = dict.fromkeys(names, lambda s, *args: 0)
# everything should work will all required methods are present
with torch._dynamo.error_on_graph_break(False):
C = type('C', (abc,), methodstubs)
C()
# Dynamo raises a hard error here that we can't easily capture
# Commenting this part as this would also fail in eager if a user
# attempt to run the same code
# instantiation should fail if a required method is missing
# for name in names:
# stubs = methodstubs.copy()
# del stubs[name]
# C = type('C', (abc,), stubs)
# self.assertRaises(TypeError, C, name)
def validate_isinstance(self, abc, name):
stub = lambda s, *args: 0
C = type('C', (object,), {'__hash__': None})
setattr(C, name, stub)
self.assertIsInstance(C(), abc)
self.assertTrue(issubclass(C, abc))
C = type('C', (object,), {'__hash__': None})
self.assertNotIsInstance(C(), abc)
self.assertFalse(issubclass(C, abc))
def validate_comparison(self, instance):
ops = ['lt', 'gt', 'le', 'ge', 'ne', 'or', 'and', 'xor', 'sub']
operators = {}
for op in ops:
name = '__' + op + '__'
operators[name] = getattr(operator, name)
class Other:
def __init__(self):
self.right_side = False
def __eq__(self, other):
self.right_side = True
return True
__lt__ = __eq__
__gt__ = __eq__
__le__ = __eq__
__ge__ = __eq__
__ne__ = __eq__
__ror__ = __eq__
__rand__ = __eq__
__rxor__ = __eq__
__rsub__ = __eq__
for name, op in operators.items():
if not hasattr(instance, name):
continue
other = Other()
op(instance, other)
self.assertTrue(other.right_side,'Right side not called for %s.%s'
% (type(instance), name))
def _test_gen():
yield
|
ABCTestCase
|
python
|
kubernetes-client__python
|
kubernetes/client/models/v1beta1_service_cidr_list.py
|
{
"start": 383,
"end": 7041
}
|
class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'api_version': 'str',
'items': 'list[V1beta1ServiceCIDR]',
'kind': 'str',
'metadata': 'V1ListMeta'
}
attribute_map = {
'api_version': 'apiVersion',
'items': 'items',
'kind': 'kind',
'metadata': 'metadata'
}
def __init__(self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None): # noqa: E501
"""V1beta1ServiceCIDRList - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._api_version = None
self._items = None
self._kind = None
self._metadata = None
self.discriminator = None
if api_version is not None:
self.api_version = api_version
self.items = items
if kind is not None:
self.kind = kind
if metadata is not None:
self.metadata = metadata
@property
def api_version(self):
"""Gets the api_version of this V1beta1ServiceCIDRList. # noqa: E501
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:return: The api_version of this V1beta1ServiceCIDRList. # noqa: E501
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""Sets the api_version of this V1beta1ServiceCIDRList.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:param api_version: The api_version of this V1beta1ServiceCIDRList. # noqa: E501
:type: str
"""
self._api_version = api_version
@property
def items(self):
"""Gets the items of this V1beta1ServiceCIDRList. # noqa: E501
items is the list of ServiceCIDRs. # noqa: E501
:return: The items of this V1beta1ServiceCIDRList. # noqa: E501
:rtype: list[V1beta1ServiceCIDR]
"""
return self._items
@items.setter
def items(self, items):
"""Sets the items of this V1beta1ServiceCIDRList.
items is the list of ServiceCIDRs. # noqa: E501
:param items: The items of this V1beta1ServiceCIDRList. # noqa: E501
:type: list[V1beta1ServiceCIDR]
"""
if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501
raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501
self._items = items
@property
def kind(self):
"""Gets the kind of this V1beta1ServiceCIDRList. # noqa: E501
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:return: The kind of this V1beta1ServiceCIDRList. # noqa: E501
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""Sets the kind of this V1beta1ServiceCIDRList.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:param kind: The kind of this V1beta1ServiceCIDRList. # noqa: E501
:type: str
"""
self._kind = kind
@property
def metadata(self):
"""Gets the metadata of this V1beta1ServiceCIDRList. # noqa: E501
:return: The metadata of this V1beta1ServiceCIDRList. # noqa: E501
:rtype: V1ListMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Sets the metadata of this V1beta1ServiceCIDRList.
:param metadata: The metadata of this V1beta1ServiceCIDRList. # noqa: E501
:type: V1ListMeta
"""
self._metadata = metadata
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1beta1ServiceCIDRList):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1beta1ServiceCIDRList):
return True
return self.to_dict() != other.to_dict()
|
V1beta1ServiceCIDRList
|
python
|
pandas-dev__pandas
|
pandas/io/clipboard/__init__.py
|
{
"start": 2079,
"end": 9757
}
|
class ____(PyperclipException):
pass
def _stringifyText(text) -> str:
acceptedTypes = (str, int, float, bool)
if not isinstance(text, acceptedTypes):
raise PyperclipException(
f"only str, int, float, and bool values "
f"can be copied to the clipboard, not {type(text).__name__}"
)
return str(text)
def init_osx_pbcopy_clipboard():
def copy_osx_pbcopy(text):
text = _stringifyText(text) # Converts non-str values to str.
with subprocess.Popen(
["pbcopy", "w"], stdin=subprocess.PIPE, close_fds=True
) as p:
p.communicate(input=text.encode(ENCODING))
def paste_osx_pbcopy():
with subprocess.Popen(
["pbpaste", "r"], stdout=subprocess.PIPE, close_fds=True
) as p:
stdout = p.communicate()[0]
return stdout.decode(ENCODING)
return copy_osx_pbcopy, paste_osx_pbcopy
def init_osx_pyobjc_clipboard():
def copy_osx_pyobjc(text):
"""Copy string argument to clipboard"""
text = _stringifyText(text) # Converts non-str values to str.
newStr = Foundation.NSString.stringWithString_(text).nsstring()
newData = newStr.dataUsingEncoding_(Foundation.NSUTF8StringEncoding)
board = AppKit.NSPasteboard.generalPasteboard()
board.declareTypes_owner_([AppKit.NSStringPboardType], None)
board.setData_forType_(newData, AppKit.NSStringPboardType)
def paste_osx_pyobjc():
"""Returns contents of clipboard"""
board = AppKit.NSPasteboard.generalPasteboard()
content = board.stringForType_(AppKit.NSStringPboardType)
return content
return copy_osx_pyobjc, paste_osx_pyobjc
def init_qt_clipboard():
global QApplication
# $DISPLAY should exist
# Try to import from qtpy, but if that fails try PyQt5 then PyQt4
try:
from qtpy.QtWidgets import QApplication
except ImportError:
try:
from PyQt5.QtWidgets import QApplication
except ImportError:
from PyQt4.QtGui import QApplication
app = QApplication.instance()
if app is None:
app = QApplication([])
def copy_qt(text):
text = _stringifyText(text) # Converts non-str values to str.
cb = app.clipboard()
cb.setText(text)
def paste_qt() -> str:
cb = app.clipboard()
return str(cb.text())
return copy_qt, paste_qt
def init_xclip_clipboard():
DEFAULT_SELECTION = "c"
PRIMARY_SELECTION = "p"
def copy_xclip(text, primary=False):
text = _stringifyText(text) # Converts non-str values to str.
selection = DEFAULT_SELECTION
if primary:
selection = PRIMARY_SELECTION
with subprocess.Popen(
["xclip", "-selection", selection], stdin=subprocess.PIPE, close_fds=True
) as p:
p.communicate(input=text.encode(ENCODING))
def paste_xclip(primary=False):
selection = DEFAULT_SELECTION
if primary:
selection = PRIMARY_SELECTION
with subprocess.Popen(
["xclip", "-selection", selection, "-o"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True,
) as p:
stdout = p.communicate()[0]
# Intentionally ignore extraneous output on stderr when clipboard is empty
return stdout.decode(ENCODING)
return copy_xclip, paste_xclip
def init_xsel_clipboard():
DEFAULT_SELECTION = "-b"
PRIMARY_SELECTION = "-p"
def copy_xsel(text, primary=False):
text = _stringifyText(text) # Converts non-str values to str.
selection_flag = DEFAULT_SELECTION
if primary:
selection_flag = PRIMARY_SELECTION
with subprocess.Popen(
["xsel", selection_flag, "-i"], stdin=subprocess.PIPE, close_fds=True
) as p:
p.communicate(input=text.encode(ENCODING))
def paste_xsel(primary=False):
selection_flag = DEFAULT_SELECTION
if primary:
selection_flag = PRIMARY_SELECTION
with subprocess.Popen(
["xsel", selection_flag, "-o"], stdout=subprocess.PIPE, close_fds=True
) as p:
stdout = p.communicate()[0]
return stdout.decode(ENCODING)
return copy_xsel, paste_xsel
def init_wl_clipboard():
PRIMARY_SELECTION = "-p"
def copy_wl(text, primary=False):
text = _stringifyText(text) # Converts non-str values to str.
args = ["wl-copy"]
if primary:
args.append(PRIMARY_SELECTION)
if not text:
args.append("--clear")
subprocess.check_call(args, close_fds=True)
else:
p = subprocess.Popen(args, stdin=subprocess.PIPE, close_fds=True)
p.communicate(input=text.encode(ENCODING))
def paste_wl(primary=False):
args = ["wl-paste", "-n"]
if primary:
args.append(PRIMARY_SELECTION)
p = subprocess.Popen(args, stdout=subprocess.PIPE, close_fds=True)
stdout, _stderr = p.communicate()
return stdout.decode(ENCODING)
return copy_wl, paste_wl
def init_klipper_clipboard():
def copy_klipper(text):
text = _stringifyText(text) # Converts non-str values to str.
with subprocess.Popen(
[
"qdbus",
"org.kde.klipper",
"/klipper",
"setClipboardContents",
text.encode(ENCODING),
],
stdin=subprocess.PIPE,
close_fds=True,
) as p:
p.communicate(input=None)
def paste_klipper():
with subprocess.Popen(
["qdbus", "org.kde.klipper", "/klipper", "getClipboardContents"],
stdout=subprocess.PIPE,
close_fds=True,
) as p:
stdout = p.communicate()[0]
# Workaround for https://bugs.kde.org/show_bug.cgi?id=342874
# TODO: https://github.com/asweigart/pyperclip/issues/43
clipboardContents = stdout.decode(ENCODING)
# even if blank, Klipper will append a newline at the end
assert len(clipboardContents) > 0
# make sure that newline is there
assert clipboardContents.endswith("\n")
if clipboardContents.endswith("\n"):
clipboardContents = clipboardContents[:-1]
return clipboardContents
return copy_klipper, paste_klipper
def init_dev_clipboard_clipboard():
def copy_dev_clipboard(text):
text = _stringifyText(text) # Converts non-str values to str.
if text == "":
warnings.warn(
"Pyperclip cannot copy a blank string to the clipboard on Cygwin. "
"This is effectively a no-op.",
stacklevel=find_stack_level(),
)
if "\r" in text:
warnings.warn(
"Pyperclip cannot handle \\r characters on Cygwin.",
stacklevel=find_stack_level(),
)
with open("/dev/clipboard", "w", encoding="utf-8") as fd:
fd.write(text)
def paste_dev_clipboard() -> str:
with open("/dev/clipboard", encoding="utf-8") as fd:
content = fd.read()
return content
return copy_dev_clipboard, paste_dev_clipboard
def init_no_clipboard():
class ClipboardUnavailable:
def __call__(self, *args, **kwargs):
raise PyperclipException(EXCEPT_MSG)
def __bool__(self) -> bool:
return False
return ClipboardUnavailable(), ClipboardUnavailable()
# Windows-related clipboard functions:
|
PyperclipTimeoutException
|
python
|
has2k1__plotnine
|
plotnine/themes/themeable.py
|
{
"start": 36705,
"end": 36883
}
|
class ____(axis_ticks_major_x, axis_ticks_major_y):
"""
x & y axis major tick lines
Parameters
----------
theme_element : element_line
"""
|
axis_ticks_major
|
python
|
dagster-io__dagster
|
python_modules/dagster/dagster/_daemon/daemon.py
|
{
"start": 9776,
"end": 10693
}
|
class ____(DagsterDaemon):
@classmethod
def daemon_type(cls) -> str:
return "SCHEDULER"
def scheduler_delay_instrumentation(
self, scheduler_id: str, next_iteration_timestamp: float, now_timestamp: float
) -> None:
pass
def core_loop(
self,
workspace_process_context: IWorkspaceProcessContext,
shutdown_event: Event,
) -> DaemonIterator:
scheduler = workspace_process_context.instance.scheduler
if not isinstance(scheduler, DagsterDaemonScheduler):
check.failed(f"Expected DagsterDaemonScheduler, got {scheduler}")
yield from execute_scheduler_iteration_loop(
workspace_process_context,
self._logger,
scheduler.max_catchup_runs,
scheduler.max_tick_retries,
shutdown_event,
self.scheduler_delay_instrumentation,
)
|
SchedulerDaemon
|
python
|
getsentry__sentry
|
src/sentry/grouping/parameterization.py
|
{
"start": 9513,
"end": 11981
}
|
class ____:
def __init__(
self,
regex_pattern_keys: Sequence[str],
experimental: bool = False,
):
self._experimental = experimental
self._parameterization_regex = self._make_regex_from_patterns(regex_pattern_keys)
self.matches_counter: defaultdict[str, int] = defaultdict(int)
def _make_regex_from_patterns(self, pattern_keys: Sequence[str]) -> re.Pattern[str]:
"""
Takes list of pattern keys and returns a compiled regex pattern that matches any of them.
@param pattern_keys: A list of keys to match in the _parameterization_regex_components dict.
@returns: A compiled regex pattern that matches any of the given keys.
@raises: KeyError on pattern key not in the _parameterization_regex_components dict
The `(?x)` tells the regex compiler to ignore comments and unescaped whitespace,
so we can use newlines and indentation for better legibility in patterns above.
"""
regexes_map = (
EXPERIMENTAL_PARAMETERIZATION_REGEXES_MAP
if self._experimental
else DEFAULT_PARAMETERIZATION_REGEXES_MAP
)
return re.compile(rf"(?x){'|'.join(regexes_map[k] for k in pattern_keys)}")
def parametrize_w_regex(self, content: str) -> str:
"""
Replace all matches of the given regex in the content with a placeholder string.
@param content: The string to replace matches in.
@param parameterization_regex: The compiled regex pattern to match.
@param match_callback: An optional callback function to call with the key of the matched pattern.
@returns: The content with all matches replaced with placeholders.
"""
def _handle_regex_match(match: re.Match[str]) -> str:
# Find the first (should be only) non-None match entry, and sub in the placeholder. For
# example, given the groupdict item `('hex', '0x40000015')`, this returns '<hex>' as a
# replacement for the original value in the string.
for key, value in match.groupdict().items():
if value is not None:
self.matches_counter[key] += 1
return f"<{key}>"
return ""
return self._parameterization_regex.sub(_handle_regex_match, content)
def parameterize_all(self, content: str) -> str:
return self.parametrize_w_regex(content)
|
Parameterizer
|
python
|
django-debug-toolbar__django-debug-toolbar
|
tests/test_integration_async.py
|
{
"start": 9595,
"end": 22824
}
|
class ____(IntegrationTestCase):
async def test_middleware_in_async_mode(self):
response = await self.async_client.get("/async_execute_sql/")
self.assertEqual(response.status_code, 200)
self.assertContains(response, "djDebug")
@override_settings(DEFAULT_CHARSET="iso-8859-1")
async def test_non_utf8_charset(self):
response = await self.async_client.get("/regular/ASCII/")
self.assertContains(response, "ASCII") # template
self.assertContains(response, "djDebug") # toolbar
response = await self.async_client.get("/regular/ASCII/")
self.assertContains(response, "ASCII") # template
self.assertContains(response, "djDebug") # toolbar
async def test_html5_validation(self):
response = await self.async_client.get("/regular/HTML5/")
parser = html5lib.HTMLParser()
content = response.content
parser.parse(content)
if parser.errors:
default_msg = ["Content is invalid HTML:"]
lines = content.split(b"\n")
for position, errorcode, datavars in parser.errors:
default_msg.append(f" {html5lib.constants.E[errorcode]}" % datavars)
default_msg.append(f" {lines[position[0] - 1]!r}")
msg = self._formatMessage(None, "\n".join(default_msg))
raise self.failureException(msg)
async def test_render_panel_checks_show_toolbar(self):
request_id = toolbar_request_id()
get_store().save_panel(
request_id, VersionsPanel.panel_id, {"value": "Test data"}
)
data = {"request_id": request_id, "panel_id": VersionsPanel.panel_id}
url = "/__debug__/render_panel/"
response = await self.async_client.get(url, data)
self.assertEqual(response.status_code, 200)
with self.settings(INTERNAL_IPS=[]):
response = await self.async_client.get(url, data)
self.assertEqual(response.status_code, 404)
async def test_middleware_render_toolbar_json(self):
"""Verify the toolbar is rendered and data is stored for a json request."""
store = get_store()
self.assertEqual(len(list(store.request_ids())), 0)
data = {"foo": "bar"}
response = await self.async_client.get(
"/json_view/", data, content_type="application/json"
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content.decode("utf-8"), '{"foo": "bar"}')
# Check the history panel's stats to verify the toolbar rendered properly.
request_ids = list(store.request_ids())
self.assertEqual(len(request_ids), 1)
toolbar = DebugToolbar.fetch(request_ids[0])
self.assertEqual(
toolbar.get_panel_by_id(HistoryPanel.panel_id).get_stats()["data"],
{"foo": "bar"},
)
async def test_template_source_checks_show_toolbar(self):
template = get_template("basic.html")
url = "/__debug__/template_source/"
data = {
"template": template.template.name,
"template_origin": signing.dumps(template.template.origin.name),
}
response = await self.async_client.get(url, data)
self.assertEqual(response.status_code, 200)
with self.settings(INTERNAL_IPS=[]):
response = await self.async_client.get(url, data)
self.assertEqual(response.status_code, 404)
async def test_template_source_errors(self):
url = "/__debug__/template_source/"
response = await self.async_client.get(url, {})
self.assertContains(
response, '"template_origin" key is required', status_code=400
)
template = get_template("basic.html")
response = await self.async_client.get(
url,
{"template_origin": signing.dumps(template.template.origin.name) + "xyz"},
)
self.assertContains(response, '"template_origin" is invalid', status_code=400)
response = await self.async_client.get(
url, {"template_origin": signing.dumps("does_not_exist.html")}
)
self.assertContains(response, "Template Does Not Exist: does_not_exist.html")
async def test_sql_select_checks_show_toolbar(self):
await self.async_client.get("/execute_sql/")
request_ids = list(get_store().request_ids())
request_id = request_ids[-1]
toolbar = DebugToolbar.fetch(request_id, SQLPanel.panel_id)
panel = toolbar.get_panel_by_id(SQLPanel.panel_id)
djdt_query_id = panel.get_stats()["queries"][-1]["djdt_query_id"]
url = "/__debug__/sql_select/"
data = {
"signed": SignedDataForm.sign(
{
"request_id": request_id,
"djdt_query_id": djdt_query_id,
}
)
}
response = await self.async_client.post(url, data)
self.assertEqual(response.status_code, 200)
with self.settings(INTERNAL_IPS=[]):
response = await self.async_client.post(url, data)
self.assertEqual(response.status_code, 404)
async def test_sql_explain_checks_show_toolbar(self):
await self.async_client.get("/execute_sql/")
request_ids = list(get_store().request_ids())
request_id = request_ids[-1]
toolbar = DebugToolbar.fetch(request_id, SQLPanel.panel_id)
panel = toolbar.get_panel_by_id(SQLPanel.panel_id)
djdt_query_id = panel.get_stats()["queries"][-1]["djdt_query_id"]
url = "/__debug__/sql_explain/"
data = {
"signed": SignedDataForm.sign(
{
"request_id": request_id,
"djdt_query_id": djdt_query_id,
}
)
}
response = await self.async_client.post(url, data)
self.assertEqual(response.status_code, 200)
with self.settings(INTERNAL_IPS=[]):
response = await self.async_client.post(url, data)
self.assertEqual(response.status_code, 404)
@unittest.skipUnless(
connection.vendor == "postgresql", "Test valid only on PostgreSQL"
)
async def test_sql_explain_postgres_union_query(self):
"""
Confirm select queries that start with a parenthesis can be explained.
"""
await self.async_client.get("/async_execute_union_sql/")
request_ids = list(get_store().request_ids())
request_id = request_ids[-1]
toolbar = DebugToolbar.fetch(request_id, SQLPanel.panel_id)
panel = toolbar.get_panel_by_id(SQLPanel.panel_id)
djdt_query_id = panel.get_stats()["queries"][-1]["djdt_query_id"]
url = "/__debug__/sql_explain/"
data = {
"signed": SignedDataForm.sign(
{
"request_id": request_id,
"djdt_query_id": djdt_query_id,
}
)
}
response = await self.async_client.post(url, data)
self.assertEqual(response.status_code, 200)
@unittest.skipUnless(
connection.vendor == "postgresql", "Test valid only on PostgreSQL"
)
async def test_sql_explain_postgres_json_field(self):
await self.async_client.get("/async_execute_json_sql/")
request_ids = list(get_store().request_ids())
request_id = request_ids[-1]
toolbar = DebugToolbar.fetch(request_id, SQLPanel.panel_id)
panel = toolbar.get_panel_by_id(SQLPanel.panel_id)
djdt_query_id = panel.get_stats()["queries"][-1]["djdt_query_id"]
url = "/__debug__/sql_explain/"
data = {
"signed": SignedDataForm.sign(
{
"request_id": request_id,
"djdt_query_id": djdt_query_id,
}
)
}
response = await self.async_client.post(url, data)
self.assertEqual(response.status_code, 200)
with self.settings(INTERNAL_IPS=[]):
response = await self.async_client.post(url, data)
self.assertEqual(response.status_code, 404)
async def test_sql_profile_checks_show_toolbar(self):
await self.async_client.get("/execute_sql/")
request_ids = list(get_store().request_ids())
request_id = request_ids[-1]
toolbar = DebugToolbar.fetch(request_id, SQLPanel.panel_id)
panel = toolbar.get_panel_by_id(SQLPanel.panel_id)
djdt_query_id = panel.get_stats()["queries"][-1]["djdt_query_id"]
url = "/__debug__/sql_profile/"
data = {
"signed": SignedDataForm.sign(
{
"request_id": request_id,
"djdt_query_id": djdt_query_id,
}
)
}
response = await self.async_client.post(url, data)
self.assertEqual(response.status_code, 200)
with self.settings(INTERNAL_IPS=[]):
response = await self.async_client.post(url, data)
self.assertEqual(response.status_code, 404)
@override_settings(DEBUG_TOOLBAR_CONFIG={"RENDER_PANELS": True})
async def test_render_panels_in_request(self):
"""
Test that panels are are rendered during the request with
RENDER_PANELS=TRUE
"""
url = "/regular/basic/"
response = await self.async_client.get(url)
self.assertIn(b'id="djDebug"', response.content)
# Verify the store id is not included.
self.assertNotIn(b"data-request-id", response.content)
# Verify the history panel was disabled
self.assertIn(
b'<input type="checkbox" data-cookie="djdtHistoryPanel" '
b'title="Enable for next and successive requests">',
response.content,
)
# Verify the a panel was rendered
self.assertIn(b"Response headers", response.content)
@override_settings(DEBUG_TOOLBAR_CONFIG={"RENDER_PANELS": False})
async def test_load_panels(self):
"""
Test that panels are not rendered during the request with
RENDER_PANELS=False
"""
url = "/execute_sql/"
response = await self.async_client.get(url)
self.assertIn(b'id="djDebug"', response.content)
# Verify the store id is included.
self.assertIn(b"data-request-id", response.content)
# Verify the history panel was not disabled
self.assertNotIn(
b'<input type="checkbox" data-cookie="djdtHistoryPanel" '
b'title="Enable for next and successive requests">',
response.content,
)
# Verify the a panel was not rendered
self.assertNotIn(b"Response headers", response.content)
async def test_view_returns_template_response(self):
response = await self.async_client.get("/template_response/basic/")
self.assertEqual(response.status_code, 200)
@override_settings(DEBUG_TOOLBAR_CONFIG={"DISABLE_PANELS": set()})
async def test_intercept_redirects(self):
response = await self.async_client.get("/redirect/")
self.assertEqual(response.status_code, 200)
# Link to LOCATION header.
self.assertIn(b'href="/regular/redirect/"', response.content)
async def test_server_timing_headers(self):
response = await self.async_client.get("/execute_sql/")
server_timing = response["Server-Timing"]
expected_partials = [
r'TimerPanel_utime;dur=(\d)*(\.(\d)*)?;desc="User CPU time", ',
r'TimerPanel_stime;dur=(\d)*(\.(\d)*)?;desc="System CPU time", ',
r'TimerPanel_total;dur=(\d)*(\.(\d)*)?;desc="Total CPU time", ',
r'TimerPanel_total_time;dur=(\d)*(\.(\d)*)?;desc="Elapsed time", ',
r'SQLPanel_sql_time;dur=(\d)*(\.(\d)*)?;desc="SQL 1 queries", ',
r'CachePanel_total_time;dur=0;desc="Cache 0 Calls"',
]
for expected in expected_partials:
self.assertTrue(re.compile(expected).search(server_timing))
@override_settings(DEBUG_TOOLBAR_CONFIG={"RENDER_PANELS": True})
async def test_timer_panel(self):
response = await self.async_client.get("/regular/basic/")
self.assertEqual(response.status_code, 200)
self.assertContains(
response,
'<script type="module" src="/static/debug_toolbar/js/timer.js" async>',
)
async def test_auth_login_view_without_redirect(self):
response = await self.async_client.get("/login_without_redirect/")
self.assertEqual(response.status_code, 200)
parser = html5lib.HTMLParser()
doc = parser.parse(response.content)
el = doc.find(".//*[@id='djDebug']")
request_id = el.attrib["data-request-id"]
response = await self.async_client.get(
"/__debug__/render_panel/",
{"request_id": request_id, "panel_id": "TemplatesPanel"},
)
self.assertEqual(response.status_code, 200)
# The key None (without quotes) exists in the list of template
# variables.
self.assertIn("None: ''", response.json()["content"])
|
DebugToolbarIntegrationTestCase
|
python
|
getsentry__sentry
|
src/sentry/users/api/endpoints/user_identity_config.py
|
{
"start": 3126,
"end": 3786
}
|
class ____(UserEndpoint):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
permission_classes = (UserAndStaffPermission,)
def get(self, request: Request, user: User) -> Response:
"""
Retrieve all of a user's SocialIdentity, Identity, and AuthIdentity values
``````````````````````````````````````````````````````````````````````````
:pparam string user ID: user ID, or 'me'
:auth: required
"""
identities = list(get_identities(user))
return Response(serialize(identities, serializer=UserIdentityConfigSerializer()))
@control_silo_endpoint
|
UserIdentityConfigEndpoint
|
python
|
getsentry__sentry
|
src/sentry/migrations/0945_move_discover_models.py
|
{
"start": 147,
"end": 2076
}
|
class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# of a table.
# Here are some things that make sense to mark as post deployment:
# - Large data migrations. Typically we want these to be run manually so that they can be
# monitored and not block the deploy for a long period of time while they run.
# - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
# run this outside deployments so that we don't block them. Note that while adding an index
# is a schema change, it's completely safe to run the operation after the code has deployed.
# Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment
is_post_deployment = False
dependencies = [
("sentry", "0944_flags_not_null"),
]
operations = [
migrations.SeparateDatabaseAndState(
state_operations=[
migrations.RemoveField(
model_name="discoversavedqueryproject",
name="discover_saved_query",
),
migrations.AlterUniqueTogether(
name="discoversavedqueryproject",
unique_together=None,
),
migrations.RemoveField(
model_name="discoversavedqueryproject",
name="project",
),
migrations.DeleteModel(
name="DiscoverSavedQuery",
),
migrations.DeleteModel(
name="DiscoverSavedQueryProject",
),
]
)
]
|
Migration
|
python
|
facebook__pyre-check
|
client/language_server/tests/connections_test.py
|
{
"start": 2813,
"end": 4685
}
|
class ____(testslide.TestCase):
async def _test_connect_async(self, socket_path: Path) -> None:
async with connect_async(socket_path) as (input_channel, output_channel):
await output_channel.write("abc\n")
result = (await input_channel.readline()).strip()
self.assertEqual("abc", result)
await output_channel.write("xyzuvw\n")
result = await input_channel.read_until("z")
self.assertEqual("xyz", result)
result = await input_channel.read_exactly(2)
self.assertEqual("uv", result)
@setup.async_test
async def test_connect(self) -> None:
with setup.spawn_unix_stream_server(EchoServerRequestHandler) as socket_path:
# Connect to test server from the main thread
await self._test_connect_async(socket_path)
@setup.async_test
async def test_read_until(self) -> None:
with setup.spawn_unix_stream_server(EchoServerRequestHandler) as socket_path:
# Intentionally use a small buffer size, to test over-sized reads
async with connect_async(socket_path, buffer_size=64) as (
input_channel,
output_channel,
):
# Try reading ~4MB of data from the input channel, and verify that
# `read_until` do not choke.
message = "a" * (2**14) + "\n"
await output_channel.write(message)
result = await input_channel.read_until("\n")
self.assertEqual(message, result)
async def test_text_errors(self) -> None:
bytes_reader = MemoryBytesReader("∅\n".encode("utf-16"))
text_reader = AsyncTextReader(bytes_reader, encoding="utf-8")
result = (await text_reader.readline()).strip()
self.assertEqual(result, '��\x05"')
|
AsyncConnectionTest
|
python
|
pytorch__pytorch
|
test/torch_np/numpy_tests/lib/test_function_base.py
|
{
"start": 5158,
"end": 7317
}
|
class ____(TestCase):
def test_axes(self):
assert_raises(np.AxisError, np.flip, np.ones(4), axis=1)
assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=2)
assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=-3)
assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=(0, 3))
@skip(reason="no [::-1] indexing")
def test_basic_lr(self):
a = get_mat(4)
b = a[:, ::-1]
assert_equal(np.flip(a, 1), b)
a = [[0, 1, 2], [3, 4, 5]]
b = [[2, 1, 0], [5, 4, 3]]
assert_equal(np.flip(a, 1), b)
@skip(reason="no [::-1] indexing")
def test_basic_ud(self):
a = get_mat(4)
b = a[::-1, :]
assert_equal(np.flip(a, 0), b)
a = [[0, 1, 2], [3, 4, 5]]
b = [[3, 4, 5], [0, 1, 2]]
assert_equal(np.flip(a, 0), b)
def test_3d_swap_axis0(self):
a = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])
b = np.array([[[4, 5], [6, 7]], [[0, 1], [2, 3]]])
assert_equal(np.flip(a, 0), b)
def test_3d_swap_axis1(self):
a = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])
b = np.array([[[2, 3], [0, 1]], [[6, 7], [4, 5]]])
assert_equal(np.flip(a, 1), b)
def test_3d_swap_axis2(self):
a = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])
b = np.array([[[1, 0], [3, 2]], [[5, 4], [7, 6]]])
assert_equal(np.flip(a, 2), b)
def test_4d(self):
a = np.arange(2 * 3 * 4 * 5).reshape(2, 3, 4, 5)
for i in range(a.ndim):
assert_equal(np.flip(a, i), np.flipud(a.swapaxes(0, i)).swapaxes(i, 0))
def test_default_axis(self):
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[6, 5, 4], [3, 2, 1]])
assert_equal(np.flip(a), b)
def test_multiple_axes(self):
a = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])
assert_equal(np.flip(a, axis=()), a)
b = np.array([[[5, 4], [7, 6]], [[1, 0], [3, 2]]])
assert_equal(np.flip(a, axis=(0, 2)), b)
c = np.array([[[3, 2], [1, 0]], [[7, 6], [5, 4]]])
assert_equal(np.flip(a, axis=(1, 2)), c)
|
TestFlip
|
python
|
dask__distributed
|
distributed/diagnostics/plugin.py
|
{
"start": 19052,
"end": 20528
}
|
class ____(InstallPlugin):
"""A plugin to conda install a set of packages
This accepts a set of packages to install on the scheduler and all
workers as well as options to use when installing.
You can also optionally ask for the workers to restart after
performing this installation.
.. note::
This will increase the time it takes to start up
the cluster. If possible, we recommend including the
libraries in the cluster environment or image. This is
primarily intended for experimentation and debugging.
Parameters
----------
packages
A list of packages (with optional versions) to install using conda
conda_options
Additional options to pass to conda
restart_workers
Whether or not to restart the worker after installing the packages
Only functions if the workers have an attached nanny process
Examples
--------
>>> from dask.distributed import CondaInstall
>>> plugin = CondaInstall(packages=["scikit-learn"], conda_options=["--update-deps"])
>>> client.register_plugin(plugin)
See Also
--------
InstallPlugin
PipInstall
"""
def __init__(
self,
packages: list[str],
conda_options: list[str] | None = None,
restart_workers: bool = False,
):
installer = _CondaInstaller(packages, conda_options)
super().__init__(installer, restart_workers=restart_workers)
|
CondaInstall
|
python
|
getsentry__sentry
|
tests/sentry/incidents/endpoints/test_organization_combined_rule_index_endpoint.py
|
{
"start": 807,
"end": 55230
}
|
class ____(BaseAlertRuleSerializerTest, APITestCase):
endpoint = "sentry-api-0-organization-combined-rules"
def setUp(self) -> None:
super().setUp()
self.team = self.create_team(
organization=self.organization,
name="Mariachi Band",
members=[self.user],
)
self.team2 = self.create_team(
organization=self.organization,
name="Folk Band",
members=[self.user],
)
self.project = self.create_project(
organization=self.organization,
teams=[self.team],
name="Bengal",
)
self.project2 = self.create_project(
organization=self.organization,
teams=[self.team],
name="Elephant",
)
self.projects = [self.project, self.project2]
self.project_ids = [str(self.project.id), str(self.project2.id)]
self.login_as(self.user)
self.combined_rules_url = f"/api/0/organizations/{self.organization.slug}/combined-rules/"
def setup_rules(self) -> None:
self.alert_rule = self.create_alert_rule(
name="alert rule",
organization=self.organization,
projects=[self.project],
date_added=before_now(minutes=6),
owner=Actor.from_id(user_id=None, team_id=self.team.id),
)
self.alert_rule_2 = self.create_alert_rule(
name="other alert rule",
organization=self.organization,
projects=[self.project2],
date_added=before_now(minutes=5),
owner=Actor.from_id(user_id=None, team_id=self.team.id),
)
self.issue_rule = self.create_issue_alert_rule(
data={
"project": self.project,
"name": "Issue Rule Test",
"conditions": [],
"actions": [],
"actionMatch": "all",
"date_added": before_now(minutes=4),
}
)
self.alert_rule_team2 = self.create_alert_rule(
name="yet another alert rule",
organization=self.organization,
projects=[self.project],
date_added=before_now(minutes=3),
owner=Actor.from_id(user_id=None, team_id=self.team2.id),
)
def test_no_cron_monitor_rules(self) -> None:
"""
Tests that the shadow cron monitor rules are NOT returned as part of
the the list of alert rules.
"""
self.create_alert_rule()
cron_rule = Rule.objects.create(
project=self.project,
label="Cron Rule",
source=RuleSource.CRON_MONITOR,
)
with self.feature("organizations:incidents"):
resp = self.get_success_response(self.organization.slug)
assert len(resp.data) == 1
assert cron_rule.id not in (r["id"] for r in resp.data), resp.data
def test_no_perf_alerts(self) -> None:
self.create_alert_rule()
perf_alert_rule = self.create_alert_rule(query="p95", dataset=Dataset.Transactions)
with self.feature("organizations:incidents"):
resp = self.get_success_response(self.organization.slug)
assert perf_alert_rule.id not in [x["id"] for x in list(resp.data)]
with self.feature(["organizations:incidents", "organizations:performance-view"]):
resp = self.get_success_response(self.organization.slug)
assert perf_alert_rule.id in [int(x["id"]) for x in list(resp.data)]
def test_simple(self) -> None:
self.setup_rules()
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"per_page": "10", "project": self.project_ids}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 4
self.assert_alert_rule_serialized(self.alert_rule_team2, result[0], skip_dates=True)
assert result[1]["id"] == str(self.issue_rule.id)
assert result[1]["type"] == "rule"
self.assert_alert_rule_serialized(self.alert_rule_2, result[2], skip_dates=True)
self.assert_alert_rule_serialized(self.alert_rule, result[3], skip_dates=True)
def test_snoozed_rules(self) -> None:
"""
Test that we properly serialize snoozed rules with and without an owner
"""
self.setup_rules()
issue_rule2 = self.create_issue_alert_rule(
data={
"project": self.project2,
"name": "Issue Rule Test",
"conditions": [],
"actions": [],
"actionMatch": "all",
"date_added": before_now(minutes=4),
}
)
self.snooze_rule(user_id=self.user.id, rule=self.issue_rule)
self.snooze_rule(user_id=self.user.id, rule=issue_rule2, owner_id=self.user.id)
self.snooze_rule(user_id=self.user.id, alert_rule=self.alert_rule)
self.snooze_rule(
user_id=self.user.id, alert_rule=self.alert_rule_team2, owner_id=self.user.id
)
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"per_page": "10", "project": self.project_ids}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 5
self.assert_alert_rule_serialized(self.alert_rule_team2, result[0], skip_dates=True)
assert result[0]["snooze"]
assert result[1]["id"] == str(issue_rule2.id)
assert result[1]["type"] == "rule"
assert result[1]["snooze"]
assert result[2]["id"] == str(self.issue_rule.id)
assert result[2]["type"] == "rule"
assert result[2]["snooze"]
self.assert_alert_rule_serialized(self.alert_rule_2, result[3], skip_dates=True)
assert not result[3].get("snooze")
self.assert_alert_rule_serialized(self.alert_rule, result[4], skip_dates=True)
assert result[4]["snooze"]
def test_invalid_limit(self) -> None:
self.setup_rules()
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"per_page": "notaninteger"}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 400
def test_limit_higher_than_results_no_cursor(self) -> None:
self.setup_rules()
# Test limit above result count (which is 4), no cursor.
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"per_page": "5", "project": self.project_ids}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 4
self.assert_alert_rule_serialized(self.alert_rule_team2, result[0], skip_dates=True)
assert result[1]["id"] == str(self.issue_rule.id)
assert result[1]["type"] == "rule"
self.assert_alert_rule_serialized(self.alert_rule_2, result[2], skip_dates=True)
self.assert_alert_rule_serialized(self.alert_rule, result[3], skip_dates=True)
def test_limit_as_1_with_paging_sort_name(self) -> None:
self.setup_rules()
# Test Limit as 1, no cursor:
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {
"per_page": "1",
"project": str(self.project.id),
"sort": "name",
"asc": "1",
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200, response.content
result = response.data
assert len(result) == 1
self.assert_alert_rule_serialized(self.alert_rule, result[0], skip_dates=True)
links = requests.utils.parse_header_links(
response.get("link", "").rstrip(">").replace(">,<", ",<")
)
next_cursor = links[1]["cursor"]
# Test Limit as 1, next page of previous request:
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {
"cursor": next_cursor,
"per_page": "1",
"project": str(self.project.id),
"sort": "name",
"asc": "1",
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200, response.content
result = response.data
assert len(result) == 1
assert result[0]["id"] == str(self.issue_rule.id)
assert result[0]["type"] == "rule"
def test_limit_as_1_with_paging_sort_name_urlencode(self) -> None:
self.org = self.create_organization(owner=self.user, name="Rowdy Tiger")
self.team = self.create_team(
organization=self.org, name="Mariachi Band", members=[self.user]
)
self.project = self.create_project(organization=self.org, teams=[self.team], name="Bengal")
alert_rule = self.create_alert_rule(
name="!1?",
organization=self.org,
projects=[self.project],
date_added=before_now(minutes=6),
owner=Actor.from_id(user_id=None, team_id=self.team.id),
)
alert_rule1 = self.create_alert_rule(
name="!1?zz",
organization=self.org,
projects=[self.project],
date_added=before_now(minutes=6),
owner=Actor.from_id(user_id=None, team_id=self.team.id),
)
# Test Limit as 1, no cursor:
url = f"/api/0/organizations/{self.org.slug}/combined-rules/"
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {
"per_page": "1",
"project": str(self.project.id),
"sort": "name",
"asc": "1",
}
response = self.client.get(
path=url,
data=request_data,
content_type="application/json",
)
assert response.status_code == 200, response.content
result = response.data
assert len(result) == 1
self.assert_alert_rule_serialized(alert_rule, result[0], skip_dates=True)
links = requests.utils.parse_header_links(
response.get("link", "").rstrip(">").replace(">,<", ",<")
)
next_cursor = links[1]["cursor"]
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {
"cursor": next_cursor,
"per_page": "1",
"project": str(self.project.id),
"sort": "name",
"asc": "1",
}
response = self.client.get(path=url, data=request_data, content_type="application/json")
assert response.status_code == 200
result = response.data
assert len(result) == 1
assert result[0]["id"] == str(alert_rule1.id)
def test_limit_as_1_with_paging(self) -> None:
self.setup_rules()
# Test Limit as 1, no cursor:
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"per_page": "1", "project": self.project_ids}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 1
self.assert_alert_rule_serialized(self.alert_rule_team2, result[0], skip_dates=True)
links = requests.utils.parse_header_links(
response.get("link", "").rstrip(">").replace(">,<", ",<")
)
next_cursor = links[1]["cursor"]
# Test Limit as 1, next page of previous request:
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"cursor": next_cursor, "per_page": "1", "project": str(self.project.id)}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 1
assert result[0]["id"] == str(self.issue_rule.id)
assert result[0]["type"] == "rule"
def test_limit_as_2_with_paging(self) -> None:
self.setup_rules()
# Test Limit as 2, no cursor:
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"per_page": "2", "project": self.project_ids}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 2
self.assert_alert_rule_serialized(self.alert_rule_team2, result[0], skip_dates=True)
assert result[1]["id"] == str(self.issue_rule.id)
assert result[1]["type"] == "rule"
links = requests.utils.parse_header_links(
response.get("link", "").rstrip(">").replace(">,<", ",<")
)
next_cursor = links[1]["cursor"]
# Test Limit 2, next page of previous request:
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"cursor": next_cursor, "per_page": "2", "project": self.project_ids}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 2
self.assert_alert_rule_serialized(self.alert_rule_2, result[0], skip_dates=True)
self.assert_alert_rule_serialized(self.alert_rule, result[1], skip_dates=True)
links = requests.utils.parse_header_links(
response.get("link", "").rstrip(">").replace(">,<", ",<")
)
next_cursor = links[1]["cursor"]
# Test Limit 2, next page of previous request - should get no results since there are only 4 total:
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"cursor": next_cursor, "per_page": "2", "project": self.project_ids}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 0
def test_offset_pagination(self) -> None:
self.setup_rules()
date_added = before_now(minutes=1)
one_alert_rule = self.create_alert_rule(
organization=self.organization,
projects=[self.project, self.project2],
date_added=date_added,
)
two_alert_rule = self.create_alert_rule(
organization=self.organization,
projects=[self.project2],
date_added=date_added,
)
three_alert_rule = self.create_alert_rule(
organization=self.organization, projects=[self.project]
)
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"per_page": "2", "project": self.project_ids}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 2
self.assert_alert_rule_serialized(three_alert_rule, result[0], skip_dates=True)
self.assert_alert_rule_serialized(one_alert_rule, result[1], skip_dates=True)
links = requests.utils.parse_header_links(
response.get("link", "").rstrip(">").replace(">,<", ",<")
)
next_cursor = links[1]["cursor"]
assert next_cursor.split(":")[1] == "1" # Assert offset is properly calculated.
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"cursor": next_cursor, "per_page": "2", "project": self.project_ids}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 2
self.assert_alert_rule_serialized(two_alert_rule, result[0], skip_dates=True)
self.assert_alert_rule_serialized(self.alert_rule_team2, result[1], skip_dates=True)
def test_filter_by_project(self) -> None:
self.setup_rules()
date_added = before_now(minutes=1)
one_alert_rule = self.create_alert_rule(
organization=self.organization,
projects=[self.project, self.project2],
date_added=date_added,
)
two_alert_rule = self.create_alert_rule(
organization=self.organization,
projects=[self.project],
date_added=date_added,
)
three_alert_rule = self.create_alert_rule(
organization=self.organization, projects=[self.project2]
)
uptime_detector = self.create_uptime_detector(project=self.project)
uptime_detector2 = self.create_uptime_detector(project=self.project2)
proj_cron_monitor = self.create_monitor(project=self.project)
proj2_cron_monitor = self.create_monitor(project=self.project2)
with self.feature(
[
"organizations:incidents",
"organizations:performance-view",
]
):
request_data = {"project": [self.project.id]}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert [r["id"] for r in result] == [
f"{proj_cron_monitor.guid}",
f"{uptime_detector.id}",
f"{one_alert_rule.id}",
f"{two_alert_rule.id}",
f"{self.alert_rule_team2.id}",
f"{self.issue_rule.id}",
f"{self.alert_rule.id}",
]
with self.feature(
[
"organizations:incidents",
"organizations:performance-view",
]
):
request_data = {"project": [self.project2.id]}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert [r["id"] for r in result] == [
f"{proj2_cron_monitor.guid}",
f"{uptime_detector2.id}",
f"{three_alert_rule.id}",
f"{one_alert_rule.id}",
f"{self.alert_rule_2.id}",
]
other_org = self.create_organization()
other_project = self.create_project(organization=other_org)
self.issue_rule = self.create_issue_alert_rule(
data={
"project": other_project,
"name": "Issue Rule Test",
"conditions": [],
"actions": [],
"actionMatch": "all",
"date_added": before_now(minutes=4),
}
)
with self.feature(["organizations:incidents", "organizations:performance-view"]):
response = self.get_error_response(self.organization.slug, project=[other_project.id])
assert response.data["detail"] == "You do not have permission to perform this action."
def test_team_filter(self) -> None:
self.setup_rules()
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"per_page": "10", "project": [self.project.id]}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 3
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {
"per_page": "10",
"project": [self.project.id],
"team": [self.team.id],
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 1
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {
"per_page": "10",
"project": [self.project.id],
"team": [self.team.id, self.team2.id],
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 2
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {
"per_page": "10",
"project": [self.project.id, self.project2.id],
"team": [self.team.id, self.team2.id],
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 3
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"per_page": "10", "project": [self.project.id], "team": ["unassigned"]}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 1
an_unassigned_alert_rule = self.create_alert_rule(
organization=self.organization,
projects=[self.project],
date_added=before_now(minutes=3),
owner=None,
)
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"per_page": "10", "project": [self.project.id], "team": ["unassigned"]}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 2
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"per_page": "10", "project": [self.project.id], "team": ["notvalid"]}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 400
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"per_page": "10", "project": [self.project.id], "team": ["myteams"]}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 2
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {
"per_page": "10",
"project": [self.project.id, self.project2.id],
"team": ["myteams"],
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 3
issue_rule2 = self.create_issue_alert_rule(
data={
"project": self.project,
"name": "Issue Rule Test",
"conditions": [],
"actions": [],
"actionMatch": "all",
"date_added": before_now(minutes=4),
"owner": f"team:{self.team.id}",
}
)
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {
"per_page": "10",
"project": [self.project.id],
"team": [self.team.id],
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 2
team_uptime_detector = self.create_uptime_detector(owner=self.team, name="Uptime owned")
unowned_uptime_detector = self.create_uptime_detector(name="Uptime unowned")
team_cron_monitor = self.create_monitor(
owner_user_id=None,
owner_team_id=self.team.id,
name="Cron owned",
)
unowned_cron_monitor = self.create_monitor(
name="Cron unowned",
owner_user_id=None,
)
with self.feature(
[
"organizations:incidents",
"organizations:performance-view",
]
):
request_data = {
"per_page": "10",
"project": [self.project.id],
"team": [self.team.id],
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert [r["id"] for r in result] == [
f"{team_cron_monitor.guid}",
f"{team_uptime_detector.id}",
f"{issue_rule2.id}",
f"{self.alert_rule.id}",
]
with self.feature(
[
"organizations:incidents",
"organizations:performance-view",
]
):
request_data = {
"per_page": "10",
"project": [self.project.id],
"team": ["unassigned"],
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert [r["id"] for r in result] == [
f"{unowned_cron_monitor.guid}",
f"{unowned_uptime_detector.id}",
f"{an_unassigned_alert_rule.id}",
f"{self.issue_rule.id}",
]
def test_myteams_filter_superuser(self) -> None:
superuser = self.create_user(is_superuser=True)
another_org = self.create_organization(owner=superuser, name="Rowdy Tiger")
another_org_rules_url = f"/api/0/organizations/{another_org.slug}/combined-rules/"
another_org_team = self.create_team(organization=another_org, name="Meow Band", members=[])
another_project = self.create_project(
organization=another_org, teams=[another_org_team], name="Woof Choir"
)
self.login_as(superuser, superuser=True)
self.create_alert_rule(
name="alert rule",
organization=another_org,
projects=[another_project],
date_added=before_now(minutes=6),
owner=Actor.from_id(user_id=None, team_id=another_org_team.id),
)
self.create_issue_alert_rule(
data={
"project": another_project,
"name": "Issue Rule Test",
"conditions": [],
"actions": [],
"actionMatch": "all",
"date_added": before_now(minutes=4),
"owner": f"team:{another_org_team.id}",
}
)
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {
"per_page": "10",
"project": [str(another_project.id)],
"team": ["myteams"],
}
response = self.client.get(
path=another_org_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
assert len(response.data) == 2
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {
"per_page": "10",
"project": [str(another_project.id)],
"team": [another_org_team.id],
}
response = self.client.get(
path=another_org_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
assert len(response.data) == 2 # We are not on this team, but we are a superuser.
def test_team_filter_no_cross_org_access(self) -> None:
self.setup_rules()
another_org = self.create_organization(owner=self.user, name="Rowdy Tiger")
another_org_team = self.create_team(organization=another_org, name="Meow Band", members=[])
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {
"per_page": "10",
"project": [self.project.id],
"team": [self.team.id, another_org_team.id],
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
assert len(response.data) == 1
assert response.data[0]["owner"] == f"team:{self.team.id}"
def test_team_filter_no_access(self) -> None:
self.setup_rules()
# disable Open Membership
self.organization.flags.allow_joinleave = False
self.organization.save()
user2 = self.create_user("bulldog@example.com")
team2 = self.create_team(organization=self.organization, name="Barking Voices")
project2 = self.create_project(organization=self.organization, teams=[team2], name="Bones")
self.create_member(user=user2, organization=self.organization, role="member", teams=[team2])
self.login_as(user2)
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {
"per_page": "10",
"project": [project2.id],
"team": [team2.id, self.team.id],
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 403
assert (
response.data["detail"] == "Error: You do not have permission to access Mariachi Band"
)
def test_name_filter(self) -> None:
self.setup_rules()
uptime_detector = self.create_uptime_detector(name="Uptime")
another_uptime_detector = self.create_uptime_detector(name="yet another Uptime")
cron_monitor = self.create_monitor(name="Cron")
another_cron_monitor = self.create_monitor(name="yet another Cron")
with self.feature(
[
"organizations:incidents",
"organizations:performance-view",
]
):
request_data = {
"per_page": "10",
"project": [self.project.id],
"name": "yet",
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert [r["id"] for r in result] == [
f"{another_cron_monitor.guid}",
f"{another_uptime_detector.id}",
f"{self.alert_rule_team2.id}",
]
with self.feature(
[
"organizations:incidents",
"organizations:performance-view",
]
):
request_data = {
"per_page": "10",
"project": [self.project.id],
"name": "issue rule",
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert [r["id"] for r in result] == [f"{self.issue_rule.id}"]
with self.feature(
[
"organizations:incidents",
"organizations:performance-view",
]
):
request_data = {
"per_page": "10",
"project": [self.project.id, self.project2.id],
"name": "aLeRt RuLe",
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 3
with self.feature(
[
"organizations:incidents",
"organizations:performance-view",
]
):
request_data = {
"per_page": "10",
"project": [self.project.id, self.project2.id],
"name": "aLeRt this RuLe",
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 0
with self.feature(
[
"organizations:incidents",
"organizations:performance-view",
]
):
request_data = {
"per_page": "10",
"project": [self.project.id, self.project2.id],
"name": "RuLe",
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert len(result) == 4
with self.feature(
[
"organizations:incidents",
"organizations:performance-view",
]
):
request_data = {
"per_page": "10",
"project": [self.project.id, self.project2.id],
"name": "uptime",
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert [r["id"] for r in result] == [
f"{another_uptime_detector.id}",
f"{uptime_detector.id}",
]
with self.feature(
[
"organizations:incidents",
"organizations:performance-view",
]
):
request_data = {
"per_page": "10",
"project": [self.project.id, self.project2.id],
"name": "cron",
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
result = response.data
assert [r["id"] for r in result] == [
f"{another_cron_monitor.guid}",
f"{cron_monitor.guid}",
]
def test_status_and_date_triggered_sort_order(self) -> None:
self.setup_rules()
alert_rule_critical = self.create_alert_rule(
organization=self.organization,
projects=[self.project],
name="some rule [crit]",
query="",
aggregate="count()",
time_window=1,
threshold_type=AlertRuleThresholdType.ABOVE,
resolve_threshold=10,
threshold_period=1,
)
another_alert_rule_warning = self.create_alert_rule(
organization=self.organization,
projects=[self.project],
name="another warning rule",
query="",
aggregate="count()",
time_window=1,
threshold_type=AlertRuleThresholdType.ABOVE,
resolve_threshold=10,
threshold_period=1,
)
alert_rule_warning = self.create_alert_rule(
organization=self.organization,
projects=[self.project],
name="warning rule",
query="",
aggregate="count()",
time_window=1,
threshold_type=AlertRuleThresholdType.ABOVE,
resolve_threshold=10,
threshold_period=1,
)
trigger = self.create_alert_rule_trigger(alert_rule_critical, "hi", 100)
trigger2 = self.create_alert_rule_trigger(alert_rule_critical, "bye", 50)
trigger3 = self.create_alert_rule_trigger(alert_rule_warning, "meow", 200)
self.create_incident(status=2, alert_rule=alert_rule_critical)
warning_incident = self.create_incident(status=10, alert_rule=alert_rule_critical)
self.create_incident(status=10, alert_rule=alert_rule_warning)
self.create_incident(status=10, alert_rule=another_alert_rule_warning)
crit_incident = self.create_incident(status=20, alert_rule=alert_rule_critical)
IncidentTrigger.objects.create(
incident=crit_incident, alert_rule_trigger=trigger, status=TriggerStatus.RESOLVED.value
)
IncidentTrigger.objects.create(
incident=crit_incident, alert_rule_trigger=trigger2, status=TriggerStatus.ACTIVE.value
)
IncidentTrigger.objects.create(
incident=warning_incident,
alert_rule_trigger=trigger3,
status=TriggerStatus.ACTIVE.value,
)
uptime_detector = self.create_uptime_detector()
failed_uptime_detector = self.create_uptime_detector(
detector_state=DetectorPriorityLevel.HIGH,
)
ok_cron_monitor = self.create_monitor(
name="OK Monitor",
)
ok_cron_monitor_env = self.create_monitor_environment(
monitor=ok_cron_monitor,
environment_id=self.environment.id,
status=MonitorStatus.OK,
)
self.create_monitor_incident(
monitor=ok_cron_monitor,
monitor_environment=ok_cron_monitor_env,
starting_timestamp=before_now(minutes=10),
)
failed_cron_monitor = self.create_monitor(
name="Failing Monitor",
)
failed_cron_monitor_env = self.create_monitor_environment(
monitor=failed_cron_monitor,
environment_id=self.environment.id,
status=MonitorStatus.ERROR,
)
self.create_monitor_incident(
monitor=failed_cron_monitor,
monitor_environment=failed_cron_monitor_env,
starting_timestamp=before_now(minutes=2),
)
with self.feature(
[
"organizations:incidents",
"organizations:performance-view",
]
):
request_data = {
"per_page": "12",
"project": [self.project.id, self.project2.id],
"sort": ["incident_status", "date_triggered"],
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200, response.content
result = response.data
# Assert failed uptime monitor is first, critical rule is next, then warnings (sorted by triggered date),
# then issue rules and finally uptime monitors in ok status.
assert [r["id"] for r in result] == [
f"{failed_cron_monitor.guid}",
f"{failed_uptime_detector.id}",
f"{alert_rule_critical.id}",
f"{another_alert_rule_warning.id}",
f"{alert_rule_warning.id}",
f"{self.alert_rule.id}",
f"{self.alert_rule_2.id}",
f"{self.alert_rule_team2.id}",
f"{self.issue_rule.id}",
f"{ok_cron_monitor.guid}",
f"{uptime_detector.id}",
]
# Test paging with the status setup:
with self.feature(
[
"organizations:incidents",
"organizations:performance-view",
]
):
request_data = {
"per_page": "3",
"project": [self.project.id, self.project2.id],
"sort": ["incident_status", "date_triggered"],
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200, response.content
result = response.data
assert [r["id"] for r in result] == [
f"{failed_cron_monitor.guid}",
f"{failed_uptime_detector.id}",
f"{alert_rule_critical.id}",
]
links = requests.utils.parse_header_links(
response.get("link", "").rstrip(">").replace(">,<", ",<")
)
next_cursor = links[1]["cursor"]
# Get next page, we should be between the two status':
with self.feature(
[
"organizations:incidents",
"organizations:performance-view",
]
):
request_data = {
"cursor": next_cursor,
"per_page": "3",
"project": [self.project.id, self.project2.id],
"sort": ["incident_status", "date_triggered"],
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200, response.content
result = response.data
assert [r["id"] for r in result] == [
f"{another_alert_rule_warning.id}",
f"{alert_rule_warning.id}",
f"{self.alert_rule.id}",
]
def test_uptime_feature(self) -> None:
self.setup_rules()
uptime_detector = self.create_uptime_detector(name="Uptime Monitor")
other_uptime_detector = self.create_uptime_detector(name="Other Uptime Monitor")
self.create_uptime_detector(
name="Onboarding Uptime monitor",
mode=UptimeMonitorMode.AUTO_DETECTED_ONBOARDING,
)
request_data = {"name": "Uptime", "project": [self.project.id]}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200, response.content
result = response.data
assert [r["id"] for r in result] == [
f"{other_uptime_detector.id}",
f"{uptime_detector.id}",
]
def test_uptime_feature_name_sort(self) -> None:
self.setup_rules()
self.create_uptime_detector(name="Uptime Monitor")
self.create_uptime_detector(
name="Other Uptime Monitor",
)
self.create_uptime_detector(
name="Onboarding Uptime monitor",
mode=UptimeMonitorMode.AUTO_DETECTED_ONBOARDING,
)
request_data = {"project": [self.project.id], "sort": "name"}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200, response.content
result = response.data
assert [r["name"] for r in result] == [
"yet another alert rule",
"Uptime Monitor",
"Other Uptime Monitor",
"Issue Rule Test",
"alert rule",
]
def test_expand_latest_incident(self) -> None:
self.setup_rules()
alert_rule_critical = self.create_alert_rule(
organization=self.organization,
projects=[self.project],
name="some rule [crit]",
query="",
aggregate="count()",
time_window=1,
threshold_type=AlertRuleThresholdType.ABOVE,
resolve_threshold=10,
threshold_period=1,
)
trigger = self.create_alert_rule_trigger(alert_rule_critical, "hi", 100)
self.create_incident(status=2, alert_rule=alert_rule_critical)
crit_incident = self.create_incident(status=20, alert_rule=alert_rule_critical)
IncidentTrigger.objects.create(
incident=crit_incident, alert_rule_trigger=trigger, status=TriggerStatus.RESOLVED.value
)
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {
"per_page": "10",
"project": [self.project.id],
"expand": "latestIncident",
}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200, response.content
result = response.data
assert len(result) == 4
assert result[0]["latestIncident"]["id"] == str(crit_incident.id)
def test_non_existing_owner(self) -> None:
self.setup_rules()
team = self.create_team(organization=self.organization, members=[self.user])
alert_rule = self.create_alert_rule(
name="the best rule",
organization=self.organization,
projects=[self.project],
date_added=before_now(minutes=1),
owner=Actor.from_id(user_id=None, team_id=team.id),
)
self.create_issue_alert_rule(
data={
"project": self.project,
"name": "Issue Rule Test",
"conditions": [],
"actions": [],
"actionMatch": "all",
"date_added": before_now(minutes=2),
"owner": f"team:{team.id}",
}
)
team.delete()
# Pick up here. Deleting the team apparently deletes the alert rule as well now
with self.feature(["organizations:incidents", "organizations:performance-view"]):
request_data = {"per_page": "10"}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert response.status_code == 200
assert response.data[0]["id"] == str(alert_rule.id)
assert response.data[0]["owner"] is None
@freeze_time()
def test_last_triggered(self) -> None:
rule = self.create_issue_alert_rule(
data={
"project": self.project,
"name": "Issue Rule Test",
"conditions": [],
"actions": [],
"actionMatch": "all",
"date_added": before_now(minutes=4),
}
)
resp = self.get_success_response(self.organization.slug, expand=["lastTriggered"])
assert resp.data[0]["lastTriggered"] is None
RuleFireHistory.objects.create(project=self.project, rule=rule, group=self.group)
resp = self.get_success_response(self.organization.slug, expand=["lastTriggered"])
assert resp.data[0]["lastTriggered"] == datetime.now(UTC)
def test_project_deleted(self) -> None:
from sentry.deletions.models.scheduleddeletion import RegionScheduledDeletion
from sentry.deletions.tasks.scheduled import run_deletion
org = self.create_organization(owner=self.user, name="Rowdy Tiger")
team = self.create_team(organization=org, name="Mariachi Band", members=[self.user])
delete_project = self.create_project(organization=org, teams=[team], name="Bengal")
self.create_project_rule(project=delete_project)
deletion = RegionScheduledDeletion.schedule(delete_project, days=0)
deletion.update(in_progress=True)
with self.tasks():
run_deletion(deletion.id)
self.get_success_response(org.slug)
def test_active_and_disabled_rules(self) -> None:
"""Test that we return both active and disabled rules"""
self.setup_rules()
disabled_alert = self.create_project_rule(name="disabled rule")
disabled_alert.status = ObjectStatus.DISABLED
disabled_alert.save()
request_data = {"per_page": "10"}
response = self.client.get(
path=self.combined_rules_url, data=request_data, content_type="application/json"
)
assert len(response.data) == 5
for data in response.data:
if data["name"] == disabled_alert.label:
assert data["status"] == "disabled"
def test_dataset_filter(self) -> None:
self.create_alert_rule(dataset=Dataset.Metrics)
transaction_rule = self.create_alert_rule(dataset=Dataset.Transactions)
events_rule = self.create_alert_rule(dataset=Dataset.Events)
with self.feature(["organizations:incidents", "organizations:performance-view"]):
transactions_res = self.get_success_response(
self.organization.slug, dataset=[Dataset.Transactions.value]
)
self.assert_alert_rule_serialized(
transaction_rule, transactions_res.data[0], skip_dates=True
)
events_res = self.get_success_response(
self.organization.slug, dataset=[Dataset.Events.value]
)
self.assert_alert_rule_serialized(events_rule, events_res.data[0], skip_dates=True)
with self.feature("organizations:incidents"):
# without performance-view, we should only see events rules
res = self.get_success_response(self.organization.slug)
self.assert_alert_rule_serialized(events_rule, res.data[0], skip_dates=True)
def test_alert_type_filter(self) -> None:
# Setup one of each type of alert rule
metric_rule = self.create_alert_rule()
issue_rule = self.create_issue_alert_rule(
data={
"project": self.project,
"name": "Issue Rule Test",
"conditions": [],
"actions": [],
"actionMatch": "all",
"date_added": before_now(minutes=4),
}
)
uptime_rule = self.create_uptime_detector(project=self.project)
cron_rule = self.create_monitor(project=self.project)
features = [
"organizations:incidents",
"organizations:performance-view",
]
# Everything comes back without the query parameter
with self.feature(features):
request_data = {"per_page": "10", "project": [self.project.id]}
response = self.client.get(
path=self.combined_rules_url,
data=request_data,
content_type="application/json",
)
assert response.status_code == 200, response.content
assert {r["id"] for r in response.data} == {
str(metric_rule.id),
str(issue_rule.id),
str(uptime_rule.id),
str(cron_rule.guid),
}
test_cases: list[tuple[list[str], set[str]]] = [
(["rule"], {str(issue_rule.id)}),
(["alert_rule"], {str(metric_rule.id)}),
(["monitor"], {str(cron_rule.guid)}),
(["uptime"], {str(uptime_rule.id)}),
(["rule", "alert_rule"], {str(issue_rule.id), str(metric_rule.id)}),
(["uptime", "monitor"], {str(uptime_rule.id), str(cron_rule.guid)}),
]
for alert_type, expected_ids in test_cases:
with self.feature(features):
request_data = {
"per_page": "10",
"project": [self.project.id],
"alertType": alert_type,
}
response = self.client.get(
path=self.combined_rules_url,
data=request_data,
content_type="application/json",
)
assert response.status_code == 200, response.content
assert {r["id"] for r in response.data} == expected_ids
|
OrganizationCombinedRuleIndexEndpointTest
|
python
|
run-llama__llama_index
|
llama-index-core/llama_index/core/indices/tree/select_leaf_retriever.py
|
{
"start": 1887,
"end": 15660
}
|
class ____(BaseRetriever):
"""
Tree select leaf retriever.
This class traverses the index graph and searches for a leaf node that can best
answer the query.
Args:
query_template (Optional[BasePromptTemplate]): Tree Select Query Prompt
(see :ref:`Prompt-Templates`).
query_template_multiple (Optional[BasePromptTemplate]): Tree Select
Query Prompt (Multiple)
(see :ref:`Prompt-Templates`).
child_branch_factor (int): Number of child nodes to consider at each level.
If child_branch_factor is 1, then the query will only choose one child node
to traverse for any given parent node.
If child_branch_factor is 2, then the query will choose two child nodes.
"""
def __init__(
self,
index: TreeIndex,
query_template: Optional[BasePromptTemplate] = None,
text_qa_template: Optional[BasePromptTemplate] = None,
refine_template: Optional[BasePromptTemplate] = None,
query_template_multiple: Optional[BasePromptTemplate] = None,
child_branch_factor: int = 1,
verbose: bool = False,
callback_manager: Optional[CallbackManager] = None,
object_map: Optional[dict] = None,
**kwargs: Any,
):
self._index = index
self._llm = index._llm
self._index_struct = index.index_struct
self._docstore = index.docstore
self._prompt_helper = Settings._prompt_helper or PromptHelper.from_llm_metadata(
self._llm.metadata,
)
self._text_qa_template = text_qa_template or DEFAULT_TEXT_QA_PROMPT
self._refine_template = refine_template or DEFAULT_REFINE_PROMPT_SEL
self.query_template = query_template or DEFAULT_QUERY_PROMPT
self.query_template_multiple = (
query_template_multiple or DEFAULT_QUERY_PROMPT_MULTIPLE
)
self.child_branch_factor = child_branch_factor
super().__init__(
callback_manager=callback_manager or Settings.callback_manager,
object_map=object_map,
verbose=verbose,
)
def _query_with_selected_node(
self,
selected_node: BaseNode,
query_bundle: QueryBundle,
prev_response: Optional[str] = None,
level: int = 0,
) -> str:
"""
Get response for selected node.
If not leaf node, it will recursively call _query on the child nodes.
If prev_response is provided, we will update prev_response with the answer.
"""
query_str = query_bundle.query_str
if len(self._index_struct.get_children(selected_node)) == 0:
response_builder = get_response_synthesizer(
llm=self._llm,
text_qa_template=self._text_qa_template,
refine_template=self._refine_template,
callback_manager=self.callback_manager,
)
# use response builder to get answer from node
node_text = get_text_from_node(selected_node, level=level)
cur_response = response_builder.get_response(
query_str, [node_text], prev_response=prev_response
)
cur_response = str(cur_response)
logger.debug(f">[Level {level}] Current answer response: {cur_response} ")
else:
cur_response = self._query_level(
self._index_struct.get_children(selected_node),
query_bundle,
level=level + 1,
)
if prev_response is None:
return cur_response
else:
context_msg = selected_node.get_content(metadata_mode=MetadataMode.LLM)
cur_response = self._llm.predict(
self._refine_template,
query_str=query_str,
existing_answer=prev_response,
context_msg=context_msg,
)
logger.debug(f">[Level {level}] Current refined response: {cur_response} ")
return str(cur_response)
def _query_level(
self,
cur_node_ids: Dict[int, str],
query_bundle: QueryBundle,
level: int = 0,
) -> str:
"""Answer a query recursively."""
query_str = query_bundle.query_str
cur_nodes = {
index: self._docstore.get_node(node_id)
for index, node_id in cur_node_ids.items()
}
cur_node_list = get_sorted_node_list(cur_nodes)
if len(cur_node_list) == 1:
logger.debug(f">[Level {level}] Only one node left. Querying node.")
return self._query_with_selected_node(
cur_node_list[0], query_bundle, level=level
)
elif self.child_branch_factor == 1:
query_template = self.query_template.partial_format(
num_chunks=len(cur_node_list), query_str=query_str
)
text_splitter = self._prompt_helper.get_text_splitter_given_prompt(
prompt=query_template,
num_chunks=len(cur_node_list),
llm=self._llm,
)
numbered_node_text = get_numbered_text_from_nodes(
cur_node_list, text_splitter=text_splitter
)
response = self._llm.predict(
query_template,
context_list=numbered_node_text,
)
else:
query_template_multiple = self.query_template_multiple.partial_format(
num_chunks=len(cur_node_list),
query_str=query_str,
branching_factor=self.child_branch_factor,
)
text_splitter = self._prompt_helper.get_text_splitter_given_prompt(
prompt=query_template_multiple,
num_chunks=len(cur_node_list),
llm=self._llm,
)
numbered_node_text = get_numbered_text_from_nodes(
cur_node_list, text_splitter=text_splitter
)
response = self._llm.predict(
query_template_multiple,
context_list=numbered_node_text,
)
debug_str = f">[Level {level}] Current response: {response}"
logger.debug(debug_str)
if self._verbose:
print_text(debug_str, end="\n")
numbers = extract_numbers_given_response(response, n=self.child_branch_factor)
if numbers is None:
debug_str = (
f">[Level {level}] Could not retrieve response - no numbers present"
)
logger.debug(debug_str)
if self._verbose:
print_text(debug_str, end="\n")
# just join text from current nodes as response
return response
result_response = None
for number_str in numbers:
number = int(number_str)
if number > len(cur_node_list):
logger.debug(
f">[Level {level}] Invalid response: {response} - "
f"number {number} out of range"
)
return response
# number is 1-indexed, so subtract 1
selected_node = cur_node_list[number - 1]
info_str = (
f">[Level {level}] Selected node: "
f"[{number}]/[{','.join([str(int(n)) for n in numbers])}]"
)
logger.info(info_str)
if self._verbose:
print_text(info_str, end="\n")
debug_str = " ".join(
selected_node.get_content(metadata_mode=MetadataMode.LLM).splitlines()
)
full_debug_str = (
f">[Level {level}] Node "
f"[{number}] Summary text: "
f"{selected_node.get_content(metadata_mode=MetadataMode.LLM)}"
)
logger.debug(full_debug_str)
if self._verbose:
print_text(full_debug_str, end="\n")
result_response = self._query_with_selected_node(
selected_node,
query_bundle,
prev_response=result_response,
level=level,
)
# result_response should not be None
return cast(str, result_response)
def _query(self, query_bundle: QueryBundle) -> Response:
"""Answer a query."""
# NOTE: this overrides the _query method in the base class
info_str = f"> Starting query: {query_bundle.query_str}"
logger.info(info_str)
if self._verbose:
print_text(info_str, end="\n")
response_str = self._query_level(
self._index_struct.root_nodes,
query_bundle,
level=0,
).strip()
# TODO: fix source nodes
return Response(response_str, source_nodes=[])
def _select_nodes(
self,
cur_node_list: List[BaseNode],
query_bundle: QueryBundle,
level: int = 0,
) -> List[BaseNode]:
query_str = query_bundle.query_str
if self.child_branch_factor == 1:
query_template = self.query_template.partial_format(
num_chunks=len(cur_node_list), query_str=query_str
)
text_splitter = self._prompt_helper.get_text_splitter_given_prompt(
prompt=query_template,
num_chunks=len(cur_node_list),
llm=self._llm,
)
numbered_node_text = get_numbered_text_from_nodes(
cur_node_list, text_splitter=text_splitter
)
response = self._llm.predict(
query_template,
context_list=numbered_node_text,
)
else:
query_template_multiple = self.query_template_multiple.partial_format(
num_chunks=len(cur_node_list),
query_str=query_str,
branching_factor=self.child_branch_factor,
)
text_splitter = self._prompt_helper.get_text_splitter_given_prompt(
prompt=query_template_multiple,
num_chunks=len(cur_node_list),
llm=self._llm,
)
numbered_node_text = get_numbered_text_from_nodes(
cur_node_list, text_splitter=text_splitter
)
response = self._llm.predict(
query_template_multiple,
context_list=numbered_node_text,
)
debug_str = f">[Level {level}] Current response: {response}"
logger.debug(debug_str)
if self._verbose:
print_text(debug_str, end="\n")
numbers = extract_numbers_given_response(response, n=self.child_branch_factor)
if numbers is None:
debug_str = (
f">[Level {level}] Could not retrieve response - no numbers present"
)
logger.debug(debug_str)
if self._verbose:
print_text(debug_str, end="\n")
# just join text from current nodes as response
return []
selected_nodes = []
for number_str in numbers:
number = int(number_str)
if number > len(cur_node_list):
logger.debug(
f">[Level {level}] Invalid response: {response} - "
f"number {number} out of range"
)
continue
# number is 1-indexed, so subtract 1
selected_node = cur_node_list[number - 1]
info_str = (
f">[Level {level}] Selected node: "
f"[{number}]/[{','.join([str(int(n)) for n in numbers])}]"
)
logger.info(info_str)
if self._verbose:
print_text(info_str, end="\n")
debug_str = " ".join(
selected_node.get_content(metadata_mode=MetadataMode.LLM).splitlines()
)
full_debug_str = (
f">[Level {level}] Node "
f"[{number}] Summary text: "
f"{selected_node.get_content(metadata_mode=MetadataMode.LLM)}"
)
logger.debug(full_debug_str)
if self._verbose:
print_text(full_debug_str, end="\n")
selected_nodes.append(selected_node)
return selected_nodes
def _retrieve_level(
self,
cur_node_ids: Dict[int, str],
query_bundle: QueryBundle,
level: int = 0,
) -> List[BaseNode]:
"""Answer a query recursively."""
cur_nodes = {
index: self._docstore.get_node(node_id)
for index, node_id in cur_node_ids.items()
}
cur_node_list = get_sorted_node_list(cur_nodes)
if len(cur_node_list) > self.child_branch_factor:
selected_nodes = self._select_nodes(
cur_node_list,
query_bundle,
level=level,
)
else:
selected_nodes = cur_node_list
children_nodes = {}
for node in selected_nodes:
node_dict = self._index_struct.get_children(node)
children_nodes.update(node_dict)
if len(children_nodes) == 0:
# NOTE: leaf level
return selected_nodes
else:
return self._retrieve_level(children_nodes, query_bundle, level + 1)
def _retrieve(
self,
query_bundle: QueryBundle,
) -> List[NodeWithScore]:
"""Get nodes for response."""
nodes = self._retrieve_level(
self._index_struct.root_nodes,
query_bundle,
level=0,
)
return [NodeWithScore(node=node) for node in nodes]
|
TreeSelectLeafRetriever
|
python
|
doocs__leetcode
|
solution/0100-0199/0166.Fraction to Recurring Decimal/Solution.py
|
{
"start": 0,
"end": 699
}
|
class ____:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
if numerator == 0:
return "0"
ans = []
neg = (numerator > 0) ^ (denominator > 0)
if neg:
ans.append("-")
a, b = abs(numerator), abs(denominator)
ans.append(str(a // b))
a %= b
if a == 0:
return "".join(ans)
ans.append(".")
d = {}
while a:
d[a] = len(ans)
a *= 10
ans.append(str(a // b))
a %= b
if a in d:
ans.insert(d[a], "(")
ans.append(")")
break
return "".join(ans)
|
Solution
|
python
|
joke2k__faker
|
faker/providers/date_time/it_IT/__init__.py
|
{
"start": 46,
"end": 786
}
|
class ____(DateTimeProvider):
DAY_NAMES = {
"0": "domenica",
"1": "lunedì",
"2": "martedì",
"3": "mercoledì",
"4": "giovedì",
"5": "venerdì",
"6": "sabato",
}
MONTH_NAMES = {
"01": "gennaio",
"02": "febbraio",
"03": "marzo",
"04": "aprile",
"05": "maggio",
"06": "giugno",
"07": "luglio",
"08": "agosto",
"09": "settembre",
"10": "ottobre",
"11": "novembre",
"12": "dicembre",
}
def day_of_week(self):
day = self.date("%w")
return self.DAY_NAMES[day]
def month_name(self):
month = self.month()
return self.MONTH_NAMES[month]
|
Provider
|
python
|
apache__airflow
|
airflow-core/src/airflow/api_fastapi/core_api/datamodels/job.py
|
{
"start": 1452,
"end": 1583
}
|
class ____(BaseModel):
"""Job Collection Response."""
jobs: Iterable[JobResponse]
total_entries: int
|
JobCollectionResponse
|
python
|
django-haystack__django-haystack
|
haystack/templatetags/highlight.py
|
{
"start": 188,
"end": 4320
}
|
class ____(template.Node):
def __init__(
self, text_block, query, html_tag=None, css_class=None, max_length=None
):
self.text_block = template.Variable(text_block)
self.query = template.Variable(query)
self.html_tag = html_tag
self.css_class = css_class
self.max_length = max_length
if html_tag is not None:
self.html_tag = template.Variable(html_tag)
if css_class is not None:
self.css_class = template.Variable(css_class)
if max_length is not None:
self.max_length = template.Variable(max_length)
def render(self, context):
text_block = self.text_block.resolve(context)
query = self.query.resolve(context)
kwargs = {}
if self.html_tag is not None:
kwargs["html_tag"] = self.html_tag.resolve(context)
if self.css_class is not None:
kwargs["css_class"] = self.css_class.resolve(context)
if self.max_length is not None:
kwargs["max_length"] = self.max_length.resolve(context)
# Handle a user-defined highlighting function.
if (
hasattr(settings, "HAYSTACK_CUSTOM_HIGHLIGHTER")
and settings.HAYSTACK_CUSTOM_HIGHLIGHTER
):
# Do the import dance.
try:
path_bits = settings.HAYSTACK_CUSTOM_HIGHLIGHTER.split(".")
highlighter_path, highlighter_classname = (
".".join(path_bits[:-1]),
path_bits[-1],
)
highlighter_module = importlib.import_module(highlighter_path)
highlighter_class = getattr(highlighter_module, highlighter_classname)
except (ImportError, AttributeError) as e:
raise ImproperlyConfigured(
"The highlighter '%s' could not be imported: %s"
% (settings.HAYSTACK_CUSTOM_HIGHLIGHTER, e)
)
else:
from haystack.utils.highlighting import Highlighter
highlighter_class = Highlighter
highlighter = highlighter_class(query, **kwargs)
highlighted_text = highlighter.highlight(text_block)
return highlighted_text
@register.tag
def highlight(parser, token):
"""
Takes a block of text and highlights words from a provided query within that
block of text. Optionally accepts arguments to provide the HTML tag to wrap
highlighted word in, a CSS class to use with the tag and a maximum length of
the blurb in characters.
Syntax::
{% highlight <text_block> with <query> [css_class "class_name"] [html_tag "span"] [max_length 200] %}
Example::
# Highlight summary with default behavior.
{% highlight result.summary with request.query %}
# Highlight summary but wrap highlighted words with a div and the
# following CSS class.
{% highlight result.summary with request.query html_tag "div" css_class "highlight_me_please" %}
# Highlight summary but only show 40 characters.
{% highlight result.summary with request.query max_length 40 %}
"""
bits = token.split_contents()
tag_name = bits[0]
if not len(bits) % 2 == 0:
raise template.TemplateSyntaxError(
"'%s' tag requires valid pairings arguments." % tag_name
)
text_block = bits[1]
if len(bits) < 4:
raise template.TemplateSyntaxError(
"'%s' tag requires an object and a query provided by 'with'." % tag_name
)
if bits[2] != "with":
raise template.TemplateSyntaxError(
"'%s' tag's second argument should be 'with'." % tag_name
)
query = bits[3]
arg_bits = iter(bits[4:])
kwargs = {}
for bit in arg_bits:
if bit == "css_class":
kwargs["css_class"] = next(arg_bits)
if bit == "html_tag":
kwargs["html_tag"] = next(arg_bits)
if bit == "max_length":
kwargs["max_length"] = next(arg_bits)
return HighlightNode(text_block, query, **kwargs)
|
HighlightNode
|
python
|
google__jax
|
tests/svd_test.py
|
{
"start": 1269,
"end": 10914
}
|
class ____(jtu.JaxTestCase):
@jtu.sample_product(
shape=[(4, 5), (3, 4, 5), (2, 3, 4, 5)],
dtype=jtu.dtypes.floating + jtu.dtypes.complex,
)
@jax.default_matmul_precision('float32')
def testSvdvals(self, shape, dtype):
rng = jtu.rand_default(self.rng())
args_maker = lambda: [rng(shape, dtype)]
jnp_fun = jax.numpy.linalg.svdvals
np_fun = np.linalg.svdvals
self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, rtol=_SVD_RTOL, atol=1E-5)
self._CompileAndCheck(jnp_fun, args_maker, rtol=_SVD_RTOL)
@jtu.sample_product(
[dict(m=m, n=n) for m, n in zip([2, 8, 10, 20], [4, 6, 10, 18])],
log_cond=np.linspace(1, _MAX_LOG_CONDITION_NUM, 4),
full_matrices=[True, False],
)
def testSvdWithRectangularInput(self, m, n, log_cond, full_matrices):
"""Tests SVD with rectangular input."""
with jax.default_matmul_precision('float32'):
a = np.random.uniform(
low=0.3, high=0.9, size=(m, n)).astype(_SVD_TEST_DTYPE)
u, s, v = osp_linalg.svd(a, full_matrices=False)
cond = 10**log_cond
s = jnp.linspace(cond, 1, min(m, n))
a = (u * s) @ v
a = a.astype(complex) * (1 + 1j)
osp_linalg_fn = functools.partial(
osp_linalg.svd, full_matrices=full_matrices)
actual_u, actual_s, actual_v = svd.svd(a, full_matrices=full_matrices)
k = min(m, n)
if m > n:
unitary_u = jnp.real(actual_u.T.conj() @ actual_u)
unitary_v = jnp.real(actual_v.T.conj() @ actual_v)
unitary_u_size = m if full_matrices else k
unitary_v_size = k
else:
unitary_u = jnp.real(actual_u @ actual_u.T.conj())
unitary_v = jnp.real(actual_v @ actual_v.T.conj())
unitary_u_size = k
unitary_v_size = n if full_matrices else k
_, expected_s, _ = osp_linalg_fn(a)
svd_fn = lambda a: svd.svd(a, full_matrices=full_matrices)
args_maker = lambda: [a]
with self.subTest('Test JIT compatibility'):
self._CompileAndCheck(svd_fn, args_maker)
with self.subTest('Test unitary u.'):
self.assertAllClose(np.eye(unitary_u_size), unitary_u, rtol=_SVD_RTOL,
atol=2E-3)
with self.subTest('Test unitary v.'):
self.assertAllClose(np.eye(unitary_v_size), unitary_v, rtol=_SVD_RTOL,
atol=2E-3)
with self.subTest('Test s.'):
self.assertAllClose(
expected_s, jnp.real(actual_s), rtol=_SVD_RTOL, atol=1E-6)
@jtu.sample_product(
[dict(m=m, n=n) for m, n in zip([50, 6], [3, 60])],
)
def testSvdWithSkinnyTallInput(self, m, n):
"""Tests SVD with skinny and tall input."""
# Generates a skinny and tall input
with jax.default_matmul_precision('float32'):
np.random.seed(1235)
a = np.random.randn(m, n).astype(_SVD_TEST_DTYPE)
u, s, v = svd.svd(a, full_matrices=False, hermitian=False)
relative_diff = np.linalg.norm(a - (u * s) @ v) / np.linalg.norm(a)
np.testing.assert_almost_equal(relative_diff, 1E-6, decimal=6)
@jtu.sample_product(
[dict(m=m, r=r) for m, r in zip([8, 8, 8, 10], [3, 5, 7, 9])],
log_cond=np.linspace(1, 3, 3),
)
def testSvdWithOnRankDeficientInput(self, m, r, log_cond):
"""Tests SVD with rank-deficient input."""
with jax.default_matmul_precision('float32'):
a = jnp.triu(jnp.ones((m, m))).astype(_SVD_TEST_DTYPE)
# Generates a rank-deficient input.
u, s, v = jnp.linalg.svd(a, full_matrices=False)
cond = 10**log_cond
s = jnp.linspace(cond, 1, m)
s = s.at[r:m].set(0)
a = (u * s) @ v
with jax.default_matmul_precision('float32'):
u, s, v = svd.svd(a, full_matrices=False, hermitian=False)
diff = np.linalg.norm(a - (u * s) @ v)
np.testing.assert_almost_equal(diff, 1E-4, decimal=2)
@jtu.sample_product(
[dict(m=m, r=r) for m, r in zip([8, 8, 8, 10], [3, 5, 7, 9])],
)
def testSvdWithOnRankDeficientInputZeroColumns(self, m, r):
"""Tests SVD with rank-deficient input."""
with jax.default_matmul_precision('float32'):
np.random.seed(1235)
a = np.random.randn(m, m).astype(_SVD_TEST_DTYPE)
d = np.ones(m).astype(_SVD_TEST_DTYPE)
d[r:m] = 0
a = a @ np.diag(d)
with jax.default_matmul_precision('float32'):
u, s, v = svd.svd(a, full_matrices=True, hermitian=False)
diff = np.linalg.norm(a - (u * s) @ v)
np.testing.assert_almost_equal(diff, 1e-4, decimal=2)
# Check that u and v are orthogonal.
self.assertAllClose(u.T.conj() @ u, np.eye(m), atol=10 * _SVD_TEST_EPS)
self.assertAllClose(v.T.conj() @ v, np.eye(m), atol=30 * _SVD_TEST_EPS)
@jtu.sample_product(
[dict(m=m, n=n) for m, n in zip([2, 8, 10, 20], [4, 6, 10, 18])],
log_cond=np.linspace(1, _MAX_LOG_CONDITION_NUM, 4),
full_matrices=[True, False],
)
def testSingularValues(self, m, n, log_cond, full_matrices):
"""Tests singular values."""
with jax.default_matmul_precision('float32'):
a = np.random.uniform(
low=0.3, high=0.9, size=(m, n)).astype(_SVD_TEST_DTYPE)
u, s, v = osp_linalg.svd(a, full_matrices=False)
cond = 10**log_cond
s = np.linspace(cond, 1, min(m, n))
a = (u * s) @ v
a = a + 1j * a
# Only computes singular values.
compute_uv = False
osp_linalg_fn = functools.partial(
osp_linalg.svd, full_matrices=full_matrices, compute_uv=compute_uv)
actual_s = svd.svd(
a, full_matrices=full_matrices, compute_uv=compute_uv
).block_until_ready()
expected_s = osp_linalg_fn(a)
svd_fn = lambda a: svd.svd(a, full_matrices=full_matrices)
args_maker = lambda: [a]
with self.subTest('Test JIT compatibility'):
self._CompileAndCheck(svd_fn, args_maker)
with self.subTest('Test s.'):
self.assertAllClose(expected_s, actual_s, rtol=_SVD_RTOL, atol=1E-6)
with self.subTest('Test non-increasing order.'):
# Computes `actual_diff[i] = s[i+1] - s[i]`.
actual_diff = jnp.diff(actual_s, append=0)
np.testing.assert_array_less(actual_diff, np.zeros_like(actual_diff))
@jtu.sample_product(
[dict(m=m, n=n) for m, n in zip([2, 4, 8], [4, 4, 6])],
full_matrices=[True, False],
compute_uv=[True, False],
dtype=jtu.dtypes.floating + jtu.dtypes.complex,
)
def testSvdAllZero(self, m, n, full_matrices, compute_uv, dtype):
"""Tests SVD on matrix of all zeros, +/-infinity or NaN."""
osp_fun = functools.partial(
osp_linalg.svd, full_matrices=full_matrices, compute_uv=compute_uv
)
lax_fun = functools.partial(
svd.svd, full_matrices=full_matrices, compute_uv=compute_uv
)
args_maker_svd = lambda: [jnp.zeros((m, n), dtype=dtype)]
self._CheckAgainstNumpy(osp_fun, lax_fun, args_maker_svd)
self._CompileAndCheck(lax_fun, args_maker_svd)
@jtu.sample_product(
[dict(m=m, n=n) for m, n in zip([2, 4, 8], [4, 4, 6])],
fill_value=[-np.inf, np.inf, np.nan],
full_matrices=[True, False],
compute_uv=[True, False],
dtype=jtu.dtypes.floating + jtu.dtypes.complex,
)
def testSvdNonFiniteValues(
self, m, n, fill_value, full_matrices, compute_uv, dtype
):
"""Tests SVD on matrix of all zeros, +/-infinity or NaN."""
lax_fun = functools.partial(
svd.svd, full_matrices=full_matrices, compute_uv=compute_uv
)
args_maker_svd = lambda: [
jnp.full((m, n), fill_value=fill_value, dtype=dtype)
]
result = lax_fun(args_maker_svd()[0])
for r in result:
self.assertTrue(jnp.all(jnp.isnan(r)))
self._CompileAndCheck(lax_fun, args_maker_svd)
@jtu.sample_product(
[dict(m=m, n=n, r=r, c=c)
for m, n, r, c in zip([2, 4, 8], [4, 4, 6], [1, 0, 1], [1, 0, 1])],
dtype=jtu.dtypes.floating,
)
def testSvdOnTinyElement(self, m, n, r, c, dtype):
"""Tests SVD on matrix of zeros and close-to-zero entries."""
a = jnp.zeros((m, n), dtype=dtype)
tiny_element = jnp.finfo(a.dtype).tiny
a = a.at[r, c].set(tiny_element)
@jax.jit
def lax_fun(a):
return svd.svd(a, full_matrices=False, compute_uv=False, hermitian=False)
actual_s = lax_fun(a)
k = min(m, n)
expected_s = np.zeros((k,), dtype=dtype)
expected_s[0] = tiny_element
self.assertAllClose(expected_s, jnp.real(actual_s), rtol=_SVD_RTOL,
atol=1E-6)
@jtu.sample_product(
start=[0, 1, 64, 126, 127],
end=[1, 2, 65, 127, 128],
)
@jtu.run_on_devices('tpu') # TODO(rmlarsen: enable on other devices)
def testSvdSubsetByIndex(self, start, end):
if start >= end:
return
dtype = np.float32
m = 256
n = 128
rng = jtu.rand_default(self.rng())
tol = np.maximum(n, 80) * np.finfo(dtype).eps
args_maker = lambda: [rng((m, n), dtype)]
subset_by_index = (start, end)
k = end - start
(a,) = args_maker()
u, s, vt = jnp.linalg.svd(
a, full_matrices=False, subset_by_index=subset_by_index
)
self.assertEqual(u.shape, (m, k))
self.assertEqual(s.shape, (k,))
self.assertEqual(vt.shape, (k, n))
with jax.numpy_rank_promotion('allow'):
self.assertLessEqual(
np.linalg.norm(np.matmul(a, vt.T) - u * s), tol * np.linalg.norm(a)
)
# Test that we get the approximately the same singular values when
# slicing the full SVD.
_, full_s, _ = jnp.linalg.svd(a, full_matrices=False)
s_slice = full_s[start:end]
self.assertAllClose(s_slice, s, atol=tol, rtol=tol)
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
|
SvdTest
|
python
|
ray-project__ray
|
doc/source/serve/doc_code/tutorial_pytorch.py
|
{
"start": 337,
"end": 1678
}
|
class ____:
def __init__(self):
self.model = resnet18(pretrained=True).eval()
self.preprocessor = transforms.Compose(
[
transforms.Resize(224),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Lambda(lambda t: t[:3, ...]), # remove alpha channel
transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
),
]
)
async def __call__(self, starlette_request: Request) -> Dict:
image_payload_bytes = await starlette_request.body()
pil_image = Image.open(BytesIO(image_payload_bytes))
print("[1/3] Parsed image data: {}".format(pil_image))
pil_images = [pil_image] # Our current batch size is one
input_tensor = torch.cat(
[self.preprocessor(i).unsqueeze(0) for i in pil_images]
)
print("[2/3] Images transformed, tensor shape {}".format(input_tensor.shape))
with torch.no_grad():
output_tensor = self.model(input_tensor)
print("[3/3] Inference done!")
return {"class_index": int(torch.argmax(output_tensor[0]))}
# __doc_define_servable_end__
# __doc_deploy_begin__
image_model = ImageModel.bind()
# __doc_deploy_end__
|
ImageModel
|
python
|
pypa__setuptools
|
setuptools/_vendor/jaraco/collections/__init__.py
|
{
"start": 3698,
"end": 9127
}
|
class ____(Dict[_RangeMapKT, _VT]):
"""
A dictionary-like object that uses the keys as bounds for a range.
Inclusion of the value for that range is determined by the
key_match_comparator, which defaults to less-than-or-equal.
A value is returned for a key if it is the first key that matches in
the sorted list of keys.
One may supply keyword parameters to be passed to the sort function used
to sort keys (i.e. key, reverse) as sort_params.
Create a map that maps 1-3 -> 'a', 4-6 -> 'b'
>>> r = RangeMap({3: 'a', 6: 'b'}) # boy, that was easy
>>> r[1], r[2], r[3], r[4], r[5], r[6]
('a', 'a', 'a', 'b', 'b', 'b')
Even float values should work so long as the comparison operator
supports it.
>>> r[4.5]
'b'
Notice that the way rangemap is defined, it must be open-ended
on one side.
>>> r[0]
'a'
>>> r[-1]
'a'
One can close the open-end of the RangeMap by using undefined_value
>>> r = RangeMap({0: RangeMap.undefined_value, 3: 'a', 6: 'b'})
>>> r[0]
Traceback (most recent call last):
...
KeyError: 0
One can get the first or last elements in the range by using RangeMap.Item
>>> last_item = RangeMap.Item(-1)
>>> r[last_item]
'b'
.last_item is a shortcut for Item(-1)
>>> r[RangeMap.last_item]
'b'
Sometimes it's useful to find the bounds for a RangeMap
>>> r.bounds()
(0, 6)
RangeMap supports .get(key, default)
>>> r.get(0, 'not found')
'not found'
>>> r.get(7, 'not found')
'not found'
One often wishes to define the ranges by their left-most values,
which requires use of sort params and a key_match_comparator.
>>> r = RangeMap({1: 'a', 4: 'b'},
... sort_params=dict(reverse=True),
... key_match_comparator=operator.ge)
>>> r[1], r[2], r[3], r[4], r[5], r[6]
('a', 'a', 'a', 'b', 'b', 'b')
That wasn't nearly as easy as before, so an alternate constructor
is provided:
>>> r = RangeMap.left({1: 'a', 4: 'b', 7: RangeMap.undefined_value})
>>> r[1], r[2], r[3], r[4], r[5], r[6]
('a', 'a', 'a', 'b', 'b', 'b')
"""
def __init__(
self,
source: (
SupportsKeysAndGetItem[_RangeMapKT, _VT] | Iterable[tuple[_RangeMapKT, _VT]]
),
sort_params: Mapping[str, Any] = {},
key_match_comparator: Callable[[_RangeMapKT, _RangeMapKT], bool] = operator.le,
):
dict.__init__(self, source)
self.sort_params = sort_params
self.match = key_match_comparator
@classmethod
def left(
cls,
source: (
SupportsKeysAndGetItem[_RangeMapKT, _VT] | Iterable[tuple[_RangeMapKT, _VT]]
),
) -> Self:
return cls(
source, sort_params=dict(reverse=True), key_match_comparator=operator.ge
)
def __getitem__(self, item: _RangeMapKT) -> _VT:
sorted_keys = sorted(self.keys(), **self.sort_params)
if isinstance(item, RangeMap.Item):
result = self.__getitem__(sorted_keys[item])
else:
key = self._find_first_match_(sorted_keys, item)
result = dict.__getitem__(self, key)
if result is RangeMap.undefined_value:
raise KeyError(key)
return result
@overload # type: ignore[override] # Signature simplified over dict and Mapping
def get(self, key: _RangeMapKT, default: _T) -> _VT | _T: ...
@overload
def get(self, key: _RangeMapKT, default: None = None) -> _VT | None: ...
def get(self, key: _RangeMapKT, default: _T | None = None) -> _VT | _T | None:
"""
Return the value for key if key is in the dictionary, else default.
If default is not given, it defaults to None, so that this method
never raises a KeyError.
"""
try:
return self[key]
except KeyError:
return default
def _find_first_match_(
self, keys: Iterable[_RangeMapKT], item: _RangeMapKT
) -> _RangeMapKT:
is_match = functools.partial(self.match, item)
matches = filter(is_match, keys)
try:
return next(matches)
except StopIteration:
raise KeyError(item) from None
def bounds(self) -> tuple[_RangeMapKT, _RangeMapKT]:
sorted_keys = sorted(self.keys(), **self.sort_params)
return (sorted_keys[RangeMap.first_item], sorted_keys[RangeMap.last_item])
# some special values for the RangeMap
undefined_value = type('RangeValueUndefined', (), {})()
class Item(int):
"""RangeMap Item"""
first_item = Item(0)
last_item = Item(-1)
def __identity(x):
return x
def sorted_items(d, key=__identity, reverse=False):
"""
Return the items of the dictionary sorted by the keys.
>>> sample = dict(foo=20, bar=42, baz=10)
>>> tuple(sorted_items(sample))
(('bar', 42), ('baz', 10), ('foo', 20))
>>> reverse_string = lambda s: ''.join(reversed(s))
>>> tuple(sorted_items(sample, key=reverse_string))
(('foo', 20), ('bar', 42), ('baz', 10))
>>> tuple(sorted_items(sample, reverse=True))
(('foo', 20), ('baz', 10), ('bar', 42))
"""
# wrap the key func so it operates on the first element of each item
def pairkey_key(item):
return key(item[0])
return sorted(d.items(), key=pairkey_key, reverse=reverse)
|
RangeMap
|
python
|
pytorch__pytorch
|
torch/_dynamo/variables/functions.py
|
{
"start": 103476,
"end": 105184
}
|
class ____(VariableTracker):
grid: "TritonGridType"
kernel: "TritonKernelType"
kernel_idx: Optional[int]
kernel_source: "AttrSource"
def __init__(
self, kernel: Any, kernel_idx: Optional[int], grid: Any, **kwargs: Any
) -> None:
self.kernel_source = kwargs.pop("kernel_source", None)
super().__init__(**kwargs)
dynamo_triton_hopifier_singleton.init_variable(self, kernel, kernel_idx, grid)
def call_function(
self,
tx: "InstructionTranslator",
args: Sequence[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker:
return dynamo_triton_hopifier_singleton.call_triton_kernel( # type: ignore[return-value]
self, args, kwargs, tx
)
def call_method(
self,
tx: "InstructionTranslator",
name: str,
args: list[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker:
if name == "__getitem__":
return dynamo_triton_hopifier_singleton.call_getitem(self, args)
elif name == "run":
return dynamo_triton_hopifier_singleton.call_run(self, args, kwargs, tx) # type: ignore[return-value]
# Bail out to parent's implementation
return super().call_method(tx, name, args, kwargs)
def specialize_symbolic(self, arg: Any) -> Any:
from .constant import ConstantVariable
from .tensor import SymNodeVariable
# See [Note: Specialize tl.constexpr args in user-defined triton kernels]
if isinstance(arg, SymNodeVariable):
return ConstantVariable.create(arg.evaluate_expr())
return arg
|
TritonKernelVariable
|
python
|
allegroai__clearml
|
clearml/backend_api/services/v2_9/models.py
|
{
"start": 79590,
"end": 83090
}
|
class ____(Response):
"""
Response of models.set_ready endpoint.
:param updated: Number of models updated (0 or 1)
:type updated: int
:param published_task: Result of publishing of the model's associated task (if
exists). Returned only if the task was published successfully as part of the
model publishing.
:type published_task: dict
"""
_service = "models"
_action = "set_ready"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {
"published_task": {
"description": "Result of publishing of the model's associated task (if exists). Returned only if the task was published successfully as part of the model publishing.",
"properties": {
"data": {
"description": "Data returned from the task publishing operation.",
"properties": {
"committed_versions_results": {
"description": "Committed versions results",
"items": {
"additionalProperties": True,
"type": "object",
},
"type": "array",
},
"fields": {
"additionalProperties": True,
"description": "Updated fields names and values",
"type": "object",
},
"updated": {
"description": "Number of tasks updated (0 or 1)",
"enum": [0, 1],
"type": "integer",
},
},
"type": "object",
},
"id": {"description": "Task id", "type": "string"},
},
"type": ["object", "null"],
},
"updated": {
"description": "Number of models updated (0 or 1)",
"enum": [0, 1],
"type": ["integer", "null"],
},
},
"type": "object",
}
def __init__(self, updated: Optional[int] = None, published_task: Optional[dict] = None, **kwargs: Any) -> None:
super(SetReadyResponse, self).__init__(**kwargs)
self.updated = updated
self.published_task = published_task
@schema_property("updated")
def updated(self) -> Optional[int]:
return self._property_updated
@updated.setter
def updated(self, value: Optional[int]) -> None:
if value is None:
self._property_updated = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "updated", six.integer_types)
self._property_updated = value
@schema_property("published_task")
def published_task(self) -> Optional[dict]:
return self._property_published_task
@published_task.setter
def published_task(self, value: Optional[dict]) -> None:
if value is None:
self._property_published_task = None
return
self.assert_isinstance(value, "published_task", (dict,))
self._property_published_task = value
|
SetReadyResponse
|
python
|
pytransitions__transitions
|
tests/test_add_remove.py
|
{
"start": 206,
"end": 2689
}
|
class ____(TestCase):
def test_garbage_collection(self):
states = ['A', 'B', 'C', 'D', 'E', 'F']
machine = Machine(model=[], states=states, initial='A', name='Test Machine')
machine.add_transition('advance', 'A', 'B')
machine.add_transition('advance', 'B', 'C')
machine.add_transition('advance', 'C', 'D')
s1 = Dummy()
s2 = Dummy()
s2_collected = threading.Event()
s2_proxy = weakref.proxy(s2, lambda _: s2_collected.set())
machine.add_model([s1, s2])
self.assertTrue(s1.is_A())
self.assertTrue(s2.is_A())
s1.advance()
self.assertTrue(s1.is_B())
self.assertTrue(s2.is_A())
self.assertFalse(s2_collected.is_set())
machine.remove_model(s2)
del s2
gc.collect()
self.assertTrue(s2_collected.is_set())
s3 = Dummy()
machine.add_model(s3)
s3.advance()
s3.advance()
self.assertTrue(s3.is_C())
def test_add_model_initial_state(self):
states = ['A', 'B', 'C', 'D', 'E', 'F']
machine = Machine(model=[], states=states, initial='A', name='Test Machine')
machine.add_transition('advance', 'A', 'B')
machine.add_transition('advance', 'B', 'C')
machine.add_transition('advance', 'C', 'D')
s1 = Dummy()
s2 = Dummy()
s3 = Dummy()
machine.add_model(s1)
machine.add_model(s2, initial='B')
machine.add_model(s3, initial='C')
s1.advance()
s2.advance()
s3.advance()
self.assertTrue(s1.is_B())
self.assertTrue(s2.is_C())
self.assertTrue(s3.is_D())
def test_add_model_no_initial_state(self):
states = ['A', 'B', 'C', 'D', 'E', 'F']
machine = Machine(model=[], states=states, name='Test Machine', initial=None)
machine.add_transition('advance', 'A', 'B')
machine.add_transition('advance', 'B', 'C')
machine.add_transition('advance', 'C', 'D')
s1 = Dummy()
s2 = Dummy()
s3 = Dummy()
with self.assertRaises(ValueError):
machine.add_model(s1)
machine.add_model(s1, initial='A')
machine.add_model(s2, initial='B')
machine.add_model(s3, initial='C')
s1.advance()
s2.advance()
s3.advance()
self.assertTrue(s1.is_B())
self.assertTrue(s2.is_C())
self.assertTrue(s3.is_D())
|
TestTransitionsAddRemove
|
python
|
pandas-dev__pandas
|
pandas/core/flags.py
|
{
"start": 219,
"end": 4211
}
|
class ____:
"""
Flags that apply to pandas objects.
“Flags” differ from “metadata”. Flags reflect properties of the pandas
object (the Series or DataFrame). Metadata refer to properties of the
dataset, and should be stored in DataFrame.attrs.
Parameters
----------
obj : Series or DataFrame
The object these flags are associated with.
allows_duplicate_labels : bool, default True
Whether to allow duplicate labels in this object. By default,
duplicate labels are permitted. Setting this to ``False`` will
cause an :class:`errors.DuplicateLabelError` to be raised when
`index` (or columns for DataFrame) is not unique, or any
subsequent operation on introduces duplicates.
See :ref:`duplicates.disallow` for more.
.. warning::
This is an experimental feature. Currently, many methods fail to
propagate the ``allows_duplicate_labels`` value. In future versions
it is expected that every method taking or returning one or more
DataFrame or Series objects will propagate ``allows_duplicate_labels``.
See Also
--------
DataFrame.attrs : Dictionary of global attributes of this dataset.
Series.attrs : Dictionary of global attributes of this dataset.
Examples
--------
Attributes can be set in two ways:
>>> df = pd.DataFrame()
>>> df.flags
<Flags(allows_duplicate_labels=True)>
>>> df.flags.allows_duplicate_labels = False
>>> df.flags
<Flags(allows_duplicate_labels=False)>
>>> df.flags["allows_duplicate_labels"] = True
>>> df.flags
<Flags(allows_duplicate_labels=True)>
"""
_keys: set[str] = {"allows_duplicate_labels"}
def __init__(self, obj: NDFrame, *, allows_duplicate_labels: bool) -> None:
self._allows_duplicate_labels = allows_duplicate_labels
self._obj = weakref.ref(obj)
@property
def allows_duplicate_labels(self) -> bool:
"""
Whether this object allows duplicate labels.
Setting ``allows_duplicate_labels=False`` ensures that the
index (and columns of a DataFrame) are unique. Most methods
that accept and return a Series or DataFrame will propagate
the value of ``allows_duplicate_labels``.
See :ref:`duplicates` for more.
See Also
--------
DataFrame.attrs : Set global metadata on this object.
DataFrame.set_flags : Set global flags on this object.
Examples
--------
>>> df = pd.DataFrame({"A": [1, 2]}, index=["a", "a"])
>>> df.flags.allows_duplicate_labels
True
>>> df.flags.allows_duplicate_labels = False
Traceback (most recent call last):
...
pandas.errors.DuplicateLabelError: Index has duplicates.
positions
label
a [0, 1]
"""
return self._allows_duplicate_labels
@allows_duplicate_labels.setter
def allows_duplicate_labels(self, value: bool) -> None:
value = bool(value)
obj = self._obj()
if obj is None:
raise ValueError("This flag's object has been deleted.")
if not value:
for ax in obj.axes:
ax._maybe_check_unique()
self._allows_duplicate_labels = value
def __getitem__(self, key: str):
if key not in self._keys:
raise KeyError(key)
return getattr(self, key)
def __setitem__(self, key: str, value) -> None:
if key not in self._keys:
raise ValueError(f"Unknown flag {key}. Must be one of {self._keys}")
setattr(self, key, value)
def __repr__(self) -> str:
return f"<Flags(allows_duplicate_labels={self.allows_duplicate_labels})>"
def __eq__(self, other: object) -> bool:
if isinstance(other, type(self)):
return self.allows_duplicate_labels == other.allows_duplicate_labels
return False
|
Flags
|
python
|
ijl__orjson
|
test/test_enum.py
|
{
"start": 429,
"end": 592
}
|
class ____:
def __init__(self, val):
self.val = val
def default(obj):
if isinstance(obj, Custom):
return obj.val
raise TypeError
|
Custom
|
python
|
airbytehq__airbyte
|
airbyte-integrations/connectors/source-github/source_github/github_schema.py
|
{
"start": 112687,
"end": 113157
}
|
class ____(sgqlc.types.Enum):
"""The different kinds of goals a GitHub Sponsors member can have.
Enumeration Choices:
* `MONTHLY_SPONSORSHIP_AMOUNT`: The goal is about getting a
certain amount in USD from sponsorships each month.
* `TOTAL_SPONSORS_COUNT`: The goal is about reaching a certain
number of sponsors.
"""
__schema__ = github_schema
__choices__ = ("MONTHLY_SPONSORSHIP_AMOUNT", "TOTAL_SPONSORS_COUNT")
|
SponsorsGoalKind
|
python
|
neetcode-gh__leetcode
|
python/0219-contains-duplicate-ii.py
|
{
"start": 0,
"end": 364
}
|
class ____:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
window = set()
L = 0
for R in range(len(nums)):
if R - L > k:
window.remove(nums[L])
L += 1
if nums[R] in window:
return True
window.add(nums[R])
return False
|
Solution
|
python
|
davidhalter__jedi
|
jedi/inference/gradual/typing.py
|
{
"start": 14352,
"end": 14907
}
|
class ____(ValueWrapper):
def py__call__(self, arguments):
ordered_args = arguments.unpack()
next(ordered_args, (None, None))
_, second_arg = next(ordered_args, (None, None))
if second_arg is None:
return NO_VALUES
return ValueSet(
NewType(
self.inference_state,
contextualized_node.context,
contextualized_node.node,
second_arg.infer(),
) for contextualized_node in arguments.get_calling_nodes())
|
NewTypeFunction
|
python
|
pandas-dev__pandas
|
pandas/tests/frame/methods/test_diff.py
|
{
"start": 166,
"end": 10246
}
|
class ____:
def test_diff_requires_integer(self):
df = DataFrame(np.random.default_rng(2).standard_normal((2, 2)))
with pytest.raises(ValueError, match="periods must be an integer"):
df.diff(1.5)
# GH#44572 np.int64 is accepted
@pytest.mark.parametrize("num", [1, np.int64(1)])
def test_diff(self, datetime_frame, num):
df = datetime_frame
the_diff = df.diff(num)
expected = df["A"] - df["A"].shift(num)
tm.assert_series_equal(the_diff["A"], expected)
def test_diff_int_dtype(self):
# int dtype
a = 10_000_000_000_000_000
b = a + 1
ser = Series([a, b])
rs = DataFrame({"s": ser}).diff()
assert rs.s[1] == 1
def test_diff_mixed_numeric(self, datetime_frame):
# mixed numeric
tf = datetime_frame.astype("float32")
the_diff = tf.diff(1)
tm.assert_series_equal(the_diff["A"], tf["A"] - tf["A"].shift(1))
def test_diff_axis1_nonconsolidated(self):
# GH#10907
df = DataFrame({"y": Series([2]), "z": Series([3])})
df.insert(0, "x", 1)
result = df.diff(axis=1)
expected = DataFrame({"x": np.nan, "y": Series(1), "z": Series(1)})
tm.assert_frame_equal(result, expected)
def test_diff_timedelta64_with_nat(self):
# GH#32441
arr = np.arange(6).reshape(3, 2).astype("timedelta64[ns]")
arr[:, 0] = np.timedelta64("NaT", "ns")
df = DataFrame(arr)
result = df.diff(1, axis=0)
expected = DataFrame({0: df[0], 1: [pd.NaT, pd.Timedelta(2), pd.Timedelta(2)]})
tm.assert_equal(result, expected)
result = df.diff(0)
expected = df - df
assert expected[0].isna().all()
tm.assert_equal(result, expected)
result = df.diff(-1, axis=1)
expected = df * np.nan
tm.assert_equal(result, expected)
@pytest.mark.parametrize("tz", [None, "UTC"])
def test_diff_datetime_axis0_with_nat(self, tz, unit):
# GH#32441
dti = pd.DatetimeIndex(["NaT", "2019-01-01", "2019-01-02"], tz=tz).as_unit(unit)
ser = Series(dti)
df = ser.to_frame()
result = df.diff()
ex_index = pd.TimedeltaIndex([pd.NaT, pd.NaT, pd.Timedelta(days=1)]).as_unit(
unit
)
expected = Series(ex_index).to_frame()
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("tz", [None, "UTC"])
def test_diff_datetime_with_nat_zero_periods(self, tz):
# diff on NaT values should give NaT, not timedelta64(0)
dti = date_range("2016-01-01", periods=4, tz=tz)
ser = Series(dti)
df = ser.to_frame().copy()
df[1] = ser.copy()
df.iloc[:, 0] = pd.NaT
expected = df - df
assert expected[0].isna().all()
result = df.diff(0, axis=0)
tm.assert_frame_equal(result, expected)
result = df.diff(0, axis=1)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("tz", [None, "UTC"])
def test_diff_datetime_axis0(self, tz):
# GH#18578
df = DataFrame(
{
0: date_range("2010", freq="D", periods=2, tz=tz, unit="ns"),
1: date_range("2010", freq="D", periods=2, tz=tz, unit="ns"),
}
)
result = df.diff(axis=0)
expected = DataFrame(
{
0: pd.TimedeltaIndex(["NaT", "1 days"]),
1: pd.TimedeltaIndex(["NaT", "1 days"]),
}
)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("tz", [None, "UTC"])
def test_diff_datetime_axis1(self, tz):
# GH#18578
df = DataFrame(
{
0: date_range("2010", freq="D", periods=2, tz=tz, unit="ns"),
1: date_range("2010", freq="D", periods=2, tz=tz, unit="ns"),
}
)
result = df.diff(axis=1)
expected = DataFrame(
{
0: pd.TimedeltaIndex(["NaT", "NaT"]),
1: pd.TimedeltaIndex(["0 days", "0 days"]),
}
)
tm.assert_frame_equal(result, expected)
def test_diff_timedelta(self, unit):
# GH#4533
df = DataFrame(
{
"time": [Timestamp("20130101 9:01"), Timestamp("20130101 9:02")],
"value": [1.0, 2.0],
}
)
df["time"] = df["time"].dt.as_unit(unit)
res = df.diff()
exp = DataFrame(
[[pd.NaT, np.nan], [pd.Timedelta("00:01:00"), 1]], columns=["time", "value"]
)
exp["time"] = exp["time"].dt.as_unit(unit)
tm.assert_frame_equal(res, exp)
def test_diff_mixed_dtype(self):
df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
df["A"] = np.array([1, 2, 3, 4, 5], dtype=object)
result = df.diff()
assert result[0].dtype == np.float64
def test_diff_neg_n(self, datetime_frame):
rs = datetime_frame.diff(-1)
xp = datetime_frame - datetime_frame.shift(-1)
tm.assert_frame_equal(rs, xp)
def test_diff_float_n(self, datetime_frame):
rs = datetime_frame.diff(1.0)
xp = datetime_frame.diff(1)
tm.assert_frame_equal(rs, xp)
def test_diff_axis(self):
# GH#9727
df = DataFrame([[1.0, 2.0], [3.0, 4.0]])
tm.assert_frame_equal(
df.diff(axis=1), DataFrame([[np.nan, 1.0], [np.nan, 1.0]])
)
tm.assert_frame_equal(
df.diff(axis=0), DataFrame([[np.nan, np.nan], [2.0, 2.0]])
)
def test_diff_period(self):
# GH#32995 Don't pass an incorrect axis
pi = date_range("2016-01-01", periods=3).to_period("D")
df = DataFrame({"A": pi})
result = df.diff(1, axis=1)
expected = (df - pd.NaT).astype(object)
tm.assert_frame_equal(result, expected)
def test_diff_axis1_mixed_dtypes(self):
# GH#32995 operate column-wise when we have mixed dtypes and axis=1
df = DataFrame({"A": range(3), "B": 2 * np.arange(3, dtype=np.float64)})
expected = DataFrame({"A": [np.nan, np.nan, np.nan], "B": df["B"] / 2})
result = df.diff(axis=1)
tm.assert_frame_equal(result, expected)
# GH#21437 mixed-float-dtypes
df = DataFrame(
{"a": np.arange(3, dtype="float32"), "b": np.arange(3, dtype="float64")}
)
result = df.diff(axis=1)
expected = DataFrame({"a": df["a"] * np.nan, "b": df["b"] * 0})
tm.assert_frame_equal(result, expected)
def test_diff_axis1_mixed_dtypes_large_periods(self):
# GH#32995 operate column-wise when we have mixed dtypes and axis=1
df = DataFrame({"A": range(3), "B": 2 * np.arange(3, dtype=np.float64)})
expected = df * np.nan
result = df.diff(axis=1, periods=3)
tm.assert_frame_equal(result, expected)
def test_diff_axis1_mixed_dtypes_negative_periods(self):
# GH#32995 operate column-wise when we have mixed dtypes and axis=1
df = DataFrame({"A": range(3), "B": 2 * np.arange(3, dtype=np.float64)})
expected = DataFrame({"A": -1.0 * df["A"], "B": df["B"] * np.nan})
result = df.diff(axis=1, periods=-1)
tm.assert_frame_equal(result, expected)
def test_diff_sparse(self):
# GH#28813 .diff() should work for sparse dataframes as well
sparse_df = DataFrame([[0, 1], [1, 0]], dtype="Sparse[int]")
result = sparse_df.diff()
expected = DataFrame(
[[np.nan, np.nan], [1.0, -1.0]], dtype=pd.SparseDtype("float", 0.0)
)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"axis,expected",
[
(
0,
DataFrame(
{
"a": [pd.NA, 0, 1, 0, pd.NA, pd.NA, pd.NA, 0],
"b": [pd.NA, 1, pd.NA, pd.NA, -2, 1, pd.NA, pd.NA],
"c": np.repeat(pd.NA, 8), # type: ignore[call-overload]
"d": [pd.NA, 3, 5, 7, 9, 11, 13, 15],
},
dtype="Int64",
),
),
(
1,
DataFrame(
{
"a": np.repeat(pd.NA, 8), # type: ignore[call-overload]
"b": [0, 1, pd.NA, 1, pd.NA, pd.NA, pd.NA, 0],
"c": np.repeat(pd.NA, 8), # type: ignore[call-overload]
"d": np.repeat(pd.NA, 8), # type: ignore[call-overload]
},
dtype="Int64",
),
),
],
)
def test_diff_integer_na(self, axis, expected):
# GH#24171 IntegerNA Support for DataFrame.diff()
df = DataFrame(
{
"a": np.repeat([0, 1, pd.NA, 2], 2),
"b": np.tile([0, 1, pd.NA, 2], 2),
"c": np.repeat(pd.NA, 8),
"d": np.arange(1, 9) ** 2,
},
dtype="Int64",
)
# Test case for default behaviour of diff
result = df.diff(axis=axis)
tm.assert_frame_equal(result, expected)
def test_diff_readonly(self):
# https://github.com/pandas-dev/pandas/issues/35559
arr = np.random.default_rng(2).standard_normal((5, 2))
arr.flags.writeable = False
df = DataFrame(arr)
result = df.diff()
expected = DataFrame(np.array(df)).diff()
tm.assert_frame_equal(result, expected)
def test_diff_all_int_dtype(self, any_int_numpy_dtype):
# GH 14773
df = DataFrame(range(5))
df = df.astype(any_int_numpy_dtype)
result = df.diff()
expected_dtype = (
"float32" if any_int_numpy_dtype in ("int8", "int16") else "float64"
)
expected = DataFrame([np.nan, 1.0, 1.0, 1.0, 1.0], dtype=expected_dtype)
tm.assert_frame_equal(result, expected)
|
TestDataFrameDiff
|
python
|
walkccc__LeetCode
|
solutions/1291. Sequential Digits/1291.py
|
{
"start": 0,
"end": 399
}
|
class ____:
def sequentialDigits(self, low: int, high: int) -> list[int]:
ans = []
q = collections.deque([num for num in range(1, 10)])
while q:
num = q.popleft()
if num > high:
return ans
if low <= num and num <= high:
ans.append(num)
lastDigit = num % 10
if lastDigit < 9:
q.append(num * 10 + lastDigit + 1)
return ans
|
Solution
|
python
|
run-llama__llama_index
|
llama-index-core/llama_index/core/langchain_helpers/streaming.py
|
{
"start": 216,
"end": 1935
}
|
class ____(BaseCallbackHandler):
"""Streaming callback handler."""
def __init__(self) -> None:
self._token_queue: Queue = Queue()
self._done = Event()
def __deepcopy__(self, memo: Any) -> "StreamingGeneratorCallbackHandler":
# NOTE: hack to bypass deepcopy in langchain
return self
def on_llm_new_token(self, token: str, **kwargs: Any) -> Any:
"""Run on new LLM token. Only available when streaming is enabled."""
self._token_queue.put_nowait(token)
def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
self._done.set()
def on_llm_error(
self,
error: BaseException,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
**kwargs: Any,
) -> None:
self._done.set()
def get_response_gen(self, timeout: float = 120.0) -> Generator:
"""
Get response generator with timeout.
Args:
timeout (float): Maximum time in seconds to wait for the complete response.
Defaults to 120 seconds.
"""
start_time = time.time()
while True:
if time.time() - start_time > timeout:
raise TimeoutError(
f"Response generation timed out after {timeout} seconds"
)
if not self._token_queue.empty():
token = self._token_queue.get_nowait()
yield token
elif self._done.is_set():
break
else:
# Small sleep to prevent CPU spinning
time.sleep(0.01)
|
StreamingGeneratorCallbackHandler
|
python
|
graphql-python__graphene
|
graphene/relay/tests/test_node.py
|
{
"start": 162,
"end": 299
}
|
class ____:
shared = String()
something_else = String()
def resolve_something_else(*_):
return "----"
|
SharedNodeFields
|
python
|
getsentry__sentry
|
src/sentry/api/endpoints/project_tags.py
|
{
"start": 626,
"end": 3360
}
|
class ____(ProjectEndpoint):
owner = ApiOwner.UNOWNED
publish_status = {
"GET": ApiPublishStatus.UNKNOWN,
}
def get(self, request: Request, project) -> Response:
try:
environment_id = get_environment_id(request, project.organization_id)
except Environment.DoesNotExist:
tag_keys = []
else:
kwargs: dict = {}
if request.GET.get("onlySamplingTags") == "1":
kwargs["denylist"] = DS_DENYLIST
# Flags are stored on the same table as tags but on a different column. Ideally both
# could be queried in a single request. But at present we're not sure if we want to
# treat tags and flags as the same or different and in which context.
use_flag_backend = request.GET.get("useFlagsBackend") == "1"
if use_flag_backend:
backend = tagstore.flag_backend
else:
backend = tagstore.backend
include_values_seen = request.GET.get("includeValuesSeen") != "0"
if features.has("organizations:tag-key-sample-n", project.organization):
# Tag queries longer than 14 days tend to time out for large customers. For getting a list of tags, clamping to 14 days is a reasonable compromise of speed vs. completeness
(start, end) = clamp_date_range(
default_start_end_dates(),
datetime.timedelta(days=options.get("visibility.tag-key-max-date-range.days")),
)
kwargs["start"] = start
kwargs["end"] = end
tag_keys = sorted(
backend.get_tag_keys(
project.id,
environment_id,
tenant_ids={"organization_id": project.organization_id},
# We might be able to stop including these values, but this
# is a pretty old endpoint, so concerned about breaking
# existing api consumers.
include_values_seen=include_values_seen,
**kwargs,
),
key=lambda x: x.key,
)
data = []
for tag_key in tag_keys:
data.append(
{
"key": tagstore.backend.get_standardized_key(tag_key.key),
"name": tagstore.backend.get_tag_key_label(tag_key.key),
**({"uniqueValues": tag_key.values_seen} if include_values_seen else {}),
"canDelete": tag_key.key not in PROTECTED_TAG_KEYS and not use_flag_backend,
}
)
return Response(data)
|
ProjectTagsEndpoint
|
python
|
numba__numba
|
numba/core/cpu_options.py
|
{
"start": 96,
"end": 416
}
|
class ____(metaclass=ABCMeta):
"""Abstract base class for custom option values.
"""
@abstractmethod
def encode(self) -> str:
"""Returns an encoding of the values
"""
...
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.encode()})"
|
AbstractOptionValue
|
python
|
python-poetry__poetry
|
src/poetry/layouts/src.py
|
{
"start": 105,
"end": 202
}
|
class ____(Layout):
@property
def basedir(self) -> Path:
return Path("src")
|
SrcLayout
|
python
|
getsentry__sentry
|
src/sentry/integrations/slack/message_builder/prompt.py
|
{
"start": 226,
"end": 708
}
|
class ____(BlockSlackMessageBuilder):
def __init__(self, url: str) -> None:
super().__init__()
self.url = url
def build(self) -> SlackBody:
return {
"blocks": orjson.dumps(
[
self.get_markdown_block(LINK_IDENTITY_MESSAGE),
self.get_action_block([("Link", self.url, "link"), ("Cancel", None, "ignore")]),
],
).decode()
}
|
SlackPromptLinkMessageBuilder
|
python
|
tqdm__tqdm
|
tqdm/std.py
|
{
"start": 1028,
"end": 1412
}
|
class ____(Warning):
"""base class for all tqdm warnings.
Used for non-external-code-breaking errors, such as garbled printing.
"""
def __init__(self, msg, fp_write=None, *a, **k):
if fp_write is not None:
fp_write("\n" + self.__class__.__name__ + ": " + str(msg).rstrip() + '\n')
else:
super().__init__(msg, *a, **k)
|
TqdmWarning
|
python
|
pytorch__pytorch
|
torch/nn/modules/container.py
|
{
"start": 22458,
"end": 27819
}
|
class ____(Module):
r"""Holds parameters in a list.
:class:`~torch.nn.ParameterList` can be used like a regular Python
list, but Tensors that are :class:`~torch.nn.Parameter` are properly registered,
and will be visible by all :class:`~torch.nn.Module` methods.
Note that the constructor, assigning an element of the list, the
:meth:`~torch.nn.ParameterList.append` method and the :meth:`~torch.nn.ParameterList.extend`
method will convert any :class:`~torch.Tensor` into :class:`~torch.nn.Parameter`.
Args:
parameters (iterable, optional): an iterable of elements to add to the list.
Example::
class MyModule(nn.Module):
def __init__(self) -> None:
super().__init__()
self.params = nn.ParameterList(
[nn.Parameter(torch.randn(10, 10)) for i in range(10)]
)
def forward(self, x):
# ParameterList can act as an iterable, or be indexed using ints
for i, p in enumerate(self.params):
x = self.params[i // 2].mm(x) + p.mm(x)
return x
"""
def __init__(self, values: Optional[Iterable[Any]] = None) -> None:
super().__init__()
self._size = 0
if values is not None:
self += values
def _get_abs_string_index(self, idx):
"""Get the absolute index for the list of modules."""
idx = operator.index(idx)
if not (-len(self) <= idx < len(self)):
raise IndexError(f"index {idx} is out of range")
if idx < 0:
idx += len(self)
return str(idx)
@overload
def __getitem__(self, idx: int) -> Any: ...
@overload
# pyrefly: ignore [inconsistent-overload]
def __getitem__(self: T, idx: slice) -> T: ...
def __getitem__(self, idx):
if isinstance(idx, slice):
start, stop, step = idx.indices(len(self))
out = self.__class__()
for i in range(start, stop, step):
out.append(self[i])
return out
else:
idx = self._get_abs_string_index(idx)
return getattr(self, str(idx))
def __setitem__(self, idx: int, param: Any) -> None:
# Note that all other function that add an entry to the list part of
# the ParameterList end up here. So this is the only place where we need
# to wrap things into Parameter if needed.
# Objects added via setattr() are not in the list part and thus won't
# call into this function.
idx = self._get_abs_string_index(idx)
if isinstance(param, torch.Tensor) and not isinstance(param, Parameter):
param = Parameter(param)
return setattr(self, str(idx), param)
def __len__(self) -> int:
return self._size
def __iter__(self) -> Iterator[Any]:
return iter(self[i] for i in range(len(self)))
def __iadd__(self, parameters: Iterable[Any]) -> Self:
return self.extend(parameters)
def __dir__(self) -> list[str]:
keys = super().__dir__()
keys = [key for key in keys if not key.isdigit()]
return keys
def append(self, value: Any) -> Self:
"""Append a given value at the end of the list.
Args:
value (Any): value to append
"""
new_idx = len(self)
self._size += 1
self[new_idx] = value
return self
def extend(self, values: Iterable[Any]) -> Self:
"""Append values from a Python iterable to the end of the list.
Args:
values (iterable): iterable of values to append
"""
# Tensor is an iterable but we never want to unpack it here
if not isinstance(values, container_abcs.Iterable) or isinstance(
values, torch.Tensor
):
raise TypeError(
"ParameterList.extend should be called with an "
"iterable, but got " + type(values).__name__
)
for value in values:
self.append(value)
return self
def extra_repr(self) -> str:
"""
Return the extra representation of the module.
"""
child_lines = []
for k, p in enumerate(self):
if isinstance(p, torch.Tensor):
size_str = "x".join(str(size) for size in p.size())
if p.device.type in ["cuda", torch._C._get_privateuse1_backend_name()]:
device_str = f" ({p.device})"
else:
device_str = ""
parastr = "{} containing: [{} of size {}{}]".format(
"Parameter" if isinstance(p, Parameter) else "Tensor",
p.dtype,
size_str,
device_str,
)
# pyrefly: ignore [bad-argument-type]
child_lines.append(" (" + str(k) + "): " + parastr)
else:
child_lines.append(
# pyrefly: ignore [bad-argument-type]
" (" + str(k) + "): Object of type: " + type(p).__name__
)
tmpstr = "\n".join(child_lines)
return tmpstr
def __call__(self, *args, **kwargs):
raise RuntimeError("ParameterList should not be called.")
|
ParameterList
|
python
|
sqlalchemy__sqlalchemy
|
test/orm/inheritance/test_poly_loading.py
|
{
"start": 51966,
"end": 55568
}
|
class ____(
testing.AssertsExecutionResults, fixtures.TestBase
):
"""test for #7799"""
@testing.fixture
def mapping_fixture(self, registry, connection):
Base = registry.generate_base()
class BaseClass(Base):
__tablename__ = "baseclass"
id = Column(
Integer,
primary_key=True,
unique=True,
)
class A(BaseClass):
__tablename__ = "a"
id = Column(ForeignKey(BaseClass.id), primary_key=True)
thing1 = Column(String(50))
__mapper_args__ = {"polymorphic_identity": "a"}
class B(BaseClass):
__tablename__ = "b"
id = Column(ForeignKey(BaseClass.id), primary_key=True)
thing2 = Column(String(50))
__mapper_args__ = {"polymorphic_identity": "b"}
registry.metadata.create_all(connection)
with Session(connection) as sess:
sess.add_all(
[
A(thing1="thing1_1"),
A(thing1="thing1_2"),
B(thing2="thing2_2"),
B(thing2="thing2_3"),
A(thing1="thing1_3"),
A(thing1="thing1_4"),
B(thing2="thing2_1"),
B(thing2="thing2_4"),
]
)
sess.commit()
return BaseClass, A, B
def test_wp(self, mapping_fixture, connection):
BaseClass, A, B = mapping_fixture
stmt = union(
select(A.id, literal("a").label("type")),
select(B.id, literal("b").label("type")),
).subquery()
wp = with_polymorphic(
BaseClass,
[A, B],
selectable=stmt,
polymorphic_on=stmt.c.type,
)
session = Session(connection)
with self.sql_execution_asserter() as asserter:
result = session.scalars(
select(wp)
.options(selectin_polymorphic(wp, [A, B]))
.order_by(wp.id)
)
for obj in result:
if isinstance(obj, A):
obj.thing1
else:
obj.thing2
asserter.assert_(
CompiledSQL(
"SELECT anon_1.id, anon_1.type FROM "
"(SELECT a.id AS id, :param_1 AS type FROM baseclass "
"JOIN a ON baseclass.id = a.id "
"UNION SELECT b.id AS id, :param_2 AS type "
"FROM baseclass JOIN b ON baseclass.id = b.id) AS anon_1 "
"ORDER BY anon_1.id",
[{"param_1": "a", "param_2": "b"}],
),
AllOf(
CompiledSQL(
"SELECT a.id AS a_id, baseclass.id AS baseclass_id, "
"a.thing1 AS a_thing1 FROM baseclass "
"JOIN a ON baseclass.id = a.id "
"WHERE baseclass.id IN (__[POSTCOMPILE_primary_keys]) "
"ORDER BY baseclass.id",
{"primary_keys": [1, 2, 5, 6]},
),
CompiledSQL(
"SELECT b.id AS b_id, baseclass.id AS baseclass_id, "
"b.thing2 AS b_thing2 FROM baseclass "
"JOIN b ON baseclass.id = b.id "
"WHERE baseclass.id IN (__[POSTCOMPILE_primary_keys]) "
"ORDER BY baseclass.id",
{"primary_keys": [3, 4, 7, 8]},
),
),
)
|
NoBaseWPPlusAliasedTest
|
python
|
openai__openai-python
|
src/openai/resources/audio/translations.py
|
{
"start": 14478,
"end": 15505
}
|
class ____:
def __init__(self, translations: AsyncTranslations) -> None:
self._translations = translations
self.create = async_to_streamed_response_wrapper(
translations.create,
)
def _get_response_format_type(
response_format: AudioResponseFormat | Omit,
) -> type[Translation | TranslationVerbose | str]:
if isinstance(response_format, Omit) or response_format is None: # pyright: ignore[reportUnnecessaryComparison]
return Translation
if response_format == "json":
return Translation
elif response_format == "verbose_json":
return TranslationVerbose
elif response_format == "srt" or response_format == "text" or response_format == "vtt":
return str
elif TYPE_CHECKING and response_format != "diarized_json": # type: ignore[unreachable]
assert_never(response_format)
else:
log.warning("Unexpected audio response format: %s", response_format)
return Translation
|
AsyncTranslationsWithStreamingResponse
|
python
|
getsentry__sentry
|
tests/sentry/api/endpoints/test_organization_auth_token_details.py
|
{
"start": 5165,
"end": 10956
}
|
class ____(APITestCase):
endpoint = "sentry-api-0-org-auth-token-details"
method = "PUT"
def test_simple(self) -> None:
token = OrgAuthToken.objects.create(
organization_id=self.organization.id,
name="token 1",
token_hashed="ABCDEF",
token_last_characters="xyz1",
scope_list=["org:ci"],
date_last_used=None,
)
payload = {"name": "new token"}
self.login_as(self.user)
response = self.get_success_response(
self.organization.slug, token.id, status_code=status.HTTP_204_NO_CONTENT, **payload
)
assert response.status_code == status.HTTP_204_NO_CONTENT
tokenNew = OrgAuthToken.objects.get(id=token.id)
assert tokenNew.name == "new token"
assert tokenNew.token_hashed == token.token_hashed
assert tokenNew.get_scopes() == token.get_scopes()
def test_no_name(self) -> None:
token = OrgAuthToken.objects.create(
organization_id=self.organization.id,
name="token 1",
token_hashed="ABCDEF",
token_last_characters="xyz1",
scope_list=["org:ci"],
date_last_used=None,
)
payload: dict[str, str] = {}
self.login_as(self.user)
response = self.get_error_response(
self.organization.slug, token.id, status_code=status.HTTP_400_BAD_REQUEST, **payload
)
assert response.content
assert response.data == {"detail": "The name cannot be blank."}
tokenNew = OrgAuthToken.objects.get(id=token.id)
assert tokenNew.name == "token 1"
def test_name_too_long(self) -> None:
token = OrgAuthToken.objects.create(
organization_id=self.organization.id,
name="token 1",
token_hashed="ABCDEF",
token_last_characters="xyz1",
scope_list=["org:ci"],
date_last_used=None,
)
payload: dict[str, str] = {"name": "a" * 300}
self.login_as(self.user)
response = self.get_error_response(
self.organization.slug, token.id, status_code=status.HTTP_400_BAD_REQUEST, **payload
)
assert response.content
assert response.data == {"detail": "The name cannot be longer than 255 characters."}
tokenNew = OrgAuthToken.objects.get(id=token.id)
assert tokenNew.name == "token 1"
def test_blank_name(self) -> None:
token = OrgAuthToken.objects.create(
organization_id=self.organization.id,
name="token 1",
token_hashed="ABCDEF",
token_last_characters="xyz1",
scope_list=["org:ci"],
date_last_used=None,
)
payload = {"name": ""}
self.login_as(self.user)
response = self.get_error_response(
self.organization.slug, token.id, status_code=status.HTTP_400_BAD_REQUEST, **payload
)
assert response.content
assert response.data == {"detail": "The name cannot be blank."}
tokenNew = OrgAuthToken.objects.get(id=token.id)
assert tokenNew.name == "token 1"
def test_no_auth(self) -> None:
token = OrgAuthToken.objects.create(
organization_id=self.organization.id,
name="token 1",
token_hashed="ABCDEF",
token_last_characters="xyz1",
scope_list=["org:ci"],
date_last_used=None,
)
payload: dict[str, str] = {}
response = self.get_error_response(self.organization.slug, token.id, **payload)
assert response.status_code == status.HTTP_403_FORBIDDEN
def test_other_org_token(self) -> None:
other_org = self.create_organization()
payload = {"name": "test token"}
token = OrgAuthToken.objects.create(
organization_id=other_org.id,
name="token 1",
token_hashed="ABCDEF",
token_last_characters="xyz1",
scope_list=["org:ci"],
date_last_used=None,
)
self.login_as(self.user)
response = self.get_error_response(other_org.slug, token.id, **payload)
assert response.status_code == status.HTTP_403_FORBIDDEN
def test_other_org(self) -> None:
other_org = self.create_organization()
payload = {"name": "test token"}
token = OrgAuthToken.objects.create(
organization_id=other_org.id,
name="token 1",
token_hashed="ABCDEF",
token_last_characters="xyz1",
scope_list=["org:ci"],
date_last_used=None,
)
self.login_as(self.user)
response = self.get_error_response(self.organization.slug, token.id, **payload)
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_not_exists(self) -> None:
payload = {"name": "test token"}
self.login_as(self.user)
response = self.get_error_response(self.organization.slug, 999999, **payload)
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_update_deleted(self) -> None:
token = OrgAuthToken.objects.create(
organization_id=self.organization.id,
name="token 1",
token_hashed="ABCDEF",
token_last_characters="xyz1",
scope_list=["org:ci"],
date_last_used=None,
date_deactivated=datetime(2023, 1, 1, tzinfo=timezone.utc),
)
payload = {"name": "test token"}
self.login_as(self.user)
response = self.get_error_response(self.organization.slug, token.id, **payload)
assert response.status_code == status.HTTP_404_NOT_FOUND
@control_silo_test
|
OrganizationAuthTokenEditTest
|
python
|
SmileyChris__easy-thumbnails
|
easy_thumbnails/optimize/conf.py
|
{
"start": 44,
"end": 816
}
|
class ____(Settings):
THUMBNAIL_OPTIMIZE_COMMAND = {'png': None, 'jpeg': None, 'gif': None}
"""
Postprocess thumbnails of type PNG, GIF or JPEG after transformation but
before storage.
Apply an external post processing program to images after they have been
manipulated by PIL or Pillow. This is strongly recommended by tools such as
Google's PageSpeed on order to reduce the payload of the thumbnailed image
files.
Example::
THUMBNAIL_OPTIMIZE_COMMAND = {
'png': '/usr/bin/optipng {filename}',
'gif': '/usr/bin/optipng {filename}',
'jpeg': '/usr/bin/jpegoptim {filename}'
}
Note that ``optipng`` can also optimize images of type GIF.
"""
settings = OptimizeSettings()
|
OptimizeSettings
|
python
|
ansible__ansible
|
lib/ansible/modules/user.py
|
{
"start": 107565,
"end": 111854
}
|
class ____(User):
"""
This is a HP-UX User manipulation class.
This overrides the following methods from the generic class:-
- create_user()
- remove_user()
- modify_user()
"""
platform = 'HP-UX'
distribution = None
SHADOWFILE = '/etc/shadow'
def create_user(self):
cmd = ['/usr/sam/lbin/useradd.sam']
if self.uid is not None:
cmd.append('-u')
cmd.append(self.uid)
if self.non_unique:
cmd.append('-o')
if self.group is not None:
if not self.group_exists(self.group):
self.module.fail_json(msg="Group %s does not exist" % self.group)
cmd.append('-g')
cmd.append(self.group)
if self.groups is not None and len(self.groups):
groups = self.get_groups_set()
cmd.append('-G')
cmd.append(','.join(groups))
if self.comment is not None:
cmd.append('-c')
cmd.append(self.comment)
if self.home is not None:
cmd.append('-d')
cmd.append(self.home)
if self.shell is not None:
cmd.append('-s')
cmd.append(self.shell)
if self.password is not None:
cmd.append('-p')
cmd.append(self.password)
if self.create_home:
cmd.append('-m')
else:
cmd.append('-M')
if self.system:
cmd.append('-r')
cmd.append(self.name)
return self.execute_command(cmd)
def remove_user(self):
cmd = ['/usr/sam/lbin/userdel.sam']
if self.force:
cmd.append('-F')
if self.remove:
cmd.append('-r')
cmd.append(self.name)
return self.execute_command(cmd)
def modify_user(self):
cmd = ['/usr/sam/lbin/usermod.sam']
info = self.user_info()
if self.uid is not None and info[2] != int(self.uid):
cmd.append('-u')
cmd.append(self.uid)
if self.non_unique:
cmd.append('-o')
if self.group is not None:
if not self.group_exists(self.group):
self.module.fail_json(msg="Group %s does not exist" % self.group)
ginfo = self.group_info(self.group)
if info[3] != ginfo[2]:
cmd.append('-g')
cmd.append(self.group)
if self.groups is not None:
current_groups = self.user_group_membership()
groups_need_mod = False
groups = []
if self.groups == '':
if current_groups and not self.append:
groups_need_mod = True
else:
groups = self.get_groups_set(remove_existing=False, names_only=True)
group_diff = set(current_groups).symmetric_difference(groups)
if group_diff:
if self.append:
for g in groups:
if g in group_diff:
groups_need_mod = True
break
else:
groups_need_mod = True
if groups_need_mod:
cmd.append('-G')
new_groups = groups
if self.append:
new_groups = groups | set(current_groups)
cmd.append(','.join(new_groups))
if self.comment is not None and info[4] != self.comment:
cmd.append('-c')
cmd.append(self.comment)
if self.home is not None and info[5] != self.home:
cmd.append('-d')
cmd.append(self.home)
if self.move_home:
cmd.append('-m')
if self.shell is not None and info[6] != self.shell:
cmd.append('-s')
cmd.append(self.shell)
if self.update_password == 'always' and self.password is not None and info[1] != self.password:
cmd.append('-F')
cmd.append('-p')
cmd.append(self.password)
# skip if no changes to be made
if len(cmd) == 1:
return (None, '', '')
cmd.append(self.name)
return self.execute_command(cmd)
|
HPUX
|
python
|
pytest-dev__pytest
|
testing/test_pastebin.py
|
{
"start": 219,
"end": 2702
}
|
class ____:
@pytest.fixture
def pastebinlist(self, monkeypatch, request) -> list[str | bytes]:
pastebinlist: list[str | bytes] = []
plugin = request.config.pluginmanager.getplugin("pastebin")
monkeypatch.setattr(plugin, "create_new_paste", pastebinlist.append)
return pastebinlist
def test_failed(self, pytester: Pytester, pastebinlist) -> None:
testpath = pytester.makepyfile(
"""
import pytest
def test_pass() -> None:
pass
def test_fail():
assert 0
def test_skip():
pytest.skip("")
"""
)
reprec = pytester.inline_run(testpath, "--pastebin=failed")
assert len(pastebinlist) == 1
s = pastebinlist[0]
assert s.find("def test_fail") != -1
assert reprec.countoutcomes() == [1, 1, 1]
def test_all(self, pytester: Pytester, pastebinlist) -> None:
from _pytest.pytester import LineMatcher
testpath = pytester.makepyfile(
"""
import pytest
def test_pass():
pass
def test_fail():
assert 0
def test_skip():
pytest.skip("")
"""
)
reprec = pytester.inline_run(testpath, "--pastebin=all", "-v")
assert reprec.countoutcomes() == [1, 1, 1]
assert len(pastebinlist) == 1
contents = pastebinlist[0].decode("utf-8")
matcher = LineMatcher(contents.splitlines())
matcher.fnmatch_lines(
[
"*test_pass PASSED*",
"*test_fail FAILED*",
"*test_skip SKIPPED*",
"*== 1 failed, 1 passed, 1 skipped in *",
]
)
def test_non_ascii_paste_text(self, pytester: Pytester, pastebinlist) -> None:
"""Make sure that text which contains non-ascii characters is pasted
correctly. See #1219.
"""
pytester.makepyfile(
test_unicode="""\
def test():
assert '☺' == 1
"""
)
result = pytester.runpytest("--pastebin=all")
expected_msg = "*assert '☺' == 1*"
result.stdout.fnmatch_lines(
[
expected_msg,
"*== 1 failed in *",
"*Sending information to Paste Service*",
]
)
assert len(pastebinlist) == 1
|
TestPasteCapture
|
python
|
mlflow__mlflow
|
mlflow/entities/run_info.py
|
{
"start": 909,
"end": 5936
}
|
class ____(_MlflowObject):
"""
Metadata about a run.
"""
def __init__(
self,
run_id,
experiment_id,
user_id,
status,
start_time,
end_time,
lifecycle_stage,
artifact_uri=None,
run_name=None,
):
if experiment_id is None:
raise Exception("experiment_id cannot be None")
if user_id is None:
raise Exception("user_id cannot be None")
if status is None:
raise Exception("status cannot be None")
if start_time is None:
raise Exception("start_time cannot be None")
self._run_id = run_id
self._experiment_id = experiment_id
self._user_id = user_id
self._status = status
self._start_time = start_time
self._end_time = end_time
self._lifecycle_stage = lifecycle_stage
self._artifact_uri = artifact_uri
self._run_name = run_name
def __eq__(self, other):
if type(other) is type(self):
# TODO deep equality here?
return self.__dict__ == other.__dict__
return False
def _copy_with_overrides(self, status=None, end_time=None, lifecycle_stage=None, run_name=None):
"""A copy of the RunInfo with certain attributes modified."""
proto = self.to_proto()
if status:
proto.status = status
if end_time:
proto.end_time = end_time
if lifecycle_stage:
proto.lifecycle_stage = lifecycle_stage
if run_name:
proto.run_name = run_name
return RunInfo.from_proto(proto)
@searchable_attribute
def run_id(self):
"""String containing run id."""
return self._run_id
@property
def experiment_id(self):
"""String ID of the experiment for the current run."""
return self._experiment_id
@searchable_attribute
def run_name(self):
"""String containing run name."""
return self._run_name
def _set_run_name(self, new_name):
self._run_name = new_name
@searchable_attribute
def user_id(self):
"""String ID of the user who initiated this run."""
return self._user_id
@searchable_attribute
def status(self):
"""
One of the values in :py:class:`mlflow.entities.RunStatus`
describing the status of the run.
"""
return self._status
@searchable_attribute
def start_time(self):
"""Start time of the run, in number of milliseconds since the UNIX epoch."""
return self._start_time
@searchable_attribute
def end_time(self):
"""End time of the run, in number of milliseconds since the UNIX epoch."""
return self._end_time
@searchable_attribute
def artifact_uri(self):
"""String root artifact URI of the run."""
return self._artifact_uri
@property
def lifecycle_stage(self):
"""
One of the values in :py:class:`mlflow.entities.lifecycle_stage.LifecycleStage`
describing the lifecycle stage of the run.
"""
return self._lifecycle_stage
def to_proto(self):
proto = ProtoRunInfo()
proto.run_uuid = self.run_id
proto.run_id = self.run_id
if self.run_name is not None:
proto.run_name = self.run_name
proto.experiment_id = self.experiment_id
proto.user_id = self.user_id
proto.status = RunStatus.from_string(self.status)
proto.start_time = self.start_time
if self.end_time:
proto.end_time = self.end_time
if self.artifact_uri:
proto.artifact_uri = self.artifact_uri
proto.lifecycle_stage = self.lifecycle_stage
return proto
@classmethod
def from_proto(cls, proto):
end_time = proto.end_time
# The proto2 default scalar value of zero indicates that the run's end time is absent.
# An absent end time is represented with a NoneType in the `RunInfo` class
if end_time == 0:
end_time = None
return cls(
run_id=proto.run_id,
run_name=proto.run_name,
experiment_id=proto.experiment_id,
user_id=proto.user_id,
status=RunStatus.to_string(proto.status),
start_time=proto.start_time,
end_time=end_time,
lifecycle_stage=proto.lifecycle_stage,
artifact_uri=proto.artifact_uri,
)
@classmethod
def get_searchable_attributes(cls):
return sorted(
[p for p in cls.__dict__ if isinstance(getattr(cls, p), searchable_attribute)]
)
@classmethod
def get_orderable_attributes(cls):
# Note that all searchable attributes are also orderable.
return sorted(
[
p
for p in cls.__dict__
if isinstance(getattr(cls, p), (searchable_attribute, orderable_attribute))
]
)
|
RunInfo
|
python
|
great-expectations__great_expectations
|
great_expectations/datasource/fluent/spark_filesystem_datasource.py
|
{
"start": 715,
"end": 3460
}
|
class ____(_SparkFilePathDatasource):
"""
SparkFilesystemDatasource is a subclass of SparkDatasource which connects to
the filesystem.
"""
# class attributes
data_connector_type: ClassVar[Type[FilesystemDataConnector]] = FilesystemDataConnector
# these fields should not be passed to the execution engine
_EXTRA_EXCLUDED_EXEC_ENG_ARGS: ClassVar[set] = {
"base_directory",
"data_context_root_directory",
}
# instance attributes
type: Literal["spark_filesystem"] = "spark_filesystem"
base_directory: pathlib.Path
data_context_root_directory: Optional[pathlib.Path] = None
@override
def test_connection(self, test_assets: bool = True) -> None:
"""Test the connection for the SparkDatasource.
Args:
test_assets: If assets have been passed to the SparkDatasource, whether to test them as well.
Raises:
TestConnectionError: If the connection test fails.
""" # noqa: E501 # FIXME CoP
# tests Filesystem connection
if not self.base_directory.exists():
raise TestConnectionError( # noqa: TRY003 # FIXME CoP
f"base_directory path: {self.base_directory.resolve()} does not exist."
)
# tests Spark connection, raising TestConnectionError
super().test_connection()
if self.assets and test_assets:
for asset in self.assets:
asset.test_connection()
@override
def _build_data_connector(
self,
data_asset: SPARK_PATH_ASSET_UNION,
glob_directive: str = "**/*",
**kwargs,
) -> None:
"""Builds and attaches the `FilesystemDataConnector` to the asset."""
if kwargs:
raise TypeError( # noqa: TRY003 # FIXME CoP
f"_build_data_connector() got unexpected keyword arguments {list(kwargs.keys())}"
)
data_asset._data_connector = self.data_connector_type.build_data_connector(
datasource_name=self.name,
data_asset_name=data_asset.name,
base_directory=self.base_directory,
glob_directive=glob_directive,
data_context_root_directory=self.data_context_root_directory,
whole_directory_path_override=data_asset.get_whole_directory_path_override(),
)
# build a more specific `_test_connection_error_message`
data_asset._test_connection_error_message = (
self.data_connector_type.build_test_connection_error_message(
data_asset_name=data_asset.name,
glob_directive=glob_directive,
base_directory=self.base_directory,
)
)
|
SparkFilesystemDatasource
|
python
|
doocs__leetcode
|
solution/2700-2799/2785.Sort Vowels in a String/Solution.py
|
{
"start": 0,
"end": 314
}
|
class ____:
def sortVowels(self, s: str) -> str:
vs = [c for c in s if c.lower() in "aeiou"]
vs.sort()
cs = list(s)
j = 0
for i, c in enumerate(cs):
if c.lower() in "aeiou":
cs[i] = vs[j]
j += 1
return "".join(cs)
|
Solution
|
python
|
ethereum__web3.py
|
web3/contract/contract.py
|
{
"start": 12008,
"end": 12329
}
|
class ____(BaseContractFunctions[ContractFunction]):
def __init__(
self,
abi: ABI,
w3: "Web3",
address: ChecksumAddress | None = None,
decode_tuples: bool | None = False,
) -> None:
super().__init__(abi, w3, ContractFunction, address, decode_tuples)
|
ContractFunctions
|
python
|
lepture__authlib
|
authlib/integrations/httpx_client/oauth1_client.py
|
{
"start": 464,
"end": 979
}
|
class ____(Auth, ClientAuth):
"""Signs the httpx request using OAuth 1 (RFC5849)."""
requires_request_body = True
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
url, headers, body = self.prepare(
request.method, str(request.url), request.headers, request.content
)
headers["Content-Length"] = str(len(body))
yield build_request(
url=url, headers=headers, body=body, initial_request=request
)
|
OAuth1Auth
|
python
|
langchain-ai__langchain
|
libs/langchain_v1/tests/unit_tests/agents/test_responses.py
|
{
"start": 601,
"end": 1689
}
|
class ____:
"""Test UsingToolStrategy dataclass."""
def test_basic_creation(self) -> None:
"""Test basic UsingToolStrategy creation."""
strategy = ToolStrategy(schema=_TestModel)
assert strategy.schema == _TestModel
assert strategy.tool_message_content is None
assert len(strategy.schema_specs) == 1
def test_multiple_schemas(self) -> None:
"""Test UsingToolStrategy with multiple schemas."""
strategy = ToolStrategy(schema=Union[_TestModel, CustomModel])
assert len(strategy.schema_specs) == 2
assert strategy.schema_specs[0].schema == _TestModel
assert strategy.schema_specs[1].schema == CustomModel
def test_schema_with_tool_message_content(self) -> None:
"""Test UsingToolStrategy with tool message content."""
strategy = ToolStrategy(schema=_TestModel, tool_message_content="custom message")
assert strategy.schema == _TestModel
assert strategy.tool_message_content == "custom message"
assert len(strategy.schema_specs) == 1
|
TestUsingToolStrategy
|
python
|
charliermarsh__ruff
|
crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_index.py
|
{
"start": 204,
"end": 290
}
|
class ____:
def __index__(self):
return 3.05 # [invalid-index-return]
|
Float
|
python
|
django-guardian__django-guardian
|
guardian/testapp/tests/test_admin.py
|
{
"start": 1086,
"end": 1225
}
|
class ____(GuardedModelAdmin):
"""Test admin for User model with inline forms."""
inlines = [UserProfileInline]
|
UserAdminWithProfile
|
python
|
geekcomputers__Python
|
venv/Lib/site-packages/pip/_vendor/distlib/metadata.py
|
{
"start": 22256,
"end": 39693
}
|
class ____(object):
"""
The metadata of a release. This implementation uses 2.1
metadata where possible. If not possible, it wraps a LegacyMetadata
instance which handles the key-value metadata format.
"""
METADATA_VERSION_MATCHER = re.compile(r'^\d+(\.\d+)*$')
NAME_MATCHER = re.compile('^[0-9A-Z]([0-9A-Z_.-]*[0-9A-Z])?$', re.I)
FIELDNAME_MATCHER = re.compile('^[A-Z]([0-9A-Z-]*[0-9A-Z])?$', re.I)
VERSION_MATCHER = PEP440_VERSION_RE
SUMMARY_MATCHER = re.compile('.{1,2047}')
METADATA_VERSION = '2.0'
GENERATOR = 'distlib (%s)' % __version__
MANDATORY_KEYS = {
'name': (),
'version': (),
'summary': ('legacy',),
}
INDEX_KEYS = ('name version license summary description author '
'author_email keywords platform home_page classifiers '
'download_url')
DEPENDENCY_KEYS = ('extras run_requires test_requires build_requires '
'dev_requires provides meta_requires obsoleted_by '
'supports_environments')
SYNTAX_VALIDATORS = {
'metadata_version': (METADATA_VERSION_MATCHER, ()),
'name': (NAME_MATCHER, ('legacy',)),
'version': (VERSION_MATCHER, ('legacy',)),
'summary': (SUMMARY_MATCHER, ('legacy',)),
'dynamic': (FIELDNAME_MATCHER, ('legacy',)),
}
__slots__ = ('_legacy', '_data', 'scheme')
def __init__(self, path=None, fileobj=None, mapping=None,
scheme='default'):
if [path, fileobj, mapping].count(None) < 2:
raise TypeError('path, fileobj and mapping are exclusive')
self._legacy = None
self._data = None
self.scheme = scheme
#import pdb; pdb.set_trace()
if mapping is not None:
try:
self._validate_mapping(mapping, scheme)
self._data = mapping
except MetadataUnrecognizedVersionError:
self._legacy = LegacyMetadata(mapping=mapping, scheme=scheme)
self.validate()
else:
data = None
if path:
with open(path, 'rb') as f:
data = f.read()
elif fileobj:
data = fileobj.read()
if data is None:
# Initialised with no args - to be added
self._data = {
'metadata_version': self.METADATA_VERSION,
'generator': self.GENERATOR,
}
else:
if not isinstance(data, text_type):
data = data.decode('utf-8')
try:
self._data = json.loads(data)
self._validate_mapping(self._data, scheme)
except ValueError:
# Note: MetadataUnrecognizedVersionError does not
# inherit from ValueError (it's a DistlibException,
# which should not inherit from ValueError).
# The ValueError comes from the json.load - if that
# succeeds and we get a validation error, we want
# that to propagate
self._legacy = LegacyMetadata(fileobj=StringIO(data),
scheme=scheme)
self.validate()
common_keys = set(('name', 'version', 'license', 'keywords', 'summary'))
none_list = (None, list)
none_dict = (None, dict)
mapped_keys = {
'run_requires': ('Requires-Dist', list),
'build_requires': ('Setup-Requires-Dist', list),
'dev_requires': none_list,
'test_requires': none_list,
'meta_requires': none_list,
'extras': ('Provides-Extra', list),
'modules': none_list,
'namespaces': none_list,
'exports': none_dict,
'commands': none_dict,
'classifiers': ('Classifier', list),
'source_url': ('Download-URL', None),
'metadata_version': ('Metadata-Version', None),
}
del none_list, none_dict
def __getattribute__(self, key):
common = object.__getattribute__(self, 'common_keys')
mapped = object.__getattribute__(self, 'mapped_keys')
if key in mapped:
lk, maker = mapped[key]
if self._legacy:
if lk is None:
result = None if maker is None else maker()
else:
result = self._legacy.get(lk)
else:
value = None if maker is None else maker()
if key not in ('commands', 'exports', 'modules', 'namespaces',
'classifiers'):
result = self._data.get(key, value)
else:
# special cases for PEP 459
sentinel = object()
result = sentinel
d = self._data.get('extensions')
if d:
if key == 'commands':
result = d.get('python.commands', value)
elif key == 'classifiers':
d = d.get('python.details')
if d:
result = d.get(key, value)
else:
d = d.get('python.exports')
if not d:
d = self._data.get('python.exports')
if d:
result = d.get(key, value)
if result is sentinel:
result = value
elif key not in common:
result = object.__getattribute__(self, key)
elif self._legacy:
result = self._legacy.get(key)
else:
result = self._data.get(key)
return result
def _validate_value(self, key, value, scheme=None):
if key in self.SYNTAX_VALIDATORS:
pattern, exclusions = self.SYNTAX_VALIDATORS[key]
if (scheme or self.scheme) not in exclusions:
m = pattern.match(value)
if not m:
raise MetadataInvalidError("'%s' is an invalid value for "
"the '%s' property" % (value,
key))
def __setattr__(self, key, value):
self._validate_value(key, value)
common = object.__getattribute__(self, 'common_keys')
mapped = object.__getattribute__(self, 'mapped_keys')
if key in mapped:
lk, _ = mapped[key]
if self._legacy:
if lk is None:
raise NotImplementedError
self._legacy[lk] = value
elif key not in ('commands', 'exports', 'modules', 'namespaces',
'classifiers'):
self._data[key] = value
else:
# special cases for PEP 459
d = self._data.setdefault('extensions', {})
if key == 'commands':
d['python.commands'] = value
elif key == 'classifiers':
d = d.setdefault('python.details', {})
d[key] = value
else:
d = d.setdefault('python.exports', {})
d[key] = value
elif key not in common:
object.__setattr__(self, key, value)
else:
if key == 'keywords':
if isinstance(value, string_types):
value = value.strip()
if value:
value = value.split()
else:
value = []
if self._legacy:
self._legacy[key] = value
else:
self._data[key] = value
@property
def name_and_version(self):
return _get_name_and_version(self.name, self.version, True)
@property
def provides(self):
if self._legacy:
result = self._legacy['Provides-Dist']
else:
result = self._data.setdefault('provides', [])
s = '%s (%s)' % (self.name, self.version)
if s not in result:
result.append(s)
return result
@provides.setter
def provides(self, value):
if self._legacy:
self._legacy['Provides-Dist'] = value
else:
self._data['provides'] = value
def get_requirements(self, reqts, extras=None, env=None):
"""
Base method to get dependencies, given a set of extras
to satisfy and an optional environment context.
:param reqts: A list of sometimes-wanted dependencies,
perhaps dependent on extras and environment.
:param extras: A list of optional components being requested.
:param env: An optional environment for marker evaluation.
"""
if self._legacy:
result = reqts
else:
result = []
extras = get_extras(extras or [], self.extras)
for d in reqts:
if 'extra' not in d and 'environment' not in d:
# unconditional
include = True
else:
if 'extra' not in d:
# Not extra-dependent - only environment-dependent
include = True
else:
include = d.get('extra') in extras
if include:
# Not excluded because of extras, check environment
marker = d.get('environment')
if marker:
include = interpret(marker, env)
if include:
result.extend(d['requires'])
for key in ('build', 'dev', 'test'):
e = ':%s:' % key
if e in extras:
extras.remove(e)
# A recursive call, but it should terminate since 'test'
# has been removed from the extras
reqts = self._data.get('%s_requires' % key, [])
result.extend(self.get_requirements(reqts, extras=extras,
env=env))
return result
@property
def dictionary(self):
if self._legacy:
return self._from_legacy()
return self._data
@property
def dependencies(self):
if self._legacy:
raise NotImplementedError
else:
return extract_by_key(self._data, self.DEPENDENCY_KEYS)
@dependencies.setter
def dependencies(self, value):
if self._legacy:
raise NotImplementedError
else:
self._data.update(value)
def _validate_mapping(self, mapping, scheme):
if mapping.get('metadata_version') != self.METADATA_VERSION:
raise MetadataUnrecognizedVersionError()
missing = []
for key, exclusions in self.MANDATORY_KEYS.items():
if key not in mapping:
if scheme not in exclusions:
missing.append(key)
if missing:
msg = 'Missing metadata items: %s' % ', '.join(missing)
raise MetadataMissingError(msg)
for k, v in mapping.items():
self._validate_value(k, v, scheme)
def validate(self):
if self._legacy:
missing, warnings = self._legacy.check(True)
if missing or warnings:
logger.warning('Metadata: missing: %s, warnings: %s',
missing, warnings)
else:
self._validate_mapping(self._data, self.scheme)
def todict(self):
if self._legacy:
return self._legacy.todict(True)
else:
result = extract_by_key(self._data, self.INDEX_KEYS)
return result
def _from_legacy(self):
assert self._legacy and not self._data
result = {
'metadata_version': self.METADATA_VERSION,
'generator': self.GENERATOR,
}
lmd = self._legacy.todict(True) # skip missing ones
for k in ('name', 'version', 'license', 'summary', 'description',
'classifier'):
if k in lmd:
if k == 'classifier':
nk = 'classifiers'
else:
nk = k
result[nk] = lmd[k]
kw = lmd.get('Keywords', [])
if kw == ['']:
kw = []
result['keywords'] = kw
keys = (('requires_dist', 'run_requires'),
('setup_requires_dist', 'build_requires'))
for ok, nk in keys:
if ok in lmd and lmd[ok]:
result[nk] = [{'requires': lmd[ok]}]
result['provides'] = self.provides
author = {}
maintainer = {}
return result
LEGACY_MAPPING = {
'name': 'Name',
'version': 'Version',
('extensions', 'python.details', 'license'): 'License',
'summary': 'Summary',
'description': 'Description',
('extensions', 'python.project', 'project_urls', 'Home'): 'Home-page',
('extensions', 'python.project', 'contacts', 0, 'name'): 'Author',
('extensions', 'python.project', 'contacts', 0, 'email'): 'Author-email',
'source_url': 'Download-URL',
('extensions', 'python.details', 'classifiers'): 'Classifier',
}
def _to_legacy(self):
def process_entries(entries):
reqts = set()
for e in entries:
extra = e.get('extra')
env = e.get('environment')
rlist = e['requires']
for r in rlist:
if not env and not extra:
reqts.add(r)
else:
marker = ''
if extra:
marker = 'extra == "%s"' % extra
if env:
if marker:
marker = '(%s) and %s' % (env, marker)
else:
marker = env
reqts.add(';'.join((r, marker)))
return reqts
assert self._data and not self._legacy
result = LegacyMetadata()
nmd = self._data
# import pdb; pdb.set_trace()
for nk, ok in self.LEGACY_MAPPING.items():
if not isinstance(nk, tuple):
if nk in nmd:
result[ok] = nmd[nk]
else:
d = nmd
found = True
for k in nk:
try:
d = d[k]
except (KeyError, IndexError):
found = False
break
if found:
result[ok] = d
r1 = process_entries(self.run_requires + self.meta_requires)
r2 = process_entries(self.build_requires + self.dev_requires)
if self.extras:
result['Provides-Extra'] = sorted(self.extras)
result['Requires-Dist'] = sorted(r1)
result['Setup-Requires-Dist'] = sorted(r2)
# TODO: any other fields wanted
return result
def write(self, path=None, fileobj=None, legacy=False, skip_unknown=True):
if [path, fileobj].count(None) != 1:
raise ValueError('Exactly one of path and fileobj is needed')
self.validate()
if legacy:
if self._legacy:
legacy_md = self._legacy
else:
legacy_md = self._to_legacy()
if path:
legacy_md.write(path, skip_unknown=skip_unknown)
else:
legacy_md.write_file(fileobj, skip_unknown=skip_unknown)
else:
if self._legacy:
d = self._from_legacy()
else:
d = self._data
if fileobj:
json.dump(d, fileobj, ensure_ascii=True, indent=2,
sort_keys=True)
else:
with codecs.open(path, 'w', 'utf-8') as f:
json.dump(d, f, ensure_ascii=True, indent=2,
sort_keys=True)
def add_requirements(self, requirements):
if self._legacy:
self._legacy.add_requirements(requirements)
else:
run_requires = self._data.setdefault('run_requires', [])
always = None
for entry in run_requires:
if 'environment' not in entry and 'extra' not in entry:
always = entry
break
if always is None:
always = { 'requires': requirements }
run_requires.insert(0, always)
else:
rset = set(always['requires']) | set(requirements)
always['requires'] = sorted(rset)
def __repr__(self):
name = self.name or '(no name)'
version = self.version or 'no version'
return '<%s %s %s (%s)>' % (self.__class__.__name__,
self.metadata_version, name, version)
|
Metadata
|
python
|
pypa__pipenv
|
pipenv/patched/pip/_internal/index/collector.py
|
{
"start": 6496,
"end": 8192
}
|
class ____(Protocol):
def __call__(self, page: "IndexContent") -> Iterable[Link]: ...
def with_cached_index_content(fn: ParseLinks) -> ParseLinks:
"""
Given a function that parses an Iterable[Link] from an IndexContent, cache the
function's result (keyed by CacheablePageContent), unless the IndexContent
`page` has `page.cache_link_parsing == False`.
"""
@functools.lru_cache(maxsize=None)
def wrapper(cacheable_page: CacheablePageContent) -> List[Link]:
return list(fn(cacheable_page.page))
@functools.wraps(fn)
def wrapper_wrapper(page: "IndexContent") -> List[Link]:
if page.cache_link_parsing:
return wrapper(CacheablePageContent(page))
return list(fn(page))
return wrapper_wrapper
@with_cached_index_content
def parse_links(page: "IndexContent") -> Iterable[Link]:
"""
Parse a Simple API's Index Content, and yield its anchor elements as Link objects.
"""
content_type_l = page.content_type.lower()
if content_type_l.startswith("application/vnd.pypi.simple.v1+json"):
data = json.loads(page.content)
for file in data.get("files", []):
link = Link.from_json(file, page.url)
if link is None:
continue
yield link
return
parser = HTMLLinkParser(page.url)
encoding = page.encoding or "utf-8"
parser.feed(page.content.decode(encoding))
url = page.url
base_url = parser.base_url or url
for anchor in parser.anchors:
link = Link.from_element(anchor, page_url=url, base_url=base_url)
if link is None:
continue
yield link
@dataclass(frozen=True)
|
ParseLinks
|
python
|
PyCQA__pylint
|
tests/functional/g/generic_alias/generic_alias_related.py
|
{
"start": 1175,
"end": 1233
}
|
class ____(ClsAbstract): # [abstract-method]
pass
|
Derived
|
python
|
sqlalchemy__sqlalchemy
|
test/perf/compiled_extensions/row.py
|
{
"start": 1687,
"end": 8285
}
|
class ____(Case):
@staticmethod
def python():
from sqlalchemy.engine import _row_cy
py_res = load_uncompiled_module(_row_cy)
assert not py_res._is_compiled()
return py_res.BaseRow
@staticmethod
def cython():
from sqlalchemy.engine import _row_cy
assert _row_cy._is_compiled()
return _row_cy.BaseRow
IMPLEMENTATIONS = {
"python": python.__func__,
"cython": cython.__func__,
}
def init_objects(self):
from sqlalchemy.engine.result import SimpleResultMetaData
from string import ascii_letters
self.parent = SimpleResultMetaData(("a", "b", "c"))
self.row_args = (
self.parent,
self.parent._processors,
self.parent._key_to_index,
(1, 2, 3),
)
self.parent_long = SimpleResultMetaData(tuple(ascii_letters))
self.row_long_args = (
self.parent_long,
self.parent_long._processors,
self.parent_long._key_to_index,
tuple(range(len(ascii_letters))),
)
self.row = self.impl(*self.row_args)
self.row_long = self.impl(*self.row_long_args)
assert isinstance(self.row, self.impl), type(self.row)
class Row(self.impl):
pass
class RowMap(self.impl):
__getitem__ = self.impl._get_by_key_impl_mapping
self.Row = Row
self.row_map = RowMap(*self.row_args)
self.row_long_map = RowMap(*self.row_long_args)
self.row_state = self.row.__getstate__()
self.row_long_state = self.row_long.__getstate__()
assert len(ascii_letters) == 52
_proc = [None, int, float, None, str] * 10
_proc += [int, float]
self.parent_proc = SimpleResultMetaData(
tuple(ascii_letters),
_processors=_proc,
)
self.row_proc_args = (
self.parent_proc,
self.parent_proc._processors,
self.parent_proc._key_to_index,
tuple(range(len(ascii_letters))),
)
self.parent_proc_none = SimpleResultMetaData(
tuple(ascii_letters), _processors=[None] * 52
)
self.row_proc_none_args = (
self.parent_proc_none,
# NOTE: usually the code calls _effective_processors that returns
# None for this case of all None.
self.parent_proc_none._processors,
self.parent_proc_none._key_to_index,
tuple(range(len(ascii_letters))),
)
@classmethod
def update_results(cls, results):
cls._divide_results(results, "c", "python", "c / py")
cls._divide_results(results, "cython", "python", "cy / py")
cls._divide_results(results, "cython", "c", "cy / c")
@test_case
def base_row_new(self):
self.impl(*self.row_args)
self.impl(*self.row_long_args)
@test_case
def row_new(self):
self.Row(*self.row_args)
self.Row(*self.row_long_args)
@test_case
def base_row_new_proc(self):
self.impl(*self.row_proc_args)
@test_case
def row_new_proc(self):
self.Row(*self.row_proc_args)
@test_case
def brow_new_proc_none(self):
self.impl(*self.row_proc_none_args)
@test_case
def row_new_proc_none(self):
self.Row(*self.row_proc_none_args)
@test_case
def row_dumps(self):
self.row.__getstate__()
self.row_long.__getstate__()
@test_case
def row_loads(self):
self.impl.__new__(self.impl).__setstate__(self.row_state)
self.impl.__new__(self.impl).__setstate__(self.row_long_state)
@test_case
def row_values_impl(self):
self.row._values_impl()
self.row_long._values_impl()
@test_case
def row_iter(self):
list(self.row)
list(self.row_long)
@test_case
def row_len(self):
len(self.row)
len(self.row_long)
@test_case
def row_hash(self):
hash(self.row)
hash(self.row_long)
@test_case
def getitem(self):
self.row[0]
self.row[1]
self.row[-1]
self.row_long[0]
self.row_long[1]
self.row_long[-1]
@test_case
def getitem_slice(self):
self.row[0:1]
self.row[1:-1]
self.row_long[0:1]
self.row_long[1:-1]
@test_case
def get_by_key(self):
self.row_map["a"]
self.row_map["b"]
self.row_long_map["s"]
self.row_long_map["a"]
@test_case
def get_by_key2(self):
# NOTE: this is not representative of real usage
self.row._get_by_key_impl_mapping("a")
self.row._get_by_key_impl_mapping("b")
self.row_long._get_by_key_impl_mapping("s")
self.row_long._get_by_key_impl_mapping("a")
@test_case
def getattr(self):
self.row.a
self.row.b
self.row_long.x
self.row_long.y
@test_case(number=15_000)
def get_by_key_recreate(self):
self.init_objects()
row = self.row_map
for _ in range(25):
row["a"]
l_row = self.row_long_map
for _ in range(25):
l_row["f"]
l_row["o"]
l_row["r"]
l_row["t"]
l_row["y"]
l_row["t"]
l_row["w"]
l_row["o"]
@test_case(number=15_000)
def get_by_key_recreate2(self):
# NOTE: this is not representative of real usage
self.init_objects()
row = self.row
for _ in range(25):
row._get_by_key_impl_mapping("a")
l_row = self.row_long
for _ in range(25):
l_row._get_by_key_impl_mapping("f")
l_row._get_by_key_impl_mapping("o")
l_row._get_by_key_impl_mapping("r")
l_row._get_by_key_impl_mapping("t")
l_row._get_by_key_impl_mapping("y")
l_row._get_by_key_impl_mapping("t")
l_row._get_by_key_impl_mapping("w")
l_row._get_by_key_impl_mapping("o")
@test_case(number=10_000)
def getattr_recreate(self):
self.init_objects()
row = self.row
for _ in range(25):
row.a
l_row = self.row_long
for _ in range(25):
l_row.f
l_row.o
l_row.r
l_row.t
l_row.y
l_row.t
l_row.w
l_row.o
@test_case
def contains(self):
1 in self.row
-1 in self.row
1 in self.row_long
-1 in self.row_long
|
BaseRow
|
python
|
Netflix__metaflow
|
metaflow/plugins/kubernetes/kubernetes_jobsets.py
|
{
"start": 16425,
"end": 32398
}
|
class ____(object):
def __init__(self, kubernetes_sdk, name, **kwargs):
self._kubernetes_sdk = kubernetes_sdk
self._kwargs = kwargs
self.name = name
def replicas(self, replicas):
self._kwargs["replicas"] = replicas
return self
def step_name(self, step_name):
self._kwargs["step_name"] = step_name
return self
def namespace(self, namespace):
self._kwargs["namespace"] = namespace
return self
def command(self, command):
self._kwargs["command"] = command
return self
def image(self, image):
self._kwargs["image"] = image
return self
def cpu(self, cpu):
self._kwargs["cpu"] = cpu
return self
def memory(self, mem):
self._kwargs["memory"] = mem
return self
def environment_variable(self, name, value):
# Never set to None
if value is None:
return self
self._kwargs["environment_variables"] = dict(
self._kwargs.get("environment_variables", {}), **{name: value}
)
return self
def secret(self, name):
if name is None:
return self
if len(self._kwargs.get("secrets", [])) == 0:
self._kwargs["secrets"] = []
self._kwargs["secrets"] = list(set(self._kwargs["secrets"] + [name]))
def environment_variable_from_selector(self, name, label_value):
# Never set to None
if label_value is None:
return self
self._kwargs["environment_variables_from_selectors"] = dict(
self._kwargs.get("environment_variables_from_selectors", {}),
**{name: label_value}
)
return self
def label(self, name, value):
self._kwargs["labels"] = dict(self._kwargs.get("labels", {}), **{name: value})
return self
def annotation(self, name, value):
self._kwargs["annotations"] = dict(
self._kwargs.get("annotations", {}), **{name: value}
)
return self
def dump(self):
client = self._kubernetes_sdk
use_tmpfs = self._kwargs["use_tmpfs"]
tmpfs_size = self._kwargs["tmpfs_size"]
tmpfs_enabled = use_tmpfs or (tmpfs_size and not use_tmpfs)
shared_memory = (
int(self._kwargs["shared_memory"])
if self._kwargs["shared_memory"]
else None
)
qos_requests, qos_limits = qos_requests_and_limits(
self._kwargs["qos"],
self._kwargs["cpu"],
self._kwargs["memory"],
self._kwargs["disk"],
)
security_context = self._kwargs.get("security_context", {})
_security_context = {}
if security_context is not None and len(security_context) > 0:
_security_context = {
"security_context": client.V1SecurityContext(**security_context)
}
return dict(
name=self.name,
template=client.api_client.ApiClient().sanitize_for_serialization(
client.V1JobTemplateSpec(
metadata=client.V1ObjectMeta(
namespace=self._kwargs["namespace"],
# We don't set any annotations here
# since they have been either set in the JobSpec
# or on the JobSet level
),
spec=client.V1JobSpec(
# Retries are handled by Metaflow when it is responsible for
# executing the flow. The responsibility is moved to Kubernetes
# when Argo Workflows is responsible for the execution.
backoff_limit=self._kwargs.get("retries", 0),
completions=1,
parallelism=1,
ttl_seconds_after_finished=7
* 60
* 60 # Remove job after a week. TODO: Make this configurable
* 24,
template=client.V1PodTemplateSpec(
metadata=client.V1ObjectMeta(
annotations=self._kwargs.get("annotations", {}),
labels=self._kwargs.get("labels", {}),
namespace=self._kwargs["namespace"],
),
spec=client.V1PodSpec(
subdomain=self._kwargs["subdomain"],
set_hostname_as_fqdn=True,
# Timeout is set on the pod and not the job (important!)
active_deadline_seconds=self._kwargs[
"timeout_in_seconds"
],
# TODO (savin): Enable affinities for GPU scheduling.
# affinity=?,
containers=[
client.V1Container(
command=self._kwargs["command"],
termination_message_policy="FallbackToLogsOnError",
ports=(
[]
if self._kwargs["port"] is None
else [
client.V1ContainerPort(
container_port=int(
self._kwargs["port"]
)
)
]
),
env=[
client.V1EnvVar(name=k, value=str(v))
for k, v in self._kwargs.get(
"environment_variables", {}
).items()
]
# And some downward API magic. Add (key, value)
# pairs below to make pod metadata available
# within Kubernetes container.
+ [
client.V1EnvVar(
name=k,
value_from=client.V1EnvVarSource(
field_ref=client.V1ObjectFieldSelector(
field_path=str(v)
)
),
)
for k, v in self._kwargs.get(
"environment_variables_from_selectors",
{},
).items()
]
+ [
client.V1EnvVar(name=k, value=str(v))
for k, v in inject_tracing_vars({}).items()
],
env_from=[
client.V1EnvFromSource(
secret_ref=client.V1SecretEnvSource(
name=str(k),
# optional=True
)
)
for k in list(
self._kwargs.get("secrets", [])
)
if k
],
image=self._kwargs["image"],
image_pull_policy=self._kwargs[
"image_pull_policy"
],
name=self._kwargs["step_name"].replace(
"_", "-"
),
resources=client.V1ResourceRequirements(
requests=qos_requests,
limits={
**qos_limits,
**{
"%s.com/gpu".lower()
% self._kwargs["gpu_vendor"]: str(
self._kwargs["gpu"]
)
for k in [0]
# Don't set GPU limits if gpu isn't specified.
if self._kwargs["gpu"] is not None
},
},
),
volume_mounts=(
[
client.V1VolumeMount(
mount_path=self._kwargs.get(
"tmpfs_path"
),
name="tmpfs-ephemeral-volume",
)
]
if tmpfs_enabled
else []
)
+ (
[
client.V1VolumeMount(
mount_path="/dev/shm", name="dhsm"
)
]
if shared_memory
else []
)
+ (
[
client.V1VolumeMount(
mount_path=path, name=claim
)
for claim, path in self._kwargs[
"persistent_volume_claims"
].items()
]
if self._kwargs["persistent_volume_claims"]
is not None
else []
),
**_security_context,
)
],
node_selector=self._kwargs.get("node_selector"),
image_pull_secrets=[
client.V1LocalObjectReference(secret)
for secret in self._kwargs.get("image_pull_secrets")
or []
],
# TODO (savin): Support preemption policies
# preemption_policy=?,
#
# A Container in a Pod may fail for a number of
# reasons, such as because the process in it exited
# with a non-zero exit code, or the Container was
# killed due to OOM etc. If this happens, fail the pod
# and let Metaflow handle the retries.
restart_policy="Never",
service_account_name=self._kwargs["service_account"],
# Terminate the container immediately on SIGTERM
termination_grace_period_seconds=0,
tolerations=[
client.V1Toleration(**toleration)
for toleration in self._kwargs.get("tolerations")
or []
],
volumes=(
[
client.V1Volume(
name="tmpfs-ephemeral-volume",
empty_dir=client.V1EmptyDirVolumeSource(
medium="Memory",
# Add default unit as ours differs from Kubernetes default.
size_limit="{}Mi".format(tmpfs_size),
),
)
]
if tmpfs_enabled
else []
)
+ (
[
client.V1Volume(
name="dhsm",
empty_dir=client.V1EmptyDirVolumeSource(
medium="Memory",
size_limit="{}Mi".format(shared_memory),
),
)
]
if shared_memory
else []
)
+ (
[
client.V1Volume(
name=claim,
persistent_volume_claim=client.V1PersistentVolumeClaimVolumeSource(
claim_name=claim
),
)
for claim in self._kwargs[
"persistent_volume_claims"
].keys()
]
if self._kwargs["persistent_volume_claims"]
is not None
else []
),
),
),
),
)
),
replicas=self._kwargs["replicas"],
)
|
JobSetSpec
|
python
|
mozilla__bleach
|
bleach/_vendor/parse.py
|
{
"start": 6307,
"end": 7227
}
|
class ____(_NetlocResultMixinBase, _ResultMixinStr):
__slots__ = ()
@property
def _userinfo(self):
netloc = self.netloc
userinfo, have_info, hostinfo = netloc.rpartition('@')
if have_info:
username, have_password, password = userinfo.partition(':')
if not have_password:
password = None
else:
username = password = None
return username, password
@property
def _hostinfo(self):
netloc = self.netloc
_, _, hostinfo = netloc.rpartition('@')
_, have_open_br, bracketed = hostinfo.partition('[')
if have_open_br:
hostname, _, port = bracketed.partition(']')
_, _, port = port.partition(':')
else:
hostname, _, port = hostinfo.partition(':')
if not port:
port = None
return hostname, port
|
_NetlocResultMixinStr
|
python
|
boto__boto3
|
tests/functional/test_utils.py
|
{
"start": 675,
"end": 1430
}
|
class ____(unittest.TestCase):
def test_runtime_error_raised_when_shadowing_client_method(self):
botocore_session = botocore.session.get_session()
session = boto3.session.Session(
region_name='us-west-2', botocore_session=botocore_session
)
def shadows_put_object(class_attributes, **kwargs):
utils.inject_attribute(class_attributes, 'put_object', 'invalid')
botocore_session.register('creating-client-class', shadows_put_object)
with pytest.raises(RuntimeError):
# This should raise an exception because we're trying to
# shadow the put_object client method in the
# shadows_put_object handler above.
session.client('s3')
|
TestUtils
|
python
|
pytorch__pytorch
|
torch/testing/_internal/common_fsdp.py
|
{
"start": 58984,
"end": 59453
}
|
class ____(nn.Module):
def __init__(self, double_nest):
super().__init__()
self.linear = nn.Linear(10, 10, bias=False).to(DEVICE_TYPE)
self.linear_skip = SkipModule().to(DEVICE_TYPE)
self.nested_linear = wrap(
NestedLinear(fsdp_wrap=double_nest), device_id=DEVICE_TYPE
)
def forward(self, x):
x = self.linear(x)
x = self.linear_skip(x)
x = self.nested_linear(x)
return x
|
SkipModel
|
python
|
cython__cython
|
Cython/Compiler/Nodes.py
|
{
"start": 207655,
"end": 207745
}
|
class ____(AsyncDefNode):
gen_type_name = 'AsyncGen'
is_asyncgen = True
|
AsyncGenNode
|
python
|
apache__airflow
|
providers/google/src/airflow/providers/google/cloud/links/dataform.py
|
{
"start": 1515,
"end": 1772
}
|
class ____(BaseGoogleLink):
"""Helper class for constructing Dataflow Job Link."""
name = "Dataform Workflow Invocation"
key = "dataform_workflow_invocation_config"
format_str = DATAFORM_WORKFLOW_INVOCATION_LINK
|
DataformWorkflowInvocationLink
|
python
|
allegroai__clearml
|
clearml/backend_api/services/v2_13/projects.py
|
{
"start": 29382,
"end": 33756
}
|
class ____(Request):
"""
Create a new project
:param name: Project name Unique within the company.
:type name: str
:param description: Project description.
:type description: str
:param tags: User-defined tags
:type tags: Sequence[str]
:param system_tags: System tags. This field is reserved for system use, please
don't use it.
:type system_tags: Sequence[str]
:param default_output_destination: The default output destination URL for new
tasks under this project
:type default_output_destination: str
"""
_service = "projects"
_action = "create"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"default_output_destination": {
"description": "The default output destination URL for new tasks under this project",
"type": "string",
},
"description": {"description": "Project description.", "type": "string"},
"name": {
"description": "Project name Unique within the company.",
"type": "string",
},
"system_tags": {
"description": "System tags. This field is reserved for system use, please don't use it.",
"items": {"type": "string"},
"type": "array",
},
"tags": {
"description": "User-defined tags",
"items": {"type": "string"},
"type": "array",
},
},
"required": ["name"],
"type": "object",
}
def __init__(
self,
name: str,
description: Optional[str] = None,
tags: Optional[List[str]] = None,
system_tags: Optional[List[str]] = None,
default_output_destination: Optional[str] = None,
**kwargs: Any
) -> None:
super(CreateRequest, self).__init__(**kwargs)
self.name = name
self.description = description
self.tags = tags
self.system_tags = system_tags
self.default_output_destination = default_output_destination
@schema_property("name")
def name(self) -> str:
return self._property_name
@name.setter
def name(self, value: str) -> None:
if value is None:
self._property_name = None
return
self.assert_isinstance(value, "name", six.string_types)
self._property_name = value
@schema_property("description")
def description(self) -> Optional[str]:
return self._property_description
@description.setter
def description(self, value: Optional[str]) -> None:
if value is None:
self._property_description = None
return
self.assert_isinstance(value, "description", six.string_types)
self._property_description = value
@schema_property("tags")
def tags(self) -> Optional[List[str]]:
return self._property_tags
@tags.setter
def tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_tags = None
return
self.assert_isinstance(value, "tags", (list, tuple))
self.assert_isinstance(value, "tags", six.string_types, is_array=True)
self._property_tags = value
@schema_property("system_tags")
def system_tags(self) -> Optional[List[str]]:
return self._property_system_tags
@system_tags.setter
def system_tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_system_tags = None
return
self.assert_isinstance(value, "system_tags", (list, tuple))
self.assert_isinstance(value, "system_tags", six.string_types, is_array=True)
self._property_system_tags = value
@schema_property("default_output_destination")
def default_output_destination(self) -> Optional[str]:
return self._property_default_output_destination
@default_output_destination.setter
def default_output_destination(self, value: Optional[str]) -> None:
if value is None:
self._property_default_output_destination = None
return
self.assert_isinstance(value, "default_output_destination", six.string_types)
self._property_default_output_destination = value
|
CreateRequest
|
python
|
pyca__cryptography
|
tests/hazmat/primitives/test_hash_vectors.py
|
{
"start": 4770,
"end": 5131
}
|
class ____:
test_sha3_384 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHA3"),
["SHA3_384LongMsg.rsp", "SHA3_384ShortMsg.rsp"],
hashes.SHA3_384(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(hashes.SHA3_512()),
skip_message="Does not support SHA3_512",
)
|
TestSHA3384
|
python
|
pytorch__pytorch
|
torch/fx/experimental/symbolic_shapes.py
|
{
"start": 88452,
"end": 97924
}
|
class ____(NamedTuple):
k: sympy.Symbol
vr: Optional[ValueRanges]
val: Optional[sympy.Integer]
is_size_like: bool
@lru_cache(None)
def _maybe_evaluate_static_worker(
expr: _SympyT,
# NB: this is a tuple to ensure it can be LRU cached
symbol_info: tuple[_SymbolInfo, ...],
unbacked_only: bool,
size_oblivious: bool,
) -> Optional[_SympyT]:
"""
This variant of ShapeEnv._maybe_evaluate_static has no dependence on
ShapeEnv and thus can be cached indefinitely. It does the "heavy" lifting
for static evaluation, including nontrivial reliance on Sympy simplification
that occurs when we reallocate the symbols
"""
# Simplify making use of value range lower bound
new_shape_env = {}
new_range_env = {}
for idx, sinfo in enumerate(symbol_info):
k, vr, val, is_size_like = sinfo
if isinstance(val, SingletonInt):
# Skip var_ranges logic for SingletonInt which is only used
# for jagged layout NestedTensors today
continue
assert vr is not None
if size_oblivious and is_size_like:
lower = max(2, vr.lower)
# Clamping size-oblivious to some quantity below sys.maxsize
# helps us determine that f(u0) != sys.maxsize, which is a
# test that is looking for sys.maxsize as a sentinel, but you
# don't really want to worry about it for unbacked SymInts.
# This is similar to the flavor where size oblivious omits
# 0/1, it changes semantics but in a benign way.
upper = min(2**48, vr.upper)
# Excluding the very upper bound can be helpful
if upper > lower:
upper = upper - 1
# This is a bit dodgy: what this means is that there was a
# size-like unbacked symbol whose upper bound < 2. This
# causes... problems.
if lower <= upper:
vr = ValueRanges(lower, upper)
else:
lower = vr.lower
# Don't do anything if we don't have a nontrivial lower bound
# Also don't do anything if we asked only to simplify unbacked
# SymInt
if lower is -int_oo or (unbacked_only and val is not None) or not vr.is_int:
new_range_env[k] = vr
continue
# The goal is to take our symbols which have various lower bounds
# and reallocate them into new symbols which are exactly positive;
# e.g., if we have s0 in [2, inf], we want to turn it into ess0 in
# [1, inf], where s0 = ess0 + 1. This gives the most information
# to sympy for subsequent simplifications.
#
# Positive means >= 1
# Positive - 1 means >= 0
# Positive + lower - 1 means >= lower
# The new symbol 's' is "too low", so when we substitute it in
# we have to increase it by offset (and conversely, the new
# variables have to have their value range bounds adjusted as
# well)
s = sympy.Symbol(f"evaluate_static_shape_{idx}", positive=True, integer=True)
# Note:
# Offset might be a fraction(e.g. aten.split.Tensor), but shapes are always integers.
# Sympy might give unexpected results when comparing an integer with a non-integer
# Therefore, we cast offset to int here.
# For example:
# shape_0 = sympy.Symbol("shape_0", positive=True, integer=True)
# expr = sympy.Eq(shape_0 - 1/3, 4)
# expr.xreplace({}) # False
offset = int(lower - 1)
new_shape_env[k] = s + offset
new_range_env[s] = SymPyValueRangeAnalysis.add(vr, -offset)
# TODO: remove this try catch (esp for unbacked_only)
try:
# pyrefly: ignore [missing-attribute]
new_expr = expr.xreplace(new_shape_env)
except RecursionError:
log.warning("RecursionError in sympy.xreplace(%s, %s)", expr, new_shape_env)
return None
# We need to canonicalize, as after expand we may have something like `a + b = a` and
# sympy will not simplify the a. The two appeareances of the a will then make value ranges
# analysis give lose bounds
new_expr = canonicalize_bool_expr(safe_expand(new_expr))
if new_expr.is_number:
return new_expr
# Check if the range can solve it statically
out = bound_sympy(new_expr, new_range_env)
if out.is_singleton():
return out.lower
return new_expr if unbacked_only else None
def error() -> NoReturn:
raise AssertionError("shouldn't be hit")
# TODO: Deduplicate this with torch/_prims_common/__init__.py
def eval_is_non_overlapping_and_dense(
sizes: Sequence[int], strides: Sequence[int]
) -> int:
return int(guard_bool(_eval_is_non_overlapping_and_dense(sizes, strides)))
def _eval_is_non_overlapping_and_dense(
sizes: Sequence[int], strides: Sequence[int]
) -> bool:
"""
Evaluates whether a tensor with the given sizes and strides is non-overlapping and dense.
A tensor is non-overlapping if there's no memory location that belongs to more than one element.
A tensor is dense if all elements are stored in memory without gaps.
Args:
sizes: Sequence of dimension sizes for the tensor
strides: Sequence of strides for the tensor
Returns:
True if the tensor is non-overlapping and dense, False otherwise
"""
dim = len(sizes)
# Short-circuits for tensors of rank one, which are
# non-overlapping and "dense" if their stride is one
# or it is a 0/1 element tensor
if dim == 1:
return strides[0] == 1 or sizes[0] < 2
# Checks that there exists a permutation of the strides s.t. the tensor would be contiguous
# Sorts (length, stride) pairs by stride
lengths_and_strides = sorted(zip(sizes, strides), key=operator.itemgetter(1))
# Unlike the C++ code, we don't move the 0/1 size dimensions to the
# end. So we have to keep going for this code.
expected_stride = 1
for length, stride in lengths_and_strides:
if length == 1:
continue
if stride != expected_stride:
return False
expected_stride *= length
return True
def _sympy_cast_symbool_to_symint_guardless(x: SympyBoolean) -> sympy.Expr:
return sympy.Piecewise((1, x), (0, True))
def cast_symbool_to_symint_guardless(
symbool: Union[bool, torch.SymBool],
) -> Union[int, torch.SymInt]:
"""
Converts a SymBool or bool to a SymInt or int without introducing guards.
This function maps True to 1 and False to 0, preserving the symbolic nature
of the input when it's a SymBool. Unlike regular casting which might introduce
guards, this function performs the conversion without adding any guards.
Args:
symbool: A boolean value, either a concrete bool or symbolic SymBool
Returns:
The corresponding integer value (1 for True, 0 for False) as either
a concrete int or symbolic SymInt
"""
if isinstance(symbool, bool):
return 1 if symbool else 0
int_sym = _sympy_cast_symbool_to_symint_guardless(symbool.node.expr)
return symbool.node.shape_env.create_symintnode(
int_sym, hint=int(symbool.node.require_hint()) if has_hint(symbool) else None
)
SYMPY_INTERP = {
"IsNonOverlappingAndDenseIndicator": eval_is_non_overlapping_and_dense,
"cast_symbool_to_symint_guardless": cast_symbool_to_symint_guardless,
"math": math,
"torch": torch,
}
def _lru_cache(
fn: Callable[..., _T], maxsize: Optional[int] = None
) -> functools._lru_cache_wrapper[_T]:
"""
Wrapper around lru_cache that clears when new info about shapes has been
updated.
Use lru_cache if the output is always the same, regardless of the
constraints we know now (i.e. evaluate_expr)
Use _lru_cache otherwise.
Also note that this depends on _update_version_counter being called on the
shape environment whenever the constraints are updated, otherwise the cache
will not be cleared.
"""
fn_cache = lru_cache(maxsize)(fn)
prior_version = 0
if config.validate_shape_env_version_key:
prior_key = None
@functools.wraps(fn)
def wrapper(self: ShapeEnv, *args: Any, **kwargs: Any) -> _T:
nonlocal prior_version, prior_key
if prior_key is None:
prior_key = self._get_key()
if prior_version != self._version_counter:
fn_cache.cache_clear()
prior_version = self._version_counter
prior_key = self._get_key()
else:
assert prior_key == self._get_key(), (
"ShapeEnv cache key changed without version being updated!"
)
return fn_cache(self, *args, **kwargs)
else:
@functools.wraps(fn)
def wrapper(self: ShapeEnv, *args: Any, **kwargs: Any) -> _T: # type: ignore[misc]
nonlocal prior_version
if prior_version != self._version_counter:
fn_cache.cache_clear()
prior_version = self._version_counter
return fn_cache(self, *args, **kwargs)
wrapper.cache_clear = fn_cache.cache_clear # type: ignore[attr-defined]
wrapper.cache_info = fn_cache.cache_info # type: ignore[attr-defined]
return wrapper # type: ignore[return-value]
@dataclass(frozen=True)
|
_SymbolInfo
|
python
|
sphinx-doc__sphinx
|
sphinx/ext/graphviz.py
|
{
"start": 3522,
"end": 6469
}
|
class ____(SphinxDirective):
"""Directive to insert arbitrary dot markup."""
has_content = True
required_arguments = 0
optional_arguments = 1
final_argument_whitespace = False
option_spec: ClassVar[OptionSpec] = {
'alt': directives.unchanged,
'align': align_spec,
'caption': directives.unchanged,
'layout': directives.unchanged,
'graphviz_dot': directives.unchanged, # an old alias of `layout` option
'name': directives.unchanged,
'class': directives.class_option,
}
def run(self) -> list[Node]:
if self.arguments:
document = self.state.document
if self.content:
return [
document.reporter.warning(
__(
'Graphviz directive cannot have both content and '
'a filename argument'
),
line=self.lineno,
)
]
argument = search_image_for_language(self.arguments[0], self.env)
rel_filename, filename = self.env.relfn2path(argument)
self.env.note_dependency(rel_filename)
try:
with open(filename, encoding='utf-8') as fp:
dotcode = fp.read()
except OSError:
return [
document.reporter.warning(
__('External Graphviz file %r not found or reading it failed')
% filename,
line=self.lineno,
)
]
else:
dotcode = '\n'.join(self.content)
rel_filename = None
if not dotcode.strip():
return [
self.state_machine.reporter.warning(
__('Ignoring "graphviz" directive without content.'),
line=self.lineno,
)
]
node = graphviz()
node['code'] = dotcode
node['options'] = {'docname': self.env.current_document.docname}
if 'graphviz_dot' in self.options:
node['options']['graphviz_dot'] = self.options['graphviz_dot']
if 'layout' in self.options:
node['options']['graphviz_dot'] = self.options['layout']
if 'alt' in self.options:
node['alt'] = self.options['alt']
if 'align' in self.options:
node['align'] = self.options['align']
if 'class' in self.options:
node['classes'] = self.options['class']
if rel_filename:
node['filename'] = rel_filename
if 'caption' not in self.options:
self.add_name(node)
return [node]
else:
figure = figure_wrapper(self, node, self.options['caption'])
self.add_name(figure)
return [figure]
|
Graphviz
|
python
|
anthropics__anthropic-sdk-python
|
src/anthropic/types/messages/message_batch.py
|
{
"start": 315,
"end": 2415
}
|
class ____(BaseModel):
id: str
"""Unique object identifier.
The format and length of IDs may change over time.
"""
archived_at: Optional[datetime] = None
"""
RFC 3339 datetime string representing the time at which the Message Batch was
archived and its results became unavailable.
"""
cancel_initiated_at: Optional[datetime] = None
"""
RFC 3339 datetime string representing the time at which cancellation was
initiated for the Message Batch. Specified only if cancellation was initiated.
"""
created_at: datetime
"""
RFC 3339 datetime string representing the time at which the Message Batch was
created.
"""
ended_at: Optional[datetime] = None
"""
RFC 3339 datetime string representing the time at which processing for the
Message Batch ended. Specified only once processing ends.
Processing ends when every request in a Message Batch has either succeeded,
errored, canceled, or expired.
"""
expires_at: datetime
"""
RFC 3339 datetime string representing the time at which the Message Batch will
expire and end processing, which is 24 hours after creation.
"""
processing_status: Literal["in_progress", "canceling", "ended"]
"""Processing status of the Message Batch."""
request_counts: MessageBatchRequestCounts
"""Tallies requests within the Message Batch, categorized by their status.
Requests start as `processing` and move to one of the other statuses only once
processing of the entire batch ends. The sum of all values always matches the
total number of requests in the batch.
"""
results_url: Optional[str] = None
"""URL to a `.jsonl` file containing the results of the Message Batch requests.
Specified only once processing ends.
Results in the file are not guaranteed to be in the same order as requests. Use
the `custom_id` field to match results to requests.
"""
type: Literal["message_batch"]
"""Object type.
For Message Batches, this is always `"message_batch"`.
"""
|
MessageBatch
|
python
|
matplotlib__matplotlib
|
lib/matplotlib/backends/backend_gtk4.py
|
{
"start": 22918,
"end": 23632
}
|
class ____(backend_tools.ToolCopyToClipboardBase):
def trigger(self, *args, **kwargs):
with io.BytesIO() as f:
self.canvas.print_rgba(f)
w, h = self.canvas.get_width_height()
pb = GdkPixbuf.Pixbuf.new_from_data(f.getbuffer(),
GdkPixbuf.Colorspace.RGB, True,
8, w, h, w*4)
clipboard = self.canvas.get_clipboard()
clipboard.set(pb)
backend_tools._register_tool_class(
FigureCanvasGTK4, _backend_gtk.ConfigureSubplotsGTK)
backend_tools._register_tool_class(
FigureCanvasGTK4, _backend_gtk.RubberbandGTK)
Toolbar = ToolbarGTK4
|
ToolCopyToClipboardGTK4
|
python
|
getsentry__sentry
|
tests/sentry/dashboards/endpoints/test_organization_dashboard_details.py
|
{
"start": 30407,
"end": 39409
}
|
class ____(OrganizationDashboardDetailsTestCase):
def test_delete(self) -> None:
response = self.do_request("delete", self.url(self.dashboard.id))
assert response.status_code == 204
assert self.client.get(self.url(self.dashboard.id)).status_code == 404
assert not Dashboard.objects.filter(id=self.dashboard.id).exists()
assert not DashboardWidget.objects.filter(id=self.widget_1.id).exists()
assert not DashboardWidget.objects.filter(id=self.widget_2.id).exists()
assert not DashboardWidgetQuery.objects.filter(widget_id=self.widget_1.id).exists()
assert not DashboardWidgetQuery.objects.filter(widget_id=self.widget_2.id).exists()
def test_delete_permission(self) -> None:
self.create_user_member_role()
self.test_delete()
def test_allow_delete_when_no_project_access(self) -> None:
# disable Open Membership
self.organization.flags.allow_joinleave = False
self.organization.save()
# assign a project to a dashboard
self.dashboard.projects.set([self.project])
# user has no access to the above project
user_no_team = self.create_user(is_superuser=False)
self.create_member(
user=user_no_team, organization=self.organization, role="member", teams=[]
)
self.login_as(user_no_team)
response = self.do_request("delete", self.url(self.dashboard.id))
assert response.status_code == 204
def test_allow_delete_all_projects_dashboard_when_no_open_membership(self) -> None:
# disable Open Membership
self.organization.flags.allow_joinleave = False
self.organization.save()
dashboard = Dashboard.objects.create(
title="Dashboard For All Projects",
created_by_id=self.user.id,
organization=self.organization,
filters={"all_projects": True},
)
# user has no access to all the projects
user_no_team = self.create_user(is_superuser=False)
self.create_member(
user=user_no_team, organization=self.organization, role="member", teams=[]
)
self.login_as(user_no_team)
response = self.do_request("delete", self.url(dashboard.id))
assert response.status_code == 204
def test_allow_delete_my_projects_dashboard_when_no_open_membership(self) -> None:
# disable Open Membership
self.organization.flags.allow_joinleave = False
self.organization.save()
dashboard = Dashboard.objects.create(
title="Dashboard For My Projects",
created_by_id=self.user.id,
organization=self.organization,
# no 'filter' field means the dashboard covers all available projects
)
# user has no access to all the projects
user_no_team = self.create_user(is_superuser=False)
self.create_member(
user=user_no_team, organization=self.organization, role="member", teams=[]
)
self.login_as(user_no_team)
response = self.do_request("delete", self.url(dashboard.id))
assert response.status_code == 204
def test_allow_delete_as_superuser_but_no_edit_perms(self) -> None:
self.create_user(id=12333)
dashboard = Dashboard.objects.create(
id=67,
title="Dashboard With Dataset Source",
created_by_id=12333,
organization=self.organization,
)
DashboardPermissions.objects.create(is_editable_by_everyone=False, dashboard=dashboard)
# Create and login as superuser
superuser = self.create_user(is_superuser=True)
self.login_as(user=superuser, superuser=True)
response = self.do_request("delete", self.url(dashboard.id))
assert response.status_code == 204, response.content
def test_dashboard_does_not_exist(self) -> None:
response = self.do_request("delete", self.url(1234567890))
assert response.status_code == 404
assert response.data == {"detail": "The requested resource does not exist"}
def test_delete_prebuilt_dashboard(self) -> None:
slug = "default-overview"
response = self.do_request("delete", self.url(slug))
assert response.status_code == 204
assert DashboardTombstone.objects.filter(organization=self.organization, slug=slug).exists()
def test_delete_last_dashboard(self) -> None:
slug = "default-overview"
response = self.do_request("delete", self.url(slug))
assert response.status_code == 204
assert DashboardTombstone.objects.filter(organization=self.organization, slug=slug).exists()
response = self.do_request("delete", self.url(self.dashboard.id))
assert response.status_code == 409
def test_delete_last_default_dashboard(self) -> None:
response = self.do_request("delete", self.url(self.dashboard.id))
assert response.status_code == 204
assert self.client.get(self.url(self.dashboard.id)).status_code == 404
slug = "default-overview"
response = self.do_request("delete", self.url(slug))
assert response.status_code == 409
def test_features_required(self) -> None:
with self.feature({"organizations:dashboards-edit": False}):
response = self.do_request("delete", self.url("default-overview"))
assert response.status_code == 404
def test_delete_dashboard_with_edit_permissions_not_granted(self) -> None:
dashboard = Dashboard.objects.create(
title="Dashboard With Dataset Source",
created_by_id=11452,
organization=self.organization,
)
DashboardPermissions.objects.create(is_editable_by_everyone=False, dashboard=dashboard)
user = self.create_user(id=1235)
self.create_member(user=user, organization=self.organization)
self.login_as(user)
response = self.do_request("delete", self.url(dashboard.id))
assert response.status_code == 403
def test_delete_dashboard_with_edit_permissions_disabled(self) -> None:
dashboard = Dashboard.objects.create(
title="Dashboard With Dataset Source",
created_by_id=11452,
organization=self.organization,
)
DashboardPermissions.objects.create(is_editable_by_everyone=True, dashboard=dashboard)
user = self.create_user(id=1235)
self.create_member(user=user, organization=self.organization)
self.login_as(user)
response = self.do_request("delete", self.url(dashboard.id))
assert response.status_code == 204
def test_creator_can_delete_dashboard(self) -> None:
dashboard = Dashboard.objects.create(
title="Dashboard With Dataset Source",
created_by_id=12333,
organization=self.organization,
)
DashboardPermissions.objects.create(is_editable_by_everyone=False, dashboard=dashboard)
user = self.create_user(id=12333)
self.create_member(user=user, organization=self.organization)
self.login_as(user)
response = self.do_request("delete", self.url(dashboard.id))
assert response.status_code == 204, response.content
def test_user_in_team_with_access_can_delete_dashboard(self) -> None:
dashboard = Dashboard.objects.create(
title="Dashboard With Dataset Source",
created_by_id=11452,
organization=self.organization,
)
permissions = DashboardPermissions.objects.create(
is_editable_by_everyone=False, dashboard=dashboard
)
# Create team and add to dashboard permissions
team = self.create_team(organization=self.organization)
permissions.teams_with_edit_access.set([team])
# Create user and add to team
user = self.create_user(id=12345)
self.create_member(user=user, organization=self.organization, teams=[team])
self.login_as(user)
response = self.do_request("delete", self.url(dashboard.id))
assert response.status_code == 204, response.content
def test_user_in_team_without_access_cannot_delete_dashboard(self) -> None:
dashboard = Dashboard.objects.create(
title="Dashboard With Dataset Source",
created_by_id=11452,
organization=self.organization,
)
permissions = DashboardPermissions.objects.create(
is_editable_by_everyone=False, dashboard=dashboard
)
# Create team and add to dashboard permissions
team = self.create_team(organization=self.organization)
permissions.teams_with_edit_access.set([team])
# Create user not in team
user = self.create_user(id=12345)
self.login_as(user)
response = self.do_request("put", self.url(dashboard.id))
assert response.status_code == 403
|
OrganizationDashboardDetailsDeleteTest
|
python
|
plotly__plotly.py
|
plotly/graph_objs/table/_cells.py
|
{
"start": 233,
"end": 13332
}
|
class ____(_BaseTraceHierarchyType):
_parent_path_str = "table"
_path_str = "table.cells"
_valid_props = {
"align",
"alignsrc",
"fill",
"font",
"format",
"formatsrc",
"height",
"line",
"prefix",
"prefixsrc",
"suffix",
"suffixsrc",
"values",
"valuessrc",
}
@property
def align(self):
"""
Sets the horizontal alignment of the `text` within the box. Has
an effect only if `text` spans two or more lines (i.e. `text`
contains one or more <br> HTML tags) or if an explicit width is
set to override the text width.
The 'align' property is an enumeration that may be specified as:
- One of the following enumeration values:
['left', 'center', 'right']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["align"]
@align.setter
def align(self, val):
self["align"] = val
@property
def alignsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `align`.
The 'alignsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["alignsrc"]
@alignsrc.setter
def alignsrc(self, val):
self["alignsrc"] = val
@property
def fill(self):
"""
The 'fill' property is an instance of Fill
that may be specified as:
- An instance of :class:`plotly.graph_objs.table.cells.Fill`
- A dict of string/value properties that will be passed
to the Fill constructor
Returns
-------
plotly.graph_objs.table.cells.Fill
"""
return self["fill"]
@fill.setter
def fill(self, val):
self["fill"] = val
@property
def font(self):
"""
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.table.cells.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Returns
-------
plotly.graph_objs.table.cells.Font
"""
return self["font"]
@font.setter
def font(self, val):
self["font"] = val
@property
def format(self):
"""
Sets the cell value formatting rule using d3 formatting mini-
languages which are very similar to those in Python. For
numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
The 'format' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["format"]
@format.setter
def format(self, val):
self["format"] = val
@property
def formatsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `format`.
The 'formatsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["formatsrc"]
@formatsrc.setter
def formatsrc(self, val):
self["formatsrc"] = val
@property
def height(self):
"""
The height of cells.
The 'height' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["height"]
@height.setter
def height(self, val):
self["height"] = val
@property
def line(self):
"""
The 'line' property is an instance of Line
that may be specified as:
- An instance of :class:`plotly.graph_objs.table.cells.Line`
- A dict of string/value properties that will be passed
to the Line constructor
Returns
-------
plotly.graph_objs.table.cells.Line
"""
return self["line"]
@line.setter
def line(self, val):
self["line"] = val
@property
def prefix(self):
"""
Prefix for cell values.
The 'prefix' property is a string and must be specified as:
- A string
- A number that will be converted to a string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["prefix"]
@prefix.setter
def prefix(self, val):
self["prefix"] = val
@property
def prefixsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `prefix`.
The 'prefixsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["prefixsrc"]
@prefixsrc.setter
def prefixsrc(self, val):
self["prefixsrc"] = val
@property
def suffix(self):
"""
Suffix for cell values.
The 'suffix' property is a string and must be specified as:
- A string
- A number that will be converted to a string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["suffix"]
@suffix.setter
def suffix(self, val):
self["suffix"] = val
@property
def suffixsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `suffix`.
The 'suffixsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["suffixsrc"]
@suffixsrc.setter
def suffixsrc(self, val):
self["suffixsrc"] = val
@property
def values(self):
"""
Cell values. `values[m][n]` represents the value of the `n`th
point in column `m`, therefore the `values[m]` vector length
for all columns must be the same (longer vectors will be
truncated). Each value must be a finite number or a string.
The 'values' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["values"]
@values.setter
def values(self, val):
self["values"] = val
@property
def valuessrc(self):
"""
Sets the source reference on Chart Studio Cloud for `values`.
The 'valuessrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["valuessrc"]
@valuessrc.setter
def valuessrc(self, val):
self["valuessrc"] = val
@property
def _prop_descriptions(self):
return """\
align
Sets the horizontal alignment of the `text` within the
box. Has an effect only if `text` spans two or more
lines (i.e. `text` contains one or more <br> HTML tags)
or if an explicit width is set to override the text
width.
alignsrc
Sets the source reference on Chart Studio Cloud for
`align`.
fill
:class:`plotly.graph_objects.table.cells.Fill` instance
or dict with compatible properties
font
:class:`plotly.graph_objects.table.cells.Font` instance
or dict with compatible properties
format
Sets the cell value formatting rule using d3 formatting
mini-languages which are very similar to those in
Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
formatsrc
Sets the source reference on Chart Studio Cloud for
`format`.
height
The height of cells.
line
:class:`plotly.graph_objects.table.cells.Line` instance
or dict with compatible properties
prefix
Prefix for cell values.
prefixsrc
Sets the source reference on Chart Studio Cloud for
`prefix`.
suffix
Suffix for cell values.
suffixsrc
Sets the source reference on Chart Studio Cloud for
`suffix`.
values
Cell values. `values[m][n]` represents the value of the
`n`th point in column `m`, therefore the `values[m]`
vector length for all columns must be the same (longer
vectors will be truncated). Each value must be a finite
number or a string.
valuessrc
Sets the source reference on Chart Studio Cloud for
`values`.
"""
def __init__(
self,
arg=None,
align=None,
alignsrc=None,
fill=None,
font=None,
format=None,
formatsrc=None,
height=None,
line=None,
prefix=None,
prefixsrc=None,
suffix=None,
suffixsrc=None,
values=None,
valuessrc=None,
**kwargs,
):
"""
Construct a new Cells object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.table.Cells`
align
Sets the horizontal alignment of the `text` within the
box. Has an effect only if `text` spans two or more
lines (i.e. `text` contains one or more <br> HTML tags)
or if an explicit width is set to override the text
width.
alignsrc
Sets the source reference on Chart Studio Cloud for
`align`.
fill
:class:`plotly.graph_objects.table.cells.Fill` instance
or dict with compatible properties
font
:class:`plotly.graph_objects.table.cells.Font` instance
or dict with compatible properties
format
Sets the cell value formatting rule using d3 formatting
mini-languages which are very similar to those in
Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
formatsrc
Sets the source reference on Chart Studio Cloud for
`format`.
height
The height of cells.
line
:class:`plotly.graph_objects.table.cells.Line` instance
or dict with compatible properties
prefix
Prefix for cell values.
prefixsrc
Sets the source reference on Chart Studio Cloud for
`prefix`.
suffix
Suffix for cell values.
suffixsrc
Sets the source reference on Chart Studio Cloud for
`suffix`.
values
Cell values. `values[m][n]` represents the value of the
`n`th point in column `m`, therefore the `values[m]`
vector length for all columns must be the same (longer
vectors will be truncated). Each value must be a finite
number or a string.
valuessrc
Sets the source reference on Chart Studio Cloud for
`values`.
Returns
-------
Cells
"""
super().__init__("cells")
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.table.Cells
constructor must be a dict or
an instance of :class:`plotly.graph_objs.table.Cells`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("align", arg, align)
self._set_property("alignsrc", arg, alignsrc)
self._set_property("fill", arg, fill)
self._set_property("font", arg, font)
self._set_property("format", arg, format)
self._set_property("formatsrc", arg, formatsrc)
self._set_property("height", arg, height)
self._set_property("line", arg, line)
self._set_property("prefix", arg, prefix)
self._set_property("prefixsrc", arg, prefixsrc)
self._set_property("suffix", arg, suffix)
self._set_property("suffixsrc", arg, suffixsrc)
self._set_property("values", arg, values)
self._set_property("valuessrc", arg, valuessrc)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
|
Cells
|
python
|
getsentry__sentry
|
fixtures/safe_migrations_apps/bad_flow_delete_field_pending_with_not_null_app/migrations/0001_initial.py
|
{
"start": 106,
"end": 589
}
|
class ____(CheckedMigration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="TestTable",
fields=[
(
"id",
models.AutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
),
),
("field", models.IntegerField()),
],
),
]
|
Migration
|
python
|
run-llama__llama_index
|
docs/examples/discover_llamaindex/document_management/group_conversations.py
|
{
"start": 25,
"end": 2102
}
|
class ____:
def __init__(
self,
message_id,
message_text,
author,
timestamp,
parent_message=None,
child_message=None,
):
self.message_id = message_id
self.message_text = message_text
self.author = author
self.parent_message = parent_message
self.child_message = child_message
self.timestamp = timestamp
def set_child(self, message):
self.child_message = message
def set_parent(self, message):
self.parent_message = message
data_file = sys.argv[1]
with open(data_file, "r") as f:
data = json.load(f)
messages = {}
for msg in data["messages"]:
_id = msg["id"]
text = msg["content"]
msg_type = msg["type"]
author = msg["author"]["name"]
timestamp = msg["timestamp"]
if msg_type in ("ThreadCreated", "ChannelPinnedMessage"):
continue
messages[_id] = Message(_id, text, author, timestamp)
if msg_type == "Reply":
parent_id = msg["reference"]["messageId"]
try:
messages[_id].set_parent(messages[parent_id])
except:
continue # deleted message reference?
messages[parent_id].set_child(messages[_id])
convo_docs = []
for msg in messages.values():
# only check top-level messages
if msg.parent_message is None:
metadata = {
"timestamp": msg.timestamp,
"id": msg.message_id,
"author": msg.author,
}
convo = ""
convo += msg.author + ":\n"
convo += msg.message_text + "\n"
cur_msg = msg
is_thread = False
while cur_msg.child_message is not None:
is_thread = True
cur_msg = cur_msg.child_message
convo += cur_msg.author + ":\n"
convo += cur_msg.message_text + "\n"
if is_thread:
convo_docs.append({"thread": convo, "metadata": metadata})
with open("conversation_docs.json", "w") as f:
json.dump(convo_docs, f)
print("Done! Written to conversation_docs.json")
|
Message
|
python
|
ray-project__ray
|
rllib/core/models/torch/heads.py
|
{
"start": 6137,
"end": 8905
}
|
class ____(TorchModel):
def __init__(self, config: CNNTransposeHeadConfig) -> None:
super().__init__(config)
# Initial, inactivated Dense layer (always w/ bias).
# This layer is responsible for getting the incoming tensor into a proper
# initial image shape (w x h x filters) for the suceeding Conv2DTranspose stack.
self.initial_dense = nn.Linear(
in_features=config.input_dims[0],
out_features=int(np.prod(config.initial_image_dims)),
bias=True,
)
# Initial Dense layer initializers.
initial_dense_weights_initializer = get_initializer_fn(
config.initial_dense_weights_initializer, framework="torch"
)
initial_dense_bias_initializer = get_initializer_fn(
config.initial_dense_bias_initializer, framework="torch"
)
# Initialize dense layer weights, if necessary.
if initial_dense_weights_initializer:
initial_dense_weights_initializer(
self.initial_dense.weight,
**config.initial_dense_weights_initializer_config or {},
)
# Initialized dense layer bais, if necessary.
if initial_dense_bias_initializer:
initial_dense_bias_initializer(
self.initial_dense.bias,
**config.initial_dense_bias_initializer_config or {},
)
# The main CNNTranspose stack.
self.cnn_transpose_net = TorchCNNTranspose(
input_dims=config.initial_image_dims,
cnn_transpose_filter_specifiers=config.cnn_transpose_filter_specifiers,
cnn_transpose_activation=config.cnn_transpose_activation,
cnn_transpose_use_layernorm=config.cnn_transpose_use_layernorm,
cnn_transpose_use_bias=config.cnn_transpose_use_bias,
cnn_transpose_kernel_initializer=config.cnn_transpose_kernel_initializer,
cnn_transpose_kernel_initializer_config=(
config.cnn_transpose_kernel_initializer_config
),
cnn_transpose_bias_initializer=config.cnn_transpose_bias_initializer,
cnn_transpose_bias_initializer_config=(
config.cnn_transpose_bias_initializer_config
),
)
@override(Model)
def _forward(self, inputs: torch.Tensor, **kwargs) -> torch.Tensor:
out = self.initial_dense(inputs)
# Reshape to initial 3D (image-like) format to enter CNN transpose stack.
out = out.reshape((-1,) + tuple(self.config.initial_image_dims))
out = self.cnn_transpose_net(out)
# Add 0.5 to center (always non-activated, non-normalized) outputs more
# around 0.0.
return out + 0.5
|
TorchCNNTransposeHead
|
python
|
getsentry__sentry
|
tests/acceptance/test_organization_sentry_app_detailed_view.py
|
{
"start": 391,
"end": 2185
}
|
class ____(AcceptanceTestCase):
def setUp(self) -> None:
super().setUp()
self.create_project(organization=self.organization)
self.sentry_app = self.create_sentry_app(
organization_id=self.organization.id,
published=True,
verify_install=False,
name="Super Awesome App",
)
self.login_as(self.user)
def load_page(self, slug: str) -> None:
url = f"/settings/{self.organization.slug}/sentry-apps/{slug}/"
self.browser.get(url)
self.browser.wait_until_not('[data-test-id="loading-indicator"]')
def test_add_sentry_app(self) -> None:
self.load_page(self.sentry_app.slug)
detail_view_page = OrganizationSentryAppDetailViewPage(browser=self.browser)
detail_view_page.click_install_button()
self.browser.wait_until('[data-test-id="toast-success"]')
assert SentryAppInstallation.objects.filter(
organization_id=self.organization.id, sentry_app=self.sentry_app
)
def test_uninstallation(self) -> None:
self.installation = self.create_sentry_app_installation(
slug=self.sentry_app.slug,
organization=self.organization,
user=self.user,
prevent_token_exchange=True,
)
self.load_page(self.sentry_app.slug)
detail_view_page = OrganizationSentryAppDetailViewPage(browser=self.browser)
detail_view_page.uninstall()
self.browser.wait_until('[data-test-id="toast-success"]')
with self.tasks():
run_scheduled_deletions_control()
assert not SentryAppInstallation.objects.filter(
organization_id=self.organization.id, sentry_app=self.sentry_app
)
|
OrganizationSentryAppDetailedView
|
python
|
ray-project__ray
|
rllib/utils/spaces/flexdict.py
|
{
"start": 88,
"end": 1298
}
|
class ____(gym.spaces.Dict):
"""Gym Dictionary with arbitrary keys updatable after instantiation
Example:
space = FlexDict({})
space['key'] = spaces.Box(4,)
See also: documentation for gym.spaces.Dict
"""
def __init__(self, spaces=None, **spaces_kwargs):
err = "Use either Dict(spaces=dict(...)) or Dict(foo=x, bar=z)"
assert (spaces is None) or (not spaces_kwargs), err
if spaces is None:
spaces = spaces_kwargs
for space in spaces.values():
self.assertSpace(space)
super().__init__(spaces=spaces)
def assertSpace(self, space):
err = "Values of the dict should be instances of gym.Space"
assert issubclass(type(space), gym.spaces.Space), err
def sample(self):
return {k: space.sample() for k, space in self.spaces.items()}
def __getitem__(self, key):
return self.spaces[key]
def __setitem__(self, key, space):
self.assertSpace(space)
self.spaces[key] = space
def __repr__(self):
return (
"FlexDict("
+ ", ".join([str(k) + ":" + str(s) for k, s in self.spaces.items()])
+ ")"
)
|
FlexDict
|
python
|
getlogbook__logbook
|
src/logbook/handlers.py
|
{
"start": 23692,
"end": 25688
}
|
class ____(FileHandler):
def __init__(
self,
filename,
encoding=None,
level=NOTSET,
format_string=None,
delay=False,
filter=None,
bubble=False,
compression_window_size=4 * 1024**2,
compression_quality=11,
):
super().__init__(
filename,
mode="wb",
encoding=encoding,
level=level,
format_string=format_string,
delay=delay,
filter=filter,
bubble=bubble,
)
try:
import brotlicffi as brotli
except ImportError:
try:
import brotli
except ImportError:
raise RuntimeError(
"The brotli/brotlicffi library is required for the "
"BrotliCompressionHandler."
)
max_window_size = int(math.log(compression_window_size, 2))
self._compressor = brotli.Compressor(
quality=compression_quality, lgwin=max_window_size
)
def _open(self, mode=None):
if mode is None:
mode = self._mode
self.stream = open(self._filename, mode)
def write(self, item):
if isinstance(item, str):
item = item.encode(encoding=self.encoding)
if ret := self._compressor.process(item):
self.ensure_stream_is_open()
self.stream.write(ret)
super().flush()
def should_flush(self):
return False
def flush(self):
if self._compressor is not None:
if ret := self._compressor.flush():
self.ensure_stream_is_open()
self.stream.write(ret)
super().flush()
def close(self):
if self._compressor is not None:
self.ensure_stream_is_open()
self.stream.write(self._compressor.finish())
self._compressor = None
super().close()
|
BrotliCompressionHandler
|
python
|
pytorch__pytorch
|
torch/_inductor/runtime/hints.py
|
{
"start": 3720,
"end": 5481
}
|
class ____(typing.NamedTuple):
"""Copy device properties into a data structure not requiring torch to be imported"""
type: str # type: ignore[assignment]
index: int # type: ignore[assignment]
multi_processor_count: int
cc: int
major: int | None = None
regs_per_multiprocessor: int | None = None
max_threads_per_multi_processor: int | None = None
warp_size: int | None = None
@classmethod
@functools.cache
def create(cls, device) -> DeviceProperties:
import torch
from torch._dynamo.device_interface import get_interface_for_device
device_type = device.type
if torch.version.hip and device_type == "cuda":
device_type = "hip"
device_interface = get_interface_for_device(device)
props = device_interface.get_device_properties(device)
try:
multi_processor_count = props.multi_processor_count
except AttributeError:
if device_type == "xpu":
multi_processor_count = props.gpu_subslice_count
elif device_type == "mtia":
multi_processor_count = 64
else:
raise
return cls(
type=device_type,
index=device.index,
multi_processor_count=multi_processor_count,
cc=device_interface.get_compute_capability(device),
major=getattr(props, "major", None),
regs_per_multiprocessor=getattr(props, "regs_per_multiprocessor", None),
max_threads_per_multi_processor=getattr(
props, "max_threads_per_multi_processor", None
),
warp_size=getattr(props, "warp_size", 32 if device_type != "cpu" else None),
)
|
DeviceProperties
|
python
|
scipy__scipy
|
benchmarks/benchmarks/optimize_linprog.py
|
{
"start": 5488,
"end": 6929
}
|
class ____(Benchmark):
params = [
methods,
problems
]
param_names = ['method', 'problems']
def setup(self, meth, prob):
if prob not in enabled_problems:
raise NotImplementedError("skipped")
dir_path = os.path.dirname(os.path.realpath(__file__))
datafile = os.path.join(dir_path, "linprog_benchmark_files",
prob + ".npz")
data = np.load(datafile, allow_pickle=True)
self.c = data["c"]
self.A_eq = data["A_eq"]
self.A_ub = data["A_ub"]
self.b_ub = data["b_ub"]
self.b_eq = data["b_eq"]
self.bounds = np.squeeze(data["bounds"])
self.obj = float(data["obj"].flatten()[0])
self.fun = None
def time_netlib(self, meth, prob):
method, options = meth
res = linprog(c=self.c,
A_ub=self.A_ub,
b_ub=self.b_ub,
A_eq=self.A_eq,
b_eq=self.b_eq,
bounds=self.bounds,
method=method,
options=options)
self.fun = res.fun
def track_netlib(self, meth, prob):
if self.fun is None:
self.time_netlib(meth, prob)
self.abs_error = np.abs(self.fun - self.obj)
self.rel_error = np.abs((self.fun - self.obj)/self.obj)
return min(self.abs_error, self.rel_error)
|
Netlib
|
python
|
pytorch__pytorch
|
test/inductor/test_torchinductor_strided_blocks.py
|
{
"start": 51067,
"end": 51548
}
|
class ____(BlockDescriptorTestBase):
device = GPU_TYPE
test_torchinductor.copy_tests(CommonTemplate, TritonBlockPointerTestGPU, GPU_TYPE)
@unittest.skipIf(
not (
HAS_CUDA_AND_TRITON
and torch.cuda.get_device_capability()[0] >= 9
and torch.version.hip is None
),
"Requires Triton CUDA backend and CUDA compute capability >= 9.0",
)
@config.patch({"triton.use_tensor_descriptor": True, "assume_aligned_inputs": True})
|
TritonBlockPointerTestGPU
|
python
|
astropy__astropy
|
astropy/table/ndarray_mixin.py
|
{
"start": 599,
"end": 2118
}
|
class ____(np.ndarray):
"""
Mixin column class to allow storage of arbitrary numpy
ndarrays within a Table. This is a subclass of numpy.ndarray
and has the same initialization options as ``np.array()``.
"""
info = NdarrayMixinInfo()
def __new__(cls, obj, *args, **kwargs):
self = np.array(obj, *args, **kwargs).view(cls)
if "info" in getattr(obj, "__dict__", ()):
self.info = obj.info
return self
def __array_finalize__(self, obj):
if obj is None:
return
super().__array_finalize__(obj)
# Self was created from template (e.g. obj[slice] or (obj * 2))
# or viewcast e.g. obj.view(Column). In either case we want to
# init Column attributes for self from obj if possible.
if "info" in getattr(obj, "__dict__", ()):
self.info = obj.info
def __reduce__(self):
# patch to pickle NdArrayMixin objects (ndarray subclasses), see
# http://www.mail-archive.com/numpy-discussion@scipy.org/msg02446.html
object_state = list(super().__reduce__())
object_state[2] = (object_state[2], self.__dict__)
return tuple(object_state)
def __setstate__(self, state):
# patch to unpickle NdarrayMixin objects (ndarray subclasses), see
# http://www.mail-archive.com/numpy-discussion@scipy.org/msg02446.html
nd_state, own_state = state
super().__setstate__(nd_state)
self.__dict__.update(own_state)
|
NdarrayMixin
|
python
|
django__django
|
tests/basic/tests.py
|
{
"start": 30361,
"end": 33035
}
|
class ____(TestCase):
def test_select_on_save(self):
a1 = Article.objects.create(pub_date=datetime.now())
with self.assertNumQueries(1):
a1.save()
asos = ArticleSelectOnSave.objects.create(pub_date=datetime.now())
with self.assertNumQueries(2):
asos.save()
with self.assertNumQueries(1):
asos.save(force_update=True)
Article.objects.all().delete()
with self.assertRaisesMessage(
DatabaseError, "Forced update did not affect any rows."
):
with self.assertNumQueries(1):
asos.save(force_update=True)
def test_select_on_save_lying_update(self):
"""
select_on_save works correctly if the database doesn't return correct
information about matched rows from UPDATE.
"""
# Change the manager to not return "row matched" for update().
# We are going to change the Article's _base_manager class
# dynamically. This is a bit of a hack, but it seems hard to
# test this properly otherwise. Article's manager, because
# proxy models use their parent model's _base_manager.
orig_class = Article._base_manager._queryset_class
class FakeQuerySet(models.QuerySet):
# Make sure the _update method below is in fact called.
called = False
def _update(self, *args, **kwargs):
FakeQuerySet.called = True
super()._update(*args, **kwargs)
return 0
try:
Article._base_manager._queryset_class = FakeQuerySet
asos = ArticleSelectOnSave.objects.create(pub_date=datetime.now())
with self.assertNumQueries(3):
asos.save()
self.assertTrue(FakeQuerySet.called)
# This is not wanted behavior, but this is how Django has always
# behaved for databases that do not return correct information
# about matched rows for UPDATE.
with self.assertRaisesMessage(
DatabaseError, "Forced update did not affect any rows."
):
asos.save(force_update=True)
msg = (
"An error occurred in the current transaction. You can't "
"execute queries until the end of the 'atomic' block."
)
with self.assertRaisesMessage(DatabaseError, msg) as cm:
asos.save(update_fields=["pub_date"])
self.assertIsInstance(cm.exception.__cause__, DatabaseError)
finally:
Article._base_manager._queryset_class = orig_class
|
SelectOnSaveTests
|
python
|
sqlalchemy__sqlalchemy
|
lib/sqlalchemy/dialects/oracle/vector.py
|
{
"start": 523,
"end": 891
}
|
class ____(Enum):
"""Enum representing different types of VECTOR index structures.
See :ref:`oracle_vector_datatype` for background.
.. versionadded:: 2.0.41
"""
HNSW = "HNSW"
"""
The HNSW (Hierarchical Navigable Small World) index type.
"""
IVF = "IVF"
"""
The IVF (Inverted File Index) index type
"""
|
VectorIndexType
|
python
|
django__django
|
django/contrib/gis/gdal/field.py
|
{
"start": 4884,
"end": 5212
}
|
class ____(Field):
@property
def value(self):
"Return a Python `date` object for the OFTDate field."
try:
yy, mm, dd, hh, mn, ss, tz = self.as_datetime()
return date(yy.value, mm.value, dd.value)
except (TypeError, ValueError, GDALException):
return None
|
OFTDate
|
python
|
dagster-io__dagster
|
python_modules/automation/automation_tests/dagster_docs_tests/test_fixtures/test_public_class.py
|
{
"start": 298,
"end": 1688
}
|
class ____:
"""A public class with mixed public and non-public methods."""
@public
def public_instance_method(self):
"""This is a public instance method that should be validated."""
return "public_instance"
def non_public_instance_method(self):
"""This is a non-public instance method that should NOT be validated."""
return "non_public_instance"
@staticmethod
@public
def public_static_method():
"""This is a public static method that should be validated."""
return "public_static"
@staticmethod
def non_public_static_method():
"""This is a non-public static method that should NOT be validated."""
return "non_public_static"
@classmethod
@public
def public_class_method(cls):
"""This is a public class method that should be validated."""
return "public_class"
@classmethod
def non_public_class_method(cls):
"""This is a non-public class method that should NOT be validated."""
return "non_public_class"
@property
@public
def public_property(self):
"""This is a public property that should be validated."""
return "public_property"
@property
def non_public_property(self):
"""This is a non-public property that should NOT be validated."""
return "non_public_property"
|
PublicClass
|
python
|
astropy__astropy
|
astropy/utils/masked/tests/test_function_helpers.py
|
{
"start": 41444,
"end": 43614
}
|
class ____(MaskedArraySetup):
def test_interp(self):
xp = np.arange(5.0)
fp = np.array([1.0, 5.0, 6.0, 19.0, 20.0])
mask_fp = np.array([False, False, False, True, False])
mfp = Masked(fp, mask=mask_fp)
x = np.array([1.5, 17.0])
mask_x = np.array([False, True])
mx = Masked(x, mask=mask_x)
out = np.interp(mx, xp, mfp)
expected = np.interp(x, xp[~mask_fp], fp[~mask_fp])
assert_array_equal(out.unmasked, expected)
assert_array_equal(out.mask, mask_x)
def test_piecewise(self):
condlist = [self.a < 1, self.a >= 1]
out = np.piecewise(self.ma, condlist, [Masked(-1, mask=True), 1.0])
expected = np.piecewise(self.a, condlist, [-1, 1.0])
expected_mask = np.piecewise(self.mask_a, condlist, [True, False])
assert_array_equal(out.unmasked, expected)
assert_array_equal(out.mask, expected_mask)
condlist2 = [self.a < 1, self.a >= 3]
out2 = np.piecewise(
self.ma,
condlist2,
[Masked(-1, True), 1, lambda x: Masked(np.full_like(x, 2.0), mask=~x.mask)],
)
expected = np.piecewise(self.a, condlist2, [-1, 1, 2])
expected_mask = np.piecewise(
self.mask_a, condlist2, [True, False, lambda x: ~x]
)
assert_array_equal(out2.unmasked, expected)
assert_array_equal(out2.mask, expected_mask)
with pytest.raises(ValueError, match="with 2 condition"):
np.piecewise(self.ma, condlist2, [])
def test_regression_12978(self):
"""Regression tests for https://github.com/astropy/astropy/pull/12978"""
# This case produced incorrect results
mask = [False, True, False]
x = np.array([1, 2, 3])
xp = Masked(np.array([1, 2, 3]), mask=mask)
fp = Masked(np.array([1, 2, 3]), mask=mask)
result = np.interp(x, xp, fp)
assert_array_equal(result, x)
# This case raised a ValueError
xp = np.array([1, 3])
fp = Masked(np.array([1, 3]))
result = np.interp(x, xp, fp)
assert_array_equal(result, x)
|
TestInterpolationFunctions
|
python
|
pypa__warehouse
|
warehouse/subscriptions/services.py
|
{
"start": 11520,
"end": 13360
}
|
class ____(GenericBillingService):
@classmethod
def create_service(cls, context, request):
# Override api_base to hit mock-stripe in development
stripe.api_base = request.registry.settings["billing.api_base"]
stripe.api_version = request.registry.settings["billing.api_version"]
stripe.api_key = "sk_test_123"
publishable_key = "pk_test_123"
webhook_secret = "whsec_123"
domain = "localhost"
return cls(stripe, publishable_key, webhook_secret, domain)
def create_customer(self, name, description):
# Mock Stripe doesn't return a customer_id so create a mock id by default
customer = super().create_customer(name, description)
customer["id"] = "mockcus_" + "".join(
random.choices(digits + ascii_letters, k=14)
)
return customer
def get_checkout_session(self, session_id, mock_checkout_session={}, **kwargs):
# Mock Stripe doesn't persist data so allow passing in a mock_checkout_session.
checkout_session = super().get_checkout_session(session_id)
# Fill in customer ID, status, and subscription ID from mock_checkout_session.
checkout_session["customer"]["id"] = mock_checkout_session.get(
"customer", checkout_session["customer"]["id"]
)
checkout_session["customer"]["email"] = mock_checkout_session.get(
"customer_email", checkout_session["customer"]["email"]
)
checkout_session["status"] = mock_checkout_session.get(
"status", checkout_session["status"]
)
checkout_session["subscription"]["id"] = mock_checkout_session.get(
"subscription", checkout_session["subscription"]["id"]
)
return checkout_session
@implementer(IBillingService)
|
MockStripeBillingService
|
python
|
kamyu104__LeetCode-Solutions
|
Python/count-equal-and-divisible-pairs-in-an-array.py
|
{
"start": 1735,
"end": 2129
}
|
class ____(object):
def countPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
idxs = collections.defaultdict(list)
for i, x in enumerate(nums):
idxs[x].append(i)
return sum(idx[i]*idx[j]%k == 0 for idx in idxs.itervalues() for i in xrange(len(idx)) for j in xrange(i+1, len(idx)))
|
Solution3
|
python
|
sqlalchemy__sqlalchemy
|
lib/sqlalchemy/dialects/postgresql/types.py
|
{
"start": 2281,
"end": 2407
}
|
class ____(_NetworkAddressTypeMixin, sqltypes.TypeEngine[str]):
__visit_name__ = "MACADDR8"
PGMacAddr8 = MACADDR8
|
MACADDR8
|
python
|
allegroai__clearml
|
clearml/backend_api/services/v2_9/models.py
|
{
"start": 67385,
"end": 72076
}
|
class ____(Response):
"""
Response of models.get_by_task_id endpoint.
:param model: Model info
:type model: Model
"""
_service = "models"
_action = "get_by_task_id"
_version = "2.9"
_schema = {
"definitions": {
"model": {
"properties": {
"comment": {
"description": "Model comment",
"type": ["string", "null"],
},
"company": {
"description": "Company id",
"type": ["string", "null"],
},
"created": {
"description": "Model creation time",
"format": "date-time",
"type": ["string", "null"],
},
"design": {
"additionalProperties": True,
"description": "Json object representing the model design. Should be identical to the network design of the task which created the model",
"type": ["object", "null"],
},
"framework": {
"description": "Framework on which the model is based. Should be identical to the framework of the task which created the model",
"type": ["string", "null"],
},
"id": {"description": "Model id", "type": ["string", "null"]},
"labels": {
"additionalProperties": {"type": "integer"},
"description": "Json object representing the ids of the labels in the model. The keys are the layers' names and the values are the ids.",
"type": ["object", "null"],
},
"name": {"description": "Model name", "type": ["string", "null"]},
"parent": {
"description": "Parent model ID",
"type": ["string", "null"],
},
"project": {
"description": "Associated project ID",
"type": ["string", "null"],
},
"ready": {
"description": "Indication if the model is final and can be used by other tasks",
"type": ["boolean", "null"],
},
"system_tags": {
"description": "System tags. This field is reserved for system use, please don't use it.",
"items": {"type": "string"},
"type": ["array", "null"],
},
"tags": {
"description": "User-defined tags",
"items": {"type": "string"},
"type": ["array", "null"],
},
"task": {
"description": "Task ID of task in which the model was created",
"type": ["string", "null"],
},
"ui_cache": {
"additionalProperties": True,
"description": "UI cache for this model",
"type": ["object", "null"],
},
"uri": {
"description": "URI for the model, pointing to the destination storage.",
"type": ["string", "null"],
},
"user": {
"description": "Associated user id",
"type": ["string", "null"],
},
},
"type": "object",
}
},
"properties": {
"model": {
"description": "Model info",
"oneOf": [{"$ref": "#/definitions/model"}, {"type": "null"}],
}
},
"type": "object",
}
def __init__(self, model: Any = None, **kwargs: Any) -> None:
super(GetByTaskIdResponse, self).__init__(**kwargs)
self.model = model
@schema_property("model")
def model(self) -> Any:
return self._property_model
@model.setter
def model(self, value: Any) -> None:
if value is None:
self._property_model = None
return
if isinstance(value, dict):
value = Model.from_dict(value)
else:
self.assert_isinstance(value, "model", Model)
self._property_model = value
|
GetByTaskIdResponse
|
python
|
apache__airflow
|
airflow-core/src/airflow/ti_deps/deps/mapped_task_upstream_dep.py
|
{
"start": 1490,
"end": 4744
}
|
class ____(BaseTIDep):
"""
Determines if the task, if mapped, is allowed to run based on its mapped dependencies.
In particular, check if upstream tasks that provide XComs used by this task for task mapping are in
states that allow the task instance to run.
"""
NAME = "Mapped dependencies have succeeded"
IGNORABLE = True
IS_TASK_DEP = True
def _get_dep_statuses(
self,
ti: TaskInstance,
session: Session,
dep_context: DepContext,
) -> Iterator[TIDepStatus]:
from airflow.models.mappedoperator import is_mapped
from airflow.models.taskinstance import TaskInstance
if ti.task is None:
return
elif is_mapped(ti.task):
mapped_dependencies = ti.task.iter_mapped_dependencies()
elif (task_group := ti.task.get_closest_mapped_task_group()) is not None:
mapped_dependencies = task_group.iter_mapped_dependencies()
else:
return
# Get the tis of all mapped dependencies. In case a mapped dependency is itself mapped, we are
# only interested in it if it hasn't been expanded yet, i.e., we filter by map_index=-1. This is
# because if it has been expanded, it did not fail and was not skipped outright which is all we need
# to know for the purposes of this check.
mapped_dependency_tis = (
session.scalars(
select(TaskInstance).where(
TaskInstance.task_id.in_(operator.task_id for operator in mapped_dependencies),
TaskInstance.dag_id == ti.dag_id,
TaskInstance.run_id == ti.run_id,
TaskInstance.map_index == -1,
)
).all()
if mapped_dependencies
else []
)
if not mapped_dependency_tis:
yield self._passing_status(reason="There are no (unexpanded) mapped dependencies!")
return
finished_states = {ti.state for ti in mapped_dependency_tis if ti.state in State.finished}
if not finished_states:
return
if finished_states == {TaskInstanceState.SUCCESS}:
# Mapped dependencies are at least partially done and only feature successes
return
# At least one mapped dependency was not successful
if ti.state not in {TaskInstanceState.FAILED, TaskInstanceState.UPSTREAM_FAILED}:
# If another dependency (such as the trigger rule dependency) has not already marked the task as
# FAILED or UPSTREAM_FAILED then we update the state
new_state = None
if (
TaskInstanceState.FAILED in finished_states
or TaskInstanceState.UPSTREAM_FAILED in finished_states
):
new_state = TaskInstanceState.UPSTREAM_FAILED
elif TaskInstanceState.SKIPPED in finished_states:
new_state = TaskInstanceState.SKIPPED
if new_state is not None and ti.set_state(new_state, session):
dep_context.have_changed_ti_states = True
yield self._failing_status(reason="At least one of task's mapped dependencies has not succeeded!")
|
MappedTaskUpstreamDep
|
python
|
pandas-dev__pandas
|
pandas/tests/io/formats/test_to_latex.py
|
{
"start": 5082,
"end": 7609
}
|
class ____:
def test_to_latex_empty_longtable(self):
df = DataFrame()
result = df.to_latex(longtable=True)
expected = _dedent(
r"""
\begin{longtable}{l}
\toprule
\midrule
\endfirsthead
\toprule
\midrule
\endhead
\midrule
\multicolumn{0}{r}{Continued on next page} \\
\midrule
\endfoot
\bottomrule
\endlastfoot
\end{longtable}
"""
)
assert result == expected
def test_to_latex_longtable_with_index(self):
df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})
result = df.to_latex(longtable=True)
expected = _dedent(
r"""
\begin{longtable}{lrl}
\toprule
& a & b \\
\midrule
\endfirsthead
\toprule
& a & b \\
\midrule
\endhead
\midrule
\multicolumn{3}{r}{Continued on next page} \\
\midrule
\endfoot
\bottomrule
\endlastfoot
0 & 1 & b1 \\
1 & 2 & b2 \\
\end{longtable}
"""
)
assert result == expected
def test_to_latex_longtable_without_index(self):
df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})
result = df.to_latex(index=False, longtable=True)
expected = _dedent(
r"""
\begin{longtable}{rl}
\toprule
a & b \\
\midrule
\endfirsthead
\toprule
a & b \\
\midrule
\endhead
\midrule
\multicolumn{2}{r}{Continued on next page} \\
\midrule
\endfoot
\bottomrule
\endlastfoot
1 & b1 \\
2 & b2 \\
\end{longtable}
"""
)
assert result == expected
@pytest.mark.parametrize(
"df_data, expected_number",
[
({"a": [1, 2]}, 1),
({"a": [1, 2], "b": [3, 4]}, 2),
({"a": [1, 2], "b": [3, 4], "c": [5, 6]}, 3),
],
)
def test_to_latex_longtable_continued_on_next_page(self, df_data, expected_number):
df = DataFrame(df_data)
result = df.to_latex(index=False, longtable=True)
assert rf"\multicolumn{{{expected_number}}}" in result
|
TestToLatexLongtable
|
python
|
pytorch__pytorch
|
test/distributed/pipelining/test_schedule.py
|
{
"start": 2140,
"end": 9166
}
|
class ____(TestCase):
def test_get_schedule_class(self):
# List of all expected schedule names
schedule_names = [
"1F1B",
"1f1b",
"Interleaved1F1B",
"INTERLEAVED1F1B",
"GPipe",
"LoopedBFS",
"PipelineScheduleSingle",
"PipelineScheduleMulti",
]
# Test each schedule name
for name in schedule_names:
with self.subTest(name=name):
schedule_class = get_schedule_class(name)
self.assertIsNotNone(
schedule_class, f"Class for {name} should not be None"
)
self.assertTrue(
issubclass(schedule_class, _PipelineSchedule),
f"{name} should be a subclass of _PipelineSchedule",
)
error_case = ["ScheduleThatDoesNotExist"]
for name in error_case:
# Test that the original name is included in the error message
with self.assertRaisesRegex(ValueError, f"{name}"):
get_schedule_class(name)
@parametrize(
"ScheduleClass",
[
Schedule1F1B,
ScheduleGPipe,
ScheduleInterleaved1F1B,
ScheduleInterleavedZeroBubble,
ScheduleLoopedBFS,
],
)
def test_schedule_with_single_stage(self, ScheduleClass):
"""
Test that schedules with only a single stage work as expected for all schedules.
"""
store = FakeStore()
torch.distributed.init_process_group(
backend="fake", rank=0, world_size=1, store=store
)
d_hid, batch_size = 512, 256
n_stages = 1
device = "cpu"
full_mod = MultiMLP(d_hid, n_layers=n_stages)
full_mod.to(device)
x = torch.randn(batch_size, d_hid, device=device)
ref_mod = copy.deepcopy(full_mod)
with torch.no_grad():
y = ref_mod(x)
# Add a small perturbation
target = y + torch.randn(batch_size, d_hid, device=device)
def loss_fn(y, target):
return torch.nn.functional.cross_entropy(y, target)
# Run reference
for _ in range(2):
ref_mod.zero_grad()
ref_out = ref_mod(x)
ref_loss = loss_fn(ref_out, target)
ref_loss.backward()
submod_name = "layers.0"
stage_module = full_mod.get_submodule(submod_name)
# Create a pipeline stage to wrap that submodule
num_microbatches = 2
stages = [
PipelineStage(
stage_module,
0,
n_stages,
device,
)
]
if issubclass(ScheduleClass, PipelineScheduleSingle):
stages = stages[0]
# Attach to a schedule
schedule = ScheduleClass(
stages,
num_microbatches,
loss_fn=loss_fn,
)
# Run
for _ in range(2):
# Zero gradients
stage_module.zero_grad()
losses = []
out = schedule.step(x, target=target, losses=losses)
# Check output
torch.testing.assert_close(out, ref_out)
# Check loss
# Since the reduction used in the loss function above is "mean", we use
# "mean" here to reduce microbatch losses into a single value too.
pipe_loss = torch.stack(losses).mean()
torch.testing.assert_close(pipe_loss, ref_loss)
# Check gradients
# Get corresponding submodule from reference model
ref_submod = ref_mod.get_submodule(submod_name)
# Check gradients per parameter
for name, p in stage_module.named_parameters():
ref_p = ref_submod.get_parameter(name)
try:
torch.testing.assert_close(p.grad, ref_p.grad, rtol=1e-5, atol=4e-5)
except AssertionError:
print(f"Gradient test failed for {name}: {p.grad} vs {ref_p.grad}")
raise
torch.distributed.destroy_process_group()
@parametrize(
"ScheduleClass",
[
Schedule1F1B,
ScheduleGPipe,
ScheduleInterleaved1F1B,
ScheduleInterleavedZeroBubble,
ScheduleLoopedBFS,
],
)
def test_schedule_eval_then_train(self, ScheduleClass):
"""
Test that simply runs evaluation followed by training.
"""
store = FakeStore()
torch.distributed.init_process_group(
backend="fake", rank=0, world_size=1, store=store
)
d_hid, batch_size = 512, 256
n_stages = 1
device = "cpu"
full_mod = MultiMLP(d_hid, n_layers=n_stages)
full_mod.to(device)
x = torch.randn(batch_size, d_hid, device=device)
target = torch.randn(batch_size, d_hid, device=device)
def loss_fn(y, target):
return torch.nn.functional.cross_entropy(y, target)
submod_name = "layers.0"
stage_module = full_mod.get_submodule(submod_name)
# Create a pipeline stage to wrap that submodule
num_microbatches = 2
stages = [PipelineStage(stage_module, 0, n_stages, device)]
if issubclass(ScheduleClass, PipelineScheduleSingle):
stages = stages[0]
# Attach to a schedule
schedule = ScheduleClass(stages, num_microbatches, loss_fn=loss_fn)
# Run eval
for _ in range(2):
# Zero gradients
stage_module.zero_grad()
losses = []
schedule.eval(x, target=target, losses=losses)
# Run training
try:
for _ in range(2):
losses = []
schedule.step(x, target=target, losses=losses)
finally:
torch.distributed.destroy_process_group()
@parametrize(
"ScheduleClass",
[
ScheduleInterleavedZeroBubble,
ScheduleZBVZeroBubble,
ScheduleDualPipeV,
],
)
def test_zero_bubble_schedule_errors_with_compile(self, ScheduleClass):
"""
Test that zero bubble schedules raise an error when used with torch.compile.
"""
store = FakeStore()
torch.distributed.init_process_group(
backend="fake", rank=0, world_size=1, store=store
)
n_stages = 1
device = torch.device("cpu")
model = MultiMLP(8, n_layers=n_stages)
# full_mod
compiled_model = torch.compile(model)
self.assertTrue(isinstance(compiled_model, OptimizedModule))
stage = PipelineStage(
compiled_model,
0,
n_stages,
device,
)
try:
with self.assertRaises(RuntimeError):
ScheduleClass([stage], 2)
finally:
torch.distributed.destroy_process_group()
instantiate_parametrized_tests(ScheduleTest)
|
ScheduleTest
|
python
|
getsentry__sentry
|
src/sentry/options/manager.py
|
{
"start": 1520,
"end": 2837
}
|
class ____(Enum):
"""
Represent the reason that prevents us from attempting an update
of an option on a specific UpdateChannel.
"""
# The option is registered with the FLAG_PRIORITIZE_DISK flag and it is
# also stored on disk as part of sentry settings. Nobody can update this.
OPTION_ON_DISK = "option_on_disk"
# The option definition is read only. It cannot be updated by anybody.
READONLY = "readonly"
# The option cannot be updated by a specific channel because it is missing
# the required flag.
CHANNEL_NOT_ALLOWED = "channel_not_allowed"
# The option could be updated but it drifted and the channel we are trying
# to update with cannot overwrite.
DRIFTED = "drifted"
# In case there is drift between the value on the external source the
# Options Automator maintains, the Automator is not allowed to overwrite
# the drift in several cases. This map contains the forbidden transitions
# of the last_updated_by column on the storage.
FORBIDDEN_TRANSITIONS = {
UpdateChannel.UNKNOWN: {UpdateChannel.AUTOMATOR},
UpdateChannel.APPLICATION: {UpdateChannel.AUTOMATOR},
UpdateChannel.CLI: {UpdateChannel.AUTOMATOR},
UpdateChannel.KILLSWITCH: {UpdateChannel.AUTOMATOR},
UpdateChannel.ADMIN: {UpdateChannel.AUTOMATOR},
}
|
NotWritableReason
|
python
|
bokeh__bokeh
|
src/bokeh/core/validation/check.py
|
{
"start": 1698,
"end": 1896
}
|
class ____:
error: list[ValidationIssue] = field(default_factory=list)
warning: list[ValidationIssue] = field(default_factory=list)
ValidatorType = Literal["error", "warning"]
|
ValidationIssues
|
python
|
getsentry__sentry
|
tests/snuba/api/endpoints/test_organization_trace_logs.py
|
{
"start": 282,
"end": 14602
}
|
class ____(OrganizationEventsEndpointTestBase):
url_name = "sentry-api-0-organization-trace-logs"
def setUp(self) -> None:
super().setUp()
self.features = {
"organizations:ourlogs-enabled": True,
}
self.login_as(user=self.user)
self.url = reverse(
self.url_name,
kwargs={"organization_id_or_slug": self.organization.slug},
)
def test_no_projects(self) -> None:
response = self.client.get(
self.url,
data={"traceId": uuid4().hex},
format="json",
)
assert response.status_code == 404, response.content
def test_invalid_trace_id(self) -> None:
trace_id_1 = "1" * 32
trace_id_2 = "2" * 32
self.store_ourlogs(
[
self.create_ourlog(
{"body": "foo", "trace_id": trace_id_1},
timestamp=self.ten_mins_ago,
),
self.create_ourlog(
{"body": "bar", "trace_id": trace_id_2},
timestamp=self.ten_mins_ago,
),
]
)
for trace_id in ["1" * 16, "test"]:
response = self.client.get(
self.url,
data={"traceId": trace_id},
format="json",
)
assert response.status_code == 400, response.content
def test_simple(self) -> None:
trace_id_1 = "1" * 32
trace_id_2 = "2" * 32
self.store_ourlogs(
[
self.create_ourlog(
{"body": "foo", "trace_id": trace_id_1},
timestamp=self.ten_mins_ago,
),
self.create_ourlog(
{"body": "bar", "trace_id": trace_id_2},
timestamp=self.ten_mins_ago,
),
]
)
response = self.client.get(
self.url,
data={"traceId": trace_id_1},
format="json",
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
log_data = data[0]
assert log_data["project.id"] == self.project.id
assert log_data["trace"] == trace_id_1
assert log_data["message"] == "foo"
def test_multiple_traces(self) -> None:
trace_id_1 = "1" * 32
trace_id_2 = "2" * 32
self.store_ourlogs(
[
self.create_ourlog(
{"body": "foo", "trace_id": trace_id_1},
timestamp=self.ten_mins_ago,
),
self.create_ourlog(
{"body": "bar", "trace_id": trace_id_2},
timestamp=self.eleven_mins_ago,
),
]
)
response = self.client.get(
self.url,
data={"traceId": [trace_id_1, trace_id_2]},
format="json",
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
log_data = data[0]
assert log_data["project.id"] == self.project.id
assert log_data["trace"] == trace_id_1
assert log_data["message"] == "foo"
log_data = data[1]
assert log_data["project.id"] == self.project.id
assert log_data["trace"] == trace_id_2
assert log_data["message"] == "bar"
def test_sort(self) -> None:
trace_id_1 = "1" * 32
trace_id_2 = "2" * 32
self.store_ourlogs(
[
self.create_ourlog(
{"body": "foo", "trace_id": trace_id_1},
timestamp=self.ten_mins_ago,
),
self.create_ourlog(
{"body": "bar", "trace_id": trace_id_2},
timestamp=self.eleven_mins_ago,
),
]
)
response = self.client.get(
self.url,
data={"traceId": [trace_id_1, trace_id_2], "sort": "timestamp"},
format="json",
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
log_data = data[0]
assert log_data["project.id"] == self.project.id
assert log_data["trace"] == trace_id_2
assert log_data["message"] == "bar"
log_data = data[1]
assert log_data["project.id"] == self.project.id
assert log_data["trace"] == trace_id_1
assert log_data["message"] == "foo"
def test_orderby_validation(self) -> None:
trace_id_1 = "1" * 32
trace_id_2 = "2" * 32
self.store_ourlogs(
[
self.create_ourlog(
{"body": "foo", "trace_id": trace_id_1},
timestamp=self.ten_mins_ago,
),
self.create_ourlog(
{"body": "bar", "trace_id": trace_id_2},
timestamp=self.eleven_mins_ago,
),
]
)
response = self.client.get(
self.url,
data={"traceId": [trace_id_1, trace_id_2], "sort": "foobar"},
format="json",
)
assert response.status_code == 400, response.content
assert "foobar must be one of" in response.data["detail"]
def test_cross_project_query(self) -> None:
trace_id_1 = "1" * 32
trace_id_2 = "2" * 32
project2 = self.create_project(organization=self.organization)
self.store_ourlogs(
[
self.create_ourlog(
{"body": "foo", "trace_id": trace_id_1},
timestamp=self.ten_mins_ago,
),
self.create_ourlog(
{"body": "bar", "trace_id": trace_id_2},
timestamp=self.eleven_mins_ago,
project=project2,
),
]
)
response = self.client.get(
self.url,
data={"traceId": [trace_id_1, trace_id_2]},
format="json",
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
log_data = data[0]
assert log_data["project.id"] == self.project.id
assert log_data["trace"] == trace_id_1
assert log_data["message"] == "foo"
log_data = data[1]
assert log_data["project.id"] == project2.id
assert log_data["trace"] == trace_id_2
assert log_data["message"] == "bar"
def test_query_field(self) -> None:
trace_id_1 = "1" * 32
trace_id_2 = "2" * 32
self.store_ourlogs(
[
self.create_ourlog(
{"body": "foo", "trace_id": trace_id_1},
timestamp=self.ten_mins_ago,
),
self.create_ourlog(
{"body": "bar", "trace_id": trace_id_2},
timestamp=self.ten_mins_ago,
),
]
)
response = self.client.get(
self.url,
data={"traceId": [trace_id_1, trace_id_2], "query": "message:foo"},
format="json",
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
log_data = data[0]
assert log_data["project.id"] == self.project.id
assert log_data["trace"] == trace_id_1
assert log_data["message"] == "foo"
def test_pagelimit(self) -> None:
trace_id = "1" * 32
log = self.create_ourlog(
{"body": "test", "trace_id": trace_id},
timestamp=self.ten_mins_ago,
)
self.store_ourlogs([log])
response = self.client.get(
self.url,
data={
"traceId": trace_id,
"per_page": "9999",
},
format="json",
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["message"] == "test"
response = self.client.get(
self.url,
data={
"traceId": trace_id,
"per_page": "10000",
},
format="json",
)
assert response.status_code == 400
assert response.data["detail"] == "Invalid per_page value. Must be between 1 and 9999."
def test_timestamp_precise_alias_and_orderby(self) -> None:
trace_id = "1" * 32
logs = [
self.create_ourlog(
{"body": "foo", "trace_id": trace_id},
timestamp=self.ten_mins_ago,
)
]
self.store_ourlogs(logs)
with patch("sentry.snuba.rpc_dataset_common.RPCBase._run_table_query") as mock_run_query:
mock_run_query.return_value = {
"data": [
{
# Data not relevant for this test
}
],
"meta": {"fields": {}, "units": {}},
}
response = self.client.get(
self.url,
data={"traceId": trace_id, "sort": "timestamp"},
format="json",
)
assert response.status_code == 200, response.content
mock_run_query.assert_called_once()
call_args = mock_run_query.call_args
query = call_args.args[0]
selected_columns = query.selected_columns
orderby = query.orderby
assert constants.TIMESTAMP_PRECISE_ALIAS in selected_columns
assert orderby == [
constants.TIMESTAMP_ALIAS,
constants.TIMESTAMP_PRECISE_ALIAS,
]
def test_timestamp_precise_alias_and_orderby_desc(self) -> None:
trace_id = "1" * 32
logs = [
self.create_ourlog(
{"body": "foo", "trace_id": trace_id},
timestamp=self.ten_mins_ago,
)
]
self.store_ourlogs(logs)
with patch("sentry.snuba.rpc_dataset_common.RPCBase._run_table_query") as mock_run_query:
mock_run_query.return_value = {
"data": [
{
# Data not relevant for this test
}
],
"meta": {"fields": {}, "units": {}},
}
response = self.client.get(
self.url,
data={"traceId": trace_id, "sort": "-timestamp"},
format="json",
)
assert response.status_code == 200, response.content
mock_run_query.assert_called_once()
call_args = mock_run_query.call_args
query = call_args.args[0]
selected_columns = query.selected_columns
orderby = query.orderby
assert constants.TIMESTAMP_PRECISE_ALIAS in selected_columns
assert orderby == [
f"-{constants.TIMESTAMP_ALIAS}",
f"-{constants.TIMESTAMP_PRECISE_ALIAS}",
]
def test_replay_id_simple(self) -> None:
replay_id = "1" * 32
self.store_ourlogs(
[
self.create_ourlog(
{"body": "foo", "replay_id": replay_id},
timestamp=self.ten_mins_ago,
),
self.create_ourlog(
{"body": "bar", "replay_id": "2" * 32},
timestamp=self.ten_mins_ago,
),
]
)
response = self.client.get(
self.url,
data={"replayId": replay_id},
format="json",
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
log_data = data[0]
assert log_data["project.id"] == self.project.id
assert log_data["message"] == "foo"
def test_replay_id_invalid(self) -> None:
self.store_ourlogs(
[
self.create_ourlog(
{"body": "foo", "replay_id": "1" * 32},
timestamp=self.ten_mins_ago,
),
]
)
for replay_id in ["1" * 16, "test"]:
response = self.client.get(
self.url,
data={"replayId": replay_id},
format="json",
)
assert response.status_code == 400, response.content
def test_trace_and_replay_id_combined(self) -> None:
trace_id = "1" * 32
replay_id = "2" * 32
self.store_ourlogs(
[
self.create_ourlog(
{"body": "trace_log", "trace_id": trace_id},
timestamp=self.ten_mins_ago,
),
self.create_ourlog(
{"body": "replay_log", "replay_id": replay_id},
timestamp=self.eleven_mins_ago,
),
self.create_ourlog(
{"body": "other_log", "trace_id": "3" * 32},
timestamp=self.ten_mins_ago,
),
]
)
response = self.client.get(
self.url,
data={"traceId": trace_id, "replayId": replay_id},
format="json",
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
messages = {log["message"] for log in data}
assert messages == {"trace_log", "replay_log"}
def test_no_trace_or_replay_id(self) -> None:
self.store_ourlogs(
[
self.create_ourlog(
{"body": "foo", "trace_id": "1" * 32},
timestamp=self.ten_mins_ago,
),
]
)
response = self.client.get(
self.url,
data={"project": self.project.id},
format="json",
)
assert response.status_code == 400, response.content
assert "Need to pass at least one traceId or replayId" in response.data["detail"]
|
OrganizationEventsTraceEndpointTest
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.