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
|
readthedocs__readthedocs.org
|
readthedocs/proxito/tests/test_old_redirects.py
|
{
"start": 802,
"end": 5416
}
|
class ____(BaseDocServing):
"""
Test our own internal redirects.
* redirects at / --happens at ``ServeDocs`` view
* redirects on /page/.* --happens at ``URLConf``
* invalid URLs --happens at ``URLConf``
"""
def test_root_url(self):
r = self.client.get("/", headers={"host": "project.dev.readthedocs.io"})
self.assertEqual(r.status_code, 302)
self.assertEqual(
r["Location"],
"http://project.dev.readthedocs.io/en/latest/",
)
def test_root_url_redirect_to_default_version(self):
fixture.get(
Version,
project=self.project,
active=True,
slug="v3.0",
)
self.project.default_version = "v3.0"
self.project.save()
r = self.client.get("/", headers={"host": "project.dev.readthedocs.io"})
self.assertEqual(r.status_code, 302)
self.assertEqual(
r["Location"],
"http://project.dev.readthedocs.io/en/v3.0/",
)
def test_page_on_main_site(self):
r = self.client.get(
"/page/test.html", headers={"host": "project.dev.readthedocs.io"}
)
self.assertEqual(r.status_code, 302)
self.assertEqual(
r["Location"],
"http://project.dev.readthedocs.io/en/latest/test.html",
)
def test_page_redirect_with_query_params(self):
r = self.client.get(
"/page/test.html?foo=bar", headers={"host": "project.dev.readthedocs.io"}
)
self.assertEqual(r.status_code, 302)
self.assertEqual(
r["Location"],
"http://project.dev.readthedocs.io/en/latest/test.html?foo=bar",
)
def test_url_with_nonexistent_slug(self):
# Invalid URL for a not single version project
r = self.client.get(
"/nonexistent/", headers={"host": "project.dev.readthedocs.io"}
)
self.assertEqual(r.status_code, 404)
def test_url_filename_only(self):
# Invalid URL for a not single version project
r = self.client.get(
"/test.html", headers={"host": "project.dev.readthedocs.io"}
)
self.assertEqual(r.status_code, 404)
def test_url_dir_file(self):
# Invalid URL for a not single version project
r = self.client.get(
"/nonexistent_dir/bogus.html",
headers={"host": "project.dev.readthedocs.io"},
)
self.assertEqual(r.status_code, 404)
def test_url_dir_subdir_file(self):
# Invalid language in the URL
r = self.client.get(
"/nonexistent_dir/subdir/bogus.html",
headers={"host": "project.dev.readthedocs.io"},
)
self.assertEqual(r.status_code, 404)
def test_url_lang_file(self):
# Invalid URL missing version
r = self.client.get(
"/en/bogus.html", headers={"host": "project.dev.readthedocs.io"}
)
self.assertEqual(r.status_code, 404)
def test_url_lang_subdir_file(self):
# El Proxito does not check that the file exists when serving it and
# returns a 200, if the file does not exist (we force this with
# ``PTYHON_MEDIA=True``) the handler404 is executed. It will check again
# for the file in the storage and it will fail.
with override_settings(PYTHON_MEDIA=True):
r = self.client.get(
# This URL looks like a valid URL.
# lang=en version=nonexistent_dir
"/en/nonexistent_dir/bogus.html",
headers={"host": "project.dev.readthedocs.io"},
)
self.assertEqual(r.status_code, 404)
def test_root_redirect_with_query_params(self):
r = self.client.get("/?foo=bar", headers={"host": "project.dev.readthedocs.io"})
self.assertEqual(r.status_code, 302)
self.assertEqual(
r["Location"],
"http://project.dev.readthedocs.io/en/latest/?foo=bar",
)
# Use ``PYTHON_MEDIA`` here to raise a 404 when trying to serve the file
# from disk and execute the code for the handler404 (the file does not
# exist). On production, this will happen when trying to serve from
# ``/proxito/ internal`` location
# NOTE: this could be achieved by mocking ``_serve_docs_nginx`` to raise a
# 404 directly and avoid using PYTHON_MEDIA.
@override_settings(
PYTHON_MEDIA=True,
PUBLIC_DOMAIN="dev.readthedocs.io",
ROOT_URLCONF="readthedocs.proxito.tests.handler_404_urls",
RTD_EXTERNAL_VERSION_DOMAIN="readthedocs.build",
)
|
InternalRedirectTests
|
python
|
qdrant__qdrant-client
|
qdrant_client/http/models/models.py
|
{
"start": 132304,
"end": 132695
}
|
class ____(BaseModel, extra="forbid"):
languages: Optional[List["Language"]] = Field(
default=None,
description="Set of languages to use for stopwords. Multiple pre-defined lists of stopwords can be combined.",
)
custom: Optional[List[str]] = Field(
default=None, description="Custom stopwords set. Will be merged with the languages set."
)
|
StopwordsSet
|
python
|
getsentry__sentry
|
src/sentry/services/filestore/gcs.py
|
{
"start": 5006,
"end": 5507
}
|
class ____(Blob):
def __init__(self, download_url, *args, **kwargs):
self.download_url = download_url
super().__init__(*args, **kwargs)
def _get_download_url(self, *args, **kwargs):
# media_link is for public objects; we completely ignore it.
download_url = f"{self.download_url}/download/storage/v1{self.path}?alt=media"
if self.generation is not None:
download_url += f"&generation={self.generation:d}"
return download_url
|
FancyBlob
|
python
|
numba__llvmlite
|
llvmlite/binding/value.py
|
{
"start": 854,
"end": 997
}
|
class ____(enum.IntEnum):
# The LLVMDLLStorageClass enum from llvm-c/Core.h
default = 0
dllimport = 1
dllexport = 2
|
StorageClass
|
python
|
sympy__sympy
|
sympy/series/sequences.py
|
{
"start": 13279,
"end": 17244
}
|
class ____(SeqExpr):
"""
Represents a periodic sequence.
The elements are repeated after a given period.
Examples
========
>>> from sympy import SeqPer, oo
>>> from sympy.abc import k
>>> s = SeqPer((1, 2, 3), (0, 5))
>>> s.periodical
(1, 2, 3)
>>> s.period
3
For value at a particular point
>>> s.coeff(3)
1
supports slicing
>>> s[:]
[1, 2, 3, 1, 2, 3]
iterable
>>> list(s)
[1, 2, 3, 1, 2, 3]
sequence starts from negative infinity
>>> SeqPer((1, 2, 3), (-oo, 0))[0:6]
[1, 2, 3, 1, 2, 3]
Periodic formulas
>>> SeqPer((k, k**2, k**3), (k, 0, oo))[0:6]
[0, 1, 8, 3, 16, 125]
See Also
========
sympy.series.sequences.SeqFormula
"""
def __new__(cls, periodical, limits=None):
periodical = sympify(periodical)
def _find_x(periodical):
free = periodical.free_symbols
if len(periodical.free_symbols) == 1:
return free.pop()
else:
return Dummy('k')
x, start, stop = None, None, None
if limits is None:
x, start, stop = _find_x(periodical), 0, S.Infinity
if is_sequence(limits, Tuple):
if len(limits) == 3:
x, start, stop = limits
elif len(limits) == 2:
x = _find_x(periodical)
start, stop = limits
if not isinstance(x, (Symbol, Idx)) or start is None or stop is None:
raise ValueError('Invalid limits given: %s' % str(limits))
if start is S.NegativeInfinity and stop is S.Infinity:
raise ValueError("Both the start and end value"
"cannot be unbounded")
limits = sympify((x, start, stop))
if is_sequence(periodical, Tuple):
periodical = sympify(tuple(flatten(periodical)))
else:
raise ValueError("invalid period %s should be something "
"like e.g (1, 2) " % periodical)
if Interval(limits[1], limits[2]) is S.EmptySet:
return S.EmptySequence
return Basic.__new__(cls, periodical, limits)
@property
def period(self):
return len(self.gen)
@property
def periodical(self):
return self.gen
def _eval_coeff(self, pt):
if self.start is S.NegativeInfinity:
idx = (self.stop - pt) % self.period
else:
idx = (pt - self.start) % self.period
return self.periodical[idx].subs(self.variables[0], pt)
def _add(self, other):
"""See docstring of SeqBase._add"""
if isinstance(other, SeqPer):
per1, lper1 = self.periodical, self.period
per2, lper2 = other.periodical, other.period
per_length = lcm(lper1, lper2)
new_per = []
for x in range(per_length):
ele1 = per1[x % lper1]
ele2 = per2[x % lper2]
new_per.append(ele1 + ele2)
start, stop = self._intersect_interval(other)
return SeqPer(new_per, (self.variables[0], start, stop))
def _mul(self, other):
"""See docstring of SeqBase._mul"""
if isinstance(other, SeqPer):
per1, lper1 = self.periodical, self.period
per2, lper2 = other.periodical, other.period
per_length = lcm(lper1, lper2)
new_per = []
for x in range(per_length):
ele1 = per1[x % lper1]
ele2 = per2[x % lper2]
new_per.append(ele1 * ele2)
start, stop = self._intersect_interval(other)
return SeqPer(new_per, (self.variables[0], start, stop))
def coeff_mul(self, coeff):
"""See docstring of SeqBase.coeff_mul"""
coeff = sympify(coeff)
per = [x * coeff for x in self.periodical]
return SeqPer(per, self.args[1])
|
SeqPer
|
python
|
pytorch__pytorch
|
torch/ao/nn/quantized/modules/conv.py
|
{
"start": 39180,
"end": 43515
}
|
class ____(_ConvTransposeNd):
r"""Applies a 3D transposed convolution operator over an input image
composed of several input planes.
For details on input arguments, parameters, and implementation see
:class:`~torch.nn.ConvTranspose3d`.
.. note:: Currently only the FBGEMM engine is implemented.
Please, set the `torch.backends.quantized.engine = 'fbgemm'`
For special notes, please, see :class:`~torch.ao.nn.quantized.Conv3d`
Attributes:
weight (Tensor): packed tensor derived from the learnable weight
parameter.
scale (Tensor): scalar for the output scale
zero_point (Tensor): scalar for the output zero point
See :class:`~torch.nn.ConvTranspose3d` for other attributes.
Examples::
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
>>> torch.backends.quantized.engine = 'fbgemm'
>>> from torch.ao.nn import quantized as nnq
>>> # With cubic kernels and equal stride
>>> m = nnq.ConvTranspose3d(16, 33, 3, stride=2)
>>> # non-cubic kernels and unequal stride and with padding
>>> m = nnq.ConvTranspose3d(16, 33, (3, 3, 5), stride=(2, 1, 1), padding=(4, 2, 2))
>>> input = torch.randn(20, 16, 50, 100, 100)
>>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
>>> output = m(q_input)
>>> # exact output size can be also specified as an argument
>>> input = torch.randn(1, 16, 12, 12, 12)
>>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
>>> downsample = nnq.Conv3d(16, 16, 3, stride=2, padding=1)
>>> upsample = nnq.ConvTranspose3d(16, 16, 3, stride=2, padding=1)
>>> h = downsample(q_input)
>>> h.size()
torch.Size([1, 16, 6, 6, 6])
>>> # xdoctest: +SKIP("FIXME: output_size is not a parameter)
>>> output = upsample(h, output_size=input.size())
>>> output.size()
torch.Size([1, 16, 12, 12, 12])
"""
_FLOAT_MODULE: ClassVar[type[nn.ConvTranspose3d]] = nn.ConvTranspose3d
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
output_padding=0,
groups=1,
bias=True,
dilation=1,
padding_mode="zeros",
device=None,
dtype=None,
):
factory_kwargs = {"device": device, "dtype": dtype}
kernel_size = _triple(kernel_size)
stride = _triple(stride)
padding = _triple(padding)
dilation = _triple(dilation)
output_padding = _triple(output_padding)
super().__init__(
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation,
True,
output_padding,
groups,
bias,
padding_mode,
**factory_kwargs,
)
def _get_name(self):
return "QuantizedConvTranspose3d"
def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None:
self._packed_params = torch.ops.quantized.conv_transpose3d_prepack(
w,
b,
self.stride,
self.padding,
self.output_padding,
self.dilation,
self.groups,
)
def _weight_bias(self):
w, b = torch.ops.quantized.conv3d_unpack(self._packed_params)
return w, b
def weight(self):
(w, _) = self._weight_bias()
return w
def bias(self):
(_, b) = self._weight_bias()
return b
def forward(self, input):
# Temporarily using len(shape) instead of ndim due to JIT issue
# https://github.com/pytorch/pytorch/issues/23890
if len(input.shape) != 5:
raise ValueError("Input shape must be `(N, C, T, H, W)`!")
return ops.quantized.conv_transpose3d(
input, self._packed_params, self.scale, self.zero_point
)
@classmethod
def from_reference(cls, ref_qconvt, output_scale, output_zero_point): # type: ignore[override]
return _ConvTransposeNd.from_reference(
cls, ref_qconvt, output_scale, output_zero_point
)
|
ConvTranspose3d
|
python
|
walkccc__LeetCode
|
solutions/1366. Rank Teams by Votes/1366.py
|
{
"start": 192,
"end": 587
}
|
class ____:
def rankTeams(self, votes: list[str]) -> str:
teamSize = len(votes[0])
teams = [Team(chr(ord('A') + i), teamSize) for i in range(26)]
for vote in votes:
for i in range(teamSize):
teams[ord(vote[i]) - ord('A')].rank[i] += 1
teams.sort(key=lambda x: (x.rank, -ord(x.name)), reverse=True)
return ''.join(team.name for team in teams[:teamSize])
|
Solution
|
python
|
pyca__cryptography
|
src/cryptography/hazmat/primitives/serialization/pkcs7.py
|
{
"start": 13650,
"end": 13943
}
|
class ____(email.message.MIMEPart):
# A MIMEPart subclass that replicates OpenSSL's behavior of not including
# a newline if there are no headers.
def _write_headers(self, generator) -> None:
if list(self.raw_items()):
generator._write_headers(self)
|
OpenSSLMimePart
|
python
|
great-expectations__great_expectations
|
great_expectations/datasource/fluent/bigquery_datasource.py
|
{
"start": 292,
"end": 886
}
|
class ____(SQLDatasource):
"""Adds a bigquery datasource to the data context.
Args:
name: The name of this big query datasource.
connection_string: The connection string used to connect to the database.
For example: "bigquery://<gcp_project_name>/<bigquery_dataset>"
assets: An optional dictionary whose keys are TableAsset or QueryAsset names and whose
values are TableAsset or QueryAsset objects.
"""
type: Literal["bigquery"] = "bigquery" # type: ignore[assignment]
connection_string: Union[ConfigStr, str]
|
BigQueryDatasource
|
python
|
dask__dask
|
dask/dataframe/dask_expr/_groupby.py
|
{
"start": 24696,
"end": 24918
}
|
class ____(SingleAggregation):
groupby_chunk = staticmethod(_head_chunk)
groupby_aggregate = staticmethod(_head_aggregate)
@classmethod
def combine(cls, inputs, **kwargs):
return _concat(inputs)
|
Head
|
python
|
qdrant__qdrant-client
|
qdrant_client/http/models/models.py
|
{
"start": 4107,
"end": 4269
}
|
class ____(str, Enum):
DEFAULT = "default"
BINARY = "binary"
SCALAR4BITS = "scalar4bits"
SCALAR8BITS = "scalar8bits"
|
BinaryQuantizationQueryEncoding
|
python
|
getsentry__sentry
|
src/sentry/models/groupsearchviewstarred.py
|
{
"start": 580,
"end": 5774
}
|
class ____(BaseManager["GroupSearchViewStarred"]):
def num_starred_views(self, organization: Organization, user_id: int) -> int:
"""
Returns the number of starred views for a user in an organization.
"""
return self.filter(organization=organization, user_id=user_id).count()
def get_starred_view(
self, organization: Organization, user_id: int, view: GroupSearchView
) -> GroupSearchViewStarred | None:
"""
Returns the starred view if it exists, otherwise None.
"""
return self.filter(
organization=organization, user_id=user_id, group_search_view=view
).first()
def reorder_starred_views(
self, organization: Organization, user_id: int, new_view_positions: list[int]
) -> None:
"""
Reorders the positions of starred views for a user in an organization.
Does NOT add or remove starred views.
Args:
organization: The organization the views belong to
user_id: The ID of the user whose starred views are being reordered
new_view_positions: List of view IDs in their new order
Raises:
ValueError: If there's a mismatch between existing starred views and the provided list
"""
existing_starred_views = self.filter(
organization=organization,
user_id=user_id,
)
existing_view_ids = {view.group_search_view_id for view in existing_starred_views}
new_view_ids = set(new_view_positions)
if existing_view_ids != new_view_ids:
raise ValueError("Mismatch between existing and provided starred views.")
position_map = {view_id: idx for idx, view_id in enumerate(new_view_positions)}
views_to_update = list(existing_starred_views)
for view in views_to_update:
view.position = position_map[view.group_search_view_id]
if views_to_update:
self.bulk_update(views_to_update, ["position"])
def insert_starred_view(
self,
organization: Organization,
user_id: int,
view: GroupSearchView,
position: int | None = None,
) -> bool:
"""
Inserts a new starred view into the list at a specific position and
increments the position of all views after the insertion point.
If position is not provided, the view is inserted at the end of the list.
If position is provided, the view is inserted at the specified position.
If the position is greater than the number of existing starred views,
the view is inserted at the end of the list.
Args:
organization: The organization the views belong to
user_id: The ID of the user whose starred views are being updated
view: The view to insert
position: The position to insert the view at
Returns:
True if the view was starred, False if the view was already starred
"""
with transaction.atomic(using=router.db_for_write(GroupSearchViewStarred)):
if self.get_starred_view(organization, user_id, view):
return False
highest_position = self.num_starred_views(organization, user_id)
if position is None or position > highest_position:
position = highest_position
self.filter(
organization=organization,
user_id=user_id,
position__gte=position,
).update(position=models.F("position") + 1)
self.create(
organization=organization,
user_id=user_id,
group_search_view=view,
position=position,
)
return True
def delete_starred_view(
self, organization: Organization, user_id: int, view: GroupSearchView
) -> bool:
"""
Deletes a starred view from the list.
Decrements the position of all views after the deletion point.
Args:
organization: The organization the views belong to
user_id: The ID of the user whose starred views are being updated
view: The view to delete
Returns:
True if the view was unstarred, False if the view was already unstarred
"""
with transaction.atomic(using=router.db_for_write(GroupSearchViewStarred)):
if not (starred_view := self.get_starred_view(organization, user_id, view)):
return False
deleted_position = starred_view.position
starred_view.delete()
self.filter(
organization=organization, user_id=user_id, position__gt=deleted_position
).update(position=models.F("position") - 1)
return True
def clear_starred_view_for_all_members(
self, organization: Organization, view: GroupSearchView
) -> None:
for starred_view in self.filter(organization=organization, group_search_view=view):
self.delete_starred_view(organization, starred_view.user_id, view)
@region_silo_model
|
GroupSearchViewStarredManager
|
python
|
django__django
|
django/contrib/staticfiles/management/commands/collectstatic.py
|
{
"start": 428,
"end": 15970
}
|
class ____(BaseCommand):
"""
Copies or symlinks static files from different locations to the
settings.STATIC_ROOT.
"""
help = "Collect static files in a single location."
requires_system_checks = [Tags.staticfiles]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.copied_files = []
self.symlinked_files = []
self.unmodified_files = []
self.post_processed_files = []
self.skipped_files = []
self.deleted_files = []
self.storage = staticfiles_storage
self.style = no_style()
@cached_property
def local(self):
try:
self.storage.path("")
except NotImplementedError:
return False
return True
def add_arguments(self, parser):
parser.add_argument(
"--noinput",
"--no-input",
action="store_false",
dest="interactive",
help="Do NOT prompt the user for input of any kind.",
)
parser.add_argument(
"--no-post-process",
action="store_false",
dest="post_process",
help="Do NOT post process collected files.",
)
parser.add_argument(
"-i",
"--ignore",
action="append",
default=[],
dest="ignore_patterns",
metavar="PATTERN",
help="Ignore files or directories matching this glob-style "
"pattern. Use multiple times to ignore more.",
)
parser.add_argument(
"-n",
"--dry-run",
action="store_true",
help="Do everything except modify the filesystem.",
)
parser.add_argument(
"-c",
"--clear",
action="store_true",
help="Clear the existing files using the storage "
"before trying to copy or link the original file.",
)
parser.add_argument(
"-l",
"--link",
action="store_true",
help="Create a symbolic link to each file instead of copying.",
)
parser.add_argument(
"--no-default-ignore",
action="store_false",
dest="use_default_ignore_patterns",
help=(
"Don't ignore the common private glob-style patterns (defaults to "
"'CVS', '.*' and '*~')."
),
)
def set_options(self, **options):
"""
Set instance variables based on an options dict
"""
self.interactive = options["interactive"]
self.verbosity = options["verbosity"]
self.symlink = options["link"]
self.clear = options["clear"]
self.dry_run = options["dry_run"]
ignore_patterns = options["ignore_patterns"]
if options["use_default_ignore_patterns"]:
ignore_patterns += apps.get_app_config("staticfiles").ignore_patterns
self.ignore_patterns = list({os.path.normpath(p) for p in ignore_patterns})
self.post_process = options["post_process"]
def collect(self):
"""
Perform the bulk of the work of collectstatic.
Split off from handle() to facilitate testing.
"""
if self.symlink and not self.local:
raise CommandError("Can't symlink to a remote destination.")
if self.clear:
self.clear_dir("")
if self.symlink:
handler = self.link_file
else:
handler = self.copy_file
found_files = {}
for finder in get_finders():
for path, storage in finder.list(self.ignore_patterns):
# Prefix the relative path if the source storage contains it
if getattr(storage, "prefix", None):
prefixed_path = os.path.join(storage.prefix, path)
else:
prefixed_path = path
if prefixed_path not in found_files:
found_files[prefixed_path] = (storage, path)
handler(path, prefixed_path, storage)
else:
self.skipped_files.append(prefixed_path)
self.log(
"Found another file with the destination path '%s'. It "
"will be ignored since only the first encountered file "
"is collected. If this is not what you want, make sure "
"every static file has a unique path." % prefixed_path,
level=2,
)
# Storage backends may define a post_process() method.
if self.post_process and hasattr(self.storage, "post_process"):
processor = self.storage.post_process(found_files, dry_run=self.dry_run)
for original_path, processed_path, processed in processor:
if isinstance(processed, Exception):
self.stderr.write("Post-processing '%s' failed!" % original_path)
# Add a blank line before the traceback, otherwise it's
# too easy to miss the relevant part of the error message.
self.stderr.write()
raise processed
if processed:
self.log(
"Post-processed '%s' as '%s'" % (original_path, processed_path),
level=2,
)
self.post_processed_files.append(original_path)
else:
self.log("Skipped post-processing '%s'" % original_path)
return {
"modified": self.copied_files + self.symlinked_files,
"unmodified": self.unmodified_files,
"post_processed": self.post_processed_files,
"skipped": self.skipped_files,
"deleted": self.deleted_files,
}
def handle(self, **options):
self.set_options(**options)
message = ["\n"]
if self.dry_run:
message.append(
"You have activated the --dry-run option so no files will be "
"modified.\n\n"
)
message.append(
"You have requested to collect static files at the destination\n"
"location as specified in your settings"
)
if self.is_local_storage() and self.storage.location:
destination_path = self.storage.location
message.append(":\n\n %s\n\n" % destination_path)
should_warn_user = self.storage.exists(destination_path) and any(
self.storage.listdir(destination_path)
)
else:
destination_path = None
message.append(".\n\n")
# Destination files existence not checked; play it safe and warn.
should_warn_user = True
if self.interactive and should_warn_user:
if self.clear:
message.append("This will DELETE ALL FILES in this location!\n")
else:
message.append("This will overwrite existing files!\n")
message.append(
"Are you sure you want to do this?\n\n"
"Type 'yes' to continue, or 'no' to cancel: "
)
if input("".join(message)) != "yes":
raise CommandError("Collecting static files cancelled.")
collected = self.collect()
if self.verbosity >= 1:
deleted_count = len(collected["deleted"])
modified_count = len(collected["modified"])
unmodified_count = len(collected["unmodified"])
post_processed_count = len(collected["post_processed"])
skipped_count = len(collected["skipped"])
return (
"\n%(deleted)s%(modified_count)s %(identifier)s %(action)s"
"%(destination)s%(unmodified)s%(post_processed)s%(skipped)s."
) % {
"deleted": (
"%s static file%s deleted, "
% (deleted_count, "" if deleted_count == 1 else "s")
if deleted_count > 0
else ""
),
"modified_count": modified_count,
"identifier": "static file" + ("" if modified_count == 1 else "s"),
"action": "symlinked" if self.symlink else "copied",
"destination": (
" to '%s'" % destination_path if destination_path else ""
),
"unmodified": (
", %s unmodified" % unmodified_count
if collected["unmodified"]
else ""
),
"post_processed": (
collected["post_processed"]
and ", %s post-processed" % post_processed_count
or ""
),
"skipped": (
", %s skipped due to conflict" % skipped_count
if collected["skipped"]
else ""
),
}
def log(self, msg, level=2):
"""
Small log helper
"""
if self.verbosity >= level:
self.stdout.write(msg)
def is_local_storage(self):
return isinstance(self.storage, FileSystemStorage)
def clear_dir(self, path):
"""
Delete the given relative path using the destination storage backend.
"""
if not self.storage.exists(path):
return
dirs, files = self.storage.listdir(path)
for f in files:
fpath = os.path.join(path, f)
if self.dry_run:
self.log("Pretending to delete '%s'" % fpath, level=2)
self.deleted_files.append(fpath)
else:
self.log("Deleting '%s'" % fpath, level=2)
self.deleted_files.append(fpath)
try:
full_path = self.storage.path(fpath)
except NotImplementedError:
self.storage.delete(fpath)
else:
if not os.path.exists(full_path) and os.path.lexists(full_path):
# Delete broken symlinks
os.unlink(full_path)
else:
self.storage.delete(fpath)
for d in dirs:
self.clear_dir(os.path.join(path, d))
def delete_file(self, path, prefixed_path, source_storage):
"""
Check if the target file should be deleted if it already exists.
"""
if self.storage.exists(prefixed_path):
try:
# When was the target file modified last time?
target_last_modified = self.storage.get_modified_time(prefixed_path)
except (OSError, NotImplementedError):
# The storage doesn't support get_modified_time() or failed
pass
else:
try:
# When was the source file modified last time?
source_last_modified = source_storage.get_modified_time(path)
except (OSError, NotImplementedError):
pass
else:
# The full path of the target file
if self.local:
full_path = self.storage.path(prefixed_path)
# If it's --link mode and the path isn't a link (i.e.
# the previous collectstatic wasn't with --link) or if
# it's non-link mode and the path is a link (i.e. the
# previous collectstatic was with --link), the old
# links/files must be deleted so it's not safe to skip
# unmodified files.
can_skip_unmodified_files = not (
self.symlink ^ os.path.islink(full_path)
)
else:
# In remote storages, skipping is only based on the
# modified times since symlinks aren't relevant.
can_skip_unmodified_files = True
# Avoid sub-second precision (see #14665, #19540)
file_is_unmodified = target_last_modified.replace(
microsecond=0
) >= source_last_modified.replace(microsecond=0)
if file_is_unmodified and can_skip_unmodified_files:
if prefixed_path not in self.unmodified_files:
self.unmodified_files.append(prefixed_path)
self.log("Skipping '%s' (not modified)" % path)
return False
# Then delete the existing file if really needed
if self.dry_run:
self.log("Pretending to delete '%s'" % path)
else:
self.log("Deleting '%s'" % path)
self.storage.delete(prefixed_path)
return True
def link_file(self, path, prefixed_path, source_storage):
"""
Attempt to link ``path``
"""
# Skip this file if it was already copied earlier
if prefixed_path in self.symlinked_files:
return self.log("Skipping '%s' (already linked earlier)" % path)
# Delete the target file if needed or break
if not self.delete_file(path, prefixed_path, source_storage):
return
# The full path of the source file
source_path = source_storage.path(path)
# Finally link the file
if self.dry_run:
self.log("Pretending to link '%s'" % source_path, level=1)
else:
self.log("Linking '%s'" % source_path, level=2)
full_path = self.storage.path(prefixed_path)
os.makedirs(os.path.dirname(full_path), exist_ok=True)
try:
if os.path.lexists(full_path):
os.unlink(full_path)
os.symlink(source_path, full_path)
except NotImplementedError:
import platform
raise CommandError(
"Symlinking is not supported in this "
"platform (%s)." % platform.platform()
)
except OSError as e:
raise CommandError(e)
if prefixed_path not in self.symlinked_files:
self.symlinked_files.append(prefixed_path)
def copy_file(self, path, prefixed_path, source_storage):
"""
Attempt to copy ``path`` with storage
"""
# Skip this file if it was already copied earlier
if prefixed_path in self.copied_files:
return self.log("Skipping '%s' (already copied earlier)" % path)
# Delete the target file if needed or break
if not self.delete_file(path, prefixed_path, source_storage):
return
# The full path of the source file
source_path = source_storage.path(path)
# Finally start copying
if self.dry_run:
self.log("Pretending to copy '%s'" % source_path, level=1)
else:
self.log("Copying '%s'" % source_path, level=2)
with source_storage.open(path) as source_file:
self.storage.save(prefixed_path, source_file)
self.copied_files.append(prefixed_path)
|
Command
|
python
|
facebook__pyre-check
|
source/interprocedural_analyses/taint/test/integration/sanitize.py
|
{
"start": 19550,
"end": 20293
}
|
class ____:
def sanitize_sources(self):
self.foo = _test_source()
def sanitize_test_a_source(self):
if 1 > 2:
self.foo = a_source()
else:
self.foo = b_source()
def sanitize_parameter(self):
self.foo = _test_source()
def sanitize_parameter_test_a_source(self):
if 1 > 2:
self.foo = a_source()
else:
self.foo = b_source()
def sanitize_all_parameters(self):
self.foo = _test_source()
def sanitize_all_parameters_test_a_source(self):
if 1 > 2:
self.foo = a_source()
else:
self.foo = b_source()
def sanitize_return(self):
self.foo = _test_source()
|
GenerationOnSelf
|
python
|
sphinx-doc__sphinx
|
sphinx/domains/cpp/_ast.py
|
{
"start": 134143,
"end": 136726
}
|
class ____(ASTTemplateParam):
def __init__(
self, key: str, identifier: ASTIdentifier, parameterPack: bool, default: ASTType
) -> None:
assert key
if parameterPack:
assert default is None
self.key = key
self.identifier = identifier
self.parameterPack = parameterPack
self.default = default
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTTemplateKeyParamPackIdDefault):
return NotImplemented
return (
self.key == other.key
and self.identifier == other.identifier
and self.parameterPack == other.parameterPack
and self.default == other.default
)
def __hash__(self) -> int:
return hash((self.key, self.identifier, self.parameterPack, self.default))
def get_identifier(self) -> ASTIdentifier:
return self.identifier
def get_id(self, version: int) -> str:
assert version >= 2
# this is not part of the normal name mangling in C++
res = []
if self.parameterPack:
res.append('Dp')
else:
res.append('0') # we need to put something
return ''.join(res)
def _stringify(self, transform: StringifyTransform) -> str:
res = [self.key]
if self.parameterPack:
if self.identifier:
res.append(' ')
res.append('...')
if self.identifier:
if not self.parameterPack:
res.append(' ')
res.append(transform(self.identifier))
if self.default:
res.extend((' = ', transform(self.default)))
return ''.join(res)
def describe_signature(
self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol
) -> None:
signode += addnodes.desc_sig_keyword(self.key, self.key)
if self.parameterPack:
if self.identifier:
signode += addnodes.desc_sig_space()
signode += addnodes.desc_sig_punctuation('...', '...')
if self.identifier:
if not self.parameterPack:
signode += addnodes.desc_sig_space()
self.identifier.describe_signature(signode, mode, env, '', '', symbol)
if self.default:
signode += addnodes.desc_sig_space()
signode += addnodes.desc_sig_punctuation('=', '=')
signode += addnodes.desc_sig_space()
self.default.describe_signature(signode, 'markType', env, symbol)
|
ASTTemplateKeyParamPackIdDefault
|
python
|
fluentpython__example-code
|
attic/sequences/table.py
|
{
"start": 2147,
"end": 2638
}
|
class ____(collections.UserList):
def __init__(self, cells):
super().__init__(cells)
if len(self) < 1:
raise ValueError('Row must have at least one cell.')
def __getitem__(self, position):
if isinstance(position, slice):
return Row(self.data[position]) # build sub-row
else:
return self.data[position] # return cell value
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.data)
|
Row
|
python
|
ipython__ipython
|
tests/test_pretty.py
|
{
"start": 881,
"end": 972
}
|
class ____(dict):
def _repr_pretty_(self, p, cycle):
p.text("MyDict(...)")
|
MyDict
|
python
|
plotly__plotly.py
|
plotly/graph_objs/layout/newshape/label/_font.py
|
{
"start": 235,
"end": 9913
}
|
class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.newshape.label"
_path_str = "layout.newshape.label.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser can only apply a font if it is
available on the system where it runs. Provide multiple font
families, separated by commas, to indicate the order in which
to apply fonts if they aren't available.
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
@property
def lineposition(self):
"""
Sets the kind of decoration line(s) with text, such as an
"under", "over" or "through" as well as combinations e.g.
"under+over", etc.
The 'lineposition' property is a flaglist and may be specified
as a string containing:
- Any combination of ['under', 'over', 'through'] joined with '+' characters
(e.g. 'under+over')
OR exactly one of ['none'] (e.g. 'none')
Returns
-------
Any
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
@property
def shadow(self):
"""
Sets the shape and color of the shadow behind text. "auto"
places minimal shadow and applies contrast text font color. See
https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow
for additional options.
The 'shadow' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def style(self):
"""
Sets whether a font should be styled with a normal or italic
face from its family.
The 'style' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'italic']
Returns
-------
Any
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
@property
def textcase(self):
"""
Sets capitalization of text. It can be used to make text appear
in all-uppercase or all-lowercase, or with each word
capitalized.
The 'textcase' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'word caps', 'upper', 'lower']
Returns
-------
Any
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
@property
def variant(self):
"""
Sets the variant of the font.
The 'variant' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'small-caps', 'all-small-caps',
'all-petite-caps', 'petite-caps', 'unicase']
Returns
-------
Any
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
@property
def weight(self):
"""
Sets the weight (or boldness) of the font.
The 'weight' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 1000]
OR exactly one of ['normal', 'bold'] (e.g. 'bold')
Returns
-------
int
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def _prop_descriptions(self):
return """\
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
"""
def __init__(
self,
arg=None,
color=None,
family=None,
lineposition=None,
shadow=None,
size=None,
style=None,
textcase=None,
variant=None,
weight=None,
**kwargs,
):
"""
Construct a new Font object
Sets the new shape label text font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.newshape.label.Font`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
Returns
-------
Font
"""
super().__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.layout.newshape.label.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.newshape.label.Font`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("family", arg, family)
self._set_property("lineposition", arg, lineposition)
self._set_property("shadow", arg, shadow)
self._set_property("size", arg, size)
self._set_property("style", arg, style)
self._set_property("textcase", arg, textcase)
self._set_property("variant", arg, variant)
self._set_property("weight", arg, weight)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
|
Font
|
python
|
microsoft__pyright
|
packages/pyright-internal/src/tests/samples/descriptor1.py
|
{
"start": 2352,
"end": 2648
}
|
class ____[GT, ST]:
@overload
def __get__(self, instance: None, owner: Any) -> Self: ...
@overload
def __get__(self, instance: Any, owner: Any) -> GT: ...
def __get__(self, instance: Any, owner: Any) -> Any: ...
def __set__(self, instance: Any, value: ST): ...
|
Descriptor6
|
python
|
weaviate__weaviate-python-client
|
weaviate/rbac/models.py
|
{
"start": 1522,
"end": 1594
}
|
class ____(TypedDict):
group: str
groupType: str
|
PermissionsGroups
|
python
|
sqlalchemy__sqlalchemy
|
test/orm/test_generative.py
|
{
"start": 6580,
"end": 9733
}
|
class ____(_fixtures.FixtureTest):
run_setup_mappers = "once"
run_inserts = "once"
run_deletes = None
@classmethod
def setup_mappers(cls):
addresses, Order, User, Address, orders, users = (
cls.tables.addresses,
cls.classes.Order,
cls.classes.User,
cls.classes.Address,
cls.tables.orders,
cls.tables.users,
)
cls.mapper_registry.map_imperatively(
User,
users,
properties={
"orders": relationship(
cls.mapper_registry.map_imperatively(
Order,
orders,
properties={
"addresses": relationship(
cls.mapper_registry.map_imperatively(
Address, addresses
)
)
},
)
)
},
)
def test_join(self):
"""Query.join"""
User, Address = self.classes.User, self.classes.Address
Order = self.classes.Order
session = fixture_session()
q = (
session.query(User)
.outerjoin(User.orders)
.outerjoin(Order.addresses)
.filter(Address.id == 1)
)
eq_([User(id=7)], q.all())
def test_outer_join(self):
"""Query.outerjoin"""
Order, User, Address = (
self.classes.Order,
self.classes.User,
self.classes.Address,
)
session = fixture_session()
q = (
session.query(User)
.outerjoin(User.orders)
.outerjoin(Order.addresses)
.filter(sa.or_(Order.id == None, Address.id == 1))
) # noqa
eq_({User(id=7), User(id=8), User(id=10)}, set(q.all()))
def test_outer_join_count(self):
"""test the join and outerjoin functions on Query"""
Order, User, Address = (
self.classes.Order,
self.classes.User,
self.classes.Address,
)
session = fixture_session()
q = (
session.query(User)
.outerjoin(User.orders)
.outerjoin(Order.addresses)
.filter(sa.or_(Order.id == None, Address.id == 1))
) # noqa
eq_(q.count(), 4)
def test_from(self):
users, Order, User, Address, orders, addresses = (
self.tables.users,
self.classes.Order,
self.classes.User,
self.classes.Address,
self.tables.orders,
self.tables.addresses,
)
session = fixture_session()
sel = users.outerjoin(orders).outerjoin(
addresses, orders.c.address_id == addresses.c.id
)
q = (
session.query(User)
.select_from(sel)
.filter(sa.or_(Order.id == None, Address.id == 1))
) # noqa
eq_({User(id=7), User(id=8), User(id=10)}, set(q.all()))
|
RelationshipsTest
|
python
|
pyca__cryptography
|
tests/hazmat/primitives/test_concatkdf.py
|
{
"start": 441,
"end": 5323
}
|
class ____:
def test_length_limit(self, backend):
big_length = hashes.SHA256().digest_size * (2**32 - 1) + 1
error = OverflowError if sys.maxsize <= 2**31 else ValueError
with pytest.raises(error):
ConcatKDFHash(hashes.SHA256(), big_length, None, backend)
def test_already_finalized(self, backend):
ckdf = ConcatKDFHash(hashes.SHA256(), 16, None, backend)
ckdf.derive(b"\x01" * 16)
with pytest.raises(AlreadyFinalized):
ckdf.derive(b"\x02" * 16)
def test_derive(self, backend):
prk = binascii.unhexlify(
b"52169af5c485dcc2321eb8d26d5efa21fb9b93c98e38412ee2484cf14f0d0d23"
)
okm = binascii.unhexlify(b"1c3bc9e7c4547c5191c0d478cccaed55")
oinfo = binascii.unhexlify(
b"a1b2c3d4e53728157e634612c12d6d5223e204aeea4341565369647bd184bcd2"
b"46f72971f292badaa2fe4124612cba"
)
ckdf = ConcatKDFHash(hashes.SHA256(), 16, oinfo, backend)
assert ckdf.derive(prk) == okm
def test_buffer_protocol(self, backend):
prk = binascii.unhexlify(
b"52169af5c485dcc2321eb8d26d5efa21fb9b93c98e38412ee2484cf14f0d0d23"
)
okm = binascii.unhexlify(b"1c3bc9e7c4547c5191c0d478cccaed55")
oinfo = binascii.unhexlify(
b"a1b2c3d4e53728157e634612c12d6d5223e204aeea4341565369647bd184bcd2"
b"46f72971f292badaa2fe4124612cba"
)
ckdf = ConcatKDFHash(hashes.SHA256(), 16, oinfo, backend)
assert ckdf.derive(bytearray(prk)) == okm
def test_verify(self, backend):
prk = binascii.unhexlify(
b"52169af5c485dcc2321eb8d26d5efa21fb9b93c98e38412ee2484cf14f0d0d23"
)
okm = binascii.unhexlify(b"1c3bc9e7c4547c5191c0d478cccaed55")
oinfo = binascii.unhexlify(
b"a1b2c3d4e53728157e634612c12d6d5223e204aeea4341565369647bd184bcd2"
b"46f72971f292badaa2fe4124612cba"
)
ckdf = ConcatKDFHash(hashes.SHA256(), 16, oinfo, backend)
ckdf.verify(prk, okm)
def test_invalid_verify(self, backend):
prk = binascii.unhexlify(
b"52169af5c485dcc2321eb8d26d5efa21fb9b93c98e38412ee2484cf14f0d0d23"
)
oinfo = binascii.unhexlify(
b"a1b2c3d4e53728157e634612c12d6d5223e204aeea4341565369647bd184bcd2"
b"46f72971f292badaa2fe4124612cba"
)
ckdf = ConcatKDFHash(hashes.SHA256(), 16, oinfo, backend)
with pytest.raises(InvalidKey):
ckdf.verify(prk, b"wrong key")
def test_unicode_typeerror(self, backend):
with pytest.raises(TypeError):
ConcatKDFHash(
hashes.SHA256(),
16,
otherinfo="foo", # type: ignore[arg-type]
backend=backend,
)
with pytest.raises(TypeError):
ckdf = ConcatKDFHash(
hashes.SHA256(), 16, otherinfo=None, backend=backend
)
ckdf.derive("foo") # type: ignore[arg-type]
with pytest.raises(TypeError):
ckdf = ConcatKDFHash(
hashes.SHA256(), 16, otherinfo=None, backend=backend
)
ckdf.verify("foo", b"bar") # type: ignore[arg-type]
with pytest.raises(TypeError):
ckdf = ConcatKDFHash(
hashes.SHA256(), 16, otherinfo=None, backend=backend
)
ckdf.verify(b"foo", "bar") # type: ignore[arg-type]
def test_derive_into(self, backend):
prk = binascii.unhexlify(
b"52169af5c485dcc2321eb8d26d5efa21fb9b93c98e38412ee2484cf14f0d0d23"
)
oinfo = binascii.unhexlify(
b"a1b2c3d4e53728157e634612c12d6d5223e204aeea4341565369647bd184bcd2"
b"46f72971f292badaa2fe4124612cba"
)
ckdf = ConcatKDFHash(hashes.SHA256(), 16, oinfo, backend)
buf = bytearray(16)
n = ckdf.derive_into(prk, buf)
assert n == 16
# Verify the output matches what derive would produce
ckdf2 = ConcatKDFHash(hashes.SHA256(), 16, oinfo, backend)
expected = ckdf2.derive(prk)
assert buf == expected
@pytest.mark.parametrize(
("buflen", "outlen"), [(15, 16), (17, 16), (8, 16), (32, 16)]
)
def test_derive_into_buffer_incorrect_size(self, buflen, outlen, backend):
ckdf = ConcatKDFHash(hashes.SHA256(), outlen, None, backend)
buf = bytearray(buflen)
with pytest.raises(ValueError, match="buffer must be"):
ckdf.derive_into(b"key", buf)
def test_derive_into_already_finalized(self, backend):
ckdf = ConcatKDFHash(hashes.SHA256(), 16, None, backend)
buf = bytearray(16)
ckdf.derive_into(b"key", buf)
with pytest.raises(AlreadyFinalized):
ckdf.derive_into(b"key", buf)
|
TestConcatKDFHash
|
python
|
pytorch__pytorch
|
test/dynamo/test_subclasses.py
|
{
"start": 100564,
"end": 102490
}
|
class ____(torch.nn.Module):
def forward(
self,
primals_5: "Sym(s47)", # SubclassSizeAOTInput(base=PlainAOTInput(idx=2), idx=0)
primals_7: "Sym(s16)", # SubclassStrideAOTInput(base=PlainAOTInput(idx=2), idx=0)
tangents_1: "f32[s16*s47]", # SubclassGetAttrAOTInput(base=TangentAOTInput(output=PlainAOTOutput(idx=1)), attr='a')
tangents_2: "f32[s16*s47]", # SubclassGetAttrAOTInput(base=TangentAOTInput(output=PlainAOTOutput(idx=1)), attr='b')
):
view_2: "f32[s47, s16]" = torch.ops.aten.view.default(tangents_1, [primals_5, primals_7]); tangents_1 = None
view_3: "f32[s47, s16]" = torch.ops.aten.view.default(tangents_2, [primals_5, primals_7]); tangents_2 = None
return (
None, # None
None, # None
view_2, # SubclassGetAttrAOTOutput(base=GradAOTOutput(grad_of=PlainAOTInput(idx=2)), attr='a')
view_3, # SubclassGetAttrAOTOutput(base=GradAOTOutput(grad_of=PlainAOTInput(idx=2)), attr='b')
primals_5, # SubclassSizeAOTOutput(base=GradAOTOutput(grad_of=PlainAOTInput(idx=2)), idx=0)
primals_7, # SubclassSizeAOTOutput(base=GradAOTOutput(grad_of=PlainAOTInput(idx=2)), idx=1)
primals_7, # SubclassStrideAOTOutput(base=GradAOTOutput(grad_of=PlainAOTInput(idx=2)), idx=0)
)
""", # noqa: B950
)
@unittest.expectedFailure
def test_tensor_subclass_TwoTensor_return_multiple(self):
def f(tt):
y = tt.clone()
z = tt.clone()
return y.a, y.view(y.shape[0] * y.shape[1]), y.b, z.view(-1)
a = torch.ones(3, 4, requires_grad=True)
b = a.clone()
tt = TwoTensor(a, b)
fw, bw = self._compile_check(f, [(tt,)], dynamic=True, call_backward=True)
self.assertExpectedInline(
normalize_gm(fw[0].print_readable(print_output=False)),
"""\
|
GraphModule
|
python
|
readthedocs__readthedocs.org
|
readthedocs/organizations/tests/test_orgs.py
|
{
"start": 7513,
"end": 9415
}
|
class ____(OrganizationTestCase):
def test_team_add(self):
"""Test member team add form."""
self.add_team(team="foobar")
self.assertEqual(self.organization.teams.count(), 1)
def test_team_add_slug_conflict(self):
"""Add multiple teams with the same slug."""
self.add_team(team="foobar")
self.assertEqual(self.organization.teams.count(), 1)
# Same name, same slug
resp = self.add_team(team="foobar", test=False)
self.assertEqual(self.organization.teams.count(), 1)
self.assertEqual(resp.status_code, 200)
# Different name, same slug
resp = self.add_team(team="FOOBAR", test=False)
self.assertEqual(self.organization.teams.count(), 2)
self.assertEqual(resp.status_code, 302)
self.assertEqual(
resp["location"],
"/organizations/mozilla/teams/foobar-2/",
)
self.assertTrue(self.organization.teams.filter(slug="foobar").exists())
self.assertTrue(
self.organization.teams.filter(slug="foobar-2").exists(),
)
def test_team_delete(self):
"""Test team delete form."""
self.test_team_add()
resp = self.client.post("/organizations/mozilla/teams/foobar/delete/")
self.assertEqual(resp.status_code, 302)
self.assertEqual(self.organization.teams.count(), 0)
self.assertEqual(
resp["location"],
"/organizations/mozilla/teams/",
)
def test_team_delete_regression(self):
"""Regression test old team delete form."""
self.test_team_add()
data = {"team": "foobar"}
resp = self.client.post(
"/organizations/mozilla/teams/delete/",
data=data,
)
self.assertEqual(resp.status_code, 405)
self.assertEqual(self.organization.teams.count(), 1)
|
OrganizationTeamTests
|
python
|
sqlalchemy__sqlalchemy
|
lib/sqlalchemy/orm/descriptor_props.py
|
{
"start": 5814,
"end": 32181
}
|
class ____(
_MapsColumns[_CC], _IntrospectsAnnotations, DescriptorProperty[_CC]
):
"""Defines a "composite" mapped attribute, representing a collection
of columns as one attribute.
:class:`.CompositeProperty` is constructed using the :func:`.composite`
function.
.. seealso::
:ref:`mapper_composite`
"""
composite_class: Union[Type[_CC], Callable[..., _CC]]
attrs: Tuple[_CompositeAttrType[Any], ...]
_generated_composite_accessor: CallableReference[
Optional[Callable[[_CC], Tuple[Any, ...]]]
]
comparator_factory: Type[Comparator[_CC]]
def __init__(
self,
_class_or_attr: Union[
None, Type[_CC], Callable[..., _CC], _CompositeAttrType[Any]
] = None,
*attrs: _CompositeAttrType[Any],
return_none_on: Union[
_NoArg, None, Callable[..., bool]
] = _NoArg.NO_ARG,
attribute_options: Optional[_AttributeOptions] = None,
active_history: bool = False,
deferred: bool = False,
group: Optional[str] = None,
comparator_factory: Optional[Type[Comparator[_CC]]] = None,
info: Optional[_InfoType] = None,
**kwargs: Any,
):
super().__init__(attribute_options=attribute_options)
if isinstance(_class_or_attr, (Mapped, str, sql.ColumnElement)):
self.attrs = (_class_or_attr,) + attrs
# will initialize within declarative_scan
self.composite_class = None # type: ignore
else:
self.composite_class = _class_or_attr # type: ignore
self.attrs = attrs
self.return_none_on = return_none_on
self.active_history = active_history
self.deferred = deferred
self.group = group
self.comparator_factory = (
comparator_factory
if comparator_factory is not None
else self.__class__.Comparator
)
self._generated_composite_accessor = None
if info is not None:
self.info.update(info)
util.set_creation_order(self)
self._create_descriptor()
self._init_accessor()
@util.memoized_property
def _construct_composite(self) -> Callable[..., Any]:
return_none_on = self.return_none_on
if callable(return_none_on):
def construct(*args: Any) -> Any:
if return_none_on(*args):
return None
else:
return self.composite_class(*args)
return construct
else:
return self.composite_class
def instrument_class(self, mapper: Mapper[Any]) -> None:
super().instrument_class(mapper)
self._setup_event_handlers()
def _composite_values_from_instance(self, value: _CC) -> Tuple[Any, ...]:
if self._generated_composite_accessor:
return self._generated_composite_accessor(value)
else:
try:
accessor = value.__composite_values__
except AttributeError as ae:
raise sa_exc.InvalidRequestError(
f"Composite class {self.composite_class.__name__} is not "
f"a dataclass and does not define a __composite_values__()"
" method; can't get state"
) from ae
else:
return accessor() # type: ignore
def do_init(self) -> None:
"""Initialization which occurs after the :class:`.Composite`
has been associated with its parent mapper.
"""
self._setup_arguments_on_columns()
_COMPOSITE_FGET = object()
def _create_descriptor(self) -> None:
"""Create the Python descriptor that will serve as
the access point on instances of the mapped class.
"""
def fget(instance: Any) -> Any:
dict_ = attributes.instance_dict(instance)
state = attributes.instance_state(instance)
if self.key not in dict_:
# key not present. Iterate through related
# attributes, retrieve their values. This
# ensures they all load.
values = [
getattr(instance, key) for key in self._attribute_keys
]
if self.key not in dict_:
dict_[self.key] = self._construct_composite(*values)
state.manager.dispatch.refresh(
state, self._COMPOSITE_FGET, [self.key]
)
return dict_.get(self.key, None)
def fset(instance: Any, value: Any) -> None:
if value is LoaderCallableStatus.DONT_SET:
return
dict_ = attributes.instance_dict(instance)
state = attributes.instance_state(instance)
attr = state.manager[self.key]
if attr.dispatch._active_history:
previous = fget(instance)
else:
previous = dict_.get(self.key, LoaderCallableStatus.NO_VALUE)
for fn in attr.dispatch.set:
value = fn(state, value, previous, attr.impl)
dict_[self.key] = value
if value is None:
for key in self._attribute_keys:
setattr(instance, key, None)
else:
for key, value in zip(
self._attribute_keys,
self._composite_values_from_instance(value),
):
setattr(instance, key, value)
def fdel(instance: Any) -> None:
state = attributes.instance_state(instance)
dict_ = attributes.instance_dict(instance)
attr = state.manager[self.key]
if attr.dispatch._active_history:
previous = fget(instance)
dict_.pop(self.key, None)
else:
previous = dict_.pop(self.key, LoaderCallableStatus.NO_VALUE)
attr = state.manager[self.key]
attr.dispatch.remove(state, previous, attr.impl)
for key in self._attribute_keys:
setattr(instance, key, None)
self.descriptor = property(fget, fset, fdel)
@util.preload_module("sqlalchemy.orm.properties")
def declarative_scan(
self,
decl_scan: _DeclarativeMapperConfig,
registry: _RegistryType,
cls: Type[Any],
originating_module: Optional[str],
key: str,
mapped_container: Optional[Type[Mapped[Any]]],
annotation: Optional[_AnnotationScanType],
extracted_mapped_annotation: Optional[_AnnotationScanType],
is_dataclass_field: bool,
) -> None:
MappedColumn = util.preloaded.orm_properties.MappedColumn
if (
self.composite_class is None
and extracted_mapped_annotation is None
):
self._raise_for_required(key, cls)
argument = extracted_mapped_annotation
if is_pep593(argument):
argument = get_args(argument)[0]
if argument and self.composite_class is None:
if isinstance(argument, str) or is_fwd_ref(
argument, check_generic=True
):
if originating_module is None:
str_arg = (
argument.__forward_arg__
if hasattr(argument, "__forward_arg__")
else str(argument)
)
raise sa_exc.ArgumentError(
f"Can't use forward ref {argument} for composite "
f"class argument; set up the type as Mapped[{str_arg}]"
)
argument = de_stringify_annotation(
cls, argument, originating_module, include_generic=True
)
if is_union(argument) and includes_none(argument):
if self.return_none_on is _NoArg.NO_ARG:
self.return_none_on = lambda *args: all(
arg is None for arg in args
)
argument = de_optionalize_union_types(argument)
self.composite_class = argument
if is_dataclass(self.composite_class):
self._setup_for_dataclass(
decl_scan, registry, cls, originating_module, key
)
else:
for attr in self.attrs:
if (
isinstance(attr, (MappedColumn, schema.Column))
and attr.name is None
):
raise sa_exc.ArgumentError(
"Composite class column arguments must be named "
"unless a dataclass is used"
)
self._init_accessor()
def _init_accessor(self) -> None:
if is_dataclass(self.composite_class) and not hasattr(
self.composite_class, "__composite_values__"
):
insp = inspect.signature(self.composite_class)
getter = operator.attrgetter(
*[p.name for p in insp.parameters.values()]
)
if len(insp.parameters) == 1:
self._generated_composite_accessor = lambda obj: (getter(obj),)
else:
self._generated_composite_accessor = getter
if (
self.composite_class is not None
and isinstance(self.composite_class, type)
and self.composite_class not in _composite_getters
):
if self._generated_composite_accessor is not None:
_composite_getters[self.composite_class] = (
self._generated_composite_accessor
)
elif hasattr(self.composite_class, "__composite_values__"):
_composite_getters[self.composite_class] = (
lambda obj: obj.__composite_values__()
)
@util.preload_module("sqlalchemy.orm.properties")
@util.preload_module("sqlalchemy.orm.decl_base")
def _setup_for_dataclass(
self,
decl_scan: _DeclarativeMapperConfig,
registry: _RegistryType,
cls: Type[Any],
originating_module: Optional[str],
key: str,
) -> None:
MappedColumn = util.preloaded.orm_properties.MappedColumn
decl_base = util.preloaded.orm_decl_base
insp = inspect.signature(self.composite_class)
for param, attr in itertools.zip_longest(
insp.parameters.values(), self.attrs
):
if param is None:
raise sa_exc.ArgumentError(
f"number of composite attributes "
f"{len(self.attrs)} exceeds "
f"that of the number of attributes in class "
f"{self.composite_class.__name__} {len(insp.parameters)}"
)
if attr is None:
# fill in missing attr spots with empty MappedColumn
attr = MappedColumn()
self.attrs += (attr,)
if isinstance(attr, MappedColumn):
attr.declarative_scan_for_composite(
decl_scan,
registry,
cls,
originating_module,
key,
param.name,
param.annotation,
)
elif isinstance(attr, schema.Column):
decl_base._undefer_column_name(param.name, attr)
@util.memoized_property
def _comparable_elements(self) -> Sequence[QueryableAttribute[Any]]:
return [getattr(self.parent.class_, prop.key) for prop in self.props]
@util.memoized_property
@util.preload_module("orm.properties")
def props(self) -> Sequence[MapperProperty[Any]]:
props = []
MappedColumn = util.preloaded.orm_properties.MappedColumn
for attr in self.attrs:
if isinstance(attr, str):
prop = self.parent.get_property(attr, _configure_mappers=False)
elif isinstance(attr, schema.Column):
prop = self.parent._columntoproperty[attr]
elif isinstance(attr, MappedColumn):
prop = self.parent._columntoproperty[attr.column]
elif isinstance(attr, attributes.InstrumentedAttribute):
prop = attr.property
else:
prop = None
if not isinstance(prop, MapperProperty):
raise sa_exc.ArgumentError(
"Composite expects Column objects or mapped "
f"attributes/attribute names as arguments, got: {attr!r}"
)
props.append(prop)
return props
def _column_strategy_attrs(self) -> Sequence[QueryableAttribute[Any]]:
return self._comparable_elements
@util.non_memoized_property
@util.preload_module("orm.properties")
def columns(self) -> Sequence[Column[Any]]:
MappedColumn = util.preloaded.orm_properties.MappedColumn
return [
a.column if isinstance(a, MappedColumn) else a
for a in self.attrs
if isinstance(a, (schema.Column, MappedColumn))
]
@property
def mapper_property_to_assign(self) -> Optional[MapperProperty[_CC]]:
return self
@property
def columns_to_assign(self) -> List[Tuple[schema.Column[Any], int]]:
return [(c, 0) for c in self.columns if c.table is None]
@util.preload_module("orm.properties")
def _setup_arguments_on_columns(self) -> None:
"""Propagate configuration arguments made on this composite
to the target columns, for those that apply.
"""
ColumnProperty = util.preloaded.orm_properties.ColumnProperty
for prop in self.props:
if not isinstance(prop, ColumnProperty):
continue
else:
cprop = prop
cprop.active_history = self.active_history
if self.deferred:
cprop.deferred = self.deferred
cprop.strategy_key = (("deferred", True), ("instrument", True))
cprop.group = self.group
def _setup_event_handlers(self) -> None:
"""Establish events that populate/expire the composite attribute."""
def load_handler(
state: InstanceState[Any], context: _ORMCompileState
) -> None:
_load_refresh_handler(state, context, None, is_refresh=False)
def refresh_handler(
state: InstanceState[Any],
context: _ORMCompileState,
to_load: Optional[Sequence[str]],
) -> None:
# note this corresponds to sqlalchemy.ext.mutable load_attrs()
if not to_load or (
{self.key}.union(self._attribute_keys)
).intersection(to_load):
_load_refresh_handler(state, context, to_load, is_refresh=True)
def _load_refresh_handler(
state: InstanceState[Any],
context: _ORMCompileState,
to_load: Optional[Sequence[str]],
is_refresh: bool,
) -> None:
dict_ = state.dict
# if context indicates we are coming from the
# fget() handler, this already set the value; skip the
# handler here. (other handlers like mutablecomposite will still
# want to catch it)
# there's an insufficiency here in that the fget() handler
# really should not be using the refresh event and there should
# be some other event that mutablecomposite can subscribe
# towards for this.
if (
not is_refresh or context is self._COMPOSITE_FGET
) and self.key in dict_:
return
# if column elements aren't loaded, skip.
# __get__() will initiate a load for those
# columns
for k in self._attribute_keys:
if k not in dict_:
return
dict_[self.key] = self._construct_composite(
*[state.dict[key] for key in self._attribute_keys]
)
def expire_handler(
state: InstanceState[Any], keys: Optional[Sequence[str]]
) -> None:
if keys is None or set(self._attribute_keys).intersection(keys):
state.dict.pop(self.key, None)
def insert_update_handler(
mapper: Mapper[Any],
connection: Connection,
state: InstanceState[Any],
) -> None:
"""After an insert or update, some columns may be expired due
to server side defaults, or re-populated due to client side
defaults. Pop out the composite value here so that it
recreates.
"""
state.dict.pop(self.key, None)
event.listen(
self.parent, "after_insert", insert_update_handler, raw=True
)
event.listen(
self.parent, "after_update", insert_update_handler, raw=True
)
event.listen(
self.parent, "load", load_handler, raw=True, propagate=True
)
event.listen(
self.parent, "refresh", refresh_handler, raw=True, propagate=True
)
event.listen(
self.parent, "expire", expire_handler, raw=True, propagate=True
)
proxy_attr = self.parent.class_manager[self.key]
proxy_attr.impl.dispatch = proxy_attr.dispatch # type: ignore
proxy_attr.impl.dispatch._active_history = self.active_history
# TODO: need a deserialize hook here
@util.memoized_property
def _attribute_keys(self) -> Sequence[str]:
return [prop.key for prop in self.props]
def _populate_composite_bulk_save_mappings_fn(
self,
) -> Callable[[Dict[str, Any]], None]:
if self._generated_composite_accessor:
get_values = self._generated_composite_accessor
else:
def get_values(val: Any) -> Tuple[Any]:
return val.__composite_values__() # type: ignore
attrs = [prop.key for prop in self.props]
def populate(dest_dict: Dict[str, Any]) -> None:
dest_dict.update(
{
key: val
for key, val in zip(
attrs, get_values(dest_dict.pop(self.key))
)
}
)
return populate
def get_history(
self,
state: InstanceState[Any],
dict_: _InstanceDict,
passive: PassiveFlag = PassiveFlag.PASSIVE_OFF,
) -> History:
"""Provided for userland code that uses attributes.get_history()."""
added: List[Any] = []
deleted: List[Any] = []
has_history = False
for prop in self.props:
key = prop.key
hist = state.manager[key].impl.get_history(state, dict_)
if hist.has_changes():
has_history = True
non_deleted = hist.non_deleted()
if non_deleted:
added.extend(non_deleted)
else:
added.append(None)
if hist.deleted:
deleted.extend(hist.deleted)
else:
deleted.append(None)
if has_history:
return attributes.History(
[self._construct_composite(*added)],
(),
[self._construct_composite(*deleted)],
)
else:
return attributes.History(
(), [self._construct_composite(*added)], ()
)
def _comparator_factory(
self, mapper: Mapper[Any]
) -> Composite.Comparator[_CC]:
return self.comparator_factory(self, mapper)
class CompositeBundle(orm_util.Bundle[_T]):
def __init__(
self,
property_: Composite[_T],
expr: ClauseList,
):
self.property = property_
super().__init__(property_.key, *expr)
def create_row_processor(
self,
query: Select[Unpack[TupleAny]],
procs: Sequence[Callable[[Row[Unpack[TupleAny]]], Any]],
labels: Sequence[str],
) -> Callable[[Row[Unpack[TupleAny]]], Any]:
def proc(row: Row[Unpack[TupleAny]]) -> Any:
return self.property._construct_composite(
*[proc(row) for proc in procs]
)
return proc
class Comparator(PropComparator[_PT]):
"""Produce boolean, comparison, and other operators for
:class:`.Composite` attributes.
See the example in :ref:`composite_operations` for an overview
of usage , as well as the documentation for :class:`.PropComparator`.
.. seealso::
:class:`.PropComparator`
:class:`.ColumnOperators`
:ref:`types_operators`
:attr:`.TypeEngine.comparator_factory`
"""
# https://github.com/python/mypy/issues/4266
__hash__ = None # type: ignore
prop: RODescriptorReference[Composite[_PT]]
@util.memoized_property
def clauses(self) -> ClauseList:
return expression.ClauseList(
group=False, *self._comparable_elements
)
def __clause_element__(self) -> CompositeProperty.CompositeBundle[_PT]:
return self.expression
@util.memoized_property
def expression(self) -> CompositeProperty.CompositeBundle[_PT]:
clauses = self.clauses._annotate(
{
"parententity": self._parententity,
"parentmapper": self._parententity,
"proxy_key": self.prop.key,
}
)
return CompositeProperty.CompositeBundle(self.prop, clauses)
def _bulk_update_tuples(
self, value: Any
) -> Sequence[Tuple[_DMLColumnArgument, Any]]:
if isinstance(value, BindParameter):
value = value.value
values: Sequence[Any]
if value is None:
values = [None for key in self.prop._attribute_keys]
elif isinstance(self.prop.composite_class, type) and isinstance(
value, self.prop.composite_class
):
values = self.prop._composite_values_from_instance(
value # type: ignore[arg-type]
)
else:
raise sa_exc.ArgumentError(
"Can't UPDATE composite attribute %s to %r"
% (self.prop, value)
)
return list(zip(self._comparable_elements, values))
def _bulk_dml_setter(self, key: str) -> Optional[Callable[..., Any]]:
return self.prop._populate_composite_bulk_save_mappings_fn()
@util.memoized_property
def _comparable_elements(self) -> Sequence[QueryableAttribute[Any]]:
if self._adapt_to_entity:
return [
getattr(self._adapt_to_entity.entity, prop.key)
for prop in self.prop._comparable_elements
]
else:
return self.prop._comparable_elements
def __eq__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501
return self._compare(operators.eq, other)
def __ne__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501
return self._compare(operators.ne, other)
def __lt__(self, other: Any) -> ColumnElement[bool]:
return self._compare(operators.lt, other)
def __gt__(self, other: Any) -> ColumnElement[bool]:
return self._compare(operators.gt, other)
def __le__(self, other: Any) -> ColumnElement[bool]:
return self._compare(operators.le, other)
def __ge__(self, other: Any) -> ColumnElement[bool]:
return self._compare(operators.ge, other)
def desc(self) -> operators.OrderingOperators: # type: ignore[override] # noqa: E501
return expression.OrderByList(
[e.desc() for e in self._comparable_elements]
)
def asc(self) -> operators.OrderingOperators: # type: ignore[override] # noqa: E501
return expression.OrderByList(
[e.asc() for e in self._comparable_elements]
)
def nulls_first(self) -> operators.OrderingOperators: # type: ignore[override] # noqa: E501
return expression.OrderByList(
[e.nulls_first() for e in self._comparable_elements]
)
def nulls_last(self) -> operators.OrderingOperators: # type: ignore[override] # noqa: E501
return expression.OrderByList(
[e.nulls_last() for e in self._comparable_elements]
)
# what might be interesting would be if we create
# an instance of the composite class itself with
# the columns as data members, then use "hybrid style" comparison
# to create these comparisons. then your Point.__eq__() method could
# be where comparison behavior is defined for SQL also. Likely
# not a good choice for default behavior though, not clear how it would
# work w/ dataclasses, etc. also no demand for any of this anyway.
def _compare(
self, operator: OperatorType, other: Any
) -> ColumnElement[bool]:
values: Sequence[Any]
if other is None:
values = [None] * len(self.prop._comparable_elements)
else:
values = self.prop._composite_values_from_instance(other)
comparisons = [
operator(a, b)
for a, b in zip(self.prop._comparable_elements, values)
]
if self._adapt_to_entity:
assert self.adapter is not None
comparisons = [self.adapter(x) for x in comparisons]
return sql.and_(*comparisons)
def __str__(self) -> str:
return str(self.parent.class_.__name__) + "." + self.key
|
CompositeProperty
|
python
|
milvus-io__pymilvus
|
tests/test_bulk_writer_stage.py
|
{
"start": 20878,
"end": 23648
}
|
class ____:
"""Integration tests for stage operations."""
@pytest.fixture
def mock_server_responses(self) -> Dict[str, Any]:
"""Mock server responses for integration testing."""
return {
"apply_stage": {
"code": 0,
"message": "success",
"data": {
"stageName": "test_stage",
"stagePrefix": "prefix/",
"endpoint": "s3.amazonaws.com",
"bucketName": "test-bucket",
"region": "us-west-2",
"cloud": "aws",
"condition": {"maxContentLength": 1073741824},
"credentials": {
"tmpAK": "test_access_key",
"tmpSK": "test_secret_key",
"sessionToken": "test_token",
"expireTime": "2099-12-31T23:59:59Z",
},
},
},
"list_stages": {
"code": 0,
"message": "success",
"data": {"stages": ["stage1", "stage2", "test_stage"]},
},
}
@patch("pymilvus.bulk_writer.stage_restful.requests.post")
@patch("pymilvus.bulk_writer.stage_restful.requests.get")
def test_full_stage_workflow(
self,
mock_get: Mock,
mock_post: Mock,
mock_server_responses: Dict[str, Any],
) -> None:
"""Test complete stage workflow from creation to upload."""
# Setup mock responses
mock_post_response = Mock()
mock_post_response.status_code = 200
mock_post_response.json.return_value = mock_server_responses["apply_stage"]
mock_post.return_value = mock_post_response
mock_get_response = Mock()
mock_get_response.status_code = 200
mock_get_response.json.return_value = mock_server_responses["list_stages"]
mock_get.return_value = mock_get_response
# Create stage manager
stage_manager = StageManager(
cloud_endpoint="https://api.cloud.zilliz.com",
api_key="test_api_key",
)
# List stages
result = stage_manager.list_stages(project_id="test_project")
assert "test_stage" in result.json()["data"]["stages"]
# Create stage file manager
file_manager = StageFileManager(
cloud_endpoint="https://api.cloud.zilliz.com",
api_key="test_api_key",
stage_name="test_stage",
connect_type=ConnectType.AUTO,
)
# Verify stage info can be refreshed
file_manager._refresh_stage_and_client("data/")
assert file_manager.stage_info["stageName"] == "test_stage"
|
TestIntegration
|
python
|
aio-libs__aiohttp
|
aiohttp/test_utils.py
|
{
"start": 6610,
"end": 7201
}
|
class ____(BaseTestServer[BaseRequest]):
def __init__(
self,
handler: _RequestHandler[BaseRequest],
*,
scheme: str = "",
host: str = "127.0.0.1",
port: int | None = None,
**kwargs: Any,
) -> None:
self._handler = handler
super().__init__(scheme=scheme, host=host, port=port, **kwargs)
async def _make_runner(self, **kwargs: Any) -> ServerRunner:
# TODO(PY311): Use Unpack to specify Server kwargs.
srv = Server(self._handler, **kwargs)
return ServerRunner(srv, **kwargs)
|
RawTestServer
|
python
|
django__django
|
django/template/base.py
|
{
"start": 3378,
"end": 3458
}
|
class ____(Enum):
TEXT = 0
VAR = 1
BLOCK = 2
COMMENT = 3
|
TokenType
|
python
|
HypothesisWorks__hypothesis
|
hypothesis-python/tests/django/toystore/models.py
|
{
"start": 1229,
"end": 1534
}
|
class ____(models.Model):
name = models.CharField(max_length=100, unique=True)
email = models.EmailField(max_length=100, unique=True)
gender = models.CharField(max_length=50, null=True) # noqa # avoid nullable strs
age = models.IntegerField()
birthday = models.DateTimeField()
|
Customer
|
python
|
doocs__leetcode
|
solution/1600-1699/1670.Design Front Middle Back Queue/Solution.py
|
{
"start": 0,
"end": 1509
}
|
class ____:
def __init__(self):
self.q1 = deque()
self.q2 = deque()
def pushFront(self, val: int) -> None:
self.q1.appendleft(val)
self.rebalance()
def pushMiddle(self, val: int) -> None:
self.q1.append(val)
self.rebalance()
def pushBack(self, val: int) -> None:
self.q2.append(val)
self.rebalance()
def popFront(self) -> int:
if not self.q1 and not self.q2:
return -1
if self.q1:
val = self.q1.popleft()
else:
val = self.q2.popleft()
self.rebalance()
return val
def popMiddle(self) -> int:
if not self.q1 and not self.q2:
return -1
if len(self.q1) == len(self.q2):
val = self.q1.pop()
else:
val = self.q2.popleft()
self.rebalance()
return val
def popBack(self) -> int:
if not self.q2:
return -1
val = self.q2.pop()
self.rebalance()
return val
def rebalance(self):
if len(self.q1) > len(self.q2):
self.q2.appendleft(self.q1.pop())
if len(self.q2) > len(self.q1) + 1:
self.q1.append(self.q2.popleft())
# Your FrontMiddleBackQueue object will be instantiated and called as such:
# obj = FrontMiddleBackQueue()
# obj.pushFront(val)
# obj.pushMiddle(val)
# obj.pushBack(val)
# param_4 = obj.popFront()
# param_5 = obj.popMiddle()
# param_6 = obj.popBack()
|
FrontMiddleBackQueue
|
python
|
Netflix__metaflow
|
metaflow/decorators.py
|
{
"start": 10401,
"end": 33295
}
|
class ____(Decorator):
"""
Base class for all step decorators.
Example:
@my_decorator
@step
def a(self):
pass
@my_decorator
@step
def b(self):
pass
To make the above work, define a subclass
class MyDecorator(StepDecorator):
name = "my_decorator"
and include it in plugins.STEP_DECORATORS. Now both a() and b()
get an instance of MyDecorator, so you can keep step-specific
state easily.
TODO (savin): Initialize the decorators with flow, graph,
step.__name__ etc., so that we don't have to
pass them around with every lifecycle call.
"""
def step_init(
self, flow, graph, step_name, decorators, environment, flow_datastore, logger
):
"""
Called when all decorators have been created for this step
"""
pass
def package_init(self, flow, step_name, environment):
"""
Called to determine package components
"""
pass
def add_to_package(self):
"""
Called to add custom files needed for this environment. This hook will be
called in the `MetaflowPackage` class where metaflow compiles the code package
tarball. This hook can return one of two things (the first is for backwards
compatibility -- move to the second):
- a generator yielding a tuple of `(file_path, arcname)` to add files to
the code package. `file_path` is the path to the file on the local filesystem
and `arcname` is the path relative to the packaged code.
- a generator yielding a tuple of `(content, arcname, type)` where:
- type is one of
ContentType.{USER_CONTENT, CODE_CONTENT, MODULE_CONTENT, OTHER_CONTENT}
- for USER_CONTENT:
- the file will be included relative to the directory containing the
user's flow file.
- content: path to the file to include
- arcname: path relative to the directory containing the user's flow file
- for CODE_CONTENT:
- the file will be included relative to the code directory in the package.
This will be the directory containing `metaflow`.
- content: path to the file to include
- arcname: path relative to the code directory in the package
- for MODULE_CONTENT:
- the module will be added to the code package as a python module. It will
be accessible as usual (import <module_name>)
- content: name of the module
- arcname: None (ignored)
- for OTHER_CONTENT:
- the file will be included relative to any other configuration/metadata
files for the flow
- content: path to the file to include
- arcname: path relative to the config directory in the package
"""
return []
def step_task_retry_count(self):
"""
Called to determine the number of times this task should be retried.
Returns a tuple of (user_code_retries, error_retries). Error retries
are attempts to run the process after the user code has failed all
its retries.
Typically, the runtime takes the maximum of retry counts across
decorators and user specification to determine the task retry count.
If you want to force no retries, return the special values (None, None).
"""
return 0, 0
def runtime_init(self, flow, graph, package, run_id):
"""
Top-level initialization before anything gets run in the runtime
context.
"""
pass
def runtime_task_created(
self, task_datastore, task_id, split_index, input_paths, is_cloned, ubf_context
):
"""
Called when the runtime has created a task related to this step.
"""
pass
def runtime_finished(self, exception):
"""
Called when the runtime created task finishes or encounters an interrupt/exception.
"""
pass
def runtime_step_cli(
self, cli_args, retry_count, max_user_code_retries, ubf_context
):
"""
Access the command line for a step execution in the runtime context.
"""
pass
def task_pre_step(
self,
step_name,
task_datastore,
metadata,
run_id,
task_id,
flow,
graph,
retry_count,
max_user_code_retries,
ubf_context,
inputs,
):
"""
Run before the step function in the task context.
"""
pass
def task_decorate(
self, step_func, flow, graph, retry_count, max_user_code_retries, ubf_context
):
return step_func
def task_post_step(
self, step_name, flow, graph, retry_count, max_user_code_retries
):
"""
Run after the step function has finished successfully in the task
context.
"""
pass
def task_exception(
self, exception, step_name, flow, graph, retry_count, max_user_code_retries
):
"""
Run if the step function raised an exception in the task context.
If this method returns True, it is assumed that the exception has
been taken care of and the flow may continue.
"""
pass
def task_finished(
self, step_name, flow, graph, is_task_ok, retry_count, max_user_code_retries
):
"""
Run after the task context has been finalized.
is_task_ok is set to False if the user code raised an exception that
was not handled by any decorator.
Note that you can't create or modify data artifacts in this method
since the task has been finalized by the time this method
is called. Also note that the task may fail after this method has been
called, so this method may get called multiple times for a task over
multiple attempts, similar to all task_ methods.
"""
pass
def _base_flow_decorator(decofunc, *args, **kwargs):
"""
Decorator prototype for all flow (class) decorators. This function gets
specialized and imported for all decorators types by
_import_plugin_decorators().
"""
if args:
# No keyword arguments specified for the decorator, e.g. @foobar.
# The first argument is the class to be decorated.
cls = args[0]
"""
When stacking decorators, cls may be another FlowMutator, for example
@flow_decorator
@flow_mutator
class MyFlow(FlowSpec):
...
"""
if isinstance(cls, (FlowMutator,)):
cls = cls._flow_cls
if isinstance(cls, type) and issubclass(cls, FlowSpec):
# flow decorators add attributes in the class dictionary,
# cls._flow_state[FlowStateItems.FLOW_DECORATORS]. This is of type `{key:[decos]}`
self_flow_decos = cls._flow_state.self_data[FlowStateItems.FLOW_DECORATORS]
inherited_flow_decos = cls._flow_state.inherited_data.get(
FlowStateItems.FLOW_DECORATORS, {}
)
if (
decofunc.name in self_flow_decos
or decofunc.name in inherited_flow_decos
) and not decofunc.allow_multiple:
raise DuplicateFlowDecoratorException(decofunc.name)
else:
deco_instance = decofunc(attributes=kwargs, statically_defined=True)
self_flow_decos.setdefault(decofunc.name, []).append(deco_instance)
else:
raise BadFlowDecoratorException(decofunc.name)
return cls
else:
# Keyword arguments specified, e.g. @foobar(a=1, b=2).
# Return a decorator function that will get the actual
# function to be decorated as the first argument.
def wrap(f):
return _base_flow_decorator(decofunc, f, **kwargs)
return wrap
def _base_step_decorator(decotype, *args, **kwargs):
"""
Decorator prototype for all step decorators. This function gets specialized
and imported for all decorators types by _import_plugin_decorators().
"""
if args:
# No keyword arguments specified for the decorator, e.g. @foobar.
# The first argument is the function to be decorated.
func = args[0]
if isinstance(func, (StepMutator, UserStepDecoratorBase)):
func = func._my_step
if not hasattr(func, "is_step"):
raise BadStepDecoratorException(decotype.name, func)
# if `allow_multiple` is not `True` then only one decorator type is allowed per step
if (
decotype.name in [deco.name for deco in func.decorators]
and not decotype.allow_multiple
):
raise DuplicateStepDecoratorException(decotype.name, func)
else:
func.decorators.append(decotype(attributes=kwargs, statically_defined=True))
return func
else:
# Keyword arguments specified, e.g. @foobar(a=1, b=2).
# Return a decorator function that will get the actual
# function to be decorated as the first argument.
def wrap(f):
return _base_step_decorator(decotype, f, **kwargs)
return wrap
_all_step_decos = None
_all_flow_decos = None
def get_all_step_decos():
global _all_step_decos
if _all_step_decos is None:
from .plugins import STEP_DECORATORS
_all_step_decos = {decotype.name: decotype for decotype in STEP_DECORATORS}
return _all_step_decos
def get_all_flow_decos():
global _all_flow_decos
if _all_flow_decos is None:
from .plugins import FLOW_DECORATORS
_all_flow_decos = {decotype.name: decotype for decotype in FLOW_DECORATORS}
return _all_flow_decos
def extract_step_decorator_from_decospec(decospec: str):
splits = decospec.split(":", 1)
deconame = splits[0]
# Check if it is a user-defined decorator or metaflow decorator
deco_cls = UserStepDecoratorMeta.get_decorator_by_name(deconame)
if deco_cls is not None:
return (
deco_cls.parse_decorator_spec(splits[1] if len(splits) > 1 else ""),
len(splits) > 1,
)
# Check if this is a decorator we can import
if "." in deconame:
# We consider this to be a import path to a user decorator so
# something like "my_package.my_decorator"
module_name, class_name = deconame.rsplit(".", 1)
try:
module = importlib.import_module(module_name)
except ImportError as e:
raise MetaflowException(
"Could not import user decorator %s" % deconame
) from e
deco_cls = getattr(module, class_name, None)
if (
deco_cls is None
or not isinstance(deco_cls, type)
or not issubclass(deco_cls, UserStepDecoratorBase)
):
raise UnknownStepDecoratorException(deconame)
return (
deco_cls.parse_decorator_spec(splits[1] if len(splits) > 1 else ""),
len(splits) > 1,
)
raise UnknownStepDecoratorException(deconame)
def extract_flow_decorator_from_decospec(decospec: str):
splits = decospec.split(":", 1)
deconame = splits[0]
# Check if it is a user-defined decorator or metaflow decorator
deco_cls = FlowMutatorMeta.get_decorator_by_name(deconame)
if deco_cls is not None:
return (
deco_cls.parse_decorator_spec(splits[1] if len(splits) > 1 else ""),
len(splits) > 1,
)
else:
raise UnknownFlowDecoratorException(deconame)
def _attach_decorators(flow, decospecs):
"""
Attach decorators to all steps during runtime. This has the same
effect as if you defined the decorators statically in the source for
every step. Used by --with command line parameter.
"""
# Attach the decorator to all steps that don't have this decorator
# already. This means that statically defined decorators are always
# preferred over runtime decorators.
#
# Note that each step gets its own instance of the decorator class,
# so decorator can maintain step-specific state.
for step in flow:
_attach_decorators_to_step(step, decospecs)
def _attach_decorators_to_step(step, decospecs):
"""
Attach decorators to a step during runtime. This has the same
effect as if you defined the decorators statically in the source for
the step.
"""
for decospec in decospecs:
step_deco, _ = extract_step_decorator_from_decospec(decospec)
if isinstance(step_deco, StepDecorator):
# Check multiple
if (
step_deco.name not in [deco.name for deco in step.decorators]
or step_deco.allow_multiple
):
step.decorators.append(step_deco)
# Else it is ignored -- this is a non-static decorator
else:
step_deco.add_or_raise(step, False, 1, None)
def _should_skip_decorator_for_spin(
deco, is_spin, skip_decorators, logger, decorator_type="decorator"
):
"""
Determine if a decorator should be skipped for spin steps.
Parameters:
-----------
deco : Decorator
The decorator instance to check
is_spin : bool
Whether this is a spin step
skip_decorators : bool
Whether to skip all decorators
logger : callable
Logger function for warnings
decorator_type : str
Type of decorator ("Flow decorator" or "Step decorator") for logging
Returns:
--------
bool
True if the decorator should be skipped, False otherwise
"""
if not is_spin:
return False
# Skip all decorator hooks if skip_decorators is True
if skip_decorators:
return True
# Run decorator hooks for spin steps only if they are in the whitelist
if deco.name not in SPIN_ALLOWED_DECORATORS:
logger(
f"[Warning] Ignoring {decorator_type} '{deco.name}' as it is not supported in spin steps.",
system_msg=True,
timestamp=False,
bad=True,
)
return True
return False
def _init(flow, only_non_static=False):
flow_decos = flow._flow_state[FlowStateItems.FLOW_DECORATORS]
for decorators in flow_decos.values():
for deco in decorators:
deco.external_init()
for flowstep in flow:
for deco in flowstep.decorators:
deco.external_init()
for deco in flowstep.config_decorators or []:
deco.external_init()
for deco in flowstep.wrappers or []:
deco.external_init()
def _init_flow_decorators(
flow,
graph,
environment,
flow_datastore,
metadata,
logger,
echo,
deco_options,
is_spin=False,
skip_decorators=False,
):
# Since all flow decorators are stored as `{key:[deco]}` we iterate through each of them.
flow_decos = flow._flow_state[FlowStateItems.FLOW_DECORATORS]
for decorators in flow_decos.values():
# First resolve the `options` for the flow decorator.
# Options are passed from cli.
# For example `@project` can take a `--name` / `--branch` from the cli as options.
deco_flow_init_options = {}
deco = decorators[0]
# If a flow decorator allow multiple of same type then we don't allow multiple options for it.
if deco.allow_multiple:
if len(deco.options) > 0:
raise MetaflowException(
"Flow decorator `@%s` has multiple options, which is not allowed. "
"Please ensure the FlowDecorator `%s` has no options since flow decorators with "
"`allow_mutiple=True` are not allowed to have options"
% (deco.name, deco.__class__.__name__)
)
else:
# Each "non-multiple" flow decorator is only allowed to have one set of options
# Note that there may be no deco_options if a MutableFlow config injected
# the decorator.
deco_flow_init_options = {
option: deco_options.get(
option.replace("-", "_"), option_info["default"]
)
for option, option_info in deco.options.items()
}
for deco in decorators:
if _should_skip_decorator_for_spin(
deco, is_spin, skip_decorators, logger, "Flow decorator"
):
continue
deco.flow_init(
flow,
graph,
environment,
flow_datastore,
metadata,
logger,
echo,
deco_flow_init_options,
)
def _init_step_decorators(
flow,
graph,
environment,
flow_datastore,
logger,
is_spin=False,
skip_decorators=False,
):
# NOTE: We don't need the graph but keeping it for backwards compatibility with
# extensions that use it directly. We will remove it at some point.
# We call the mutate method for both the flow and step mutators.
cls = flow.__class__
# Run all the decorators. We first run the flow-level decorators
# and then the step level ones to maintain a consistent order with how
# other decorators are run.
for deco in cls._flow_state[FlowStateItems.FLOW_MUTATORS]:
if isinstance(deco, FlowMutator):
inserted_by_value = [deco.decorator_name] + (deco.inserted_by or [])
mutable_flow = MutableFlow(
cls,
pre_mutate=False,
statically_defined=deco.statically_defined,
inserted_by=inserted_by_value,
)
# Sanity check to make sure we are applying the decorator to the right
# class
if not deco._flow_cls == cls and not issubclass(cls, deco._flow_cls):
raise MetaflowInternalError(
"FlowMutator registered on the wrong flow -- "
"expected %s but got %s" % (deco._flow_cls.__name__, cls.__name__)
)
debug.userconf_exec(
"Evaluating flow level decorator %s (mutate)" % deco.__class__.__name__
)
deco.mutate(mutable_flow)
# We reset cached_parameters on the very off chance that the user added
# more configurations based on the configuration
cls._flow_state[FlowStateItems.CACHED_PARAMETERS] = None
else:
raise MetaflowInternalError(
"A non FlowMutator found in flow custom decorators"
)
for step in cls._steps:
for deco in step.config_decorators:
inserted_by_value = [deco.decorator_name] + (deco.inserted_by or [])
if isinstance(deco, StepMutator):
debug.userconf_exec(
"Evaluating step level decorator %s for %s (mutate)"
% (deco.__class__.__name__, step.name)
)
deco.mutate(
MutableStep(
cls,
step,
pre_mutate=False,
statically_defined=deco.statically_defined,
inserted_by=inserted_by_value,
)
)
else:
raise MetaflowInternalError(
"A non StepMutator found in step custom decorators"
)
if step.config_decorators:
# We remove all mention of the custom step decorator
setattr(cls, step.name, step)
cls._init_graph()
graph = flow._graph
for step in flow:
for deco in step.decorators:
if _should_skip_decorator_for_spin(
deco, is_spin, skip_decorators, logger, "Step decorator"
):
continue
deco.step_init(
flow,
graph,
step.__name__,
step.decorators,
environment,
flow_datastore,
logger,
)
FlowSpecDerived = TypeVar("FlowSpecDerived", bound=FlowSpec)
# The StepFlag is a "fake" input item to be able to distinguish
# callables and those that have had a `@step` decorator on them. This enables us
# to check the ordering of decorators (ie: put @step first) with the type
# system. There should be a better way to do this with a more flexible type
# system but this is what works for now with the Python type system
StepFlag = NewType("StepFlag", bool)
@overload
def step(
f: Callable[[FlowSpecDerived], None],
) -> Callable[[FlowSpecDerived, StepFlag], None]: ...
@overload
def step(
f: Callable[[FlowSpecDerived, Any], None],
) -> Callable[[FlowSpecDerived, Any, StepFlag], None]: ...
def step(
f: Union[Callable[[FlowSpecDerived], None], Callable[[FlowSpecDerived, Any], None]],
):
"""
Marks a method in a FlowSpec as a Metaflow Step. Note that this
decorator needs to be placed as close to the method as possible (ie:
before other decorators).
In other words, this is valid:
```
@batch
@step
def foo(self):
pass
```
whereas this is not:
```
@step
@batch
def foo(self):
pass
```
Parameters
----------
f : Union[Callable[[FlowSpecDerived], None], Callable[[FlowSpecDerived, Any], None]]
Function to make into a Metaflow Step
Returns
-------
Union[Callable[[FlowSpecDerived, StepFlag], None], Callable[[FlowSpecDerived, Any, StepFlag], None]]
Function that is a Metaflow Step
"""
f.is_step = True
f.decorators = []
f.config_decorators = []
f.wrappers = []
f.name = f.__name__
return f
def _import_plugin_decorators(globals_dict):
"""
Auto-generate a decorator function for every decorator
defined in plugins.STEP_DECORATORS and plugins.FLOW_DECORATORS.
"""
from .plugins import STEP_DECORATORS, FLOW_DECORATORS
# Q: Why not use StepDecorators directly as decorators?
# A: Getting an object behave as a decorator that can work
# both with and without arguments is surprisingly hard.
# It is easier to make plain function decorators work in
# the dual mode - see _base_step_decorator above.
for decotype in STEP_DECORATORS:
globals_dict[decotype.name] = partial(_base_step_decorator, decotype)
# add flow-level decorators
for decotype in FLOW_DECORATORS:
globals_dict[decotype.name] = partial(_base_flow_decorator, decotype)
|
StepDecorator
|
python
|
tensorflow__tensorflow
|
tensorflow/python/distribute/tpu_values.py
|
{
"start": 16682,
"end": 21450
}
|
class ____(values.OnWritePolicy):
"""Policy defined for `tf.VariableSynchronization.ON_WRITE` synchronization.
This policy is created when `synchronization` is set to
`tf.VariableSynchronization.AUTO` or `tf.VariableSynchronization.ON_WRITE`.
"""
def assign_sub(self,
var,
value,
use_locking=False,
name=None,
read_value=True):
if (tpu_util.enclosing_tpu_context() and
var.aggregation == variable_scope.VariableAggregation.NONE):
return tpu_util.make_raw_assign_fn(
gen_resource_variable_ops.assign_sub_variable_op)(
var,
value=value,
use_locking=use_locking,
name=name,
read_value=read_value)
return assign_sub(
var, value, use_locking=use_locking, name=name, read_value=read_value)
def assign_add(self,
var,
value,
use_locking=False,
name=None,
read_value=True):
if (tpu_util.enclosing_tpu_context() and
var.aggregation == variable_scope.VariableAggregation.NONE):
return tpu_util.make_raw_assign_fn(
gen_resource_variable_ops.assign_add_variable_op)(
var,
value=value,
use_locking=use_locking,
name=name,
read_value=read_value)
return assign_add(
var, value, use_locking=use_locking, name=name, read_value=read_value)
def assign(self, var, value, use_locking=False, name=None, read_value=True):
if (tpu_util.enclosing_tpu_context() and
var.aggregation == variable_scope.VariableAggregation.NONE):
return tpu_util.make_raw_assign_fn(
gen_resource_variable_ops.assign_variable_op)(
var,
value=value,
use_locking=use_locking,
name=name,
read_value=read_value)
return assign(
var, value, use_locking=use_locking, name=name, read_value=read_value)
def _scatter_xxx(self,
raw_scater_xxx_fn,
op_name,
var,
sparse_delta,
use_locking=False,
name=None):
scater_xxx_fn = tpu_util.make_raw_scatter_xxx_fn(raw_scater_xxx_fn)
if tpu_util.enclosing_tpu_context():
if self._aggregation != variable_scope.VariableAggregation.NONE:
raise NotImplementedError(
_scatter_error_msg.format(
op_name=op_name, aggregation=self._aggregation))
return scater_xxx_fn(
var, sparse_delta=sparse_delta, use_locking=use_locking, name=name)
else:
return var._update( # pylint: disable=protected-access
update_fn=scater_xxx_fn,
value=sparse_delta,
use_locking=use_locking,
name=name)
def scatter_sub(self, var, sparse_delta, use_locking=False, name=None):
return self._scatter_xxx(gen_resource_variable_ops.resource_scatter_sub,
"scatter_sub", var, sparse_delta, use_locking,
name)
def scatter_add(self, var, sparse_delta, use_locking=False, name=None):
return self._scatter_xxx(gen_resource_variable_ops.resource_scatter_add,
"scatter_add", var, sparse_delta, use_locking,
name)
def scatter_max(self, var, sparse_delta, use_locking=False, name=None):
return self._scatter_xxx(gen_resource_variable_ops.resource_scatter_max,
"scatter_max", var, sparse_delta, use_locking,
name)
def scatter_min(self, var, sparse_delta, use_locking=False, name=None):
return self._scatter_xxx(gen_resource_variable_ops.resource_scatter_min,
"scatter_min", var, sparse_delta, use_locking,
name)
def scatter_mul(self, var, sparse_delta, use_locking=False, name=None):
return self._scatter_xxx(gen_resource_variable_ops.resource_scatter_mul,
"scatter_mul", var, sparse_delta, use_locking,
name)
def scatter_div(self, var, sparse_delta, use_locking=False, name=None):
return self._scatter_xxx(gen_resource_variable_ops.resource_scatter_div,
"scatter_div", var, sparse_delta, use_locking,
name)
def scatter_update(self, var, sparse_delta, use_locking=False, name=None):
return self._scatter_xxx(gen_resource_variable_ops.resource_scatter_update,
"scatter_update", var, sparse_delta, use_locking,
name)
|
TPUOnWritePolicy
|
python
|
getsentry__sentry
|
src/sentry/lang/native/symbolicator.py
|
{
"start": 15666,
"end": 20485
}
|
class ____:
"""
The `SymbolicatorSession` is a glorified HTTP request wrapper that does the following things:
- Maintains a `worker_id` which is used downstream in the load balancer for routing.
- Maintains `timeout` parameters which are passed to Symbolicator.
- Converts 404 and 503 errors into proper classes so they can be handled upstream.
- Otherwise, it retries failed requests.
"""
def __init__(
self,
url=None,
project_id=None,
event_id=None,
timeout=None,
):
self.url = url
self.project_id = project_id
self.event_id = event_id
self.timeout = timeout
self.session = None
self.reset_worker_id()
def __enter__(self):
self.open()
return self
def __exit__(self, *args):
self.close()
def open(self):
if self.session is None:
self.session = Session()
def close(self):
if self.session is not None:
self.session.close()
self.session = None
def _request(self, method, path, **kwargs):
if not self.session:
raise RuntimeError("Session not opened")
url = urljoin(self.url, path)
# required for load balancing
kwargs.setdefault("headers", {})["x-sentry-project-id"] = self.project_id
kwargs.setdefault("headers", {})["x-sentry-event-id"] = self.event_id
kwargs.setdefault("headers", {})["x-sentry-worker-id"] = self.worker_id
attempts = 0
wait = 0.5
while True:
try:
with metrics.timer(
"events.symbolicator.session.request", tags={"attempt": attempts}
):
response = self.session.request(method, url, timeout=self.timeout + 1, **kwargs)
metrics.incr(
"events.symbolicator.status_code",
tags={"status_code": response.status_code},
)
if (
method.lower() == "get"
and path.startswith("requests/")
and response.status_code == 404
):
# The symbolicator does not know this task. This is
# expected to happen when we're currently deploying
# symbolicator (which will clear all of its state). Re-send
# the symbolication task.
raise TaskIdNotFound()
if response.status_code in (502, 503):
raise ServiceUnavailable()
if response.ok:
json = response.json()
if json["status"] != "pending":
metrics.distribution(
"events.symbolicator.response.completed.size",
len(response.content),
unit="byte",
)
else:
with sentry_sdk.isolation_scope():
sentry_sdk.set_extra("symbolicator_response", response.text)
sentry_sdk.capture_message("Symbolicator request failed")
json = {"status": "failed", "message": "internal server error"}
return json
except (OSError, RequestException) as e:
metrics.incr(
"events.symbolicator.request_error",
tags={
"exc": ".".join([e.__class__.__module__, e.__class__.__name__]),
"attempt": attempts,
},
)
attempts += 1
# Any server error needs to be treated as a failure. We can
# retry a couple of times, but ultimately need to bail out.
#
# This can happen for any network failure.
if attempts > MAX_ATTEMPTS:
logger.exception("Failed to contact symbolicator")
raise
time.sleep(wait)
wait *= 2.0
def create_task(self, path, **kwargs):
params = {"timeout": self.timeout, "scope": self.project_id}
with metrics.timer(
"events.symbolicator.create_task",
tags={"path": path},
):
return self._request(method="post", path=path, params=params, **kwargs)
def query_task(self, task_id):
params = {"timeout": self.timeout, "scope": self.project_id}
task_url = f"requests/{task_id}"
with metrics.timer("events.symbolicator.query_task"):
return self._request("get", task_url, params=params)
def reset_worker_id(self):
self.worker_id = uuid.uuid4().hex
|
SymbolicatorSession
|
python
|
airbytehq__airbyte
|
airbyte-integrations/connectors/source-tplcentral/source_tplcentral/source.py
|
{
"start": 483,
"end": 2286
}
|
class ____(Oauth2Authenticator):
def __init__(
self,
token_refresh_endpoint: str,
client_id: str,
client_secret: str,
user_login_id: int = None,
user_login: str = None,
scopes: List[str] = None,
):
super().__init__(
token_refresh_endpoint=token_refresh_endpoint,
client_id=client_id,
client_secret=client_secret,
refresh_token=None,
)
self.token_refresh_endpoint = token_refresh_endpoint
self.client_id = client_id
self.client_secret = client_secret
self.scopes = scopes
self.access_token_name = "access_token"
self.expires_in_name = "expires_in"
self.user_login_id = user_login_id
self.user_login = user_login
def get_refresh_request_body(self) -> Mapping[str, Any]:
payload: MutableMapping[str, Any] = {
"grant_type": "client_credentials",
}
if self.scopes:
payload["scopes"] = self.scopes
if self.user_login_id:
payload["user_login_id"] = self.user_login_id
if self.user_login:
payload["user_login"] = self.user_login
return payload
def refresh_access_token(self) -> Tuple[str, int]:
try:
response = requests.post(
self.token_refresh_endpoint, auth=HTTPBasicAuth(self.client_id, self.client_secret), json=self.get_refresh_request_body()
)
response.raise_for_status()
response_json = response.json()
return response_json[self.access_token_name], response_json[self.expires_in_name]
except Exception as e:
raise Exception(f"Error while refreshing access token: {e}") from e
|
TplcentralAuthenticator
|
python
|
apache__airflow
|
providers/google/src/airflow/providers/google/cloud/operators/dataform.py
|
{
"start": 27477,
"end": 30689
}
|
class ____(GoogleCloudBaseOperator):
"""
Creates workspace.
:param project_id: Required. The ID of the Google Cloud project where workspace should be in.
:param region: Required. Name of the Google Cloud region that where workspace should be in.
:param repository_id: Required. The ID of the Dataform repository that the workspace belongs to.
:param workspace_id: Required. The ID of the new workspace that will be created.
:param retry: Designation of what errors, if any, should be retried.
:param timeout: The timeout for this request.
:param metadata: Strings which should be sent along with the request as metadata.
:param gcp_conn_id: The connection ID to use when fetching connection info.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
operator_extra_links = (DataformWorkspaceLink(),)
template_fields = (
"project_id",
"region",
"repository_id",
"workspace_id",
"impersonation_chain",
)
def __init__(
self,
project_id: str,
region: str,
repository_id: str,
workspace_id: str,
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
*args,
**kwargs,
):
super().__init__(*args, **kwargs)
self.project_id = project_id
self.workspace_id = workspace_id
self.repository_id = repository_id
self.region = region
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
def execute(self, context: Context) -> dict:
hook = DataformHook(
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
)
workspace = hook.create_workspace(
project_id=self.project_id,
region=self.region,
repository_id=self.repository_id,
workspace_id=self.workspace_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
DataformWorkspaceLink.persist(
context=context,
project_id=self.project_id,
region=self.region,
repository_id=self.repository_id,
workspace_id=self.workspace_id,
)
return Workspace.to_dict(workspace)
|
DataformCreateWorkspaceOperator
|
python
|
pytorch__pytorch
|
test/onnx/test_pytorch_onnx_shape_inference.py
|
{
"start": 1241,
"end": 16471
}
|
class ____(pytorch_test_common.ExportTestCase):
def setUp(self):
self.opset_version = _constants.ONNX_TORCHSCRIPT_EXPORTER_MAX_OPSET
GLOBALS.export_onnx_opset_version = self.opset_version
def run_test(self, g, n, type_assertion_funcs):
if not isinstance(type_assertion_funcs, list):
type_assertion_funcs = [type_assertion_funcs]
torch._C._jit_pass_onnx_graph_shape_type_inference(g, {}, self.opset_version)
for out, type_assertion_func in zip(n.outputs(), type_assertion_funcs):
type_assertion_func(out.type())
def create_empty_graph(self):
g = torch._C.Graph()
# kick off initialization for ConstantMap.
torch._C._jit_pass_onnx_graph_shape_type_inference(g, {}, self.opset_version)
return g
def insert_tensor_constant(self, g, tensor):
return g_op(g, "Constant", value_t=tensor)
def test_cast(self):
# Test cast with input of unknown scalar type.
g = self.create_empty_graph()
input = g.addInput()
cast_out = g_op(g, "Cast", input, to_i=1)
self.run_test(g, cast_out.node(), expect_tensor("Float"))
def test_constant_of_shape(self):
# Test ConstantOfShape with input of onnx::Shape node.
g = self.create_empty_graph()
constant = self.insert_tensor_constant(g, torch.ones(1, 2, 3, 4))
shape = g_op(g, "Shape", constant)
constant_of_shape = g_op(
g, "ConstantOfShape", shape, value_t=torch.tensor([2.0])
)
self.run_test(
g, constant_of_shape.node(), expect_tensor("Float", shape=(1, 2, 3, 4))
)
def test_constant_of_shape_static(self):
# Test ConstantOfShape with input of prim::ListConstruct of static tensor
rank = 4
g = self.create_empty_graph()
constants = [
self.insert_tensor_constant(g, torch.tensor(i + 1)) for i in range(rank)
]
shape = g_op(g, "prim::ListConstruct", *constants)
shape.setType(torch._C.ListType.ofInts())
constant_of_shape = g_op(
g, "ConstantOfShape", shape, value_t=torch.tensor([2.0])
)
self.run_test(
g, constant_of_shape.node(), expect_tensor("Float", shape=(1, 2, 3, 4))
)
def test_constant_of_shape_dynamic(self):
# Test ConstantOfShape with input of prim::ListConstruct of dynamic tensor
rank = 4
g = self.create_empty_graph()
inputs = [g.addInput() for i in range(rank)]
shape = g_op(g, "prim::ListConstruct", *inputs)
shape.setType(torch._C.ListType.ofInts())
constant_of_shape = g_op(
g, "ConstantOfShape", shape, value_t=torch.tensor([2.0])
)
self.run_test(
g,
constant_of_shape.node(),
expect_tensor("Float", shape=(None, None, None, None)),
)
def test_gather_dynamic_index(self):
g = self.create_empty_graph()
input = g.addInput()
input.setType(
input.type().with_dtype(torch.float).with_sizes([None, 3, 16, 16])
)
indices = g.addInput()
indices.setType(indices.type().with_dtype(torch.int64).with_sizes([None]))
output = g_op(g, "Gather", input, indices, axis_i=1)
self.run_test(
g, output.node(), expect_tensor("Float", shape=([None, None, 16, 16]))
)
def test_gather_scalar_index(self):
g = self.create_empty_graph()
input = g.addInput()
input.setType(
input.type().with_dtype(torch.float).with_sizes([None, 3, 16, 16])
)
indices = self.insert_tensor_constant(g, torch.tensor(1))
output = g_op(g, "Gather", input, indices, axis_i=1)
self.run_test(g, output.node(), expect_tensor("Float", shape=([None, 16, 16])))
def test_reshape(self):
g = self.create_empty_graph()
constant = self.insert_tensor_constant(g, torch.ones(2, 16, 5, 5))
constant_2 = self.insert_tensor_constant(g, torch.tensor([2, 0, -1]))
shape = g_op(g, "Reshape", constant, constant_2)
self.run_test(g, shape.node(), expect_tensor("Float", shape=(2, 16, 25)))
g = self.create_empty_graph()
constant = self.insert_tensor_constant(g, torch.ones(2, 16, 5, 4))
constant_2 = self.insert_tensor_constant(g, torch.tensor([-1, 0, 4]))
shape = g_op(g, "Reshape", constant, constant_2)
self.run_test(g, shape.node(), expect_tensor("Float", shape=(10, 16, 4)))
g = self.create_empty_graph()
constant = self.insert_tensor_constant(g, torch.ones(2, 16, 5, 4))
constant_2 = self.insert_tensor_constant(g, torch.tensor([-1, 0, 0]))
shape = g_op(g, "Reshape", constant, constant_2)
self.run_test(g, shape.node(), expect_tensor("Float", shape=(8, 16, 5)))
def test_reshape_symbolic(self):
g = self.create_empty_graph()
input = g.addInput()
input.setType(input.type().with_sizes([None, None, 2, 8]))
constant = self.insert_tensor_constant(g, torch.tensor([0, 0, -1]))
output = g_op(g, "Reshape", input, constant)
self.run_test(g, output.node(), expect_tensor(None, shape=(None, None, 16)))
@skipIfUnsupportedMinOpsetVersion(14)
def test_reshape_allowzero(self):
g = self.create_empty_graph()
input = g.addInput()
input.setType(input.type().with_sizes([3, 4, 0]))
constant = self.insert_tensor_constant(g, torch.tensor([0, 4, 3]))
output = g_op(g, "Reshape", input, constant, allowzero_i=1)
self.run_test(g, output.node(), expect_tensor(None, shape=(0, 4, 3)))
def test_slice(self):
g = self.create_empty_graph()
input = g.addInput()
input.setType(input.type().with_sizes([None, None]))
start_input = g.addInput()
start_input.setType(start_input.type().with_sizes([None]))
end = self.insert_tensor_constant(g, torch.tensor([3]))
axis = self.insert_tensor_constant(g, torch.tensor([0]))
step = self.insert_tensor_constant(g, torch.tensor([1]))
slice = g_op(g, "Slice", input, start_input, end, axis, step)
self.run_test(g, slice.node(), expect_tensor(None, shape=(None, None)))
def test_slice_with_dynamic_start_index(self):
g = self.create_empty_graph()
input = self.insert_tensor_constant(g, torch.ones(2, 3, 4, 5))
start_input = g.addInput()
start_input.setType(start_input.type().with_sizes([2]))
end = self.insert_tensor_constant(g, torch.tensor([3, 4]))
axis = self.insert_tensor_constant(g, torch.tensor([1, -1]))
slice = g_op(g, "Slice", input, start_input, end, axis)
self.run_test(g, slice.node(), expect_tensor(None, shape=(2, None, 4, None)))
def test_broadcast_matmul(self):
g = self.create_empty_graph()
constant = self.insert_tensor_constant(g, torch.ones(5, 1, 2))
constant_2 = self.insert_tensor_constant(g, torch.ones(3, 1, 2, 1))
shape = g_op(g, "MatMul", constant, constant_2)
self.run_test(g, shape.node(), expect_tensor("Float", shape=(3, 5, 1, 1)))
# test when first input is of rank 1
g = self.create_empty_graph()
constant = self.insert_tensor_constant(g, torch.ones(2))
constant_2 = self.insert_tensor_constant(g, torch.ones(3, 1, 2, 1))
shape = g_op(g, "MatMul", constant, constant_2)
self.run_test(g, shape.node(), expect_tensor("Float", shape=(3, 1, 1)))
# test when second input is of rank 1
g = self.create_empty_graph()
constant = self.insert_tensor_constant(g, torch.ones(5, 1, 2))
constant_2 = self.insert_tensor_constant(g, torch.ones(2))
shape = g_op(g, "MatMul", constant, constant_2)
self.run_test(g, shape.node(), expect_tensor("Float", shape=(5, 1)))
# test when both inputs are of rank 1
g = self.create_empty_graph()
constant = self.insert_tensor_constant(g, torch.ones(2))
constant_2 = self.insert_tensor_constant(g, torch.ones(2))
shape = g_op(g, "MatMul", constant, constant_2)
self.run_test(g, shape.node(), expect_tensor("Float", shape=()))
def test_expand(self):
g = self.create_empty_graph()
input = g.addInput()
constant = self.insert_tensor_constant(g, torch.ones(2, 4))
input.setType(constant.type().with_sizes([None, None]))
shape = g_op(g, "Shape", input)
expand = g_op(g, "Expand", constant, shape)
self.run_test(g, expand.node(), expect_tensor("Float", shape=(None, None)))
def test_pad(self):
g = self.create_empty_graph()
input = g.addInput()
input.setType(input.type().with_dtype(torch.float).with_sizes([3, 320, 100]))
constant = self.insert_tensor_constant(g, torch.ones(6, dtype=torch.long))
none = g_op(g, "prim::Constant").setType(torch.NoneType.get())
pad = g_op(g, "Pad", input, constant, none, mode_s="constant")
self.run_test(g, pad.node(), expect_tensor("Float", shape=(5, 322, 102)))
def test_pad_with_dynamic_input_shape(self):
g = self.create_empty_graph()
input = g.addInput()
input.setType(input.type().with_dtype(torch.float).with_sizes([3, None, None]))
constant = self.insert_tensor_constant(g, torch.ones(6, dtype=torch.long))
none = g_op(g, "prim::Constant").setType(torch.NoneType.get())
pad = g_op(g, "Pad", input, constant, none, mode_s="constant")
self.run_test(g, pad.node(), expect_tensor("Float", shape=(5, None, None)))
def test_pad_with_dynamic_pad_size(self):
g = self.create_empty_graph()
input = g.addInput()
input.setType(input.type().with_dtype(torch.float).with_sizes([3, 320, 100]))
pad_size = g.addInput()
pad_size.setType(pad_size.type().with_dtype(torch.long).with_sizes([6]))
none = g_op(g, "prim::Constant").setType(torch.NoneType.get())
pad = g_op(g, "Pad", input, pad_size, none, mode_s="constant")
self.run_test(g, pad.node(), expect_tensor("Float", shape=(None, None, None)))
def test_resize(self):
g = self.create_empty_graph()
input = g.addInput()
input.setType(input.type().with_dtype(torch.float).with_sizes([4, 32, 64, 64]))
none = g_op(g, "prim::Constant").setType(torch.NoneType.get())
scales = self.insert_tensor_constant(
g, torch.tensor([1, 1, 2, 2], dtype=torch.float)
)
resize = g_op(
g,
"Resize",
input,
none,
scales,
coordinate_transformation_mode_s="align_corners",
cubic_coeff_a_f=-0.75,
mode_s="linear",
nearest_mode_s="floor",
)
self.run_test(g, resize.node(), expect_tensor("Float", shape=(4, 32, 128, 128)))
def test_resize_after_concat(self):
g = self.create_empty_graph()
input = g.addInput()
input.setType(input.type().with_dtype(torch.float).with_sizes([4, 32, 64, 64]))
none = g_op(g, "prim::Constant").setType(torch.NoneType.get())
scale_1 = self.insert_tensor_constant(
g, torch.tensor([1, 1], dtype=torch.float)
)
scale_2 = self.insert_tensor_constant(
g, torch.tensor([2, 2], dtype=torch.float)
)
# `scales` values should be statically known due to constant folding in shape inference.
scales = g_op(g, "Concat", scale_1, scale_2, axis_i=0)
resize = g_op(
g,
"Resize",
input,
none,
scales,
coordinate_transformation_mode_s="align_corners",
cubic_coeff_a_f=-0.75,
mode_s="linear",
nearest_mode_s="floor",
)
self.run_test(g, resize.node(), expect_tensor("Float", shape=(4, 32, 128, 128)))
def test_reduce_prod_with_axes(self):
g = self.create_empty_graph()
input = g.addInput()
input.setType(input.type().with_dtype(torch.long).with_sizes([2]))
reduce_prod = g_op(g, "ReduceProd", input, axes_i=[0])
self.run_test(g, reduce_prod.node(), expect_tensor("Long", shape=(1,)))
def test_reduce_prod_without_axes(self):
g = self.create_empty_graph()
input = g.addInput()
input.setType(input.type().with_dtype(torch.long).with_sizes([2]))
reduce_prod = g_op(g, "ReduceProd", input)
self.run_test(g, reduce_prod.node(), expect_tensor("Long", shape=(1,)))
def test_proceeding_nodes_use_prim_pack_padded_output_dtype_correctly(self):
g = self.create_empty_graph()
input = g.addInput()
input.setType(input.type().with_dtype(torch.float).with_sizes([4, 16]))
length = g.addInput()
length.setType(length.type().with_dtype(torch.long).with_sizes([4]))
padded, batch_size = g_op(g, "prim::PackPadded", input, length, outputs=2)
# `prim::PackPadded` only occurs in tracing mode. Hence its outputs inherits
# shape and data type from traced graph.
padded.setType(padded.type().with_dtype(torch.float).with_sizes([None, None]))
batch_size.setType(batch_size.type().with_dtype(torch.long).with_sizes([None]))
# `Gather` should use the data type of `batch_size` as the data type of its output.
gather_idx = self.insert_tensor_constant(g, torch.tensor([0], dtype=torch.long))
gather = g_op(g, "Gather", batch_size, gather_idx, axis_i=0)
self.run_test(g, gather.node(), expect_tensor("Long", shape=(None,)))
def test_squeeze_after_dynamic_if(self):
from torch.onnx.symbolic_opset11 import squeeze as squeeze11
g = self.create_empty_graph()
input = g.addInput()
input.setType(input.type().with_dtype(torch.float).with_sizes([1, None, 5]))
# Type is intentionally not bool to test that
# the added "Cast" node doesn't stop shape inference.
cond = g.addInput()
cond.setType(input.type().with_dtype(torch.int32).with_sizes([1]))
_, (if_context, else_context), new_node = jit_utils.add_op_with_blocks(
as_graphcontext(g), "If", cond, n_blocks=2
)
block1_output = if_context.op("Add", input, input)
block2_output = else_context.op("Identity", input)
utils._add_output_to_block(if_context.block, block1_output)
utils._add_output_to_block(else_context.block, block2_output)
if_output = torch._C._jit_pass_fixup_onnx_controlflow_node(
new_node, _constants.ONNX_TORCHSCRIPT_EXPORTER_MAX_OPSET
)[0]
torch._C._jit_pass_onnx_node_shape_type_inference(
new_node, {}, _constants.ONNX_TORCHSCRIPT_EXPORTER_MAX_OPSET
)
# Exporter will add "If" instead of raw "Squeeze" if it does not know
# that if the dimension it is squeezing has size 1.
squeezed = squeeze11(as_graphcontext(g), if_output, dim=0)
assert squeezed.node().kind() == "onnx::Squeeze"
self.run_test(g, squeezed.node(), expect_tensor("Float", shape=(None, 5)))
|
TestONNXShapeInference
|
python
|
python-attrs__attrs
|
tests/test_validators.py
|
{
"start": 9241,
"end": 11504
}
|
class ____:
"""
Tests for `in_`.
"""
def test_in_all(self):
"""
Verify that this validator is in ``__all__``.
"""
assert in_.__name__ in validator_module.__all__
def test_success_with_value(self):
"""
If the value is in our options, nothing happens.
"""
v = in_([1, 2, 3])
a = simple_attr("test")
v(1, a, 3)
def test_fail(self):
"""
Raise ValueError if the value is outside our options.
"""
v = in_([1, 2, 3])
a = simple_attr("test")
with pytest.raises(ValueError) as e:
v(None, a, None)
assert (
"'test' must be in [1, 2, 3] (got None)",
a,
[1, 2, 3],
None,
) == e.value.args
def test_fail_with_string(self):
"""
Raise ValueError if the value is outside our options when the
options are specified as a string and the value is not a string.
"""
v = in_("abc")
a = simple_attr("test")
with pytest.raises(ValueError) as e:
v(None, a, None)
assert (
"'test' must be in 'abc' (got None)",
a,
"abc",
None,
) == e.value.args
def test_repr(self):
"""
Returned validator has a useful `__repr__`.
"""
v = in_([3, 4, 5])
assert ("<in_ validator with options [3, 4, 5]>") == repr(v)
def test_is_hashable(self):
"""
`in_` is hashable, so fields using it can be used with the include and
exclude filters.
"""
@attr.s
class C:
x: int = attr.ib(validator=attr.validators.in_({1, 2}))
i = C(2)
attr.asdict(i, filter=attr.filters.include(lambda val: True))
attr.asdict(i, filter=attr.filters.exclude(lambda val: True))
@pytest.fixture(
name="member_validator",
params=(
instance_of(int),
[always_pass, instance_of(int)],
(always_pass, instance_of(int)),
),
scope="module",
)
def _member_validator(request):
"""
Provides sample `member_validator`s for some tests in `TestDeepIterable`
"""
return request.param
|
TestIn_
|
python
|
pytorch__pytorch
|
torch/ao/quantization/fx/_model_report/detector.py
|
{
"start": 1096,
"end": 4436
}
|
class ____:
r"""
This class contains the QConfig information for a single module.
The list of variables / values this contains can grow depending on the
extensibility of the qconfig mapping feature set but this currently includes:
- if activation observer is dynamic
- if weight observer is per channel
Args:
module_fqn (str): The fully qualified name (fqn) of the module that this
information contains info relevant to qconfig for
"""
def __init__(self, module_fqn: str):
super().__init__()
self.module_fqn = module_fqn
# populate this section with all the variables we might find important
# change from none if your detector is actually using this
self.is_activation_dynamic = False
self.is_weight_per_channel = False
# equalization related options
self.is_equalization_recommended = False
def generate_quantization_qconfig(self, module: torch.nn.Module) -> QConfig:
r"""
Args:
module (torch.nn.Module) The module we are generating
the qconfig for
Returns the generated quantization QConfig according to what a valid configuration is
"""
# Apply suggestions to new qconfig
module_qconfig = default_qconfig
# keep track of dynamic and per_channel recommendations
recommendations_list = []
# append as if a list of combinations
recommendations_list.append(
(self.is_activation_dynamic, self.is_weight_per_channel)
)
recommendations_list.append(
(self.is_activation_dynamic, False)
) # only trying dynamic rec
recommendations_list.append(
(False, self.is_weight_per_channel)
) # only trying dynamic
# now we try each of the combinations
for rec in recommendations_list:
# rec[0] -> dynamic recommended
# rec[1] -> per channel recommended
activation = default_dynamic_quant_observer if rec[0] else default_observer
weight = (
default_per_channel_weight_observer
if rec[1]
else default_weight_observer
)
test_config = QConfig(activation, weight)
try:
_assert_valid_qconfig(test_config, module)
module_qconfig = test_config
break
except AssertionError:
# if not a valid configuration, we move on to the next one in priority
continue
# return the QConfig chosen
return module_qconfig
def generate_equalization_qconfig(self) -> EqualizationQConfig:
r"""
This returns the equalization configuration for a module.
For now, it just returns the default, but as more equalization options become
possible, this method can get more fleshed out with more nuanced granularity.
Returns the generated equalization QConfig according to what a valid configuration is
"""
# in this case, we just return default equalization config
# we know this is valid because only valid modules would even
# have this option
return default_equalization_qconfig
# Adding base class for detectors
|
DetectorQConfigInfo
|
python
|
huggingface__transformers
|
src/transformers/models/ibert/modeling_ibert.py
|
{
"start": 43148,
"end": 43938
}
|
class ____(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
def forward(self, features, **kwargs):
hidden_states = features[:, 0, :] # take <s> token (equiv. to [CLS])
hidden_states = self.dropout(hidden_states)
hidden_states = self.dense(hidden_states)
hidden_states = torch.tanh(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.out_proj(hidden_states)
return hidden_states
@auto_docstring
|
IBertClassificationHead
|
python
|
numba__numba
|
numba/tests/test_sort.py
|
{
"start": 4597,
"end": 16275
}
|
class ____(BaseSortingTest):
def merge_init(self, keys):
f = self.timsort.merge_init
return f(keys)
def test_binarysort(self):
n = 20
def check(l, n, start=0):
res = self.array_factory(l)
f(res, res, 0, n, start)
self.assertSorted(l, res)
f = self.timsort.binarysort
l = self.sorted_list(n)
check(l, n)
check(l, n, n//2)
l = self.revsorted_list(n)
check(l, n)
l = self.initially_sorted_list(n, n//2)
check(l, n)
check(l, n, n//2)
l = self.revsorted_list(n)
check(l, n)
l = self.random_list(n)
check(l, n)
l = self.duprandom_list(n)
check(l, n)
def test_binarysort_with_values(self):
n = 20
v = list(range(100, 100+n))
def check(l, n, start=0):
res = self.array_factory(l)
res_v = self.array_factory(v)
f(res, res_v, 0, n, start)
self.assertSortedValues(l, v, res, res_v)
f = self.timsort.binarysort
l = self.sorted_list(n)
check(l, n)
check(l, n, n//2)
l = self.revsorted_list(n)
check(l, n)
l = self.initially_sorted_list(n, n//2)
check(l, n)
check(l, n, n//2)
l = self.revsorted_list(n)
check(l, n)
l = self.random_list(n)
check(l, n)
l = self.duprandom_list(n)
check(l, n)
def test_count_run(self):
n = 16
f = self.timsort.count_run
def check(l, lo, hi):
n, desc = f(self.array_factory(l), lo, hi)
# Fully check invariants
if desc:
for k in range(lo, lo + n - 1):
a, b = l[k], l[k + 1]
self.assertGreater(a, b)
if lo + n < hi:
self.assertLessEqual(l[lo + n - 1], l[lo + n])
else:
for k in range(lo, lo + n - 1):
a, b = l[k], l[k + 1]
self.assertLessEqual(a, b)
if lo + n < hi:
self.assertGreater(l[lo + n - 1], l[lo + n], l)
l = self.sorted_list(n, offset=100)
check(l, 0, n)
check(l, 1, n - 1)
check(l, 1, 2)
l = self.revsorted_list(n, offset=100)
check(l, 0, n)
check(l, 1, n - 1)
check(l, 1, 2)
l = self.random_list(n, offset=100)
for i in range(len(l) - 1):
check(l, i, n)
l = self.duprandom_list(n, offset=100)
for i in range(len(l) - 1):
check(l, i, n)
def test_gallop_left(self):
n = 20
f = self.timsort.gallop_left
def check(l, key, start, stop, hint):
k = f(key, l, start, stop, hint)
# Fully check invariants
self.assertGreaterEqual(k, start)
self.assertLessEqual(k, stop)
if k > start:
self.assertLess(l[k - 1], key)
if k < stop:
self.assertGreaterEqual(l[k], key)
def check_all_hints(l, key, start, stop):
for hint in range(start, stop):
check(l, key, start, stop, hint)
def check_sorted_list(l):
l = self.array_factory(l)
for key in (l[5], l[15], l[0], -1000, l[-1], 1000):
check_all_hints(l, key, 0, n)
check_all_hints(l, key, 1, n - 1)
check_all_hints(l, key, 8, n - 8)
l = self.sorted_list(n, offset=100)
check_sorted_list(l)
l = self.dupsorted_list(n, offset=100)
check_sorted_list(l)
def test_gallop_right(self):
n = 20
f = self.timsort.gallop_right
def check(l, key, start, stop, hint):
k = f(key, l, start, stop, hint)
# Fully check invariants
self.assertGreaterEqual(k, start)
self.assertLessEqual(k, stop)
if k > start:
self.assertLessEqual(l[k - 1], key)
if k < stop:
self.assertGreater(l[k], key)
def check_all_hints(l, key, start, stop):
for hint in range(start, stop):
check(l, key, start, stop, hint)
def check_sorted_list(l):
l = self.array_factory(l)
for key in (l[5], l[15], l[0], -1000, l[-1], 1000):
check_all_hints(l, key, 0, n)
check_all_hints(l, key, 1, n - 1)
check_all_hints(l, key, 8, n - 8)
l = self.sorted_list(n, offset=100)
check_sorted_list(l)
l = self.dupsorted_list(n, offset=100)
check_sorted_list(l)
def test_merge_compute_minrun(self):
f = self.timsort.merge_compute_minrun
for i in range(0, 64):
self.assertEqual(f(i), i)
for i in range(6, 63):
if 2**i > sys.maxsize:
break
self.assertEqual(f(2**i), 32)
for i in self.fibo():
if i < 64:
continue
if i >= sys.maxsize:
break
k = f(i)
self.assertGreaterEqual(k, 32)
self.assertLessEqual(k, 64)
if i > 500:
# i/k is close to, but strictly less than, an exact power of 2
quot = i // k
p = 2 ** utils.bit_length(quot)
self.assertLess(quot, p)
self.assertGreaterEqual(quot, 0.9 * p)
def check_merge_lo_hi(self, func, a, b):
na = len(a)
nb = len(b)
# Add sentinels at start and end, to check they weren't moved
orig_keys = [42] + a + b + [-42]
keys = self.array_factory(orig_keys)
ms = self.merge_init(keys)
ssa = 1
ssb = ssa + na
#new_ms = func(ms, keys, [], ssa, na, ssb, nb)
new_ms = func(ms, keys, keys, ssa, na, ssb, nb)
self.assertEqual(keys[0], orig_keys[0])
self.assertEqual(keys[-1], orig_keys[-1])
self.assertSorted(orig_keys[1:-1], keys[1:-1])
# Check the MergeState result
self.assertGreaterEqual(len(new_ms.keys), len(ms.keys))
self.assertGreaterEqual(len(new_ms.values), len(ms.values))
self.assertIs(new_ms.pending, ms.pending)
self.assertGreaterEqual(new_ms.min_gallop, 1)
def test_merge_lo_hi(self):
f_lo = self.timsort.merge_lo
f_hi = self.timsort.merge_hi
# The larger sizes exercise galloping
for (na, nb) in [(12, 16), (40, 40), (100, 110), (1000, 1100)]:
for a, b in itertools.product(self.make_sample_sorted_lists(na),
self.make_sample_sorted_lists(nb)):
self.check_merge_lo_hi(f_lo, a, b)
self.check_merge_lo_hi(f_hi, b, a)
def check_merge_at(self, a, b):
f = self.timsort.merge_at
# Prepare the array to be sorted
na = len(a)
nb = len(b)
# Add sentinels at start and end, to check they weren't moved
orig_keys = [42] + a + b + [-42]
ssa = 1
ssb = ssa + na
stack_sentinel = MergeRun(-42, -42)
def run_merge_at(ms, keys, i):
new_ms = f(ms, keys, keys, i)
self.assertEqual(keys[0], orig_keys[0])
self.assertEqual(keys[-1], orig_keys[-1])
self.assertSorted(orig_keys[1:-1], keys[1:-1])
# Check stack state
self.assertIs(new_ms.pending, ms.pending)
self.assertEqual(ms.pending[i], (ssa, na + nb))
self.assertEqual(ms.pending[0], stack_sentinel)
return new_ms
# First check with i == len(stack) - 2
keys = self.array_factory(orig_keys)
ms = self.merge_init(keys)
# Push sentinel on stack, to check it wasn't touched
ms = self.timsort.merge_append(ms, stack_sentinel)
i = ms.n
ms = self.timsort.merge_append(ms, MergeRun(ssa, na))
ms = self.timsort.merge_append(ms, MergeRun(ssb, nb))
ms = run_merge_at(ms, keys, i)
self.assertEqual(ms.n, i + 1)
# Now check with i == len(stack) - 3
keys = self.array_factory(orig_keys)
ms = self.merge_init(keys)
# Push sentinel on stack, to check it wasn't touched
ms = self.timsort.merge_append(ms, stack_sentinel)
i = ms.n
ms = self.timsort.merge_append(ms, MergeRun(ssa, na))
ms = self.timsort.merge_append(ms, MergeRun(ssb, nb))
# A last run (trivial here)
last_run = MergeRun(ssb + nb, 1)
ms = self.timsort.merge_append(ms, last_run)
ms = run_merge_at(ms, keys, i)
self.assertEqual(ms.n, i + 2)
self.assertEqual(ms.pending[ms.n - 1], last_run)
def test_merge_at(self):
# The larger sizes exercise galloping
for (na, nb) in [(12, 16), (40, 40), (100, 110), (500, 510)]:
for a, b in itertools.product(self.make_sample_sorted_lists(na),
self.make_sample_sorted_lists(nb)):
self.check_merge_at(a, b)
self.check_merge_at(b, a)
def test_merge_force_collapse(self):
f = self.timsort.merge_force_collapse
# Test with runs of ascending sizes, then descending sizes
sizes_list = [(8, 10, 15, 20)]
sizes_list.append(sizes_list[0][::-1])
for sizes in sizes_list:
for chunks in itertools.product(*(self.make_sample_sorted_lists(n)
for n in sizes)):
# Create runs of the given sizes
orig_keys = sum(chunks, [])
keys = self.array_factory(orig_keys)
ms = self.merge_init(keys)
pos = 0
for c in chunks:
ms = self.timsort.merge_append(ms, MergeRun(pos, len(c)))
pos += len(c)
# Sanity check
self.assertEqual(sum(ms.pending[ms.n - 1]), len(keys))
# Now merge the runs
ms = f(ms, keys, keys)
# Remaining run is the whole list
self.assertEqual(ms.n, 1)
self.assertEqual(ms.pending[0], MergeRun(0, len(keys)))
# The list is now sorted
self.assertSorted(orig_keys, keys)
def test_run_timsort(self):
f = self.timsort.run_timsort
for size_factor in (1, 10):
# Make lists to be sorted from three chunks of different kinds.
sizes = (15, 30, 20)
all_lists = [self.make_sample_lists(n * size_factor) for n in sizes]
for chunks in itertools.product(*all_lists):
orig_keys = sum(chunks, [])
keys = self.array_factory(orig_keys)
f(keys)
# The list is now sorted
self.assertSorted(orig_keys, keys)
def test_run_timsort_with_values(self):
# Run timsort, but also with a values array
f = self.timsort.run_timsort_with_values
for size_factor in (1, 5):
chunk_size = 80 * size_factor
a = self.dupsorted_list(chunk_size)
b = self.duprandom_list(chunk_size)
c = self.revsorted_list(chunk_size)
orig_keys = a + b + c
orig_values = list(range(1000, 1000 + len(orig_keys)))
keys = self.array_factory(orig_keys)
values = self.array_factory(orig_values)
f(keys, values)
# This checks sort stability
self.assertSortedValues(orig_keys, orig_values, keys, values)
|
BaseTimsortTest
|
python
|
scipy__scipy
|
scipy/sparse/linalg/_eigen/tests/test_svds.py
|
{
"start": 35961,
"end": 36616
}
|
class ____(SVDSCommonTests):
def setup_method(self):
self.solver = 'propack'
def test_svd_LM_ones_matrix(self):
message = ("PROPACK does not return orthonormal singular vectors "
"associated with zero singular values.")
# There are some other issues with this matrix of all ones, e.g.
# `which='sm'` and `k=1` returns the largest singular value
pytest.xfail(message)
def test_svd_LM_zeros_matrix(self):
message = ("PROPACK does not return orthonormal singular vectors "
"associated with zero singular values.")
pytest.xfail(message)
|
Test_SVDS_PROPACK
|
python
|
PyCQA__pylint
|
doc/data/messages/i/invalid-length-returned/good.py
|
{
"start": 0,
"end": 159
}
|
class ____:
def __init__(self, fruits):
self.fruits = ["Apple", "Banana", "Orange"]
def __len__(self):
return len(self.fruits)
|
FruitBasket
|
python
|
great-expectations__great_expectations
|
great_expectations/render/components.py
|
{
"start": 1430,
"end": 1743
}
|
class ____(str, Enum):
"""Available atomic diagnostic renderer names"""
FAILED = ".".join([AtomicRendererType.DIAGNOSTIC, "failed"])
OBSERVED_VALUE = ".".join([AtomicRendererType.DIAGNOSTIC, "observed_value"])
@override
def __str__(self):
return self.value
|
AtomicDiagnosticRendererType
|
python
|
Lightning-AI__lightning
|
tests/tests_pytorch/strategies/test_ddp_integration.py
|
{
"start": 12663,
"end": 13350
}
|
class ____(BoringModel):
def configure_optimizers(self):
assert all(param.device.type == "cuda" for param in self.parameters())
super().configure_optimizers()
@RunIf(min_cuda_gpus=1)
@pytest.mark.parametrize("strategy", ["ddp", "ddp_spawn"])
def test_model_parameters_on_device_for_optimizer(strategy):
"""Test that the strategy has moved the parameters to the device by the time the optimizer gets created."""
model = CheckOptimizerDeviceModel()
trainer = Trainer(
default_root_dir=os.getcwd(),
fast_dev_run=1,
accelerator="gpu",
devices=1,
strategy=strategy,
)
trainer.fit(model)
|
CheckOptimizerDeviceModel
|
python
|
PyCQA__pylint
|
tests/regrtest_data/max_inferable_limit_for_classes/main.py
|
{
"start": 577,
"end": 667
}
|
class ____(FunctionElement):
def __init__(self):
super().__init__()
|
months_between
|
python
|
conda__conda
|
conda/models/records.py
|
{
"start": 1656,
"end": 2986
}
|
class ____(NumberField):
def __init__(self):
super().__init__(default=0, required=False, default_in_dump=False)
@staticmethod
def _make_seconds(val):
if val:
val = val
if val > 253402300799: # 9999-12-31
val /= (
1000 # convert milliseconds to seconds; see conda/conda-build#1988
)
return val
@staticmethod
def _make_milliseconds(val):
if val:
if val < 253402300799: # 9999-12-31
val *= 1000 # convert seconds to milliseconds
val = val
return val
def box(self, instance, instance_type, val):
return self._make_seconds(super().box(instance, instance_type, val))
def dump(self, instance, instance_type, val):
return int(
self._make_milliseconds(super().dump(instance, instance_type, val))
) # whether in seconds or milliseconds, type must be int (not float) for backward compat
def __get__(self, instance, instance_type):
try:
return super().__get__(instance, instance_type)
except AttributeError:
try:
return int(dt_to_timestamp(isoparse(instance.date)))
except (AttributeError, ValueError):
return 0
|
TimestampField
|
python
|
xlwings__xlwings
|
tests/test_shape.py
|
{
"start": 8240,
"end": 8772
}
|
class ____(TestBase):
def test_add_no_name(self):
fig = plt.figure()
plt.plot([-1, 1, -2, 2, -3, 3, 2])
self.wb1.sheets[0].pictures.add(fig)
self.assertEqual(len(self.wb1.sheets[0].pictures), 1)
def test_add_with_name(self):
fig = plt.figure()
plt.plot([-1, 1, -2, 2, -3, 3, 2])
self.wb1.sheets[0].pictures.add(fig, name="Test1")
self.assertEqual(self.wb1.sheets[0].pictures[0].name, "Test1")
@unittest.skipIf(plotly_go is None, "plotly missing")
|
TestMatplotlib
|
python
|
getsentry__sentry
|
tests/sentry/monitors/consumers/test_end_to_end.py
|
{
"start": 1711,
"end": 10877
}
|
class ____(TestCase):
def send_checkin(
self,
status: str,
guid: str | None = None,
ts: datetime | None = None,
item_ts: datetime | None = None,
) -> str:
if ts is None:
ts = self.time.replace(tzinfo=None)
if item_ts is None:
item_ts = ts
guid = uuid.uuid4().hex if not guid else guid
trace_id = uuid.uuid4().hex
payload = {
"monitor_slug": self.monitor.slug,
"status": status,
"check_in_id": guid,
"environment": "production",
"contexts": {"trace": {"trace_id": trace_id}},
}
wrapper: CheckIn = {
"message_type": "check_in",
"start_time": ts.timestamp(),
"project_id": self.project.id,
"payload": json.dumps(payload).encode(),
"sdk": "test/1.0",
"retention_days": 90,
}
with self.check_processing_errors(wrapper, None, None):
self.consumer.submit(
Message(
BrokerValue(
KafkaPayload(b"fake-key", msgpack.packb(wrapper), []),
self.partition,
1,
item_ts,
)
)
)
return guid
@contextlib.contextmanager
def check_processing_errors(
self,
expected_checkin: CheckIn,
expected_error: ProcessingErrorsException | ExpectNoProcessingError | None,
expected_monitor_slug: str | None,
) -> Generator:
if expected_error is None:
yield None
return
with mock.patch(
"sentry.monitors.consumers.monitor_consumer.handle_processing_errors"
) as handle_processing_errors:
yield
args_list = handle_processing_errors.call_args_list
if isinstance(expected_error, ExpectNoProcessingError):
assert len(args_list) == 0
return
assert len(args_list) == 1
checkin_item, error = args_list[0][0]
expected_checkin_item = CheckinItem(
datetime.fromtimestamp(expected_checkin["start_time"]),
self.partition.index,
expected_checkin,
json.loads(expected_checkin["payload"]),
)
if expected_monitor_slug:
expected_error.monitor = Monitor.objects.get(
project_id=expected_checkin["project_id"], slug=expected_monitor_slug
)
assert checkin_item == expected_checkin_item
assert error.monitor == expected_error.monitor
assert error.processing_errors == expected_error.processing_errors
def init(self, checkin_margin=1, max_runtime=1):
self.time = timezone.now().replace(second=0, microsecond=0)
self.time_delta = timedelta(minutes=1)
self.broker: LocalBroker[KafkaPayload] = LocalBroker(MemoryMessageStorage())
self.clock_tick_topic = Topic("monitors-clock-tick")
self.clock_tasks_topic = Topic("monitors-clock-tasks")
self.broker.create_topic(self.clock_tick_topic, partitions=1)
self.broker.create_topic(self.clock_tasks_topic, partitions=1)
self.consumer = create_consumer()
self.partition = partition
# Setup one monitor which should be marked as missed, and one check-in that
# should be marked as timed-out
self.monitor = Monitor.objects.create(
organization_id=self.organization.id,
project_id=self.project.id,
config={
"schedule": "* * * * *",
"schedule_type": ScheduleType.CRONTAB,
"checkin_margin": checkin_margin,
"max_runtime": max_runtime,
},
)
self.monitor_environment = MonitorEnvironment.objects.ensure_environment(
self.project, self.monitor, "production"
)
self.monitor_environment.status = MonitorStatus.OK
self.monitor_environment.last_checkin = self.time
self.monitor_environment.next_checkin = self.time + self.time_delta
self.monitor_environment.next_checkin_latest = self.time + self.time_delta * 2
self.monitor_environment.save()
self.producer = self.broker.get_producer()
self.tick_consumer = self.broker.get_consumer("monitors-clock-tick")
self.tasks_consumer = self.broker.get_consumer("monitors-clock-tasks")
self.tick_processor = StreamProcessor(
consumer=self.tick_consumer,
topic=self.clock_tick_topic,
processor_factory=MonitorClockTickStrategyFactory(),
commit_policy=ONCE_PER_SECOND,
)
self.task_processor = StreamProcessor(
consumer=self.tasks_consumer,
topic=self.clock_tasks_topic,
processor_factory=MonitorClockTasksStrategyFactory(),
commit_policy=ONCE_PER_SECOND,
)
def tick_clock(self, delta: timedelta | None = None):
if delta is None:
delta = self.time_delta
self.time = self.time + delta
# Dispatch a clock tick
with mock.patch(
"sentry.monitors.clock_dispatch._clock_tick_producer",
self.producer,
):
try_monitor_clock_tick(self.time, 0)
# Process the tick. This will produce two tasks, one for the missed
# check-in and one for the timed-out check-in. This will produce two
# tasks, one for the missed check-in and one for the timed-out check-in
with mock.patch(
"sentry.monitors.clock_tasks.producer._clock_task_producer",
self.producer,
):
self.tick_processor._run_once()
# process the two tasks
self.task_processor._run_once()
self.task_processor._run_once()
@override_settings(SENTRY_EVENTSTREAM="sentry.eventstream.kafka.KafkaEventStream")
def test_two_in_progress_timeout(self) -> None:
self.init()
self.send_checkin("in_progress")
self.tick_clock()
self.send_checkin("in_progress")
self.tick_clock(timedelta(seconds=59))
self.monitor_environment.refresh_from_db()
checkins = list(MonitorCheckIn.objects.filter(monitor_environment=self.monitor_environment))
checkins.sort(key=lambda checkin: checkin.id)
assert checkins[0].status == CheckInStatus.TIMEOUT
assert checkins[1].status == CheckInStatus.IN_PROGRESS
assert self.monitor_environment.status == MonitorStatus.ERROR
@override_settings(SENTRY_EVENTSTREAM="sentry.eventstream.kafka.KafkaEventStream")
def test_timeout_followed_by_checkin(self) -> None:
self.init()
self.send_checkin("in_progress")
self.tick_clock()
guid = self.send_checkin("in_progress")
self.tick_clock(timedelta(seconds=1))
self.send_checkin("ok", guid)
self.tick_clock(timedelta(seconds=59))
self.monitor_environment.refresh_from_db()
checkins = list(MonitorCheckIn.objects.filter(monitor_environment=self.monitor_environment))
checkins.sort(key=lambda checkin: checkin.id)
assert len(checkins) == 2
assert checkins[0].status == CheckInStatus.TIMEOUT
assert checkins[1].status == CheckInStatus.OK
assert self.monitor_environment.status == MonitorStatus.OK
@override_settings(SENTRY_EVENTSTREAM="sentry.eventstream.kafka.KafkaEventStream")
def test_late_ok_followed_by_timeout(self) -> None:
self.init(1, 2)
first_guid = self.send_checkin("in_progress")
self.tick_clock()
self.send_checkin("in_progress")
self.tick_clock(timedelta(seconds=59))
self.send_checkin("ok", first_guid)
self.monitor_environment.refresh_from_db()
checkins = list(MonitorCheckIn.objects.filter(monitor_environment=self.monitor_environment))
checkins.sort(key=lambda checkin: checkin.id)
assert len(checkins) == 2
assert checkins[0].status == CheckInStatus.OK
assert checkins[1].status == CheckInStatus.IN_PROGRESS
assert self.monitor_environment.status == MonitorStatus.OK
@override_settings(SENTRY_EVENTSTREAM="sentry.eventstream.kafka.KafkaEventStream")
def test_late_ok_followed_by_missed(self) -> None:
self.init(1, 3)
first_guid = self.send_checkin("in_progress")
self.tick_clock()
self.tick_clock()
self.tick_clock(timedelta(seconds=59))
self.send_checkin("ok", first_guid)
self.monitor_environment.refresh_from_db()
checkins = list(MonitorCheckIn.objects.filter(monitor_environment=self.monitor_environment))
checkins.sort(key=lambda checkin: checkin.id)
assert len(checkins) == 2
assert checkins[0].status == CheckInStatus.OK
assert checkins[1].status == CheckInStatus.MISSED
assert self.monitor_environment.status == MonitorStatus.OK
|
MonitorsClockTickEndToEndTest
|
python
|
pytorch__pytorch
|
test/distributed/tensor/experimental/test_tp_transform.py
|
{
"start": 1387,
"end": 5602
}
|
class ____(DTensorTestBase):
def setUp(self) -> None:
super().setUp()
def assert_has_c10d_ops(
self, gm: torch.fx.GraphModule, expected_ops_count: dict[str, int]
) -> None:
actual_ops_count: dict[str, int] = defaultdict(int)
for node in gm.graph.nodes:
if node.op == "call_function":
if "c10d_functional" in str(node.target):
actual_ops_count[str(node.target)] += 1
self.assertDictEqual(expected_ops_count, actual_ops_count)
@with_comms
def test_tp_transform_with_uncovered_op(self):
model = DummyModel().to(device=self.device_type)
inputs = (torch.randn(7, 3, requires_grad=False).to(device=self.device_type),)
with torch.no_grad():
res = model(*inputs)
exported_program = torch.export.export(
model, inputs, strict=True
).run_decompositions()
tp_exported_program = tensor_parallel_transformation(
exported_program,
self.rank,
self.world_size,
self.device_type,
{"fc": ColwiseParallel},
)
tp_model = tp_exported_program.module()
with torch.no_grad():
tp_res = tp_model(*inputs)
self.assertEqual(res, tp_res)
# Expect all_gather to be inserted to distributed sharded fc results
self.assert_has_c10d_ops(
tp_exported_program.graph_module,
{
"_c10d_functional.all_gather_into_tensor.default": 1,
"_c10d_functional.wait_tensor.default": 1,
},
)
@with_comms
def test_tp_transform_e2e(self):
torch.manual_seed(0)
model = MLPListModule(2).to(device=self.device_type)
inputs = (torch.randn((10, 12)).to(device=self.device_type),)
parallel_strategies: dict[str, ParallelStyle] = {
"mlps.0.0": ColwiseParallel,
"mlps.0.2": RowwiseParallel,
"mlps.1.0": ColwiseParallel,
"mlps.1.2": RowwiseParallel,
}
with torch.inference_mode():
res = model(*inputs)
exported_program = torch.export.export(
model, inputs, strict=True
).run_decompositions()
tp_exported_program = tensor_parallel_transformation(
exported_program,
self.rank,
self.world_size,
self.device_type,
parallel_strategies,
)
tp_model = tp_exported_program.module()
with torch.inference_mode():
tp_res = tp_model(*inputs)
self.assertEqual(res, tp_res)
# Expect all_reduce to be inserted at the end of each MLP
self.assert_has_c10d_ops(
tp_exported_program.graph_module,
{
"_c10d_functional.all_reduce.default": 2,
"_c10d_functional.wait_tensor.default": 2,
},
)
@with_comms
def test_tp_transform_no_bias(self):
torch.manual_seed(0)
model = MLPListModule(1, bias=False).to(device=self.device_type)
inputs = (torch.randn((10, 12)).to(device=self.device_type),)
parallel_strategies: dict[str, ParallelStyle] = {
"mlps.0.0": ColwiseParallel,
"mlps.0.2": RowwiseParallel,
}
with torch.inference_mode():
res = model(*inputs)
exported_program = torch.export.export(
model, inputs, strict=True
).run_decompositions()
tp_exported_program = tensor_parallel_transformation(
exported_program,
self.rank,
self.world_size,
self.device_type,
parallel_strategies,
)
tp_model = tp_exported_program.module()
with torch.inference_mode():
tp_res = tp_model(*inputs)
self.assertEqual(res, tp_res)
self.assert_has_c10d_ops(
tp_exported_program.graph_module,
{
"_c10d_functional.all_reduce.default": 1,
"_c10d_functional.wait_tensor.default": 1,
},
)
if __name__ == "__main__":
run_tests()
|
TensorParallelTest
|
python
|
kamyu104__LeetCode-Solutions
|
Python/all-paths-from-source-lead-to-destination.py
|
{
"start": 58,
"end": 1102
}
|
class ____(object):
def leadsToDestination(self, n, edges, source, destination):
"""
:type n: int
:type edges: List[List[int]]
:type source: int
:type destination: int
:rtype: bool
"""
UNVISITED, VISITING, DONE = range(3)
def dfs(children, node, destination, status):
if status[node] == DONE:
return True
if status[node] == VISITING:
return False
status[node] = VISITING
if node not in children and node != destination:
return False
if node in children:
for child in children[node]:
if not dfs(children, child, destination, status):
return False
status[node] = DONE
return True
children = collections.defaultdict(list)
for parent, child in edges:
children[parent].append(child)
return dfs(children, source, destination, [0]*n)
|
Solution
|
python
|
bokeh__bokeh
|
src/bokeh/events.py
|
{
"start": 9465,
"end": 9731
}
|
class ____(ModelEvent):
''' Announce a click event on a Bokeh legend item.
'''
event_name = 'legend_item_click'
def __init__(self, model: Legend, item: LegendItem) -> None:
self.item = item
super().__init__(model=model)
|
LegendItemClick
|
python
|
pydantic__pydantic
|
pydantic-core/tests/validators/test_dataclasses.py
|
{
"start": 46844,
"end": 46927
}
|
class ____:
a: str
b: bool
@dataclasses.dataclass(**kwargs)
|
FooDataclassSlots
|
python
|
pallets__werkzeug
|
src/werkzeug/datastructures/range.py
|
{
"start": 194,
"end": 1147
}
|
class ____:
"""Very simple object that represents the `If-Range` header in parsed
form. It will either have neither a etag or date or one of either but
never both.
.. versionadded:: 0.7
"""
def __init__(self, etag: str | None = None, date: datetime | None = None):
#: The etag parsed and unquoted. Ranges always operate on strong
#: etags so the weakness information is not necessary.
self.etag = etag
#: The date in parsed format or `None`.
self.date = date
def to_header(self) -> str:
"""Converts the object back into an HTTP header."""
if self.date is not None:
return http.http_date(self.date)
if self.etag is not None:
return http.quote_etag(self.etag)
return ""
def __str__(self) -> str:
return self.to_header()
def __repr__(self) -> str:
return f"<{type(self).__name__} {str(self)!r}>"
|
IfRange
|
python
|
ray-project__ray
|
python/ray/autoscaler/v2/scheduler.py
|
{
"start": 3395,
"end": 3870
}
|
class ____(ABC):
"""
Interface for a resource scheduler.
Implements the `instance_manager.proto ResourceSchedulerService` interface.
"""
@abstractmethod
def schedule(self, request: SchedulingRequest) -> SchedulingReply:
"""
Given the resource requests and the current cluster state, calculate the
target cluster shape by trying to schedule the resource requests on the
nodes.
"""
pass
|
IResourceScheduler
|
python
|
vyperlang__vyper
|
vyper/venom/analysis/mem_ssa.py
|
{
"start": 1869,
"end": 1961
}
|
class ____(MemoryAccess):
"""
For type checking purposes
"""
pass
|
LiveOnEntry
|
python
|
dateutil__dateutil
|
src/dateutil/parser/_parser.py
|
{
"start": 58616,
"end": 58796
}
|
class ____(RuntimeWarning):
"""Raised when the parser finds a timezone it cannot parse into a tzinfo.
.. versionadded:: 2.7.0
"""
# vim:ts=4:sw=4:et
|
UnknownTimezoneWarning
|
python
|
jmcnamara__XlsxWriter
|
xlsxwriter/test/comparison/test_defined_name02.py
|
{
"start": 315,
"end": 865
}
|
class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("defined_name02.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with defined names."""
workbook = Workbook(self.got_filename)
worksheet1 = workbook.add_worksheet("sheet One")
workbook.define_name("Sales", "='sheet One'!$G$1:$H$10")
workbook.close()
self.assertExcelEqual()
|
TestCompareXLSXFiles
|
python
|
getsentry__sentry
|
tests/sentry/api/endpoints/release_thresholds/test_release_threshold_details.py
|
{
"start": 2686,
"end": 4798
}
|
class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user(is_staff=True, is_superuser=True)
self.canary_environment = Environment.objects.create(
organization_id=self.organization.id, name="canary"
)
self.production_environment = Environment.objects.create(
organization_id=self.organization.id, name="production"
)
self.login_as(user=self.user)
self.basic_threshold = ReleaseThreshold.objects.create(
threshold_type=0,
trigger_type=0,
value=100,
window_in_seconds=1800,
project=self.project,
environment=self.canary_environment,
)
def test_invalid_threshold_id(self) -> None:
url = reverse(
"sentry-api-0-project-release-thresholds-details",
kwargs={
"organization_id_or_slug": self.organization.slug,
"project_id_or_slug": self.project.slug,
"release_threshold": 123,
},
)
response = self.client.delete(url)
assert response.status_code == 404
def test_invalid_project(self) -> None:
url = reverse(
"sentry-api-0-project-release-thresholds-details",
kwargs={
"organization_id_or_slug": self.organization.slug,
"project_id_or_slug": "kingdom_of_the_crystal_skull",
"release_threshold": self.basic_threshold.id,
},
)
response = self.client.delete(url)
assert response.status_code == 404
def test_valid(self) -> None:
url = reverse(
"sentry-api-0-project-release-thresholds-details",
kwargs={
"organization_id_or_slug": self.organization.slug,
"project_id_or_slug": self.project.slug,
"release_threshold": self.basic_threshold.id,
},
)
response = self.client.delete(url)
assert response.status_code == 204
|
ReleaseThresholdDetailsDELETETest
|
python
|
huggingface__transformers
|
src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
|
{
"start": 13323,
"end": 15139
}
|
class ____(InstructBlipVideoPreTrainedModel):
main_input_name = "pixel_values"
input_modalities = "video"
config: InstructBlipVideoVisionConfig
_can_record_outputs = {
"hidden_states": InstructBlipVideoEncoderLayer,
"attentions": InstructBlipVideoAttention,
}
def __init__(self, config: InstructBlipVideoVisionConfig):
super().__init__(config)
self.config = config
embed_dim = config.hidden_size
self.embeddings = InstructBlipVideoVisionEmbeddings(config)
self.encoder = InstructBlipVideoEncoder(config)
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
self.post_init()
@check_model_inputs(tie_last_hidden_states=False)
@auto_docstring
def forward(
self,
pixel_values: Optional[torch.FloatTensor] = None,
interpolate_pos_encoding: bool = False,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple, BaseModelOutputWithPooling]:
if pixel_values is None:
raise ValueError("You have to specify pixel_values")
hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
encoder_outputs: BaseModelOutput = self.encoder(
inputs_embeds=hidden_states,
**kwargs,
)
last_hidden_state = encoder_outputs.last_hidden_state
last_hidden_state = self.post_layernorm(last_hidden_state)
pooled_output = last_hidden_state[:, 0, :]
pooled_output = self.post_layernorm(pooled_output)
return BaseModelOutputWithPooling(
last_hidden_state=last_hidden_state,
pooler_output=pooled_output,
)
def get_input_embeddings(self):
return self.embeddings
|
InstructBlipVideoVisionModel
|
python
|
coleifer__peewee
|
tests/manytomany.py
|
{
"start": 21568,
"end": 22642
}
|
class ____(ModelTestCase):
database = get_in_memory_db()
requires = [Permission, Visitor, Visitor.allowed.through_model,
Visitor.denied.through_model]
def test_multiple_manytomany_same_tables(self):
p1, p2, p3 = [Permission.create(name=n) for n in ('p1', 'p2', 'p3')]
v1, v2, v3 = [Visitor.create(name=n) for n in ('v1', 'v2', 'v3')]
v1.allowed.add([p1, p2, p3])
v2.allowed.add(p2)
v2.denied.add([p1, p3])
v3.allowed.add(p3)
v3.denied.add(p1)
accum = []
for v in Visitor.select().order_by(Visitor.name):
allowed, denied = [], []
for p in v.allowed.order_by(Permission.name):
allowed.append(p.name)
for p in v.denied.order_by(Permission.name):
denied.append(p.name)
accum.append((v.name, allowed, denied))
self.assertEqual(accum, [
('v1', ['p1', 'p2', 'p3'], []),
('v2', ['p2'], ['p1', 'p3']),
('v3', ['p3'], ['p1'])])
|
TestMultipleManyToManySameTables
|
python
|
huggingface__transformers
|
src/transformers/models/sam3_tracker_video/modeling_sam3_tracker_video.py
|
{
"start": 39439,
"end": 41935
}
|
class ____(nn.Module):
def __init__(self, config: Sam3TrackerVideoConfig):
super().__init__()
self.layers = nn.ModuleList(
[Sam3TrackerVideoMemoryAttentionLayer(config) for _ in range(config.memory_attention_num_layers)]
)
self.layer_norm = nn.LayerNorm(config.memory_attention_hidden_size)
self.rotary_emb = Sam3TrackerVideoVisionRotaryEmbedding(config=config)
def forward(
self,
current_vision_features: torch.Tensor,
memory: torch.Tensor,
current_vision_position_embeddings: Optional[Tensor] = None,
memory_posision_embeddings: Optional[Tensor] = None,
num_object_pointer_tokens: int = 0,
):
"""
Args:
current_vision_features (`torch.FloatTensor`):
The current vision features used for self-attention.
memory (`torch.FloatTensor`):
The memory features used for cross-attention.
current_vision_position_embeddings (`torch.FloatTensor`, *optional*):
The position embeddings for the current vision features.
memory_posision_embeddings (`torch.FloatTensor`, *optional*):
The position embeddings for the memory features.
num_object_pointer_tokens (`int`, *optional*, defaults to 0):
The number of object pointer tokens.
"""
output = current_vision_features
if current_vision_position_embeddings is not None:
output = output + 0.1 * current_vision_position_embeddings
# Convert to batch first
output = output.transpose(0, 1)
memory = memory.transpose(0, 1).unsqueeze(1)
memory_posision_embeddings = memory_posision_embeddings.transpose(0, 1).unsqueeze(1)
rope_position_embeddings = self.rotary_emb()
for layer in self.layers:
output = layer(
queries=output.unsqueeze(1) if output.ndim == 3 else output,
keys=memory,
key_point_embedding=memory_posision_embeddings,
rope_position_embeddings=rope_position_embeddings,
num_k_exclude_rope=num_object_pointer_tokens,
)
normed_output = self.layer_norm(output)
# Convert back to seq first
normed_output = normed_output.transpose(0, 1)
return normed_output
# Lightly adapted from ConvNext (https://github.com/facebookresearch/ConvNeXt)
|
Sam3TrackerVideoMemoryAttention
|
python
|
pytorch__pytorch
|
torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py
|
{
"start": 1816,
"end": 2467
}
|
class ____:
def __init__(self, group: dist.ProcessGroup, *args: Any, **kwargs: Any):
self._group = group
super().__init__(*args, **kwargs)
def allocate(
self,
size: Sequence[Union[int, torch.SymInt]],
*,
dtype: torch.dtype,
device: torch.device,
) -> torch.Tensor:
backend = self._group._get_backend(device)
if backend.supports_tensor_alloc(device):
size_1d = math.prod(int(s) for s in size)
return backend.allocate_tensor(size_1d, dtype=dtype, device=device)
return torch.empty(*size, dtype=dtype, device=device)
|
ProcessGroupAllocMixin
|
python
|
numba__llvmlite
|
llvmlite/tests/test_binding.py
|
{
"start": 84866,
"end": 87677
}
|
class ____(BaseTest):
mod_asm = """
;ModuleID = <string>
target triple = "{triple}"
declare i32 @sum(i32 %.1, i32 %.2)
define i32 @sum_twice(i32 %.1, i32 %.2) {{
%.3 = call i32 @sum(i32 %.1, i32 %.2)
%.4 = call i32 @sum(i32 %.3, i32 %.3)
ret i32 %.4
}}
"""
def test_object_file(self):
target_machine = self.target_machine(jit=False)
mod = self.module()
obj_bin = target_machine.emit_object(mod)
obj = llvm.ObjectFileRef.from_data(obj_bin)
# Check that we have a text section, and that she has a name and data
has_text_and_data = False
last_address = -1
for s in obj.sections():
if (
s.is_text()
and len(s.data()) > 0
and s.address() is not None
and last_address < s.address()
):
has_text_and_data = True
last_address = s.address()
break
self.assertTrue(has_text_and_data)
def test_add_object_file(self):
target_machine = self.target_machine(jit=False)
mod = self.module()
obj_bin = target_machine.emit_object(mod)
obj = llvm.ObjectFileRef.from_data(obj_bin)
jit = llvm.create_mcjit_compiler(self.module(self.mod_asm),
target_machine)
jit.add_object_file(obj)
sum_twice = CFUNCTYPE(c_int, c_int, c_int)(
jit.get_function_address("sum_twice"))
self.assertEqual(sum_twice(2, 3), 10)
def test_add_object_file_from_filesystem(self):
target_machine = self.target_machine(jit=False)
mod = self.module()
obj_bin = target_machine.emit_object(mod)
temp_desc, temp_path = mkstemp()
try:
try:
f = os.fdopen(temp_desc, "wb")
f.write(obj_bin)
f.flush()
finally:
f.close()
jit = llvm.create_mcjit_compiler(self.module(self.mod_asm),
target_machine)
jit.add_object_file(temp_path)
finally:
os.unlink(temp_path)
sum_twice = CFUNCTYPE(c_int, c_int, c_int)(
jit.get_function_address("sum_twice"))
self.assertEqual(sum_twice(2, 3), 10)
def test_get_section_content(self):
# See Issue #632 - section contents were getting truncated at null
# bytes.
elf = bytes.fromhex(issue_632_elf)
obj = llvm.ObjectFileRef.from_data(elf)
for s in obj.sections():
if s.is_text():
self.assertEqual(len(s.data()), 31)
self.assertEqual(s.data().hex(), issue_632_text)
|
TestObjectFile
|
python
|
tornadoweb__tornado
|
tornado/test/gen_test.py
|
{
"start": 28117,
"end": 31862
}
|
class ____(AsyncTestCase):
def is_pypy3(self):
return platform.python_implementation() == "PyPy" and sys.version_info > (3,)
@gen_test
def test_gc(self):
# GitHub issue 1769: Runner objects can get GCed unexpectedly
# while their future is alive.
weakref_scope = [None] # type: List[Optional[weakref.ReferenceType]]
def callback():
gc.collect(2)
weakref_scope[0]().set_result(123) # type: ignore
@gen.coroutine
def tester():
fut = Future() # type: Future[int]
weakref_scope[0] = weakref.ref(fut)
self.io_loop.add_callback(callback)
yield fut
yield gen.with_timeout(datetime.timedelta(seconds=0.2), tester())
def test_gc_infinite_coro(self):
# GitHub issue 2229: suspended coroutines should be GCed when
# their loop is closed, even if they're involved in a reference
# cycle.
loop = self.get_new_ioloop()
result = [] # type: List[Optional[bool]]
wfut = []
@gen.coroutine
def infinite_coro():
try:
while True:
yield gen.sleep(1e-3)
result.append(True)
finally:
# coroutine finalizer
result.append(None)
@gen.coroutine
def do_something():
fut = infinite_coro()
fut._refcycle = fut # type: ignore
wfut.append(weakref.ref(fut))
yield gen.sleep(0.2)
loop.run_sync(do_something)
loop.close()
gc.collect()
# Future was collected
self.assertIsNone(wfut[0]())
# At least one wakeup
self.assertGreaterEqual(len(result), 2)
if not self.is_pypy3():
# coroutine finalizer was called (not on PyPy3 apparently)
self.assertIsNone(result[-1])
def test_gc_infinite_async_await(self):
# Same as test_gc_infinite_coro, but with a `async def` function
import asyncio
async def infinite_coro(result):
try:
while True:
await gen.sleep(1e-3)
result.append(True)
finally:
# coroutine finalizer
result.append(None)
loop = self.get_new_ioloop()
result = [] # type: List[Optional[bool]]
wfut = []
@gen.coroutine
def do_something():
fut = asyncio.get_event_loop().create_task(infinite_coro(result))
fut._refcycle = fut # type: ignore
wfut.append(weakref.ref(fut))
yield gen.sleep(0.2)
loop.run_sync(do_something)
with ExpectLog("asyncio", "Task was destroyed but it is pending"):
loop.close()
gc.collect()
# Future was collected
self.assertIsNone(wfut[0]())
# At least one wakeup and one finally
self.assertGreaterEqual(len(result), 2)
if not self.is_pypy3():
# coroutine finalizer was called (not on PyPy3 apparently)
self.assertIsNone(result[-1])
def test_multi_moment(self):
# Test gen.multi with moment
# now that it's not a real Future
@gen.coroutine
def wait_a_moment():
result = yield gen.multi([gen.moment, gen.moment])
raise gen.Return(result)
loop = self.get_new_ioloop()
result = loop.run_sync(wait_a_moment)
self.assertEqual(result, [None, None])
if contextvars is not None:
ctx_var = contextvars.ContextVar("ctx_var") # type: contextvars.ContextVar[int]
@unittest.skipIf(contextvars is None, "contextvars module not present")
|
RunnerGCTest
|
python
|
huggingface__transformers
|
src/transformers/models/janus/modular_janus.py
|
{
"start": 29190,
"end": 31885
}
|
class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.num_resolutions = len(config.channel_multiplier)
self.num_res_blocks = config.num_res_blocks
base_channels = config.base_channels
latent_channels = config.latent_channels
out_channels = config.out_channels
# compute in_ch_mult, block_in and curr_res at lowest res
block_in = base_channels * config.channel_multiplier[self.num_resolutions - 1]
# z to block_in
self.conv_in = torch.nn.Conv2d(latent_channels, block_in, kernel_size=3, stride=1, padding=1)
# middle
self.mid = JanusVQVAEMidBlock(config, block_in)
# upsampling
self.up = nn.ModuleList()
for i_level in reversed(range(self.num_resolutions)):
block = nn.ModuleList()
attn = nn.ModuleList()
block_out = base_channels * config.channel_multiplier[i_level]
for i_block in range(self.num_res_blocks + 1):
block.append(
JanusVQVAEResnetBlock(
config=config,
in_channels=block_in,
out_channels=block_out,
)
)
block_in = block_out
if i_level == self.num_resolutions - 1:
attn.append(JanusVQVAEAttnBlock(block_in))
up = nn.Module()
up.block = block
up.attn = attn
if i_level != 0:
up.upsample = JanusVQVAEConvUpsample(block_in)
self.up.append(up)
# end
self.norm_out = torch.nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)
self.conv_out = torch.nn.Conv2d(block_in, out_channels, kernel_size=3, stride=1, padding=1)
def forward(self, hidden_state: torch.FloatTensor) -> torch.FloatTensor:
hidden_state = self.conv_in(hidden_state)
# middle
hidden_state = self.mid(hidden_state)
# upsampling
for i_level in range(self.num_resolutions):
for i_block in range(self.num_res_blocks + 1):
hidden_state = self.up[i_level].block[i_block](hidden_state)
if len(self.up[i_level].attn) > 0:
hidden_state = self.up[i_level].attn[i_block](hidden_state)
if i_level != self.num_resolutions - 1:
hidden_state = self.up[i_level].upsample(hidden_state)
hidden_state = self.norm_out(hidden_state)
hidden_state *= torch.sigmoid(hidden_state)
hidden_state = self.conv_out(hidden_state)
return hidden_state
|
JanusVQVAEDecoder
|
python
|
realpython__materials
|
python-maze-solver/source_code_final/src/maze_solver/view/renderer.py
|
{
"start": 573,
"end": 1307
}
|
class ____:
xml_content: str
@property
def html_content(self) -> str:
return textwrap.dedent(
"""\
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SVG Preview</title>
</head>
<body>
{0}
</body>
</html>"""
).format(self.xml_content)
def preview(self) -> None:
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", suffix=".html", delete=False
) as file:
file.write(self.html_content)
webbrowser.open(f"file://{file.name}")
@dataclass(frozen=True)
|
SVG
|
python
|
astropy__astropy
|
astropy/coordinates/tests/test_celestial_transformations.py
|
{
"start": 6478,
"end": 8758
}
|
class ____:
"""
Check HCRS<->ICRS coordinate conversions.
Uses ICRS Solar positions predicted by get_body_barycentric; with `t1` and
`tarr` as defined below, the ICRS Solar positions were predicted using, e.g.
coord.ICRS(coord.get_body_barycentric(tarr, 'sun')).
"""
def setup_method(self):
self.t1 = Time("2013-02-02T23:00")
self.t2 = Time("2013-08-02T23:00")
self.tarr = Time(["2013-02-02T23:00", "2013-08-02T23:00"])
self.sun_icrs_scalar = ICRS(
ra=244.52984668 * u.deg,
dec=-22.36943723 * u.deg,
distance=406615.66347377 * u.km,
)
# array of positions corresponds to times in `tarr`
self.sun_icrs_arr = ICRS(
ra=[244.52989062, 271.40976248] * u.deg,
dec=[-22.36943605, -25.07431079] * u.deg,
distance=[406615.66347377, 375484.13558956] * u.km,
)
# corresponding HCRS positions
self.sun_hcrs_t1 = HCRS(
CartesianRepresentation([0.0, 0.0, 0.0] * u.km), obstime=self.t1
)
twod_rep = CartesianRepresentation([[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]] * u.km)
self.sun_hcrs_tarr = HCRS(twod_rep, obstime=self.tarr)
self.tolerance = 5 * u.km
def test_from_hcrs(self):
# test scalar transform
transformed = self.sun_hcrs_t1.transform_to(ICRS())
separation = transformed.separation_3d(self.sun_icrs_scalar)
assert_allclose(separation, 0 * u.km, atol=self.tolerance)
# test non-scalar positions and times
transformed = self.sun_hcrs_tarr.transform_to(ICRS())
separation = transformed.separation_3d(self.sun_icrs_arr)
assert_allclose(separation, 0 * u.km, atol=self.tolerance)
def test_from_icrs(self):
# scalar positions
transformed = self.sun_icrs_scalar.transform_to(HCRS(obstime=self.t1))
separation = transformed.separation_3d(self.sun_hcrs_t1)
assert_allclose(separation, 0 * u.km, atol=self.tolerance)
# nonscalar positions
transformed = self.sun_icrs_arr.transform_to(HCRS(obstime=self.tarr))
separation = transformed.separation_3d(self.sun_hcrs_tarr)
assert_allclose(separation, 0 * u.km, atol=self.tolerance)
|
TestHCRS
|
python
|
sphinx-doc__sphinx
|
sphinx/builders/linkcheck.py
|
{
"start": 2144,
"end": 7557
}
|
class ____(DummyBuilder):
"""Checks for broken external links."""
name = 'linkcheck'
epilog = __('Look for any errors in the above output or in %(outdir)s/output.txt')
def init(self) -> None:
self.broken_hyperlinks = 0
self.timed_out_hyperlinks = 0
self.hyperlinks: dict[str, Hyperlink] = {}
# set a timeout for non-responding servers
socket.setdefaulttimeout(5.0)
def finish(self) -> None:
checker = HyperlinkAvailabilityChecker(self.config)
logger.info('')
output_text = self.outdir / 'output.txt'
output_json = self.outdir / 'output.json'
with (
open(output_text, 'w', encoding='utf-8') as self.txt_outfile,
open(output_json, 'w', encoding='utf-8') as self.json_outfile,
):
for result in checker.check(self.hyperlinks):
self.process_result(result)
if self.broken_hyperlinks or self.timed_out_hyperlinks:
self._app.statuscode = 1
def process_result(self, result: CheckResult) -> None:
filename = self.env.doc2path(result.docname, False)
res_uri = result.uri
linkstat: dict[str, str | int | _Status] = {
'filename': str(filename),
'lineno': result.lineno,
'status': result.status,
'code': result.code,
'uri': res_uri,
'info': result.message,
}
self.write_linkstat(linkstat)
if result.lineno and result.status != _Status.UNCHECKED:
# unchecked links are not logged
logger.info('(%16s: line %4d) ', result.docname, result.lineno, nonl=True)
match result.status:
case _Status.RATE_LIMITED | _Status.UNCHECKED:
pass
case _Status.IGNORED:
if result.message:
msg = f'{res_uri}: {result.message}'
else:
msg = res_uri
logger.info(darkgray('-ignored- ') + msg) # NoQA: G003
case _Status.WORKING:
logger.info(darkgreen('ok ') + f'{res_uri}{result.message}') # NoQA: G003
case _Status.TIMEOUT:
if self.config.verbosity < 0:
msg = 'timeout ' + f'{res_uri}{result.message}'
logger.warning(msg, location=(result.docname, result.lineno))
else:
msg = red('timeout ') + res_uri + red(f' - {result.message}')
logger.info(msg)
self.write_entry(
_Status.TIMEOUT,
result.docname,
filename,
result.lineno,
f'{res_uri}: {result.message}',
)
self.timed_out_hyperlinks += 1
case _Status.BROKEN:
if self.config.verbosity < 0:
logger.warning(
__('broken link: %s (%s)'),
res_uri,
result.message,
location=(result.docname, result.lineno),
)
else:
msg = red('broken ') + res_uri + red(f' - {result.message}')
logger.info(msg)
self.write_entry(
_Status.BROKEN,
result.docname,
filename,
result.lineno,
f'{res_uri}: {result.message}',
)
self.broken_hyperlinks += 1
case _Status.REDIRECTED:
match result.code:
case 301:
text = 'permanently'
case 302:
text = 'with Found'
case 303:
text = 'with See Other'
case 307:
text = 'temporarily'
case 308:
text = 'permanently'
case _:
text = 'with unknown code'
linkstat['text'] = text
redirection = f'{text} to {result.message}'
if self.config.linkcheck_allowed_redirects is not _SENTINEL_LAR:
msg = f'redirect {res_uri} - {redirection}'
logger.warning(msg, location=(result.docname, result.lineno))
else:
colour = turquoise if result.code == 307 else purple
msg = colour('redirect ') + res_uri + colour(f' - {redirection}')
logger.info(msg)
self.write_entry(
f'redirected {text}',
result.docname,
filename,
result.lineno,
f'{res_uri} to {result.message}',
)
case _Status.UNKNOWN:
msg = 'Unknown status.'
raise ValueError(msg)
def write_linkstat(self, data: dict[str, str | int | _Status]) -> None:
self.json_outfile.write(json.dumps(data))
self.json_outfile.write('\n')
def write_entry(
self, what: _Status | str, docname: str, filename: _StrPath, line: int, uri: str
) -> None:
self.txt_outfile.write(f'{filename}:{line}: [{what}] {uri}\n')
|
CheckExternalLinksBuilder
|
python
|
dask__dask
|
dask/dataframe/dask_expr/io/parquet.py
|
{
"start": 8471,
"end": 25085
}
|
class ____(Expr):
_parameters = ToParquet._parameters
@property
def _meta(self):
return None
def _divisions(self):
return (None, None)
def _layer(self):
if self.write_metadata_file:
append = self.append
compression = self.write_kwargs.get("compression")
return {
(self._name, 0): (
apply,
self.engine.write_metadata,
[
self.frame.__dask_keys__(),
self.fmd,
self.fs,
self.path,
],
{"append": append, "compression": compression},
)
}
else:
return {(self._name, 0): (lambda x: None, self.frame.__dask_keys__())}
def to_parquet(
df,
path,
compression="snappy",
write_index=True,
append=False,
overwrite=False,
ignore_divisions=False,
partition_on=None,
storage_options=None,
custom_metadata=None,
write_metadata_file=None,
compute=True,
compute_kwargs=None,
schema="infer",
name_function=None,
filesystem=None,
engine=None,
**kwargs,
):
"""Store Dask.dataframe to Parquet files
Notes
-----
Each partition will be written to a separate file.
Parameters
----------
df : dask.dataframe.DataFrame
path : string or pathlib.Path
Destination directory for data. Prepend with protocol like ``s3://``
or ``hdfs://`` for remote data.
compression : string or dict, default 'snappy'
Either a string like ``"snappy"`` or a dictionary mapping column names
to compressors like ``{"name": "gzip", "values": "snappy"}``. Defaults
to ``"snappy"``.
write_index : bool, default True
Whether or not to write the index. Defaults to True.
append : bool, default False
If False (default), construct data-set from scratch. If True, add new
row-group(s) to an existing data-set. In the latter case, the data-set
must exist, and the schema must match the input data.
overwrite : bool, default False
Whether or not to remove the contents of `path` before writing the dataset.
The default is False. If True, the specified path must correspond to
a directory (but not the current working directory). This option cannot
be set to True if `append=True`.
NOTE: `overwrite=True` will remove the original data even if the current
write operation fails. Use at your own risk.
ignore_divisions : bool, default False
If False (default) raises error when previous divisions overlap with
the new appended divisions. Ignored if append=False.
partition_on : list, default None
Construct directory-based partitioning by splitting on these fields'
values. Each dask partition will result in one or more datafiles,
there will be no global groupby.
storage_options : dict, default None
Key/value pairs to be passed on to the file-system backend, if any.
custom_metadata : dict, default None
Custom key/value metadata to include in all footer metadata (and
in the global "_metadata" file, if applicable). Note that the custom
metadata may not contain the reserved b"pandas" key.
write_metadata_file : bool or None, default None
Whether to write the special ``_metadata`` file. If ``None`` (the
default), a ``_metadata`` file will only be written if ``append=True``
and the dataset already has a ``_metadata`` file.
compute : bool, default True
If ``True`` (default) then the result is computed immediately. If
``False`` then a ``dask.dataframe.Scalar`` object is returned for
future computation.
compute_kwargs : dict, default True
Options to be passed in to the compute method
schema : pyarrow.Schema, dict, "infer", or None, default "infer"
Global schema to use for the output dataset. Defaults to "infer", which
will infer the schema from the dask dataframe metadata. This is usually
sufficient for common schemas, but notably will fail for ``object``
dtype columns that contain things other than strings. These columns
will require an explicit schema be specified. The schema for a subset
of columns can be overridden by passing in a dict of column names to
pyarrow types (for example ``schema={"field": pa.string()}``); columns
not present in this dict will still be automatically inferred.
Alternatively, a full ``pyarrow.Schema`` may be passed, in which case
no schema inference will be done. Passing in ``schema=None`` will
disable the use of a global file schema - each written file may use a
different schema dependent on the dtypes of the corresponding
partition.
name_function : callable, default None
Function to generate the filename for each output partition.
The function should accept an integer (partition index) as input and
return a string which will be used as the filename for the corresponding
partition. Should preserve the lexicographic order of partitions.
If not specified, files will created using the convention
``part.0.parquet``, ``part.1.parquet``, ``part.2.parquet``, ...
and so on for each partition in the DataFrame.
filesystem: "fsspec", "arrow", or fsspec.AbstractFileSystem backend to use.
**kwargs :
Extra options to be passed on to the specific backend.
Examples
--------
>>> df = dd.read_csv(...) # doctest: +SKIP
>>> df.to_parquet('/path/to/output/', ...) # doctest: +SKIP
By default, files will be created in the specified output directory using the
convention ``part.0.parquet``, ``part.1.parquet``, ``part.2.parquet``, ... and so on for
each partition in the DataFrame. To customize the names of each file, you can use the
``name_function=`` keyword argument. The function passed to ``name_function`` will be
used to generate the filename for each partition and should expect a partition's index
integer as input and return a string which will be used as the filename for the corresponding
partition. Strings produced by ``name_function`` must preserve the order of their respective
partition indices.
For example:
>>> name_function = lambda x: f"data-{x}.parquet"
>>> df.to_parquet('/path/to/output/', name_function=name_function) # doctest: +SKIP
will result in the following files being created::
/path/to/output/
├── data-0.parquet
├── data-1.parquet
├── data-2.parquet
└── ...
See Also
--------
read_parquet: Read parquet data to dask.dataframe
"""
from dask.dataframe.dask_expr._collection import new_collection
engine = _set_parquet_engine(engine=engine, meta=df._meta)
compute_kwargs = compute_kwargs or {}
partition_on = partition_on or []
if isinstance(partition_on, str):
partition_on = [partition_on]
if set(partition_on) - set(df.columns):
raise ValueError(
"Partitioning on non-existent column. "
f"partition_on={partition_on} ."
f"columns={list(df.columns)}"
)
if df.columns.inferred_type not in {"string", "empty"}:
raise ValueError("parquet doesn't support non-string column names")
if isinstance(engine, str):
engine = get_engine(engine)
if hasattr(path, "name"):
path = stringify_path(path)
fs, _paths, _, _ = engine.extract_filesystem(
path,
filesystem=filesystem,
dataset_options={},
open_file_options={},
storage_options=storage_options,
)
assert len(_paths) == 1, "only one path"
path = _paths[0]
if overwrite:
if append:
raise ValueError("Cannot use both `overwrite=True` and `append=True`!")
if fs.exists(path) and fs.isdir(path):
# Check for any previous parquet ops reading from a file in the
# output directory, since deleting those files now would result in
# errors or incorrect results.
for read_op in df.expr.find_operations(ReadParquet):
read_path_with_slash = str(read_op.path).rstrip("/") + "/"
write_path_with_slash = path.rstrip("/") + "/"
if read_path_with_slash.startswith(write_path_with_slash):
raise ValueError(
"Cannot overwrite a path that you are reading "
"from in the same task graph."
)
# Don't remove the directory if it's the current working directory
if _is_local_fs(fs):
working_dir = fs.expand_path(".")[0]
if path.rstrip("/") == working_dir.rstrip("/"):
raise ValueError(
"Cannot clear the contents of the current working directory!"
)
# It's safe to clear the output directory
fs.rm(path, recursive=True)
# Clear read_parquet caches in case we are
# also reading from the overwritten path
_cached_plan.clear()
# Always skip divisions checks if divisions are unknown
if not df.known_divisions:
ignore_divisions = True
# Save divisions and corresponding index name. This is necessary,
# because we may be resetting the index to write the file
division_info = {"divisions": df.divisions, "name": df.index.name}
if division_info["name"] is None:
# As of 0.24.2, pandas will rename an index with name=None
# when df.reset_index() is called. The default name is "index",
# but dask will always change the name to the NONE_LABEL constant
if NONE_LABEL not in df.columns:
division_info["name"] = NONE_LABEL
elif write_index:
raise ValueError(
"Index must have a name if __null_dask_index__ is a column."
)
else:
warnings.warn(
"If read back by Dask, column named __null_dask_index__ "
"will be set to the index (and renamed to None)."
)
# There are some "reserved" names that may be used as the default column
# name after resetting the index. However, we don't want to treat it as
# a "special" name if the string is already used as a "real" column name.
reserved_names = []
for name in ["index", "level_0"]:
if name not in df.columns:
reserved_names.append(name)
# If write_index==True (default), reset the index and record the
# name of the original index in `index_cols` (we will set the name
# to the NONE_LABEL constant if it is originally `None`).
# `pyarrow` will revert the `reset_index` call
# below if `index_cols` is populated (because pyarrow will want to handle
# index preservation itself). The column index
# will be written to "pandas metadata" if write_index=True
index_cols = []
if write_index:
real_cols = set(df.columns)
none_index = list(df._meta.index.names) == [None]
df = df.reset_index()
if none_index:
rename_columns = {c: NONE_LABEL for c in df.columns if c in reserved_names}
df = df.rename(columns=rename_columns)
index_cols = [c for c in set(df.columns) - real_cols]
else:
# Not writing index - might as well drop it
df = df.reset_index(drop=True)
if custom_metadata and b"pandas" in custom_metadata.keys():
raise ValueError(
"User-defined key/value metadata (custom_metadata) can not "
"contain a b'pandas' key. This key is reserved by Pandas, "
"and overwriting the corresponding value can render the "
"entire dataset unreadable."
)
# Engine-specific initialization steps to write the dataset.
# Possibly create parquet metadata, and load existing stuff if appending
i_offset, fmd, metadata_file_exists, extra_write_kwargs = engine.initialize_write(
df,
fs,
path,
append=append,
ignore_divisions=ignore_divisions,
partition_on=partition_on,
division_info=division_info,
index_cols=index_cols,
schema=schema,
custom_metadata=custom_metadata,
**kwargs,
)
# By default we only write a metadata file when appending if one already
# exists
if append and write_metadata_file is None:
write_metadata_file = metadata_file_exists
# Check that custom name_function is valid,
# and that it will produce unique names
if name_function is not None:
if not callable(name_function):
raise ValueError("``name_function`` must be a callable with one argument.")
filenames = [name_function(i + i_offset) for i in range(df.npartitions)]
if len(set(filenames)) < len(filenames):
raise ValueError("``name_function`` must produce unique filenames.")
# If we are using a remote filesystem and retries is not set, bump it
# to be more fault tolerant, as transient transport errors can occur.
# The specific number 5 isn't hugely motivated: it's less than ten and more
# than two.
annotations = dask.config.get("annotations", {})
if "retries" not in annotations and not _is_local_fs(fs):
ctx = dask.annotate(retries=5)
else:
ctx = contextlib.nullcontext()
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore", message="Dask annotations ", category=UserWarning
)
with ctx:
out = new_collection(
ToParquet(
df,
path,
fs,
fmd,
engine,
i_offset,
partition_on,
write_metadata_file,
name_function,
toolz.merge(
kwargs,
{
"compression": compression,
"custom_metadata": custom_metadata,
},
extra_write_kwargs,
),
append,
)
)
if compute:
out = out.compute(**compute_kwargs)
# Invalidate the filesystem listing cache for the output path after write.
# We do this before returning, even if `compute=False`. This helps ensure
# that reading files that were just written succeeds.
fs.invalidate_cache(path)
return out
def _determine_type_mapper(
*, user_types_mapper, dtype_backend, pyarrow_strings_enabled
):
type_mappers = []
def pyarrow_type_mapper(pyarrow_dtype):
# Special case pyarrow strings to use more feature complete dtype
# See https://github.com/pandas-dev/pandas/issues/50074
if pyarrow_dtype == pa.string():
return pd.StringDtype("pyarrow")
else:
return pd.ArrowDtype(pyarrow_dtype)
# always use the user-defined mapper first, if available
if user_types_mapper is not None:
type_mappers.append(user_types_mapper)
# next in priority is converting strings
if pyarrow_strings_enabled:
type_mappers.append({pa.string(): pd.StringDtype("pyarrow")}.get)
type_mappers.append({pa.date32(): pd.ArrowDtype(pa.date32())}.get)
type_mappers.append({pa.date64(): pd.ArrowDtype(pa.date64())}.get)
def _convert_decimal_type(type):
if pa.types.is_decimal(type):
return pd.ArrowDtype(type)
return None
type_mappers.append(_convert_decimal_type)
# and then nullable types
if dtype_backend == "numpy_nullable":
type_mappers.append(PYARROW_NULLABLE_DTYPE_MAPPING.get)
elif dtype_backend == "pyarrow":
type_mappers.append(pyarrow_type_mapper)
def default_types_mapper(pyarrow_dtype):
"""Try all type mappers in order, starting from the user type mapper."""
for type_converter in type_mappers:
converted_type = type_converter(pyarrow_dtype)
if converted_type is not None:
return converted_type
if len(type_mappers) > 0:
return default_types_mapper
|
ToParquetBarrier
|
python
|
dagster-io__dagster
|
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
|
{
"start": 130564,
"end": 132550
}
|
class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
api_key: str,
start_date: Optional[str] = None,
lookback_window_days: Optional[int] = None,
string_event_properties_keys: Optional[list[str]] = None,
numeric_event_properties_keys: Optional[list[str]] = None,
):
"""Airbyte Source for Orb.
Documentation can be found at https://docs.withorb.com/
Args:
name (str): The name of the destination.
api_key (str): Orb API Key, issued from the Orb admin console.
start_date (Optional[str]): UTC date and time in the format 2022-03-01T00:00:00Z. Any data with created_at before this data will not be synced.
lookback_window_days (Optional[int]): When set to N, the connector will always refresh resources created within the past N days. By default, updated objects that are not newly created are not incrementally synced.
string_event_properties_keys (Optional[List[str]]): Property key names to extract from all events, in order to enrich ledger entries corresponding to an event deduction.
numeric_event_properties_keys (Optional[List[str]]): Property key names to extract from all events, in order to enrich ledger entries corresponding to an event deduction.
"""
self.api_key = check.str_param(api_key, "api_key")
self.start_date = check.opt_str_param(start_date, "start_date")
self.lookback_window_days = check.opt_int_param(
lookback_window_days, "lookback_window_days"
)
self.string_event_properties_keys = check.opt_nullable_list_param(
string_event_properties_keys, "string_event_properties_keys", str
)
self.numeric_event_properties_keys = check.opt_nullable_list_param(
numeric_event_properties_keys, "numeric_event_properties_keys", str
)
super().__init__("Orb", name)
|
OrbSource
|
python
|
gevent__gevent
|
src/gevent/tests/lock_tests.py
|
{
"start": 5019,
"end": 6490
}
|
class ____(BaseLockTests):
"""
Tests for recursive locks.
"""
def test_reacquire(self):
lock = self.locktype()
lock.acquire()
lock.acquire()
lock.release()
lock.acquire()
lock.release()
lock.release()
def test_release_unacquired(self):
# Cannot release an unacquired lock
lock = self.locktype()
self.assertRaises(RuntimeError, lock.release)
lock.acquire()
lock.acquire()
lock.release()
lock.acquire()
lock.release()
lock.release()
self.assertRaises(RuntimeError, lock.release)
def test_different_thread(self):
# Cannot release from a different thread
lock = self.locktype()
def f():
lock.acquire()
b = Bunch(f, 1, True)
try:
self.assertRaises(RuntimeError, lock.release)
finally:
b.do_finish()
def test__is_owned(self):
lock = self.locktype()
self.assertFalse(lock._is_owned())
lock.acquire()
self.assertTrue(lock._is_owned())
lock.acquire()
self.assertTrue(lock._is_owned())
result = []
def f():
result.append(lock._is_owned())
Bunch(f, 1).wait_for_finished()
self.assertFalse(result[0])
lock.release()
self.assertTrue(lock._is_owned())
lock.release()
self.assertFalse(lock._is_owned())
|
RLockTests
|
python
|
huggingface__transformers
|
src/transformers/models/pvt_v2/configuration_pvt_v2.py
|
{
"start": 1065,
"end": 8005
}
|
class ____(BackboneConfigMixin, PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`PvtV2Model`]. It is used to instantiate a Pvt V2
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the Pvt V2 B0
[OpenGVLab/pvt_v2_b0](https://huggingface.co/OpenGVLab/pvt_v2_b0) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
image_size (`Union[int, tuple[int, int]]`, *optional*, defaults to 224):
The input image size. Pass int value for square image, or tuple of (height, width).
num_channels (`int`, *optional*, defaults to 3):
The number of input channels.
num_encoder_blocks (`[int]`, *optional*, defaults to 4):
The number of encoder blocks (i.e. stages in the Mix Transformer encoder).
depths (`list[int]`, *optional*, defaults to `[2, 2, 2, 2]`):
The number of layers in each encoder block.
sr_ratios (`list[int]`, *optional*, defaults to `[8, 4, 2, 1]`):
Spatial reduction ratios in each encoder block.
hidden_sizes (`list[int]`, *optional*, defaults to `[32, 64, 160, 256]`):
Dimension of each of the encoder blocks.
patch_sizes (`list[int]`, *optional*, defaults to `[7, 3, 3, 3]`):
Patch size for overlapping patch embedding before each encoder block.
strides (`list[int]`, *optional*, defaults to `[4, 2, 2, 2]`):
Stride for overlapping patch embedding before each encoder block.
num_attention_heads (`list[int]`, *optional*, defaults to `[1, 2, 5, 8]`):
Number of attention heads for each attention layer in each block of the Transformer encoder.
mlp_ratios (`list[int]`, *optional*, defaults to `[8, 8, 4, 4]`):
Ratio of the size of the hidden layer compared to the size of the input layer of the Mix FFNs in the
encoder blocks.
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"selu"` and `"gelu_new"` are supported.
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
drop_path_rate (`float`, *optional*, defaults to 0.0):
The dropout probability for stochastic depth, used in the blocks of the Transformer encoder.
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
The epsilon used by the layer normalization layers.
qkv_bias (`bool`, *optional*, defaults to `True`):
Whether or not a learnable bias should be added to the queries, keys and values.
linear_attention (`bool`, *optional*, defaults to `False`):
Use linear attention complexity. If set to True, `sr_ratio` is ignored and average pooling is used for
dimensionality reduction in the attention layers rather than strided convolution.
out_features (`list[str]`, *optional*):
If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
(depending on how many stages the model has). If unset and `out_indices` is set, will default to the
corresponding stages. If unset and `out_indices` is unset, will default to the last stage.
out_indices (`list[int]`, *optional*):
If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
If unset and `out_features` is unset, will default to the last stage.
Example:
```python
>>> from transformers import PvtV2Model, PvtV2Config
>>> # Initializing a pvt_v2_b0 style configuration
>>> configuration = PvtV2Config()
>>> # Initializing a model from the OpenGVLab/pvt_v2_b0 style configuration
>>> model = PvtV2Model(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "pvt_v2"
def __init__(
self,
image_size: Union[int, tuple[int, int]] = 224,
num_channels: int = 3,
num_encoder_blocks: int = 4,
depths: list[int] = [2, 2, 2, 2],
sr_ratios: list[int] = [8, 4, 2, 1],
hidden_sizes: list[int] = [32, 64, 160, 256],
patch_sizes: list[int] = [7, 3, 3, 3],
strides: list[int] = [4, 2, 2, 2],
num_attention_heads: list[int] = [1, 2, 5, 8],
mlp_ratios: list[int] = [8, 8, 4, 4],
hidden_act: Union[str, Callable] = "gelu",
hidden_dropout_prob: float = 0.0,
attention_probs_dropout_prob: float = 0.0,
initializer_range: float = 0.02,
drop_path_rate: float = 0.0,
layer_norm_eps: float = 1e-6,
qkv_bias: bool = True,
linear_attention: bool = False,
out_features=None,
out_indices=None,
**kwargs,
):
super().__init__(**kwargs)
image_size = (image_size, image_size) if isinstance(image_size, int) else image_size
self.image_size = image_size
self.num_channels = num_channels
self.num_encoder_blocks = num_encoder_blocks
self.depths = depths
self.sr_ratios = sr_ratios
self.hidden_sizes = hidden_sizes
self.patch_sizes = patch_sizes
self.strides = strides
self.mlp_ratios = mlp_ratios
self.num_attention_heads = num_attention_heads
self.hidden_act = hidden_act
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.initializer_range = initializer_range
self.drop_path_rate = drop_path_rate
self.layer_norm_eps = layer_norm_eps
self.qkv_bias = qkv_bias
self.linear_attention = linear_attention
self.stage_names = [f"stage{idx}" for idx in range(1, len(depths) + 1)]
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
)
__all__ = ["PvtV2Config"]
|
PvtV2Config
|
python
|
pandas-dev__pandas
|
pandas/tests/series/methods/test_copy.py
|
{
"start": 115,
"end": 2451
}
|
class ____:
@pytest.mark.parametrize("deep", ["default", None, False, True])
def test_copy(self, deep):
ser = Series(np.arange(10), dtype="float64")
# default deep is True
if deep == "default":
ser2 = ser.copy()
else:
ser2 = ser.copy(deep=deep)
# INFO(CoW) a shallow copy doesn't yet copy the data
# but parent will not be modified (CoW)
if deep is None or deep is False:
assert np.may_share_memory(ser.values, ser2.values)
else:
assert not np.may_share_memory(ser.values, ser2.values)
ser2[::2] = np.nan
# Did not modify original Series
assert np.isnan(ser2[0])
assert not np.isnan(ser[0])
@pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning")
@pytest.mark.parametrize("deep", ["default", None, False, True])
def test_copy_tzaware(self, deep):
# GH#11794
# copy of tz-aware
expected = Series([Timestamp("2012/01/01", tz="UTC")])
expected2 = Series([Timestamp("1999/01/01", tz="UTC")])
ser = Series([Timestamp("2012/01/01", tz="UTC")])
if deep == "default":
ser2 = ser.copy()
else:
ser2 = ser.copy(deep=deep)
# INFO(CoW) a shallow copy doesn't yet copy the data
# but parent will not be modified (CoW)
if deep is None or deep is False:
assert np.may_share_memory(ser.values, ser2.values)
else:
assert not np.may_share_memory(ser.values, ser2.values)
ser2[0] = Timestamp("1999/01/01", tz="UTC")
# Did not modify original Series
tm.assert_series_equal(ser2, expected2)
tm.assert_series_equal(ser, expected)
def test_copy_name(self, datetime_series):
result = datetime_series.copy()
assert result.name == datetime_series.name
def test_copy_index_name_checking(self, datetime_series):
# don't want to be able to modify the index stored elsewhere after
# making a copy
datetime_series.index.name = None
assert datetime_series.index.name is None
assert datetime_series is datetime_series
cp = datetime_series.copy()
cp.index.name = "foo"
assert datetime_series.index.name is None
|
TestCopy
|
python
|
mlflow__mlflow
|
mlflow/server/graphql/graphql_schema_extensions.py
|
{
"start": 2180,
"end": 2766
}
|
class ____(QueryType):
test = graphene.Field(Test, input_string=graphene.String(), description="Simple echoing field")
mlflow_search_runs = graphene.Field(MlflowSearchRunsResponse, input=MlflowSearchRunsInput())
def resolve_test(self, info, input_string):
return {"output": input_string}
def resolve_mlflow_search_runs(self, info, input):
input_dict = vars(input)
request_message = mlflow.protos.service_pb2.SearchRuns()
parse_dict(input_dict, request_message)
return mlflow.server.handlers.search_runs_impl(request_message)
|
Query
|
python
|
huggingface__transformers
|
src/transformers/utils/auto_docstring.py
|
{
"start": 6971,
"end": 20106
}
|
class ____:
labels = {
"description": """
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
""",
"shape": "of shape `(batch_size, sequence_length)`",
}
num_logits_to_keep = {
"description": """
Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
""",
"shape": None,
}
input_ids = {
"description": """
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
""",
"shape": "of shape `(batch_size, sequence_length)`",
}
input_values = {
"description": """
Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
(`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
into a tensor of type `torch.FloatTensor`. See [`{processor_class}.__call__`] for details.
""",
"shape": "of shape `(batch_size, sequence_length)`",
}
attention_mask = {
"description": """
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
""",
"shape": "of shape `(batch_size, sequence_length)`",
}
decoder_attention_mask = {
"description": """
Mask to avoid performing attention on certain token indices. By default, a causal mask will be used, to
make sure the model can only look at previous inputs in order to predict the future.
""",
"shape": "of shape `(batch_size, target_sequence_length)`",
}
encoder_hidden_states = {
"description": """
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
if the model is configured as a decoder.
""",
"shape": "of shape `(batch_size, sequence_length, hidden_size)`",
}
encoder_attention_mask = {
"description": """
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
""",
"shape": "of shape `(batch_size, sequence_length)`",
}
token_type_ids = {
"description": """
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
- 0 corresponds to a *sentence A* token,
- 1 corresponds to a *sentence B* token.
[What are token type IDs?](../glossary#token-type-ids)
""",
"shape": "of shape `(batch_size, sequence_length)`",
}
position_ids = {
"description": """
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`.
[What are position IDs?](../glossary#position-ids)
""",
"shape": "of shape `(batch_size, sequence_length)`",
}
past_key_values = {
"description": """
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
Only [`~cache_utils.Cache`] instance is allowed as input, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
If no `past_key_values` are passed, [`~cache_utils.DynamicCache`] will be initialized by default.
The model will output the same cache format that is fed as input.
If `past_key_values` are used, the user is expected to input only unprocessed `input_ids` (those that don't
have their past key value states given to this model) of shape `(batch_size, unprocessed_length)` instead of all `input_ids`
of shape `(batch_size, sequence_length)`.
""",
"shape": None,
}
inputs_embeds = {
"description": """
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
model's internal embedding lookup matrix.
""",
"shape": "of shape `(batch_size, sequence_length, hidden_size)`",
}
decoder_input_ids = {
"description": """
Indices of decoder input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are decoder input IDs?](../glossary#decoder-input-ids)
""",
"shape": "of shape `(batch_size, target_sequence_length)`",
}
decoder_inputs_embeds = {
"description": """
Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
input (see `past_key_values`). This is useful if you want more control over how to convert
`decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
of `inputs_embeds`.
""",
"shape": "of shape `(batch_size, target_sequence_length, hidden_size)`",
}
use_cache = {
"description": """
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
`past_key_values`).
""",
"shape": None,
}
output_attentions = {
"description": """
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
tensors for more detail.
""",
"shape": None,
}
output_hidden_states = {
"description": """
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
""",
"shape": None,
}
return_dict = {
"description": """
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
""",
"shape": None,
}
cache_position = {
"description": """
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
the complete sequence length.
""",
"shape": "of shape `(sequence_length)`",
}
hidden_states = {
"description": """ input to the layer of shape `(batch, seq_len, embed_dim)""",
"shape": None,
}
interpolate_pos_encoding = {
"description": """
Whether to interpolate the pre-trained position encodings.
""",
"shape": None,
}
position_embeddings = {
"description": """
Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
with `head_dim` being the embedding dimension of each attention head.
""",
"shape": None,
}
config = {
"description": """
Model configuration class with all the parameters of the model. Initializing with a config file does not
load the weights associated with the model, only the configuration. Check out the
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
""",
"shape": None,
}
start_positions = {
"description": """
Labels for position (index) of the start of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
are not taken into account for computing the loss.
""",
"shape": "of shape `(batch_size,)`",
}
end_positions = {
"description": """
Labels for position (index) of the end of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
are not taken into account for computing the loss.
""",
"shape": "of shape `(batch_size,)`",
}
encoder_outputs = {
"description": """
Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
`last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
""",
"shape": None,
}
output_router_logits = {
"description": """
Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
should not be returned during inference.
""",
"shape": None,
}
logits_to_keep = {
"description": """
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
This is useful when using packed tensor format (single dimension for batch and sequence length).
""",
"shape": None,
}
pixel_values = {
"description": """
The tensors corresponding to the input images. Pixel values can be obtained using
[`{image_processor_class}`]. See [`{image_processor_class}.__call__`] for details ([`{processor_class}`] uses
[`{image_processor_class}`] for processing images).
""",
"shape": "of shape `(batch_size, num_channels, image_size, image_size)`",
}
pixel_values_videos = {
"description": """
The tensors corresponding to the input video. Pixel values for videos can be obtained using
[`{video_processor_class}`]. See [`{video_processor_class}.__call__`] for details ([`{processor_class}`] uses
[`{video_processor_class}`] for processing videos).
""",
"shape": "of shape `(batch_size, num_frames, num_channels, frame_size, frame_size)`",
}
vision_feature_layer = {
"description": """
The index of the layer to select the vision feature. If multiple indices are provided,
the vision feature of the corresponding indices will be concatenated to form the
vision features.
""",
"shape": None,
}
vision_feature_select_strategy = {
"description": """
The feature selection strategy used to select the vision feature from the vision backbone.
Can be one of `"default"` or `"full"`.
""",
"shape": None,
}
image_sizes = {
"description": """
The sizes of the images in the batch, being (height, width) for each image.
""",
"shape": "of shape `(batch_size, 2)`",
}
pixel_mask = {
"description": """
Mask to avoid performing attention on padding pixel values. Mask values selected in `[0, 1]`:
- 1 for pixels that are real (i.e. **not masked**),
- 0 for pixels that are padding (i.e. **masked**).
[What are attention masks?](../glossary#attention-mask)
""",
"shape": "of shape `(batch_size, height, width)`",
}
input_features = {
"description": """
The tensors corresponding to the input audio features. Audio features can be obtained using
[`{feature_extractor_class}`]. See [`{feature_extractor_class}.__call__`] for details ([`{processor_class}`] uses
[`{feature_extractor_class}`] for processing audios).
""",
"shape": "of shape `(batch_size, sequence_length, feature_dim)`",
}
|
ModelArgs
|
python
|
ray-project__ray
|
python/ray/serve/tests/unit/test_proxy_state.py
|
{
"start": 699,
"end": 949
}
|
class ____:
def __init__(self):
self.alive_nodes = []
def get_alive_nodes(self):
return self.alive_nodes
def get_alive_node_ids(self):
return {node_id for node_id, _, _ in self.alive_nodes}
|
MockClusterNodeInfoCache
|
python
|
pallets__jinja
|
src/jinja2/nodes.py
|
{
"start": 30255,
"end": 30815
}
|
class ____(Expr):
"""An internal name in the compiler. You cannot create these nodes
yourself but the parser provides a
:meth:`~jinja2.parser.Parser.free_identifier` method that creates
a new identifier for you. This identifier is not available from the
template and is not treated specially by the compiler.
"""
fields = ("name",)
name: str
def __init__(self) -> None:
raise TypeError(
"Can't create internal names. Use the "
"`free_identifier` method on a parser."
)
|
InternalName
|
python
|
pypa__pip
|
src/pip/_vendor/rich/highlighter.py
|
{
"start": 3543,
"end": 4755
}
|
class ____(RegexHighlighter):
"""Highlights JSON"""
# Captures the start and end of JSON strings, handling escaped quotes
JSON_STR = r"(?<![\\\w])(?P<str>b?\".*?(?<!\\)\")"
JSON_WHITESPACE = {" ", "\n", "\r", "\t"}
base_style = "json."
highlights = [
_combine_regex(
r"(?P<brace>[\{\[\(\)\]\}])",
r"\b(?P<bool_true>true)\b|\b(?P<bool_false>false)\b|\b(?P<null>null)\b",
r"(?P<number>(?<!\w)\-?[0-9]+\.?[0-9]*(e[\-\+]?\d+?)?\b|0x[0-9a-fA-F]*)",
JSON_STR,
),
]
def highlight(self, text: Text) -> None:
super().highlight(text)
# Additional work to handle highlighting JSON keys
plain = text.plain
append = text.spans.append
whitespace = self.JSON_WHITESPACE
for match in re.finditer(self.JSON_STR, plain):
start, end = match.span()
cursor = end
while cursor < len(plain):
char = plain[cursor]
cursor += 1
if char == ":":
append(Span(start, end, "json.key"))
elif char in whitespace:
continue
break
|
JSONHighlighter
|
python
|
pytorch__pytorch
|
test/dynamo/cpython/3_13/test_baseexception.py
|
{
"start": 676,
"end": 1570
}
|
class ____(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path, target=None):
# Check if the import is the problematic one
if fullname in redirect_imports:
try:
# Attempt to import the standalone module
name = fullname.removeprefix("test.")
r = importlib.import_module(name)
# Redirect the module in sys.modules
sys.modules[fullname] = r
# Return a module spec from the found module
return importlib.util.find_spec(name)
except ImportError:
return None
return None
# Add the custom finder to sys.meta_path
sys.meta_path.insert(0, RedirectImportFinder())
# ======= END DYNAMO PATCH =======
import unittest
import builtins
import os
from platform import system as platform_system
|
RedirectImportFinder
|
python
|
kamyu104__LeetCode-Solutions
|
Python/number-of-paths-with-max-score.py
|
{
"start": 31,
"end": 1042
}
|
class ____(object):
def pathsWithMaxScore(self, board):
"""
:type board: List[str]
:rtype: List[int]
"""
MOD = 10**9+7
directions = [[1, 0], [0, 1], [1, 1]]
dp = [[[0, 0] for r in xrange(len(board[0])+1)]
for r in xrange(2)]
dp[(len(board)-1)%2][len(board[0])-1] = [0, 1]
for r in reversed(xrange(len(board))):
for c in reversed(xrange(len(board[0]))):
if board[r][c] in "XS":
continue
dp[r%2][c] = [0, 0]
for dr, dc in directions:
if dp[r%2][c][0] < dp[(r+dr)%2][c+dc][0]:
dp[r%2][c] = dp[(r+dr)%2][c+dc][:]
elif dp[r%2][c][0] == dp[(r+dr)%2][c+dc][0]:
dp[r%2][c][1] = (dp[r%2][c][1]+dp[(r+dr)%2][c+dc][1]) % MOD
if dp[r%2][c][1] and board[r][c] != 'E':
dp[r%2][c][0] += int(board[r][c])
return dp[0][0]
|
Solution
|
python
|
doocs__leetcode
|
solution/0300-0399/0344.Reverse String/Solution.py
|
{
"start": 0,
"end": 185
}
|
class ____:
def reverseString(self, s: List[str]) -> None:
i, j = 0, len(s) - 1
while i < j:
s[i], s[j] = s[j], s[i]
i, j = i + 1, j - 1
|
Solution
|
python
|
encode__django-rest-framework
|
tests/schemas/views.py
|
{
"start": 4441,
"end": 4992
}
|
class ____(generics.GenericAPIView):
serializer_class = ExampleValidatedSerializer
def get(self, *args, **kwargs):
serializer = self.get_serializer(integer=33, string='hello', regex='foo', decimal1=3.55,
decimal2=5.33, email='a@b.co',
url='http://localhost', uuid=uuid.uuid4(), ip4='127.0.0.1', ip6='::1',
ip='192.168.1.1')
return Response(serializer.data)
# Serializer with model.
|
ExampleValidatedAPIView
|
python
|
sqlalchemy__sqlalchemy
|
test/orm/test_attributes.py
|
{
"start": 111976,
"end": 113418
}
|
class ____(fixtures.TestBase):
def setup_test(self):
class A:
pass
class B:
pass
self.A = A
self.B = B
instrumentation.register_class(A)
instrumentation.register_class(B)
_register_attribute(A, "bs", uselist=True, useobject=True)
def test_expired(self):
A, B = self.A, self.B
a1 = A()
coll = a1.bs
a1.bs.append(B())
state = attributes.instance_state(a1)
state._expire(state.dict, set())
assert_warns(Warning, coll.append, B())
def test_replaced(self):
A, B = self.A, self.B
a1 = A()
coll = a1.bs
a1.bs.append(B())
a1.bs = []
# a bulk replace no longer empties the old collection
# as of [ticket:3913]
assert len(coll) == 1
coll.append(B())
assert len(coll) == 2
def test_pop_existing(self):
A, B = self.A, self.B
a1 = A()
coll = a1.bs
a1.bs.append(B())
state = attributes.instance_state(a1)
state._reset(state.dict, "bs")
assert_warns(Warning, coll.append, B())
def test_ad_hoc_lazy(self):
A, B = self.A, self.B
a1 = A()
coll = a1.bs
a1.bs.append(B())
state = attributes.instance_state(a1)
_set_callable(state, state.dict, "bs", lambda: B())
assert_warns(Warning, coll.append, B())
|
TestUnlink
|
python
|
numba__numba
|
numba/tests/test_np_functions.py
|
{
"start": 9188,
"end": 233635
}
|
class ____(MemoryLeakMixin, TestCase):
"""
Tests for various Numpy functions.
"""
def setUp(self):
super(TestNPFunctions, self).setUp()
self.rnd = np.random.RandomState(42)
def run_unary(self, pyfunc, x_types, x_values, func_extra_types=None,
func_extra_args=None, ignore_sign_on_zero=False, abs_tol=None,
**kwargs):
"""
Runs tests for a unary function operating in the numerical real space.
Parameters
----------
pyfunc : a python function definition holding that calls the numpy
functions to be tested.
x_types: the types of the values being tested, see numba.types
x_values: the numerical values of the values to be tested
func_extra_types: the types of additional arguments to the numpy
function
func_extra_args: additional arguments to the numpy function
ignore_sign_on_zero: boolean as to whether to allow zero values
with incorrect signs to be considered equal
prec: the required precision match, see assertPreciseEqual
Notes:
------
x_types and x_values must have the same length
"""
for tx, vx in zip(x_types, x_values):
if func_extra_args is None:
func_extra_types = func_extra_args = [()]
for xtypes, xargs in zip(func_extra_types, func_extra_args):
cfunc = njit((tx,) + xtypes,)(pyfunc)
got = cfunc(vx, *xargs)
expected = pyfunc(vx, *xargs)
try:
scalty = tx.dtype
except AttributeError:
scalty = tx
prec = ('single'
if scalty in (types.float32, types.complex64)
else 'double')
msg = 'for input %r with prec %r' % (vx, prec)
self.assertPreciseEqual(got, expected,
prec=prec,
msg=msg,
ignore_sign_on_zero=ignore_sign_on_zero,
abs_tol=abs_tol, **kwargs)
def test_sinc(self):
"""
Tests the sinc() function.
This test is purely to assert numerical computations are correct.
"""
# Ignore sign of zeros, this will need masking depending on numpy
# version once the fix to numpy complex division is in upstream
# See: https://github.com/numpy/numpy/pull/6699
isoz = True
# Testing sinc(1.) leads to sin(pi)/pi, which is below machine
# precision in practice on most machines. Small floating point
# differences in sin() etc. may lead to large differences in the result
# that are at a range that is inaccessible using standard width
# floating point representations.
# e.g. Assume float64 type.
# sin(pi) ~= 1e-16, but should be zero
# sin(pi)/pi ~= 1e-17, should be zero, error carried from above
# float64 has log10(2^53)~=15.9 digits of precision and the magnitude
# change in the alg is > 16 digits (1.0...0 -> 0.0...0),
# so comparison via ULP is invalid.
# We therefore opt to assume that values under machine precision are
# equal in this case.
tol = "eps"
pyfunc = sinc
def check(x_types, x_values, **kwargs):
self.run_unary(pyfunc, x_types, x_values,
ignore_sign_on_zero=isoz, abs_tol=tol,
**kwargs)
# real domain scalar context
x_values = [1., -1., 0.0, -0.0, 0.5, -0.5, 5, -5, 5e-21, -5e-21]
real_types = ([types.float64]
if REDUCED_TESTING
else [types.float32, types.float64])
x_types = real_types * (len(x_values) // len(real_types) + 1)
check(x_types, x_values)
# real domain vector context
x_values = [np.array(x_values, dtype=np.float64)]
x_types = [typeof(v) for v in x_values]
check(x_types, x_values)
# complex domain scalar context
x_values = [1.+0j, -1+0j, 0.0+0.0j, -0.0+0.0j, 0+1j, 0-1j, 0.5+0.0j, # noqa
-0.5+0.0j, 0.5+0.5j, -0.5-0.5j, 5+5j, -5-5j, # noqa
# the following are to test sin(x)/x for small x
5e-21+0j, -5e-21+0j, 5e-21j, +(0-5e-21j) # noqa
]
complex_types = ([types.complex128]
if REDUCED_TESTING
else [types.complex64, types.complex128])
x_types = complex_types * (len(x_values) // len(complex_types) + 1)
check(x_types, x_values, ulps=2)
# complex domain vector context
x_values = [np.array(x_values, dtype=np.complex128)]
x_types = [typeof(v) for v in x_values]
check(x_types, x_values, ulps=2)
def test_sinc_exceptions(self):
pyfunc = sinc
cfunc = jit(nopython=True)(pyfunc)
with self.assertRaises(TypingError) as raises:
cfunc('str')
self.assertIn('Argument "x" must be a Number or array-like',
str(raises.exception))
# Exceptions leak references
self.disable_leak_check()
def test_contains(self):
def arrs():
a_0 = np.arange(10, 50)
k_0 = 20
yield a_0, k_0
a_1 = np.arange(6)
k_1 = 10
yield a_1, k_1
single_val_a = np.asarray([20])
k_in = 20
k_out = 13
yield single_val_a, k_in
yield single_val_a, k_out
empty_arr = np.asarray([])
yield empty_arr, k_out
# np scalars
bool_arr = np.array([True, False])
yield bool_arr, True
yield bool_arr, k_0
np.random.seed(2)
float_arr = np.random.rand(10)
np.random.seed(2)
rand_k = np.random.rand()
present_k = float_arr[0]
yield float_arr, rand_k
yield float_arr, present_k
complx_arr = float_arr.view(np.complex128)
yield complx_arr, complx_arr[0]
yield complx_arr, rand_k
np.random.seed(2)
uint_arr = np.random.randint(10, size=15, dtype=np.uint8)
yield uint_arr, 5
yield uint_arr, 25
pyfunc = array_contains
cfunc = jit(nopython=True)(pyfunc)
for arr, key in arrs():
expected = pyfunc(arr, key)
received = cfunc(arr, key)
self.assertPreciseEqual(expected, received)
def test_angle(self):
"""
Tests the angle() function.
This test is purely to assert numerical computations are correct.
"""
pyfunc1 = angle1
pyfunc2 = angle2
def check(x_types, x_values):
# angle(x)
self.run_unary(pyfunc1, x_types, x_values)
# angle(x, deg)
xtra_values = [(True,), (False,)]
xtra_types = [(types.bool_,)] * len(xtra_values)
self.run_unary(pyfunc2, x_types, x_values,
func_extra_types=xtra_types,
func_extra_args=xtra_values,)
# real domain scalar context
x_values = [1., -1., 0.0, -0.0, 0.5, -0.5, 5, -5]
real_types = ([types.float64]
if REDUCED_TESTING
else [types.float32, types.float64])
x_types = real_types * (len(x_values) // len(real_types) + 1)
check(x_types, x_values)
# real domain vector context
x_values = [np.array(x_values, dtype=np.float64)]
x_types = [typeof(v) for v in x_values]
check(x_types, x_values)
# complex domain scalar context
x_values = [1.+0j, -1+0j, 0.0+0.0j, -0.0+0.0j, 1j, -1j, 0.5+0.0j, # noqa
-0.5+0.0j, 0.5+0.5j, -0.5-0.5j, 5+5j, -5-5j] # noqa
complex_types = ([types.complex128]
if REDUCED_TESTING
else [types.complex64, types.complex128])
x_types = complex_types * (len(x_values) // len(complex_types) + 1)
check(x_types, x_values)
# complex domain vector context
x_values = np.array(x_values)
x_types = ([types.complex128]
if REDUCED_TESTING
else [types.complex64, types.complex128])
check(x_types, x_values)
def test_angle_return_type(self):
# see issue #8949
def numba_angle(x):
r = np.angle(x)
return r.dtype
pyfunc = numba_angle
x_values = [1., -1., 1. + 0j, -5 - 5j]
x_types = ['f4', 'f8', 'c8', 'c16']
for val, typ in zip(x_values, x_types):
x = np.array([val], dtype=typ)
cfunc = jit(nopython=True)(pyfunc)
expected = pyfunc(x)
got = cfunc(x)
self.assertEqual(expected, got)
def test_angle_exceptions(self):
pyfunc = angle1
cfunc = jit(nopython=True)(pyfunc)
with self.assertRaises(TypingError) as raises:
cfunc('hello')
self.assertIn('Argument "z" must be a complex or Array[complex]',
str(raises.exception))
# Exceptions leak references
self.disable_leak_check()
def test_array_equal(self):
def arrays():
yield np.array([]), np.array([])
yield np.array([1, 2]), np.array([1, 2])
yield np.array([]), np.array([1])
x = np.arange(10).reshape(5, 2)
x[1][1] = 30
yield np.arange(10).reshape(5, 2), x
yield x, x
yield (1, 2, 3), (1, 2, 3)
yield 2, 2
yield 3, 2
yield True, True
yield True, False
yield True, 2
yield True, 1
yield False, 0
pyfunc = array_equal
cfunc = jit(nopython=True)(pyfunc)
for arr, obj in arrays():
expected = pyfunc(arr, obj)
got = cfunc(arr, obj)
self.assertPreciseEqual(expected, got)
def test_array_equal_exception(self):
pyfunc = array_equal
cfunc = jit(nopython=True)(pyfunc)
with self.assertRaises(TypingError) as raises:
cfunc(np.arange(3 * 4).reshape(3, 4), None)
self.assertIn(
'Both arguments to "array_equals" must be array-like',
str(raises.exception)
)
def test_intersect1d_2(self):
def arrays():
yield (List.empty_list(types.float64),
List.empty_list(types.float64)) # two empty arrays
yield [1], List.empty_list(types.float64) # empty right
yield List.empty_list(types.float64), [1] # empty left
yield [1], [2] # singletons no intersection
yield [1], [1] # singletons one intersection
yield [1, 2], [1]
yield [1, 2, 2], [2, 2]
yield [1, 2], [2, 1]
yield [1, 2, 3], [1, 2, 3]
# from numpy:
# https://github.com/numpy/numpy/blob/b0371ef240560e78b651a5d7c9407ae3212a3d56/numpy/lib/tests/test_arraysetops.py#L17 # noqa: E501
yield [5, 7, 1, 2], [2, 4, 3, 1, 5]
yield [5, 5, 7, 1, 2], [2, 1, 4, 3, 3, 1, 5]
pyfunc = intersect1d_2
cfunc = jit(nopython=True)(pyfunc)
for a, b in arrays():
# a = np.array(a)
# b = np.array(b)
if isinstance(a, list):
a = List(a)
if isinstance(b, list):
b = List(b)
expected = pyfunc(a, b)
got = cfunc(a, b)
self.assertPreciseEqual(expected, got)
def test_intersect1d_3(self):
def arrays():
yield (List.empty_list(types.float64),
List.empty_list(types.float64)) # two empty arrays
yield [1], List.empty_list(types.float64) # empty right
yield List.empty_list(types.float64), [1] # empty left
yield [1], [2] # singletons no intersection
yield [1], [1] # singletons one intersection
yield [1, 2], [1]
yield [1, 2, 2], [2, 2]
yield [1, 2], [2, 1]
yield [1, 2, 3], [1, 2, 3]
# from numpy:
# https://github.com/numpy/numpy/blob/b0371ef240560e78b651a5d7c9407ae3212a3d56/numpy/lib/tests/test_arraysetops.py#L17 # noqa: E501
yield [5, 7, 1, 2], [2, 4, 3, 1, 5]
yield [5, 5, 7, 1, 2], [2, 1, 4, 3, 3, 1, 5]
pyfunc = intersect1d_3
cfunc = jit(nopython=True)(pyfunc)
for a, b in arrays():
if isinstance(a, list):
a = List(a)
if isinstance(b, list):
b = List(b)
expected = pyfunc(a, b, assume_unique=False)
got = cfunc(a, b, assume_unique=False)
self.assertPreciseEqual(expected, got)
if len(np.unique(a)) == len(a) and len(np.unique(b)) == len(b):
expected = pyfunc(a, b, assume_unique=True)
got = cfunc(a, b, assume_unique=True)
self.assertPreciseEqual(expected, got)
def test_intersect1d_errors(self):
np_pyfunc = intersect1d_3
np_nbfunc = njit(np_pyfunc)
a = np.array([1])
b = np.array([2])
self.disable_leak_check()
with self.assertRaises(TypingError):
np_nbfunc(a, b, "foo")
with self.assertRaises(TypingError):
np_nbfunc("foo", b, True)
with self.assertRaises(TypingError):
np_nbfunc(a, "foo", True)
def test_count_nonzero(self):
def arrays():
yield np.array([]), None
yield np.zeros(10), None
yield np.arange(10), None
yield np.ones(10, dtype=np.bool_), 0
yield np.arange(3 * 4 * 5).reshape(3, 4, 5), None
yield np.arange(3 * 4).reshape(3, 4), 0
yield np.arange(3 * 4).reshape(3, 4), 1
pyfunc = count_nonzero
cfunc = jit(nopython=True)(pyfunc)
for arr, axis in arrays():
expected = pyfunc(arr, axis)
got = cfunc(arr, axis)
self.assertPreciseEqual(expected, got)
def test_np_append(self):
def arrays():
yield 2, 2, None
yield np.arange(10), 3, None
yield np.arange(10), np.arange(3), None
yield np.arange(10).reshape(5, 2), np.arange(3), None
yield np.array([[1, 2, 3], [4, 5, 6]]), np.array([[7, 8, 9]]), 0
arr = np.array([[1, 2, 3], [4, 5, 6]])
yield arr, arr, 1
pyfunc = append
cfunc = jit(nopython=True)(pyfunc)
for arr, obj, axis in arrays():
expected = pyfunc(arr, obj, axis)
got = cfunc(arr, obj, axis)
self.assertPreciseEqual(expected, got)
def test_np_append_exceptions(self):
pyfunc = append
cfunc = jit(nopython=True)(pyfunc)
arr = np.array([[1, 2, 3], [4, 5, 6]])
values = np.array([[7, 8, 9]])
axis = 0
# first argument must be array-like
with self.assertRaises(TypingError) as raises:
cfunc(None, values, axis)
self.assertIn(
'The first argument "arr" must be array-like',
str(raises.exception)
)
# second argument must also be array-like
with self.assertRaises(TypingError) as raises:
cfunc(arr, None, axis)
self.assertIn(
'The second argument "values" must be array-like',
str(raises.exception)
)
# third argument must be either nonelike or an integer
with self.assertRaises(TypingError) as raises:
cfunc(arr, values, axis=0.0)
self.assertIn(
'The third argument "axis" must be an integer',
str(raises.exception)
)
# Exceptions leak references
self.disable_leak_check()
def test_delete(self):
def arrays():
# array, obj
#
# an array-like type
yield [1, 2, 3, 4, 5], 3
yield [1, 2, 3, 4, 5], [2, 3]
# 1d array, scalar
yield np.arange(10), 3
yield np.arange(10), -3 # Negative obj
# 1d array, list
yield np.arange(10), [3, 5, 6]
yield np.arange(10), [2, 3, 4, 5]
# 3d array, scalar
yield np.arange(3 * 4 * 5).reshape(3, 4, 5), 2
# 3d array, list
yield np.arange(3 * 4 * 5).reshape(3, 4, 5), [5, 30, 27, 8]
# slices
yield [1, 2, 3, 4], slice(1, 3, 1)
yield np.arange(10), slice(10)
pyfunc = delete
cfunc = jit(nopython=True)(pyfunc)
for arr, obj in arrays():
expected = pyfunc(arr, obj)
got = cfunc(arr, obj)
self.assertPreciseEqual(expected, got)
def test_delete_exceptions(self):
pyfunc = delete
cfunc = jit(nopython=True)(pyfunc)
self.disable_leak_check()
with self.assertRaises(TypingError) as raises:
cfunc([1, 2], 3.14)
self.assertIn(
'obj should be of Integer dtype',
str(raises.exception)
)
with self.assertRaises(TypingError) as raises:
cfunc(np.arange(10), [3.5, 5.6, 6.2])
self.assertIn(
'obj should be of Integer dtype',
str(raises.exception)
)
with self.assertRaises(TypingError) as raises:
cfunc(2, 3)
self.assertIn(
'arr must be either an Array or a Sequence',
str(raises.exception)
)
with self.assertRaises(IndexError) as raises:
cfunc([1, 2], 3)
self.assertIn(
'obj must be less than the len(arr)',
str(raises.exception),
)
# Exceptions leak references
self.disable_leak_check()
def diff_arrays(self):
"""
Some test arrays for np.diff()
"""
a = np.arange(12) ** 3
yield a
b = a.reshape((3, 4))
yield b
c = np.arange(24).reshape((3, 2, 4)) ** 3
yield c
def test_diff1(self):
pyfunc = diff1
cfunc = jit(nopython=True)(pyfunc)
for arr in self.diff_arrays():
expected = pyfunc(arr)
got = cfunc(arr)
self.assertPreciseEqual(expected, got)
# 0-dim array
a = np.array(42)
with self.assertTypingError():
cfunc(a)
def test_diff2(self):
pyfunc = diff2
cfunc = jit(nopython=True)(pyfunc)
for arr in self.diff_arrays():
size = arr.shape[-1]
for n in (0, 1, 2, 3, size - 1, size, size + 1, 421):
expected = pyfunc(arr, n)
got = cfunc(arr, n)
self.assertPreciseEqual(expected, got)
def test_diff2_exceptions(self):
pyfunc = diff2
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
# 0-dim array
arr = np.array(42)
with self.assertTypingError():
cfunc(arr, 1)
# Invalid `n`
arr = np.arange(10)
for n in (-1, -2, -42):
with self.assertRaises(ValueError) as raises:
cfunc(arr, n)
self.assertIn("order must be non-negative", str(raises.exception))
# Exceptions leak references
self.disable_leak_check()
def test_isscalar(self):
def values():
yield 3
yield np.asarray([3])
yield (3,)
yield 3j
yield 'numba'
yield int(10)
yield np.int16(12345)
yield 4.234
yield True
yield None
yield np.timedelta64(10, 'Y')
yield np.datetime64('nat')
yield np.datetime64(1, 'Y')
pyfunc = isscalar
cfunc = jit(nopython=True)(pyfunc)
for x in values():
expected = pyfunc(x)
got = cfunc(x)
self.assertEqual(expected, got, x)
def test_isobj_functions(self):
def values():
yield 1
yield 1 + 0j
yield np.asarray([3, 1 + 0j, True])
yield "hello world"
@jit(nopython=True)
def optional_fn(x, cond, cfunc):
y = x if cond else None
return cfunc(y)
pyfuncs = [iscomplexobj, isrealobj]
for pyfunc in pyfuncs:
cfunc = jit(nopython=True)(pyfunc)
for x in values():
expected = pyfunc(x)
got = cfunc(x)
self.assertEqual(expected, got)
# optional type
expected_optional = optional_fn.py_func(x, True, pyfunc)
got_optional = optional_fn(x, True, cfunc)
self.assertEqual(expected_optional, got_optional)
# none type
expected_none = optional_fn.py_func(x, False, pyfunc)
got_none = optional_fn(x, False, cfunc)
self.assertEqual(expected_none, got_none)
self.assertEqual(len(cfunc.signatures), 8)
def test_is_real_or_complex(self):
def values():
yield np.array([1 + 1j, 1 + 0j, 4.5, 3, 2, 2j])
yield np.array([1, 2, 3])
yield 3
yield 12j
yield 1 + 4j
yield 10 + 0j
yield (1 + 4j, 2 + 0j)
yield np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
pyfuncs = [iscomplex, isreal]
for pyfunc in pyfuncs:
cfunc = jit(nopython=True)(pyfunc)
for x in values():
expected = pyfunc(x)
got = cfunc(x)
self.assertPreciseEqual(expected, got)
def test_isneg_or_ispos_inf(self):
def values():
yield -np.inf, None
yield np.inf, None
yield np.inf, None
yield np.asarray([-np.inf, 0., np.inf]), None
yield -np.inf, np.zeros(1, dtype=np.bool_)
yield np.inf, np.zeros(1, dtype=np.bool_)
yield np.inf, np.zeros(1, dtype=np.bool_)
yield -np.inf, np.empty(12)
yield np.asarray([-np.inf, 0., np.inf]), np.zeros(3, dtype=np.bool_)
pyfuncs = [isneginf, isposinf]
for pyfunc in pyfuncs:
cfunc = jit(nopython=True)(pyfunc)
for x, out in values():
expected = pyfunc(x, out)
got = cfunc(x, out)
self.assertPreciseEqual(expected, got)
def test_isclose(self):
rtol = 1e-5
atol = 1e-8
arr = np.array([100, 1000])
aran = np.arange(8).reshape((2, 2, 2))
kw = {'rtol': rtol, 'atol': atol}
def values():
yield 1e10, 1.00001e10, {}
yield 1e10, np.nan, {}
yield np.array([1e-8, 1e-7]), np.array([0.0, 0.0]), {}
yield np.array([1e10, 1e-7]), np.array([1.00001e10, 1e-8]), {}
yield np.array([1e10, 1e-8]), np.array([1.00001e10, 1e-9]), {}
yield np.array([1e10, 1e-8]), np.array([1.0001e10, 1e-9]), {}
yield np.array([1.0, np.nan]), np.array([1.0, np.nan]), {}
yield np.array([1.0, np.nan]), np.array([1.0, np.nan]), {'equal_nan': True} # noqa
yield np.array([np.nan, np.nan]), np.array([1.0, np.nan]), {'equal_nan': True} # noqa
yield np.array([1e-100, 1e-7]), np.array([0.0, 0.0]), {'atol': 0.0}
yield np.array([1e-10, 1e-10]), np.array([1e-20, 0.0]), {}
yield np.array([1e-10, 1e-10]), np.array([1e-20, 0.999999e-10]), {'atol': 0.0} # noqa
yield np.array([1, np.inf, 2]), np.array([3, np.inf, 4]), kw
yield np.array([atol, np.inf, -np.inf, np.nan]), np.array([0]), kw
yield np.array([atol, np.inf, -np.inf, np.nan]), 0, kw
yield 0, np.array([atol, np.inf, -np.inf, np.nan]), kw
# tests taken from
# https://github.com/numpy/numpy/blob/aac965af6032b69d5cb515ad785cc9a331e816f4/numpy/core/tests/test_numeric.py#L2298-L2335 # noqa: E501
# all close tests
yield np.array([0, 1]), np.array([1, 0]), kw
yield arr, arr, kw
yield np.array([1]), np.array([1 + rtol + atol]), kw
yield arr, arr + arr * rtol, kw
yield arr, arr + arr * rtol + atol, kw
yield aran, aran + aran * rtol, kw
yield np.inf, np.inf, kw
yield -np.inf, np.inf, kw
yield np.inf, np.array([np.inf]), kw
yield np.array([np.inf, -np.inf]), np.array([np.inf, -np.inf]), kw
# none close tests
yield np.array([np.inf, 0]), np.array([1, np.inf]), kw
yield np.array([np.inf, -np.inf]), np.array([1, 0]), kw
yield np.array([np.inf, np.inf]), np.array([1, -np.inf]), kw
yield np.array([np.inf, np.inf]), np.array([1, 0]), kw
yield np.array([np.nan, 0]), np.array([np.nan, -np.inf]), kw
yield np.array([atol * 2]), np.array([0]), kw
yield np.array([1]), np.array([1 + rtol + atol * 2]), kw
yield aran, aran + rtol * 1.1 * aran + atol * 1.1, kw
yield np.array(np.array([np.inf, 1])), np.array(np.array([0, np.inf])), kw # noqa
# some close tests
yield np.array([np.inf, 0]), np.array([atol * 2, atol * 2]), kw
yield np.array([np.inf, 0]), np.array([np.inf, atol * 2]), kw
yield np.array([atol, 1, 1e6 * (1 + 2 * rtol) + atol]), np.array([0, np.nan, 1e6]), kw # noqa
yield np.arange(3), np.array([0, 1, 2.1]), kw
yield np.nan, np.array([np.nan, np.nan, np.nan]), kw
yield np.array([0]), np.array([atol, np.inf, -np.inf, np.nan]), kw
yield 0, np.array([atol, np.inf, -np.inf, np.nan]), kw
pyfunc = isclose
cfunc = jit(nopython=True)(pyfunc)
for a, b, kwargs in values():
expected = pyfunc(a, b, **kwargs)
got = cfunc(a, b, **kwargs)
if isinstance(expected, np.bool_):
self.assertEqual(expected, got)
else:
self.assertTrue(np.array_equal(expected, got))
def isclose_exception(self):
pyfunc = isclose
cfunc = jit(nopython=True)(pyfunc)
inps = [
(np.asarray([1e10, 1e-9, np.nan]),
np.asarray([1.0001e10, 1e-9]),
1e-05, 1e-08, False,
"shape mismatch: objects cannot be broadcast to a single shape",
ValueError),
('hello', 3, False, 1e-08, False,
'The first argument "a" must be array-like',
TypingError),
(3, 'hello', False, 1e-08, False,
'The second argument "b" must be array-like',
TypingError),
(2, 3, False, 1e-08, False,
'The third argument "rtol" must be a floating point',
TypingError),
(2, 3, 1e-05, False, False,
'The fourth argument "atol" must be a floating point',
TypingError),
(2, 3, 1e-05, 1e-08, 1,
'The fifth argument "equal_nan" must be a boolean',
TypingError),
]
for a, b, rtol, atol, equal_nan, exc_msg, exc in inps:
with self.assertRaisesRegex(exc, exc_msg):
cfunc(a, b, rtol, atol, equal_nan)
def bincount_sequences(self):
"""
Some test sequences for np.bincount()
"""
a = [1, 2, 5, 2, 3, 20]
b = np.array([5, 8, 42, 5])
c = self.rnd.randint(0, 100, size=300).astype(np.int8)
return (a, b, c)
def test_bincount1(self):
pyfunc = bincount1
cfunc = jit(nopython=True)(pyfunc)
for seq in self.bincount_sequences():
expected = pyfunc(seq)
got = cfunc(seq)
self.assertPreciseEqual(expected, got)
def test_bincount1_exceptions(self):
pyfunc = bincount1
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
# Negative input
with self.assertRaises(ValueError) as raises:
cfunc([2, -1])
self.assertIn("first argument must be non-negative",
str(raises.exception))
# Exceptions leak references
self.disable_leak_check()
def test_bincount2(self):
pyfunc = bincount2
cfunc = jit(nopython=True)(pyfunc)
for seq in self.bincount_sequences():
w = [math.sqrt(x) - 2 for x in seq]
# weights as list, then array, mixed types, check upcast is ok
for weights in (w, np.array(w), seq, np.array(seq)):
expected = pyfunc(seq, weights)
got = cfunc(seq, weights)
self.assertPreciseEqual(expected, got)
def test_bincount2_exceptions(self):
pyfunc = bincount2
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
# Negative input
with self.assertRaises(ValueError) as raises:
cfunc([2, -1], [0, 0])
self.assertIn("first argument must be non-negative",
str(raises.exception))
# Mismatching input sizes
with self.assertRaises(ValueError) as raises:
cfunc([2, -1], [0])
self.assertIn("weights and list don't have the same length",
str(raises.exception))
def test_bincount3(self):
pyfunc = bincount3
cfunc = jit(nopython=True)(pyfunc)
for seq in self.bincount_sequences():
a_max = max(seq)
# Length should be a_max in the first case, minlength in the second
for minlength in (a_max, a_max + 2):
expected = pyfunc(seq, None, minlength)
got = cfunc(seq, None, minlength)
self.assertEqual(len(expected), len(got))
self.assertPreciseEqual(expected, got)
def test_bincount3_exceptions(self):
pyfunc = bincount3
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
# Negative input
with self.assertRaises(ValueError) as raises:
cfunc([2, -1], [0, 0])
self.assertIn("first argument must be non-negative",
str(raises.exception))
# Negative minlength
with self.assertRaises(ValueError) as raises:
cfunc([17, 38], None, -1)
self.assertIn("'minlength' must not be negative",
str(raises.exception))
def test_searchsorted(self):
pyfunc = searchsorted
cfunc = jit(nopython=True)(pyfunc)
pyfunc_left = searchsorted_left
cfunc_left = jit(nopython=True)(pyfunc_left)
pyfunc_right = searchsorted_right
cfunc_right = jit(nopython=True)(pyfunc_right)
def check(a, v):
expected = pyfunc(a, v)
got = cfunc(a, v)
self.assertPreciseEqual(expected, got)
expected = pyfunc_left(a, v)
got = cfunc_left(a, v)
self.assertPreciseEqual(expected, got)
expected = pyfunc_right(a, v)
got = cfunc_right(a, v)
self.assertPreciseEqual(expected, got)
if REDUCED_TESTING:
# Minimal essential testing for reduced mode
bins = np.array([0, 1, 4]) # Simple sorted array
values = np.array([0, 2, 5]) # Simple test values
# Test basic functionality only
check(bins, values[0]) # scalar
check(bins, values) # array
check(list(bins), values) # list input
return
# First with integer values (no NaNs)
bins = np.arange(5) ** 2
values = np.arange(20) - 1
for a in (bins, list(bins)):
# Scalar values
for v in values:
check(a, v)
# Array values
for v in (values, values.reshape((4, 5))):
check(a, v)
# Sequence values
check(a, list(values))
# Second with float values (including NaNs)
bins = np.float64(list(bins) + [float('nan')] * 7) / 2.0
values = np.arange(20) - 0.5
for a in (bins, list(bins)):
# Scalar values
for v in values:
check(a, v)
# Array values
for v in (values, values.reshape((4, 5))):
check(a, v)
# Sequence values
check(a, list(values))
# nonsense value for 'side' raises TypingError
def bad_side(a, v):
return np.searchsorted(a, v, side='nonsense')
cfunc = jit(nopython=True)(bad_side)
with self.assertTypingError():
cfunc([1,2], 1)
# non-constant value for 'side' raises TypingError
def nonconst_side(a, v, side='left'):
return np.searchsorted(a, v, side=side)
cfunc = jit(nopython=True)(nonconst_side)
with self.assertTypingError():
cfunc([1,2], 1, side='right')
# Test unordered values
a = np.array([1, 2, 0])
v = np.array(
[
[5, 4],
[6, 7],
[2, 1],
[0, 3],
]
)
check(a, v)
a = np.array([9, 1, 4, 2, 0, 3, 7, 6, 8])
v = np.array(
[
[5, 10],
[10, 5],
[-1, 5],
]
)
check(a, v)
def test_searchsorted_supplemental(self):
pyfunc = searchsorted
cfunc = jit(nopython=True)(pyfunc)
pyfunc_left = searchsorted_left
cfunc_left = jit(nopython=True)(pyfunc_left)
pyfunc_right = searchsorted_right
cfunc_right = jit(nopython=True)(pyfunc_right)
def check(a, v):
expected = pyfunc(a, v)
got = cfunc(a, v)
self.assertPreciseEqual(expected, got)
expected = pyfunc_left(a, v)
got = cfunc_left(a, v)
self.assertPreciseEqual(expected, got)
expected = pyfunc_right(a, v)
got = cfunc_right(a, v)
self.assertPreciseEqual(expected, got)
if REDUCED_TESTING:
# Essential tests only - minimal cases
a = np.array([1, 3, 5])
v = np.array([0, 2, 4, 6])
check(a, v)
check(np.sort(a), v)
return
element_pool = list(range(-5, 50))
element_pool += [np.nan] * 5 + [np.inf] * 3 + [-np.inf] * 3
for i in range(1000):
sample_size = self.rnd.choice([5, 10, 25])
# `a` and `v` not sorted; either may have repeating values
a = self.rnd.choice(element_pool, sample_size)
v = self.rnd.choice(element_pool, sample_size + (i % 3 - 1))
# output should match numpy regardless of whether `a` is sorted
check(a, v)
check(np.sort(a), v)
ones = np.ones(5)
nans = np.full(len(ones), fill_value=np.nan)
check(ones, ones)
# `a` and / or `v` full of nans
check(ones, nans)
check(nans, ones)
check(nans, nans)
# `a` and `v` are float32
a = np.array([9, np.nan], dtype=np.float32)
v = np.array([np.nan], dtype=np.float32)
check(a, v)
# `v` is zero size
a = np.arange(1)
v = np.arange(0)
check(a, v)
# `a` and `v` booleans
a = np.array([False, False, True, True])
v = np.array([False, True])
check(a, v)
# `v` is a (scalar) boolean
a = [1, 2, 3]
v = True
check(a, v)
# `a` and `v` arrays of strings
a = np.array(['1', '2', '3'])
v = np.array(['2', '4'])
check(a, v)
def test_searchsorted_complex(self):
pyfunc = searchsorted
cfunc = jit(nopython=True)(pyfunc)
pyfunc_left = searchsorted_left
cfunc_left = jit(nopython=True)(pyfunc_left)
pyfunc_right = searchsorted_right
cfunc_right = jit(nopython=True)(pyfunc_right)
def check(a, v):
expected = pyfunc(a, v)
got = cfunc(a, v)
self.assertPreciseEqual(expected, got)
expected = pyfunc_left(a, v)
got = cfunc_left(a, v)
self.assertPreciseEqual(expected, got)
expected = pyfunc_right(a, v)
got = cfunc_right(a, v)
self.assertPreciseEqual(expected, got)
if REDUCED_TESTING:
# Essential complex number test only
a = np.array([1 + 0j, 2 + 1j, 3 + 0j])
v = np.array([1 + 1j, 2 + 0j])
check(a, v)
check(np.sort(a), v)
return
pool = [0, 1, np.nan]
element_pool = [complex(*c) for c in itertools.product(pool, pool)]
for i in range(100):
sample_size = self.rnd.choice([3, 5, len(element_pool)])
# `a` and `v` not sorted; either may have repeating values
a = self.rnd.choice(element_pool, sample_size)
v = self.rnd.choice(element_pool, sample_size + (i % 3 - 1))
# output should match numpy regardless of whether `a` is sorted
check(a, v)
check(np.sort(a), v)
# check type promotion (a complex; v not so much)
check(a=np.array(element_pool), v=np.arange(2))
def test_digitize(self):
pyfunc = digitize
cfunc = jit(nopython=True)(pyfunc)
def check(*args):
expected = pyfunc(*args)
got = cfunc(*args)
self.assertPreciseEqual(expected, got)
values = np.float64((0, 0.99, 1, 4.4, 4.5, 7, 8, 9, 9.5,
float('inf'), float('-inf'), float('nan')))
assert len(values) == 12
self.rnd.shuffle(values)
bins1 = np.float64([1, 3, 4.5, 8])
bins2 = np.float64([1, 3, 4.5, 8, float('inf'), float('-inf')])
bins3 = np.float64([1, 3, 4.5, 8, float('inf'), float('-inf')]
+ [float('nan')] * 10)
all_bins = [bins1, bins2, bins3]
xs = [values, values.reshape((3, 4))]
# 2-ary digitize()
for bins in all_bins:
bins.sort()
for x in xs:
check(x, bins)
check(x, bins[::-1])
# 3-ary digitize()
for bins in all_bins:
for right in (True, False):
check(values, bins, right)
check(values, bins[::-1], right)
# Sequence input
check(list(values), bins1)
# per https://github.com/numba/numba/issues/8768
check(np.array([np.nan, 1]), np.array([1.5, np.nan]))
def test_digitize_non_monotonic_bins(self):
# Exceptions leak references
self.disable_leak_check()
pyfunc = digitize
cfunc = jit(nopython=True)(pyfunc)
def check_error(*args):
for fn in (pyfunc, cfunc):
with self.assertRaises(ValueError) as raises:
fn(*args)
msg = 'bins must be monotonically increasing or decreasing'
self.assertIn(msg, str(raises.exception))
x = np.array([np.nan, 1])
bins = np.array([np.nan, 1.5, 2.3, np.nan])
check_error(x, bins)
x = [-1, 0, 1, 2]
bins = [0, 0, 1, 0]
check_error(x, bins)
bins = [1, 1, 0, 1]
check_error(x, bins)
def test_digitize_supplemental(self):
# inspired by the tests in
# https://github.com/numpy/numpy/blob/a277f62/numpy/lib/tests/test_function_base.py
pyfunc = digitize
cfunc = jit(nopython=True)(pyfunc)
def check(*args):
expected = pyfunc(*args)
got = cfunc(*args)
self.assertPreciseEqual(expected, got)
# forward
x = np.arange(-6, 5)
bins = np.arange(-5, 5)
check(x, bins)
# reverse
x = np.arange(5, -6, -1)
bins = np.arange(5, -5, -1)
check(x, bins)
# random
x = self.rnd.rand(10)
bins = np.linspace(x.min(), x.max(), 10)
check(x, bins)
# right_basic
x = [1, 5, 4, 10, 8, 11, 0]
bins = [1, 5, 10]
check(x, bins)
# right_open
x = np.arange(-6, 5)
bins = np.arange(-6, 4)
check(x, bins, True)
# right_open_reverse
x = np.arange(5, -6, -1)
bins = np.arange(4, -6, -1)
check(x, bins, True)
# right_open_random
x = self.rnd.rand(10)
bins = np.linspace(x.min(), x.max(), 10)
check(x, bins, True)
# monotonic
x = [-1, 0, 1, 2]
bins = [0, 0, 1]
check(x, bins)
bins = [1, 1, 0]
check(x, bins)
bins = [1, 1, 1, 1]
check(x, bins)
# large_integers_increasing
x = 2 ** 54 # loses precision in a float
check([x], [x - 1, x + 1])
def test_digitize_raise_if_x_complex(self):
# Exceptions leak references
self.disable_leak_check()
pyfunc = digitize
cfunc = jit(nopython=True)(pyfunc)
x = np.array([1 + 1j])
y = np.array([1., 3., 4.5, 8.])
msg = 'x may not be complex'
for func in pyfunc, cfunc:
with self.assertTypingError() as raises:
func(x, y)
self.assertIn(msg, str(raises.exception))
def test_histogram(self):
pyfunc = histogram
cfunc = jit(nopython=True)(pyfunc)
def check(*args):
pyhist, pybins = pyfunc(*args)
chist, cbins = cfunc(*args)
self.assertPreciseEqual(pyhist, chist)
# There can be a slight discrepancy in the linspace() result
# when `bins` is an integer...
self.assertPreciseEqual(pybins, cbins, prec='double', ulps=2)
def check_values(values):
# Explicit bins array
# (note Numpy seems to not support NaN bins)
bins = np.float64([1, 3, 4.5, 8])
check(values, bins)
check(values.reshape((3, 4)), bins)
# Explicit number of bins
check(values, 7)
# Explicit number of bins and bins range
check(values, 7, (1.0, 13.5))
# Implicit bins=10
check(values)
values = np.float64((0, 0.99, 1, 4.4, 4.5, 7, 8,
9, 9.5, 42.5, -1.0, -0.0))
assert len(values) == 12
self.rnd.shuffle(values)
check_values(values)
def _test_correlate_convolve(self, pyfunc):
cfunc = jit(nopython=True)(pyfunc)
# only 1d arrays are accepted, test varying lengths
# and varying dtype
def check(lengths, dts, modes):
for dt1, dt2, n, m, mode in itertools.product(
dts, dts, lengths, lengths, modes
):
a = np.arange(n, dtype=dt1)
v = np.arange(m, dtype=dt2)
if np.issubdtype(dt1, np.complexfloating):
a = (a + 1j * a).astype(dt1)
if np.issubdtype(dt2, np.complexfloating):
v = (v + 1j * v).astype(dt2)
expected = pyfunc(a, v, mode=mode)
got = cfunc(a, v, mode=mode)
self.assertPreciseEqual(expected, got)
if REDUCED_TESTING:
lengths = (1, 2)
dts = [np.float64, np.complex128]
modes = ["full", "valid"]
check(lengths, dts, modes)
return
lengths = (1, 2, 3, 7)
dts = [np.int8, np.int32, np.int64, np.float32, np.float64,
np.complex64, np.complex128]
modes = ["full", "valid", "same"]
check(lengths, dts, modes)
_a = np.arange(12).reshape(4, 3)
_b = np.arange(12)
for x, y in [(_a, _b), (_b, _a)]:
with self.assertRaises(TypingError) as raises:
cfunc(x, y)
msg = 'only supported on 1D arrays'
self.assertIn(msg, str(raises.exception))
def test_correlate(self):
self._test_correlate_convolve(correlate)
def _test_correlate_convolve_exceptions(self, fn):
# Exceptions leak references
self.disable_leak_check()
# convolve raises if either array has a 0 dimension
_a = np.ones(shape=(0,))
_b = np.arange(5)
cfunc = jit(nopython=True)(fn)
for x, y in [(_a, _b), (_b, _a)]:
with self.assertRaises(ValueError) as raises:
cfunc(x, y)
if len(x) == 0:
self.assertIn("'a' cannot be empty", str(raises.exception))
else:
self.assertIn("'v' cannot be empty", str(raises.exception))
with self.assertRaises(ValueError) as raises:
cfunc(_b, _b, mode="invalid mode")
self.assertIn("Invalid 'mode'", str(raises.exception))
def test_correlate_exceptions(self):
# correlate supported 0 dimension arrays until 1.18
self._test_correlate_convolve_exceptions(correlate)
def test_convolve(self):
self._test_correlate_convolve(convolve)
def test_convolve_exceptions(self):
self._test_correlate_convolve_exceptions(convolve)
def _check_output(self, pyfunc, cfunc, params, abs_tol=None):
expected = pyfunc(**params)
got = cfunc(**params)
self.assertPreciseEqual(expected, got, abs_tol=abs_tol)
def test_vander_basic(self):
pyfunc = vander
cfunc = jit(nopython=True)(pyfunc)
_check_output = partial(self._check_output, pyfunc, cfunc)
def _check(x):
if REDUCED_TESTING:
n_choices = [None, 1, 2]
increasing_choices = [False]
else:
n_choices = [None, 0, 1, 2, 3, 4]
increasing_choices = [True, False]
# N and increasing defaulted
params = {'x': x}
_check_output(params)
# N provided and increasing defaulted
for n in n_choices:
params = {'x': x, 'N': n}
_check_output(params)
if not REDUCED_TESTING:
# increasing provided and N defaulted:
for increasing in increasing_choices:
params = {'x': x, 'increasing': increasing}
_check_output(params)
# both n and increasing supplied
for n in n_choices:
for increasing in increasing_choices:
params = {'x': x, 'N': n, 'increasing': increasing}
_check_output(params)
if REDUCED_TESTING:
# Minimal test cases for memory optimization
_check(np.array([1, 2, 3]))
_check(np.array([]))
_check([0, 1, 2])
return
_check(np.array([1, 2, 3, 5]))
_check(np.arange(7) - 10.5)
_check(np.linspace(3, 10, 5))
_check(np.array([1.2, np.nan, np.inf, -np.inf]))
_check(np.array([]))
_check(np.arange(-5, 5) - 0.3)
# # boolean array
_check(np.array([True] * 5 + [False] * 4))
# cycle through dtypes to check type promotion a la numpy
for dtype in np.int32, np.int64, np.float32, np.float64:
_check(np.arange(10, dtype=dtype))
# non array inputs
_check([0, 1, 2, 3])
_check((4, 5, 6, 7))
_check((0.0, 1.0, 2.0))
_check(())
# edge cases
_check((3, 4.444, 3.142))
_check((True, False, 4))
def test_vander_exceptions(self):
pyfunc = vander
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
x = np.arange(5) - 0.5
def _check_n(N):
with self.assertTypingError() as raises:
cfunc(x, N=N)
self.assertIn("Second argument N must be None or an integer",
str(raises.exception))
for N in 1.1, True, np.inf, [1, 2]:
_check_n(N)
with self.assertRaises(ValueError) as raises:
cfunc(x, N=-1)
self.assertIn("Negative dimensions are not allowed",
str(raises.exception))
def _check_1d(x):
with self.assertRaises(ValueError) as raises:
cfunc(x)
self.assertEqual("x must be a one-dimensional array or sequence.",
str(raises.exception))
x = np.arange(27).reshape((3, 3, 3))
_check_1d(x)
x = ((2, 3), (4, 5))
_check_1d(x)
def test_tri_n_basic(self):
pyfunc = tri_n
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc)
def n_variations():
return np.arange(-4, 8) # number of rows
# N supplied, M and k defaulted
for n in n_variations():
params = {'N': n}
_check(params)
def test_tri_n_m_basic(self):
pyfunc = tri_n_m
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc)
def n_variations():
return np.arange(-4, 8) # number of rows
def m_variations():
# number of columns
return itertools.chain.from_iterable(([None], range(-5, 9)))
# N supplied, M and k defaulted
for n in n_variations():
params = {'N': n}
_check(params)
# N and M supplied, k defaulted
for n in n_variations():
for m in m_variations():
params = {'N': n, 'M': m}
_check(params)
def test_tri_n_k_basic(self):
pyfunc = tri_n_k
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc)
def n_variations():
return np.arange(-4, 8) # number of rows
def k_variations():
return np.arange(-10, 10) # offset
# N supplied, M and k defaulted
for n in n_variations():
params = {'N': n}
_check(params)
# N and k supplied, M defaulted
for n in n_variations():
for k in k_variations():
params = {'N': n, 'k': k}
_check(params)
def test_tri_n_m_k_basic(self):
pyfunc = tri_n_m_k
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc)
def n_variations():
return np.arange(-4, 8) # number of rows
def m_variations():
# number of columns
return itertools.chain.from_iterable(([None], range(-5, 9)))
def k_variations():
return np.arange(-10, 10) # offset
# N supplied, M and k defaulted
for n in n_variations():
params = {'N': n}
_check(params)
# N and M supplied, k defaulted
for n in n_variations():
for m in m_variations():
params = {'N': n, 'M': m}
_check(params)
# N and k supplied, M defaulted
for n in n_variations():
for k in k_variations():
params = {'N': n, 'k': k}
_check(params)
# N, M and k supplied
for n in n_variations():
for k in k_variations():
for m in m_variations():
params = {'N': n, 'M': m, 'k': k}
_check(params)
def test_tri_exceptions(self):
pyfunc = tri_n_m_k
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
def _check(k):
with self.assertTypingError() as raises:
cfunc(5, 6, k=k)
assert "k must be an integer" in str(raises.exception)
for k in 1.5, True, np.inf, [1, 2]:
_check(k)
def _triangular_matrix_tests_m(self, pyfunc):
cfunc = jit(nopython=True)(pyfunc)
def _check(arr):
expected = pyfunc(arr)
got = cfunc(arr)
# TODO: Contiguity of result not consistent with numpy
self.assertEqual(got.dtype, expected.dtype)
np.testing.assert_array_equal(got, expected)
return self._triangular_matrix_tests_inner(self, pyfunc, _check)
def _triangular_matrix_tests_m_k(self, pyfunc):
cfunc = jit(nopython=True)(pyfunc)
def _check(arr):
for k in itertools.chain.from_iterable(([None], range(-10, 10))):
if k is None:
params = {}
else:
params = {'k': k}
expected = pyfunc(arr, **params)
got = cfunc(arr, **params)
# TODO: Contiguity of result not consistent with numpy
self.assertEqual(got.dtype, expected.dtype)
np.testing.assert_array_equal(got, expected)
return self._triangular_matrix_tests_inner(self, pyfunc, _check)
@staticmethod
def _triangular_matrix_tests_inner(self, pyfunc, _check):
def check_odd(a):
_check(a)
a = a.reshape((9, 7))
_check(a)
a = a.reshape((7, 1, 3, 3))
_check(a)
_check(a.T)
def check_even(a):
_check(a)
a = a.reshape((4, 16))
_check(a)
a = a.reshape((4, 2, 2, 4))
_check(a)
_check(a.T)
check_odd(np.arange(63) + 10.5)
check_even(np.arange(64) - 10.5)
# edge cases
_check(np.arange(360).reshape(3, 4, 5, 6))
_check(np.array([]))
_check(np.arange(9).reshape((3, 3))[::-1])
_check(np.arange(9).reshape((3, 3), order='F'))
arr = (np.arange(64) - 10.5).reshape((4, 2, 2, 4))
_check(arr)
_check(np.asfortranarray(arr))
def _triangular_matrix_exceptions(self, pyfunc):
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
a = np.ones((5, 6))
with self.assertTypingError() as raises:
cfunc(a, k=1.5)
self.assertIn("k must be an integer", str(raises.exception))
def _triangular_indices_tests_base(self, pyfunc, args):
cfunc = jit(nopython=True)(pyfunc)
for x in args:
expected = pyfunc(*x)
got = cfunc(*x)
self.assertEqual(type(expected), type(got))
self.assertEqual(len(expected), len(got))
for e, g in zip(expected, got):
np.testing.assert_array_equal(e, g)
def _triangular_indices_tests_n(self, pyfunc):
self._triangular_indices_tests_base(
pyfunc,
[[n] for n in range(10)]
)
def _triangular_indices_tests_n_k(self, pyfunc):
self._triangular_indices_tests_base(
pyfunc,
[[n, k] for n in range(10) for k in range(-n - 1, n + 2)]
)
def _triangular_indices_tests_n_m(self, pyfunc):
self._triangular_indices_tests_base(
pyfunc,
[[n, m] for n in range(10) for m in range(2 * n)]
)
def _triangular_indices_tests_n_k_m(self, pyfunc):
self._triangular_indices_tests_base(
pyfunc,
[[n, k, m] for n in range(10)
for k in range(-n - 1, n + 2)
for m in range(2 * n)]
)
# Check jitted version works with default values for kwargs
cfunc = jit(nopython=True)(pyfunc)
cfunc(1)
def _triangular_indices_from_tests_arr(self, pyfunc):
cfunc = jit(nopython=True)(pyfunc)
for dtype in [int, float, bool]:
for n,m in itertools.product(range(10), range(10)):
arr = np.ones((n, m), dtype)
expected = pyfunc(arr)
got = cfunc(arr)
self.assertEqual(type(expected), type(got))
self.assertEqual(len(expected), len(got))
for e, g in zip(expected, got):
np.testing.assert_array_equal(e, g)
def _triangular_indices_from_tests_arr_k(self, pyfunc):
cfunc = jit(nopython=True)(pyfunc)
for dtype in [int, float, bool]:
for n,m in itertools.product(range(10), range(10)):
arr = np.ones((n, m), dtype)
for k in range(-10, 10):
expected = pyfunc(arr)
got = cfunc(arr)
self.assertEqual(type(expected), type(got))
self.assertEqual(len(expected), len(got))
for e, g in zip(expected, got):
np.testing.assert_array_equal(e, g)
def _triangular_indices_exceptions(self, pyfunc):
cfunc = jit(nopython=True)(pyfunc)
parameters = pysignature(pyfunc).parameters
with self.assertTypingError() as raises:
cfunc(1.0)
self.assertIn("n must be an integer", str(raises.exception))
if 'k' in parameters:
with self.assertTypingError() as raises:
cfunc(1, k=1.0)
self.assertIn("k must be an integer", str(raises.exception))
if 'm' in parameters:
with self.assertTypingError() as raises:
cfunc(1, m=1.0)
self.assertIn("m must be an integer", str(raises.exception))
def _triangular_indices_from_exceptions(self, pyfunc, test_k=True):
cfunc = jit(nopython=True)(pyfunc)
for ndims in [0, 1, 3]:
a = np.ones([5] * ndims)
with self.assertTypingError() as raises:
cfunc(a)
self.assertIn("input array must be 2-d", str(raises.exception))
if test_k:
a = np.ones([5, 5])
with self.assertTypingError() as raises:
cfunc(a, k=0.5)
self.assertIn("k must be an integer", str(raises.exception))
def test_tril_basic(self):
self._triangular_matrix_tests_m(tril_m)
self._triangular_matrix_tests_m_k(tril_m_k)
def test_tril_exceptions(self):
self._triangular_matrix_exceptions(tril_m_k)
def test_tril_indices(self):
self._triangular_indices_tests_n(tril_indices_n)
self._triangular_indices_tests_n_k(tril_indices_n_k)
self._triangular_indices_tests_n_m(tril_indices_n_m)
self._triangular_indices_tests_n_k_m(tril_indices_n_k_m)
self._triangular_indices_exceptions(tril_indices_n)
self._triangular_indices_exceptions(tril_indices_n_k)
self._triangular_indices_exceptions(tril_indices_n_m)
self._triangular_indices_exceptions(tril_indices_n_k_m)
def test_tril_indices_from(self):
self._triangular_indices_from_tests_arr(tril_indices_from_arr)
self._triangular_indices_from_tests_arr_k(tril_indices_from_arr_k)
self._triangular_indices_from_exceptions(tril_indices_from_arr, False)
self._triangular_indices_from_exceptions(tril_indices_from_arr_k, True)
def test_triu_basic(self):
self._triangular_matrix_tests_m(triu_m)
self._triangular_matrix_tests_m_k(triu_m_k)
def test_triu_exceptions(self):
self._triangular_matrix_exceptions(triu_m_k)
def test_triu_indices(self):
self._triangular_indices_tests_n(triu_indices_n)
self._triangular_indices_tests_n_k(triu_indices_n_k)
self._triangular_indices_tests_n_m(triu_indices_n_m)
self._triangular_indices_tests_n_k_m(triu_indices_n_k_m)
self._triangular_indices_exceptions(triu_indices_n)
self._triangular_indices_exceptions(triu_indices_n_k)
self._triangular_indices_exceptions(triu_indices_n_m)
self._triangular_indices_exceptions(triu_indices_n_k_m)
def test_triu_indices_from(self):
self._triangular_indices_from_tests_arr(triu_indices_from_arr)
self._triangular_indices_from_tests_arr_k(triu_indices_from_arr_k)
self._triangular_indices_from_exceptions(triu_indices_from_arr, False)
self._triangular_indices_from_exceptions(triu_indices_from_arr_k, True)
def test_indices_basic(self):
pyfunc = np_indices
cfunc = njit(np_indices)
def inputs():
# Taken from https://github.com/numpy/numpy/blob/db4f43983cb938f12c311e1f5b7165e270c393b4/numpy/core/tests/test_numeric.py#L3383-L3407 # noqa: E501
yield (4, 3)
yield (4,)
yield (0,)
yield (2, 2, 3, 5)
for dims in inputs():
self.assertPreciseEqual(pyfunc(dims), cfunc(dims))
def test_indices_exception(self):
cfunc = njit(np_indices)
self.disable_leak_check()
errmsg = 'The argument "dimensions" must be a tuple of integers'
with self.assertRaises(TypingError) as raises:
cfunc("abc")
self.assertIn(errmsg,
str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc((2.0, 3.0))
self.assertIn(errmsg,
str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc((2, 3.0))
self.assertIn(errmsg,
str(raises.exception))
def partition_sanity_check(self, pyfunc, cfunc, a, kth):
# as NumPy uses a different algorithm, we do not expect to
# match outputs exactly...
expected = pyfunc(a, kth)
got = cfunc(a, kth)
# but we do expect the unordered collection of elements up to the
# kth to tie out
self.assertPreciseEqual(np.unique(expected[:kth]), np.unique(got[:kth]))
# likewise the unordered collection of elements from the kth onwards
self.assertPreciseEqual(np.unique(expected[kth:]), np.unique(got[kth:]))
def argpartition_sanity_check(self, pyfunc, cfunc, a, kth):
# as NumPy uses a different algorithm, we do not expect to
# match outputs exactly...
expected = pyfunc(a, kth)
got = cfunc(a, kth)
# but we do expect the unordered collection of elements up to the
# kth to tie out
self.assertPreciseEqual(np.unique(a[expected[:kth]]),
np.unique(a[got[:kth]]))
# likewise the unordered collection of elements from the kth onwards
self.assertPreciseEqual(np.unique(a[expected[kth:]]),
np.unique(a[got[kth:]]))
def test_partition_fuzz(self):
# inspired by the test of the same name in:
# https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501
pyfunc = partition
cfunc = jit(nopython=True)(pyfunc)
j_range_args = ((10, 15) if REDUCED_TESTING else (10, 30))
j_range = range(*j_range_args)
for j in j_range:
i_range_args = ((1, min(5, j - 2))
if REDUCED_TESTING
else (1, j - 2))
i_range = range(*i_range_args)
for i in i_range:
d = np.arange(j)
self.rnd.shuffle(d)
d = d % self.rnd.randint(2, 30)
idx = self.rnd.randint(d.size)
kth = [0, idx, i, i + 1, -idx, -i] # include negative kth's
tgt = np.sort(d)[kth]
self.assertPreciseEqual(cfunc(d, kth)[kth],
tgt) # a -> array
# Skip list/tuple variations in reduced mode
if not REDUCED_TESTING:
self.assertPreciseEqual(cfunc(d.tolist(), kth)[kth],
tgt) # a -> list
self.assertPreciseEqual(cfunc(tuple(d.tolist()), kth)[kth],
tgt) # a -> tuple
for k in kth:
self.partition_sanity_check(pyfunc, cfunc, d, k)
def test_argpartition_fuzz(self):
# inspired by the test of the same name in:
# https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501
pyfunc = argpartition
cfunc = jit(nopython=True)(pyfunc)
j_range_args = ((10, 15) if REDUCED_TESTING else (10, 30))
j_range = range(*j_range_args)
for j in j_range:
i_range_args = ((1, min(5, j - 2))
if REDUCED_TESTING
else (1, j - 2))
i_range = range(*i_range_args)
for i in i_range:
d = np.arange(j)
self.rnd.shuffle(d)
d = d % self.rnd.randint(2, 30)
idx = self.rnd.randint(d.size)
kth = [0, idx, i, i + 1, -idx, -i] # include negative kth's
tgt = np.argsort(d)[kth]
self.assertPreciseEqual(d[cfunc(d, kth)[kth]],
d[tgt]) # a -> array
# Skip list/tuple variations in reduced mode
if not REDUCED_TESTING:
self.assertPreciseEqual(d[cfunc(d.tolist(), kth)[kth]],
d[tgt]) # a -> list
self.assertPreciseEqual(
d[cfunc(tuple(d.tolist()), kth)[kth]],
d[tgt]) # a -> tuple
for k in kth:
self.argpartition_sanity_check(pyfunc, cfunc, d, k)
def test_partition_exception_out_of_range(self):
# inspired by the test of the same name in:
# https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501
pyfunc = partition
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
# Test out of range values in kth raise an error
a = np.arange(10)
def _check(a, kth):
with self.assertRaises(ValueError) as e:
cfunc(a, kth)
assert str(e.exception) == "kth out of bounds"
_check(a, 10)
_check(a, -11)
_check(a, (3, 30))
def test_argpartition_exception_out_of_range(self):
# inspired by the test of the same name in:
# https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501
pyfunc = argpartition
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
# Test out of range values in kth raise an error
a = np.arange(10)
def _check(a, kth):
with self.assertRaises(ValueError) as e:
cfunc(a, kth)
assert str(e.exception) == "kth out of bounds"
_check(a, 10)
_check(a, -11)
_check(a, (3, 30))
def test_partition_exception_non_integer_kth(self):
# inspired by the test of the same name in:
# https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501
pyfunc = partition
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
def _check(a, kth):
with self.assertTypingError() as raises:
cfunc(a, kth)
self.assertIn("Partition index must be integer",
str(raises.exception))
a = np.arange(10)
_check(a, 9.0)
_check(a, (3.3, 4.4))
_check(a, np.array((1, 2, np.nan)))
def test_argpartition_exception_non_integer_kth(self):
# inspired by the test of the same name in:
# https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501
pyfunc = argpartition
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
def _check(a, kth):
with self.assertTypingError() as raises:
cfunc(a, kth)
self.assertIn("Partition index must be integer",
str(raises.exception))
a = np.arange(10)
_check(a, 9.0)
_check(a, (3.3, 4.4))
_check(a, np.array((1, 2, np.nan)))
def test_partition_exception_a_not_array_like(self):
pyfunc = partition
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
def _check(a, kth):
with self.assertTypingError() as raises:
cfunc(a, kth)
self.assertIn('The first argument must be an array-like',
str(raises.exception))
_check(4, 0)
_check('Sausages', 0)
def test_argpartition_exception_a_not_array_like(self):
pyfunc = argpartition
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
def _check(a, kth):
with self.assertTypingError() as raises:
cfunc(a, kth)
self.assertIn('The first argument must be an array-like',
str(raises.exception))
_check(4, 0)
_check('Sausages', 0)
def test_partition_exception_a_zero_dim(self):
pyfunc = partition
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
def _check(a, kth):
with self.assertTypingError() as raises:
cfunc(a, kth)
self.assertIn('The first argument must be at least 1-D (found 0-D)',
str(raises.exception))
_check(np.array(1), 0)
def test_argpartition_exception_a_zero_dim(self):
pyfunc = argpartition
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
def _check(a, kth):
with self.assertTypingError() as raises:
cfunc(a, kth)
self.assertIn('The first argument must be at least 1-D (found 0-D)',
str(raises.exception))
_check(np.array(1), 0)
def test_partition_exception_kth_multi_dimensional(self):
pyfunc = partition
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
def _check(a, kth):
with self.assertRaises(ValueError) as raises:
cfunc(a, kth)
self.assertIn('kth must be scalar or 1-D', str(raises.exception))
_check(np.arange(10), kth=np.arange(6).reshape(3, 2))
def test_argpartition_exception_kth_multi_dimensional(self):
pyfunc = argpartition
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
def _check(a, kth):
with self.assertRaises(ValueError) as raises:
cfunc(a, kth)
self.assertIn('kth must be scalar or 1-D', str(raises.exception))
_check(np.arange(10), kth=np.arange(6).reshape(3, 2))
def test_partition_empty_array(self):
# inspired by the test of the same name in:
# https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501
pyfunc = partition
cfunc = jit(nopython=True)(pyfunc)
def check(a, kth=0):
expected = pyfunc(a, kth)
got = cfunc(a, kth)
self.assertPreciseEqual(expected, got)
# check axis handling for multidimensional empty arrays
a = np.array([])
a.shape = (3, 2, 1, 0)
# include this with some other empty data structures
for arr in a, (), np.array([]):
check(arr)
def test_argpartition_empty_array(self):
# inspired by the test of the same name in:
# https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501
pyfunc = argpartition
cfunc = jit(nopython=True)(pyfunc)
def check(a, kth=0):
expected = pyfunc(a, kth)
got = cfunc(a, kth)
self.assertPreciseEqual(expected, got)
# check axis handling for multidimensional empty arrays
a = np.array([])
a.shape = (3, 2, 1, 0)
# include this with some other empty data structures
for arr in a, (), np.array([]):
check(arr)
def test_partition_basic(self):
# inspired by the test of the same name in:
# https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501
pyfunc = partition
cfunc = jit(nopython=True)(pyfunc)
d = np.array([])
got = cfunc(d, 0)
self.assertPreciseEqual(d, got)
d = np.ones(1)
got = cfunc(d, 0)
self.assertPreciseEqual(d, got)
# kth not modified
kth = np.array([30, 15, 5])
okth = kth.copy()
cfunc(np.arange(40), kth)
self.assertPreciseEqual(kth, okth)
for r in ([2, 1], [1, 2], [1, 1]):
d = np.array(r)
tgt = np.sort(d)
for k in 0, 1:
self.assertPreciseEqual(cfunc(d, k)[k], tgt[k])
self.partition_sanity_check(pyfunc, cfunc, d, k)
for r in ([3, 2, 1], [1, 2, 3], [2, 1, 3], [2, 3, 1],
[1, 1, 1], [1, 2, 2], [2, 2, 1], [1, 2, 1]):
d = np.array(r)
tgt = np.sort(d)
for k in 0, 1, 2:
self.assertPreciseEqual(cfunc(d, k)[k], tgt[k])
self.partition_sanity_check(pyfunc, cfunc, d, k)
d = np.ones(50)
self.assertPreciseEqual(cfunc(d, 0), d)
# sorted
d = np.arange(49)
for k in 5, 15:
self.assertEqual(cfunc(d, k)[k], k)
self.partition_sanity_check(pyfunc, cfunc, d, k)
# rsorted, with input flavours: array, list and tuple
d = np.arange(47)[::-1]
for a in d, d.tolist(), tuple(d.tolist()):
self.assertEqual(cfunc(a, 6)[6], 6)
self.assertEqual(cfunc(a, 16)[16], 16)
self.assertPreciseEqual(cfunc(a, -6), cfunc(a, 41))
self.assertPreciseEqual(cfunc(a, -16), cfunc(a, 31))
self.partition_sanity_check(pyfunc, cfunc, d, -16)
# median of 3 killer, O(n^2) on pure median 3 pivot quickselect
# exercises the median of median of 5 code used to keep O(n)
if REDUCED_TESTING:
# Use much smaller arrays to reduce memory usage
SIZE = 100
else:
SIZE = 1000000
d = np.arange(SIZE)
x = np.roll(d, d.size // 2)
mid = x.size // 2 + 1
self.assertEqual(cfunc(x, mid)[mid], mid)
d = np.arange(SIZE + 1)
x = np.roll(d, d.size // 2 + 1)
mid = x.size // 2 + 1
self.assertEqual(cfunc(x, mid)[mid], mid)
# max
d = np.ones(10)
d[1] = 4
self.assertEqual(cfunc(d, (2, -1))[-1], 4)
self.assertEqual(cfunc(d, (2, -1))[2], 1)
d[1] = np.nan
assert np.isnan(cfunc(d, (2, -1))[-1])
# equal elements
if REDUCED_TESTING:
# Use smaller array for equal elements test
d = np.arange(15) % 3
tgt = np.sort(np.arange(15) % 3)
self.rnd.shuffle(d)
for i in range(0, d.size, 3): # Sample fewer indices
self.assertEqual(cfunc(d, i)[i], tgt[i])
self.partition_sanity_check(pyfunc, cfunc, d, i)
else:
d = np.arange(47) % 7
tgt = np.sort(np.arange(47) % 7)
self.rnd.shuffle(d)
for i in range(d.size):
self.assertEqual(cfunc(d, i)[i], tgt[i])
self.partition_sanity_check(pyfunc, cfunc, d, i)
d = np.array([0, 1, 2, 3, 4, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 9])
kth = [0, 3, 19, 20]
self.assertEqual(tuple(cfunc(d, kth)[kth]), (0, 3, 7, 7))
td = [(dt, s) for dt in [np.int32, np.float32] for s in (9, 16)]
for dt, s in td:
d = np.arange(s, dtype=dt)
self.rnd.shuffle(d)
d1 = np.tile(np.arange(s, dtype=dt), (4, 1))
map(self.rnd.shuffle, d1)
for i in range(d.size):
p = cfunc(d, i)
self.assertEqual(p[i], i)
# all before are smaller
np.testing.assert_array_less(p[:i], p[i])
# all after are larger
np.testing.assert_array_less(p[i], p[i + 1:])
# sanity check
self.partition_sanity_check(pyfunc, cfunc, d, i)
def test_argpartition_basic(self):
# inspired by the test of the same name in:
# https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501
pyfunc = argpartition
cfunc = jit(nopython=True)(pyfunc)
d = np.array([], dtype=np.int64)
expected = pyfunc(d, 0)
got = cfunc(d, 0)
self.assertPreciseEqual(expected, got)
d = np.ones(1, dtype=np.int64)
expected = pyfunc(d, 0)
got = cfunc(d, 0)
self.assertPreciseEqual(expected, got)
# kth not modified
kth = np.array([30, 15, 5])
okth = kth.copy()
cfunc(np.arange(40), kth)
self.assertPreciseEqual(kth, okth)
for r in ([2, 1], [1, 2], [1, 1]):
d = np.array(r)
tgt = np.argsort(d)
for k in 0, 1:
self.assertPreciseEqual(d[cfunc(d, k)[k]], d[tgt[k]])
self.argpartition_sanity_check(pyfunc, cfunc, d, k)
for r in ([3, 2, 1], [1, 2, 3], [2, 1, 3], [2, 3, 1],
[1, 1, 1], [1, 2, 2], [2, 2, 1], [1, 2, 1]):
d = np.array(r)
tgt = np.argsort(d)
for k in 0, 1, 2:
self.assertPreciseEqual(d[cfunc(d, k)[k]], d[tgt[k]])
self.argpartition_sanity_check(pyfunc, cfunc, d, k)
d = np.ones(50)
self.assertPreciseEqual(d[cfunc(d, 0)], d)
# sorted
d = np.arange(49)
for k in 5, 15:
self.assertEqual(cfunc(d, k)[k], k)
self.partition_sanity_check(pyfunc, cfunc, d, k)
# rsorted, with input flavours: array, list and tuple
d = np.arange(47)[::-1]
for a in d, d.tolist(), tuple(d.tolist()):
self.assertEqual(cfunc(a, 6)[6], 40)
self.assertEqual(cfunc(a, 16)[16], 30)
self.assertPreciseEqual(cfunc(a, -6), cfunc(a, 41))
self.assertPreciseEqual(cfunc(a, -16), cfunc(a, 31))
self.argpartition_sanity_check(pyfunc, cfunc, d, -16)
# median of 3 killer, O(n^2) on pure median 3 pivot quickselect
# exercises the median of median of 5 code used to keep O(n)
if REDUCED_TESTING:
# Use much smaller arrays to reduce memory usage
SIZE = 1000
else:
SIZE = 1000000
d = np.arange(SIZE)
x = np.roll(d, d.size // 2)
mid = x.size // 2 + 1
self.assertEqual(x[cfunc(x, mid)[mid]], mid)
d = np.arange(SIZE + 1)
x = np.roll(d, d.size // 2 + 1)
mid = x.size // 2 + 1
self.assertEqual(x[cfunc(x, mid)[mid]], mid)
# max
d = np.ones(10)
d[1] = 4
self.assertEqual(d[cfunc(d, (2, -1))[-1]], 4)
self.assertEqual(d[cfunc(d, (2, -1))[2]], 1)
d[1] = np.nan
assert np.isnan(d[cfunc(d, (2, -1))[-1]])
# equal elements
d = np.arange(47) % 7
tgt = np.sort(np.arange(47) % 7)
self.rnd.shuffle(d)
for i in range(d.size):
self.assertEqual(d[cfunc(d, i)[i]], tgt[i])
self.argpartition_sanity_check(pyfunc, cfunc, d, i)
d = np.array([0, 1, 2, 3, 4, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 9])
kth = [0, 3, 19, 20]
self.assertEqual(tuple(d[cfunc(d, kth)[kth]]), (0, 3, 7, 7))
td = [(dt, s) for dt in [np.int32, np.float32] for s in (9, 16)]
for dt, s in td:
d = np.arange(s, dtype=dt)
self.rnd.shuffle(d)
d1 = np.tile(np.arange(s, dtype=dt), (4, 1))
map(self.rnd.shuffle, d1)
for i in range(d.size):
p = d[cfunc(d, i)]
self.assertEqual(p[i], i)
# all before are smaller
np.testing.assert_array_less(p[:i], p[i])
# all after are larger
np.testing.assert_array_less(p[i], p[i + 1:])
# sanity check
self.argpartition_sanity_check(pyfunc, cfunc, d, i)
def assert_partitioned(self, pyfunc, cfunc, d, kth):
prev = 0
for k in np.sort(kth):
np.testing.assert_array_less(d[prev:k], d[k],
err_msg='kth %d' % k)
self.assertTrue((d[k:] >= d[k]).all(),
msg=("kth %d, %r not greater equal "
"%d" % (k, d[k:], d[k])))
prev = k + 1
self.partition_sanity_check(pyfunc, cfunc, d, k)
def assert_argpartitioned(self, pyfunc, cfunc, d, kth):
prev = 0
for k in np.sort(kth):
np.testing.assert_array_less(d[prev:k], d[k],
err_msg='kth %d' % k)
self.assertTrue((d[k:] >= d[k]).all(),
msg=("kth %d, %r not greater equal "
"%d" % (k, d[k:], d[k])))
prev = k + 1
self.argpartition_sanity_check(pyfunc, cfunc, d, k)
def test_partition_iterative(self):
# inspired by the test of the same name in:
# https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py
pyfunc = partition
cfunc = jit(nopython=True)(pyfunc)
assert_partitioned = partial(self.assert_partitioned, pyfunc, cfunc)
d = np.array([3, 4, 2, 1])
p = cfunc(d, (0, 3))
assert_partitioned(p, (0, 3))
assert_partitioned(d[np.argpartition(d, (0, 3))], (0, 3))
self.assertPreciseEqual(p, cfunc(d, (-3, -1)))
d = np.arange(17)
self.rnd.shuffle(d)
self.assertPreciseEqual(np.arange(17), cfunc(d, list(range(d.size))))
# test unsorted kth
d = np.arange(17)
self.rnd.shuffle(d)
keys = np.array([1, 3, 8, -2])
self.rnd.shuffle(d)
p = cfunc(d, keys)
assert_partitioned(p, keys)
self.rnd.shuffle(keys)
self.assertPreciseEqual(cfunc(d, keys), p)
# equal kth
d = np.arange(20)[::-1]
assert_partitioned(cfunc(d, [5] * 4), [5])
assert_partitioned(cfunc(d, [5] * 4 + [6, 13]), [5] * 4 + [6, 13])
def test_argpartition_iterative(self):
# inspired by the test of the same name in:
# https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py
pyfunc = argpartition
cfunc = jit(nopython=True)(pyfunc)
assert_argpartitioned = partial(self.assert_argpartitioned,
pyfunc,
cfunc)
d = np.array([3, 4, 2, 1])
p = d[cfunc(d, (0, 3))]
assert_argpartitioned(p, (0, 3))
assert_argpartitioned(d[np.argpartition(d, (0, 3))], (0, 3))
self.assertPreciseEqual(p, d[cfunc(d, (-3, -1))])
d = np.arange(17)
self.rnd.shuffle(d)
self.assertPreciseEqual(np.arange(17), d[cfunc(d, list(range(d.size)))])
# test unsorted kth
d = np.arange(17)
self.rnd.shuffle(d)
keys = np.array([1, 3, 8, -2])
self.rnd.shuffle(d)
p = d[cfunc(d, keys)]
assert_argpartitioned(p, keys)
self.rnd.shuffle(keys)
self.assertPreciseEqual(d[cfunc(d, keys)], p)
# equal kth
d = np.arange(20)[::-1]
assert_argpartitioned(d[cfunc(d, [5] * 4)], [5])
assert_argpartitioned(d[cfunc(d, [5] * 4 + [6, 13])], [5] * 4 + [6, 13])
def test_partition_multi_dim(self):
pyfunc = partition
cfunc = jit(nopython=True)(pyfunc)
def check(a, kth):
expected = pyfunc(a, kth)
got = cfunc(a, kth)
self.assertPreciseEqual(expected[:, :, kth], got[:, :, kth])
for s in np.ndindex(expected.shape[:-1]):
self.assertPreciseEqual(np.unique(expected[s][:kth]),
np.unique(got[s][:kth]))
self.assertPreciseEqual(np.unique(expected[s][kth:]),
np.unique(got[s][kth:]))
def a_variations(a):
yield a
yield a.T
yield np.asfortranarray(a)
yield np.full_like(a, fill_value=np.nan)
yield np.full_like(a, fill_value=np.inf)
# multi-dimensional tuple input
yield (((1.0, 3.142, -np.inf, 3),),)
a = np.linspace(1, 10, 48)
a[4:7] = np.nan
a[8] = -np.inf
a[9] = np.inf
a = a.reshape((4, 3, 4))
for arr in a_variations(a):
for k in range(-3, 3):
check(arr, k)
def test_argpartition_multi_dim(self):
pyfunc = argpartition
cfunc = jit(nopython=True)(pyfunc)
def check(a, kth):
expected = pyfunc(a, kth)
got = cfunc(a, kth)
a = np.asarray(a)
idx = np.ndindex(a.shape[:-1])
for s in idx:
self.assertPreciseEqual(a[s][expected[s][kth]],
a[s][got[s][kth]])
for s in np.ndindex(expected.shape[:-1]):
self.assertPreciseEqual(np.unique(a[s][expected[s][:kth]]),
np.unique(a[s][got[s][:kth]]))
self.assertPreciseEqual(np.unique(a[s][expected[s][kth:]]),
np.unique(a[s][got[s][kth:]]))
def a_variations(a):
yield a
yield a.T
yield np.asfortranarray(a)
yield np.full_like(a, fill_value=np.nan)
yield np.full_like(a, fill_value=np.inf)
# multi-dimensional tuple input
yield (((1.0, 3.142, -np.inf, 3),),)
a = np.linspace(1, 10, 48)
a[4:7] = np.nan
a[8] = -np.inf
a[9] = np.inf
a = a.reshape((4, 3, 4))
for arr in a_variations(a):
for k in range(-3, 3):
check(arr, k)
def test_partition_boolean_inputs(self):
pyfunc = partition
cfunc = jit(nopython=True)(pyfunc)
kths = (-1, 0, 1)
if numpy_version < (2, 3):
kths = (True, False) + kths
for d in np.linspace(1, 10, 17), np.array((True, False, True)):
for kth in kths:
self.partition_sanity_check(pyfunc, cfunc, d, kth)
def test_argpartition_boolean_inputs(self):
pyfunc = argpartition
cfunc = jit(nopython=True)(pyfunc)
kths = (-1, 0, 1)
if numpy_version < (2, 3):
kths = (True, False) + kths
for d in np.linspace(1, 10, 17), np.array((True, False, True)):
for kth in kths:
self.argpartition_sanity_check(pyfunc, cfunc, d, kth)
@needs_blas
def test_cov_invalid_ddof(self):
pyfunc = cov
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
m = np.array([[0, 2], [1, 1], [2, 0]]).T
for ddof in np.arange(4), 4j:
with self.assertTypingError() as raises:
cfunc(m, ddof=ddof)
self.assertIn('ddof must be a real numerical scalar type',
str(raises.exception))
for ddof in np.nan, np.inf:
with self.assertRaises(ValueError) as raises:
cfunc(m, ddof=ddof)
self.assertIn('Cannot convert non-finite ddof to integer',
str(raises.exception))
for ddof in 1.1, -0.7:
with self.assertRaises(ValueError) as raises:
cfunc(m, ddof=ddof)
self.assertIn('ddof must be integral value', str(raises.exception))
def corr_corrcoef_basic(self, pyfunc, first_arg_name):
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc, abs_tol=1e-14)
def input_variations():
# array inputs
yield np.array([[0, 2], [1, 1], [2, 0]]).T
yield self.rnd.randn(100).reshape(5, 20)
yield np.asfortranarray(np.array([[0, 2], [1, 1], [2, 0]]).T)
yield self.rnd.randn(100).reshape(5, 20)[:, ::2]
yield np.array([0.3942, 0.5969, 0.7730, 0.9918, 0.7964])
yield np.full((4, 5), fill_value=True)
yield np.array([np.nan, 0.5969, -np.inf, 0.9918, 0.7964])
yield np.linspace(-3, 3, 33).reshape(33, 1)
# non-array inputs
yield ((0.1, 0.2), (0.11, 0.19), (0.09, 0.21)) # UniTuple
yield ((0.1, 0.2), (0.11, 0.19), (0.09j, 0.21j)) # Tuple
yield (-2.1, -1, 4.3)
yield (1, 2, 3)
yield [4, 5, 6]
yield ((0.1, 0.2, 0.3), (0.1, 0.2, 0.3))
yield [(1, 2, 3), (1, 3, 2)]
yield 3.142
yield ((1.1, 2.2, 1.5),)
# empty data structures
yield np.array([])
yield np.array([]).reshape(0, 2)
yield np.array([]).reshape(2, 0)
yield ()
# all inputs other than the first are defaulted
for input_arr in input_variations():
_check({first_arg_name: input_arr})
@needs_blas
def test_corrcoef_basic(self):
pyfunc = corrcoef
self.corr_corrcoef_basic(pyfunc, first_arg_name='x')
@needs_blas
def test_cov_basic(self):
pyfunc = cov
self.corr_corrcoef_basic(pyfunc, first_arg_name='m')
@needs_blas
def test_cov_explicit_arguments(self):
pyfunc = cov
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc, abs_tol=1e-14)
m = self.rnd.randn(105).reshape(15, 7)
y_choices = None, m[::-1]
rowvar_choices = False, True
bias_choices = False, True
ddof_choice = None, -1, 0, 1, 3.0, True
products = itertools.product(y_choices, rowvar_choices,
bias_choices, ddof_choice)
for y, rowvar, bias, ddof in products:
params = {'m': m, 'y': y, 'ddof': ddof,
'bias': bias, 'rowvar': rowvar}
_check(params)
@needs_blas
def test_corrcoef_explicit_arguments(self):
pyfunc = corrcoef
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc, abs_tol=1e-14)
x = self.rnd.randn(105).reshape(15, 7)
y_choices = None, x[::-1]
rowvar_choices = False, True
for y, rowvar in itertools.product(y_choices, rowvar_choices):
params = {'x': x, 'y': y, 'rowvar': rowvar}
_check(params)
def cov_corrcoef_edge_cases(self, pyfunc, first_arg_name):
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc, abs_tol=1e-14)
# some of these examples borrowed from numpy doc string examples:
# https://github.com/numpy/numpy/blob/v1.15.0/numpy/lib/function_base.py#L2199-L2231 # noqa: E501
# some borrowed from TestCov and TestCorrCoef:
# https://github.com/numpy/numpy/blob/80d3a7a/numpy/lib/tests/test_function_base.py # noqa: E501
m = np.array([-2.1, -1, 4.3])
y = np.array([3, 1.1, 0.12])
params = {first_arg_name: m, 'y': y}
_check(params)
m = np.array([1, 2, 3]) # test case modified such that m is 1D
y = np.array([[1j, 2j, 3j]])
params = {first_arg_name: m, 'y': y}
_check(params)
m = np.array([1, 2, 3])
y = (1j, 2j, 3j)
params = {first_arg_name: m, 'y': y}
_check(params)
params = {first_arg_name: y, 'y': m} # flip real and complex inputs
_check(params)
m = np.array([1, 2, 3])
y = (1j, 2j, 3) # note last item is not complex
params = {first_arg_name: m, 'y': y}
_check(params)
params = {first_arg_name: y, 'y': m} # flip real and complex inputs
_check(params)
m = np.array([])
y = np.array([])
params = {first_arg_name: m, 'y': y}
_check(params)
m = 1.1
y = 2.2
params = {first_arg_name: m, 'y': y}
_check(params)
m = self.rnd.randn(10, 3)
y = np.array([-2.1, -1, 4.3]).reshape(1, 3) / 10
params = {first_arg_name: m, 'y': y}
_check(params)
m = np.array([-2.1, -1, 4.3])
y = np.array([[3, 1.1, 0.12], [3, 1.1, 0.12]])
params = {first_arg_name: m, 'y': y}
_check(params)
for rowvar in False, True:
m = np.array([-2.1, -1, 4.3])
y = np.array([[3, 1.1, 0.12], [3, 1.1, 0.12], [4, 1.1, 0.12]])
params = {first_arg_name: m, 'y': y, 'rowvar': rowvar}
_check(params)
# swap m and y
params = {first_arg_name: y, 'y': m, 'rowvar': rowvar}
_check(params)
@needs_blas
def test_corrcoef_edge_cases(self):
pyfunc = corrcoef
self.cov_corrcoef_edge_cases(pyfunc, first_arg_name='x')
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc, abs_tol=1e-14)
for x in (np.nan, -np.inf, 3.142, 0):
params = {'x': x}
_check(params)
@needs_blas
def test_corrcoef_edge_case_extreme_values(self):
pyfunc = corrcoef
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc, abs_tol=1e-14)
# extreme values
x = ((1e-100, 1e100), (1e100, 1e-100))
params = {'x': x}
_check(params)
@needs_blas
def test_cov_edge_cases(self):
pyfunc = cov
self.cov_corrcoef_edge_cases(pyfunc, first_arg_name='m')
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc, abs_tol=1e-14)
# invalid ddof
m = np.array([[0, 2], [1, 1], [2, 0]]).T
params = {'m': m, 'ddof': 5}
_check(params)
@needs_blas
def test_cov_exceptions(self):
pyfunc = cov
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
def _check_m(m):
with self.assertTypingError() as raises:
cfunc(m)
self.assertIn('m has more than 2 dimensions', str(raises.exception))
m = np.ones((5, 6, 7))
_check_m(m)
m = ((((1, 2, 3), (2, 2, 2)),),)
_check_m(m)
m = [[[5, 6, 7]]]
_check_m(m)
def _check_y(m, y):
with self.assertTypingError() as raises:
cfunc(m, y=y)
self.assertIn('y has more than 2 dimensions', str(raises.exception))
m = np.ones((5, 6))
y = np.ones((5, 6, 7))
_check_y(m, y)
m = np.array((1.1, 2.2, 1.1))
y = (((1.2, 2.2, 2.3),),)
_check_y(m, y)
m = np.arange(3)
y = np.arange(4)
with self.assertRaises(ValueError) as raises:
cfunc(m, y=y)
self.assertIn('m and y have incompatible dimensions',
str(raises.exception))
# Numpy raises ValueError: all the input array dimensions except for the
# concatenation axis must match exactly.
m = np.array([-2.1, -1, 4.3]).reshape(1, 3)
with self.assertRaises(RuntimeError) as raises:
cfunc(m)
self.assertIn('2D array containing a single row is unsupported',
str(raises.exception))
def test_ediff1d_basic(self):
pyfunc = ediff1d
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc)
def to_variations(a):
yield None
yield a
# Skip additional type variations in reduced mode
if not REDUCED_TESTING:
yield a.astype(np.int16)
def ary_variations(a):
yield a
# Skip reshape and type variations in reduced mode
if not REDUCED_TESTING:
yield a.reshape(3, 2, 2)
yield a.astype(np.int32)
array_size = 6 if REDUCED_TESTING else 12
for ary in ary_variations(np.linspace(-2, 7, array_size)):
params = {'ary': ary}
_check(params)
for a in to_variations(ary):
params = {'ary': ary, 'to_begin': a}
_check(params)
params = {'ary': ary, 'to_end': a}
_check(params)
for b in to_variations(ary):
params = {'ary': ary, 'to_begin': a, 'to_end': b}
_check(params)
def test_ediff1d_exceptions(self):
pyfunc = ediff1d
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
with self.assertTypingError() as e:
cfunc(np.array((True, True, False)))
msg = "Boolean dtype is unsupported (as per NumPy)"
assert msg in str(e.exception)
def test_fliplr_basic(self):
pyfunc = fliplr
cfunc = jit(nopython=True)(pyfunc)
def a_variations():
yield np.arange(10).reshape(5, 2)
yield np.arange(20).reshape(5, 2, 2)
yield ((1, 2),)
yield ([1, 2], [3, 4],)
for a in a_variations():
expected = pyfunc(a)
got = cfunc(a)
self.assertPreciseEqual(expected, got)
with self.assertRaises(TypingError) as raises:
cfunc("abc")
self.assertIn("Cannot np.fliplr on %s type" % types.unicode_type,
str(raises.exception))
def test_fliplr_exception(self):
pyfunc = fliplr
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
with self.assertRaises(TypingError) as raises:
cfunc(np.arange(3))
self.assertIn("cannot index array", str(raises.exception))
self.assertIn("with 2 indices", str(raises.exception))
def test_flipud_basic(self):
pyfunc = flipud
cfunc = jit(nopython=True)(pyfunc)
def a_variations():
yield [1]
yield np.arange(10)
yield np.arange(10).reshape(5, 2)
yield np.arange(20).reshape(5, 2, 2)
yield ((1, 2),)
yield ([1, 2], [3, 4],)
for a in a_variations():
expected = pyfunc(a)
got = cfunc(a)
self.assertPreciseEqual(expected, got)
with self.assertRaises(TypingError) as raises:
cfunc("abc")
self.assertIn("Cannot np.flipud on %s type" % types.unicode_type,
str(raises.exception))
def test_flipud_exception(self):
pyfunc = flipud
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
with self.assertRaises(TypingError) as raises:
cfunc(1)
self.assertIn("cannot index array", str(raises.exception))
self.assertIn("with 1 indices", str(raises.exception))
def test_flip_basic(self):
pyfunc = flip
cfunc = jit(nopython=True)(pyfunc)
def a_variations():
yield np.array(1)
yield np.arange(10)
yield np.arange(10).reshape(5, 2)
yield np.arange(20).reshape(5, 2, 2)
for a in a_variations():
expected = pyfunc(a)
got = cfunc(a)
self.assertPreciseEqual(expected, got)
with self.assertRaises(TypingError) as raises:
cfunc((1, 2, 3))
self.assertIn("Cannot np.flip on UniTuple", str(raises.exception))
def test_logspace2_basic(self):
def inputs():
#start, stop
yield 1, 60
yield -1, 60
yield -60, -1
yield -1, -60
yield 60, -1
yield 1.0, 60.0
yield -60.0, -1.0
yield -1.0, 60.0
yield 0.0, np.e
yield 0.0, np.pi
if numpy_version < (2, 0):
yield np.complex64(1), np.complex64(2)
yield np.complex64(2j), np.complex64(4j)
yield np.complex64(2), np.complex64(4j)
yield np.complex64(1 + 2j), np.complex64(3 + 4j)
yield np.complex64(1 - 2j), np.complex64(3 - 4j)
yield np.complex64(-1 + 2j), np.complex64(3 + 4j)
pyfunc = logspace2
cfunc = jit(nopython=True)(pyfunc)
for start, stop in inputs():
np.testing.assert_allclose(pyfunc(start, stop), cfunc(start, stop))
def test_logspace2_exception(self):
cfunc = jit(nopython=True)(logspace2)
self.disable_leak_check()
with self.assertRaises(TypingError) as raises:
cfunc("abc", 5)
self.assertIn('The first argument "start" must be a number',
str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc(5, "abc")
self.assertIn('The second argument "stop" must be a number',
str(raises.exception))
def test_logspace3_basic(self):
def inputs():
#start, stop
yield 1, 60
yield -1, 60
yield -60, -1
yield -1, -60
yield 60, -1
yield 1.0, 60.0
yield -60.0, -1.0
yield -1.0, 60.0
yield 0.0, np.e
yield 0.0, np.pi
if numpy_version < (2, 0):
yield np.complex64(1), np.complex64(2)
yield np.complex64(2j), np.complex64(4j)
yield np.complex64(2), np.complex64(4j)
yield np.complex64(1 + 2j), np.complex64(3 + 4j)
yield np.complex64(1 - 2j), np.complex64(3 - 4j)
yield np.complex64(-1 + 2j), np.complex64(3 + 4j)
pyfunc = logspace3
cfunc = jit(nopython=True)(pyfunc)
for start, stop in inputs():
np.testing.assert_allclose(pyfunc(start, stop), cfunc(start, stop))
def test_logspace3_with_num_basic(self):
def inputs():
#start, stop, num
yield 1, 60, 20
yield -1, 60, 30
yield -60, -1, 40
yield -1, -60, 50
yield 60, -1, 60
yield 1.0, 60.0, 70
yield -60.0, -1.0, 80
yield -1.0, 60.0, 90
yield 0.0, np.e, 20
yield 0.0, np.pi, 30
if numpy_version < (2, 0):
yield np.complex64(1), np.complex64(2), 40
yield np.complex64(2j), np.complex64(4j), 50
yield np.complex64(2), np.complex64(4j), 60
yield np.complex64(1 + 2j), np.complex64(3 + 4j), 70
yield np.complex64(1 - 2j), np.complex64(3 - 4j), 80
yield np.complex64(-1 + 2j), np.complex64(3 + 4j), 90
pyfunc = logspace3
cfunc = jit(nopython=True)(pyfunc)
for start, stop, num in inputs():
np.testing.assert_allclose(pyfunc(start, stop, num),
cfunc(start, stop, num))
def test_logspace3_exception(self):
cfunc = jit(nopython=True)(logspace3)
self.disable_leak_check()
with self.assertRaises(TypingError) as raises:
cfunc("abc", 5)
self.assertIn('The first argument "start" must be a number',
str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc(5, "abc")
self.assertIn('The second argument "stop" must be a number',
str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc(0, 5, "abc")
self.assertIn('The third argument "num" must be an integer',
str(raises.exception))
def test_geomspace2_basic(self):
def inputs():
#start, stop
yield -1, -60
yield 1.0, 60.0
yield -60.0, -1.0
yield 1, 1000
yield 1000, 1
yield 1, 256
yield -1000, -1
yield -1, np.complex64(2j)
yield np.complex64(2j), -1
yield -1.0, np.complex64(2j)
yield np.complex64(1j), np.complex64(1000j)
yield np.complex64(-1 + 0j), np.complex64(1 + 0j)
yield np.complex64(1), np.complex64(2)
yield np.complex64(2j), np.complex64(4j)
yield np.complex64(2), np.complex64(4j)
yield np.complex64(1 + 2j), np.complex64(3 + 4j)
yield np.complex64(1 - 2j), np.complex64(3 - 4j)
yield np.complex64(-1 + 2j), np.complex64(3 + 4j)
pyfunc = geomspace2
cfunc = jit(nopython=True)(pyfunc)
for start, stop in inputs():
self.assertPreciseEqual(pyfunc(start, stop),
cfunc(start, stop),
abs_tol=1e-12)
def test_geomspace2_exception(self):
cfunc = jit(nopython=True)(geomspace2)
self.disable_leak_check()
with self.assertRaises(TypingError) as raises:
cfunc("abc", 5)
self.assertIn('The argument "start" must be a number',
str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc(5, "abc")
self.assertIn('The argument "stop" must be a number',
str(raises.exception))
with self.assertRaises(ValueError) as raises:
cfunc(0, 5)
self.assertIn('Geometric sequence cannot include zero',
str(raises.exception))
with self.assertRaises(ValueError) as raises:
cfunc(5, 0)
self.assertIn('Geometric sequence cannot include zero',
str(raises.exception))
def test_geomspace3_basic(self):
def inputs():
#start, stop, num
yield -1, -60, 50
yield 1.0, 60.0, 70
yield -60.0, -1.0, 80
yield 1, 1000, 4
yield 1, 1000, 3
yield 1000, 1, 4
yield 1, 256, 9
yield -1000, -1, 4
yield -1, np.complex64(2j), 10
yield np.complex64(2j), -1, 20
yield -1.0, np.complex64(2j), 30
yield np.complex64(1j), np.complex64(1000j), 4
yield np.complex64(-1 + 0j), np.complex64(1 + 0j), 5
yield np.complex64(1), np.complex64(2), 40
yield np.complex64(2j), np.complex64(4j), 50
yield np.complex64(2), np.complex64(4j), 60
yield np.complex64(1 + 2j), np.complex64(3 + 4j), 70
yield np.complex64(1 - 2j), np.complex64(3 - 4j), 80
yield np.complex64(-1 + 2j), np.complex64(3 + 4j), 90
pyfunc = geomspace3
cfunc = jit(nopython=True)(pyfunc)
for start, stop, num in inputs():
self.assertPreciseEqual(pyfunc(start, stop, num),
cfunc(start, stop, num),
abs_tol=1e-14)
def test_geomspace3_exception(self):
cfunc = jit(nopython=True)(geomspace3)
self.disable_leak_check()
with self.assertRaises(TypingError) as raises:
cfunc("abc", 5, 10)
self.assertIn('The argument "start" must be a number',
str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc(5, "abc", 10)
self.assertIn('The argument "stop" must be a number',
str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc(5, 10, "abc")
self.assertIn('The argument "num" must be an integer',
str(raises.exception))
with self.assertRaises(ValueError) as raises:
cfunc(0, 5, 5)
self.assertIn('Geometric sequence cannot include zero',
str(raises.exception))
with self.assertRaises(ValueError) as raises:
cfunc(5, 0, 5)
self.assertIn('Geometric sequence cannot include zero',
str(raises.exception))
def test_geomspace_numpy(self):
cfunc2 = jit(nopython=True)(geomspace2)
cfunc3 = jit(nopython=True)(geomspace3)
pfunc3 = geomspace3
# https://github.com/numpy/numpy/blob/ab2178b47c0ee834180c318db196976623710691/numpy/core/tests/test_function_base.py#L122C3-L142
# test_basic
y = cfunc2(1, 1e6)
self.assertEqual(len(y), 50)
y = cfunc3(1, 1e6, num=100)
self.assertEqual(y[-1], 10 ** 6)
y = cfunc3(1, 1e6, num=7)
self.assertPreciseEqual(y, pfunc3(1,1e6, num=7))
y = cfunc3(8, 2, num=3)
self.assertPreciseEqual(y, pfunc3(8, 2, num=3))
self.assertTrue([x == 0 for x in y.imag])
y = cfunc3(-1, -100, num=3)
self.assertPreciseEqual(y, pfunc3(-1, -100, num=3))
self.assertTrue([x == 0 for x in y.imag])
y = cfunc3(-100, -1, num=3)
self.assertPreciseEqual(y, pfunc3(-100, -1, num=3))
self.assertTrue([x == 0 for x in y.imag])
# test_boundaries_match_start_and_stop_exactly
start = 0.3
stop = 20.3
y = cfunc3(start, stop, num=1)
self.assertPreciseEqual(y[0], start)
y = cfunc3(start, stop, num=3)
self.assertPreciseEqual(y[0], start)
self.assertPreciseEqual(y[-1], stop)
# test_nan_interior
with np.errstate(invalid='ignore'):
y = cfunc3(-3, 3, num=4)
self.assertPreciseEqual(y[0], -3.0)
self.assertTrue(np.isnan(y[1:-1]).all())
self.assertPreciseEqual(y[3], 3.0)
# test_complex
# Purely imaginary
y = cfunc3(1j, 16j, num=5)
self.assertPreciseEqual(y, pfunc3(1j, 16j, num=5), abs_tol=1e-14)
self.assertTrue([x == 0 for x in y.real])
y = cfunc3(-4j, -324j, num=5)
self.assertPreciseEqual(y, pfunc3(-4j, -324j, num=5), abs_tol=1e-13)
self.assertTrue([x == 0 for x in y.real])
y = cfunc3(1 + 1j, 1000 + 1000j, num=4)
self.assertPreciseEqual(y,
pfunc3(1 + 1j, 1000 + 1000j, num=4),
abs_tol=1e-13)
y = cfunc3(-1 + 1j, -1000 + 1000j, num=4)
self.assertPreciseEqual(y,
pfunc3(-1 + 1j, -1000 + 1000j, num=4),
abs_tol=1e-13)
# Logarithmic spirals
if numpy_version < (2, 0):
y = cfunc3(-1 + 0j, 1 + 0j, num=3)
self.assertPreciseEqual(y, pfunc3(-1 + 0j, 1 + 0j, num=3))
y = cfunc3(0 + 3j, -3 + 0j, 3)
self.assertPreciseEqual(y, pfunc3(0 + 3j, -3 + 0j, 3), abs_tol=1e-15)
y = cfunc3(0 + 3j, 3 + 0j, 3)
self.assertPreciseEqual(y, pfunc3(0 + 3j, 3 + 0j, 3), abs_tol=1e-15)
y = cfunc3(-3 + 0j, 0 - 3j, 3)
self.assertPreciseEqual(y, pfunc3(-3 + 0j, 0 - 3j, 3), abs_tol=1e-15)
y = cfunc3(0 + 3j, -3 + 0j, 3)
self.assertPreciseEqual(y, pfunc3(0 + 3j, -3 + 0j, 3), abs_tol=1e-15)
y = cfunc3(-2 - 3j, 5 + 7j, 7)
self.assertPreciseEqual(y, pfunc3(-2 - 3j, 5 + 7j, 7), abs_tol=1e-14)
y = cfunc3(3j, -5, 2)
self.assertPreciseEqual(y, pfunc3(3j, -5, 2))
y = cfunc3(-5, 3j, 2)
self.assertPreciseEqual(y, pfunc3(-5, 3j, 2))
def test_rot90_basic(self):
pyfunc = rot90
cfunc = jit(nopython=True)(pyfunc)
def a_variations():
yield np.arange(10).reshape(5, 2)
yield np.arange(20).reshape(5, 2, 2)
yield np.arange(64).reshape(2, 2, 2, 2, 2, 2)
for a in a_variations():
expected = pyfunc(a)
got = cfunc(a)
self.assertPreciseEqual(expected, got)
def test_rot90_with_k_basic(self):
pyfunc = rot90_k
cfunc = jit(nopython=True)(pyfunc)
def a_variations():
yield np.arange(10).reshape(5, 2)
yield np.arange(20).reshape(5, 2, 2)
yield np.arange(64).reshape(2, 2, 2, 2, 2, 2)
for a in a_variations():
for k in range(-5, 6):
expected = pyfunc(a, k)
got = cfunc(a, k)
self.assertPreciseEqual(expected, got)
def test_rot90_exception(self):
pyfunc = rot90_k
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
with self.assertRaises(TypingError) as raises:
cfunc("abc")
self.assertIn('The first argument "m" must be an array',
str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc(np.arange(4).reshape(2, 2), k="abc")
self.assertIn('The second argument "k" must be an integer',
str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc(np.arange(3))
self.assertIn("Input must be >= 2-d.", str(raises.exception))
def _check_split(self, func):
# Since np.split and np.array_split are very similar
pyfunc = func
cfunc = jit(nopython=True)(pyfunc)
def args_variations():
a = np.arange(100)
yield a, 2
yield a, 2, 0
yield a, [1, 4, 72]
yield list(a), [1, 4, 72]
yield tuple(a), [1, 4, 72]
yield a, [1, 4, 72], 0
yield list(a), [1, 4, 72], 0
yield tuple(a), [1, 4, 72], 0
a = np.arange(64).reshape(4, 4, 4)
yield a, 2
yield a, 2, 0
yield a, 2, 1
yield a, [2, 1, 5]
yield a, [2, 1, 5], 1
yield a, [2, 1, 5], 2
yield a, [1, 3]
yield a, [1, 3], 1
yield a, [1, 3], 2
yield a, [1], -1
yield a, [1], -2
yield a, [1], -3
yield a, np.array([], dtype=np.int64), 0
a = np.arange(100).reshape(2, -1)
yield a, 1
yield a, 1, 0
yield a, [1], 0
yield a, 50, 1
yield a, np.arange(10, 50, 10), 1
yield a, (1,)
yield a, (np.int32(4), 10)
a = np.array([])
yield a, 1
yield a, 2
yield a, (2, 3), 0
yield a, 1, 0
a = np.array([[]])
yield a, 1
yield a, (2, 3), 1
yield a, 1, 0
yield a, 1, 1
for args in args_variations():
expected = pyfunc(*args)
got = cfunc(*args)
np.testing.assert_equal(expected, list(got))
def _check_array_split(self, func):
# array_split specific checks, mainly dealing with `int`s
pyfunc = func
cfunc = jit(nopython=True)(pyfunc)
def args_variations():
yield np.arange(8), 3
yield list(np.arange(8)), 3
yield tuple(np.arange(8)), 3
yield np.arange(24).reshape(12, 2), 5
for args in args_variations():
expected = pyfunc(*args)
got = cfunc(*args)
np.testing.assert_equal(expected, list(got))
def test_array_split_basic(self):
self._check_split(array_split)
self._check_array_split(array_split)
def test_split_basic(self):
self._check_split(split)
self.disable_leak_check() # The exception leaks
with self.assertRaises(ValueError) as raises:
njit(split)(np.ones(5), 2)
self.assertIn(
"array split does not result in an equal division",
str(raises.exception)
)
with self.assertRaises(ValueError) as raises:
njit(split)(np.ones(5), [3], axis=-3)
self.assertIn("np.split: Argument axis out of bounds",
str(raises.exception))
def test_vhdsplit_basic(self):
# split and array_split have more comprehensive tests of splitting.
# only do simple tests on vsplit, hsplit and dsplit
# Based on tests from https://github.com/numpy/numpy/blob/f0befec40376fc46fdaceac2c49c7349ad671bde/numpy/lib/tests/test_shape_base.py#L538-L624 # noqa: E501
def inputs1D():
# test_1D_array
yield np.array([1, 2, 3, 4]), 2
yield np.array([1., 2., 3., 4.]), 2
def inputs2D():
# test_2D_array
yield np.array([[1, 2, 3, 4], [1, 2, 3, 4]]), 2
yield np.array([[1., 2., 3., 4.], [1., 2., 3., 4.]]), 2
yield np.arange(16.0).reshape(4, 4), 2
yield np.arange(16.0).reshape(4, 4), np.array([3, 6])
yield np.arange(16.0).reshape(4, 4), [3, 6]
yield np.arange(16.0).reshape(4, 4), (3, 6)
yield np.arange(8.0).reshape(2, 2, 2), 2
def inputs3D():
# test_3D_array
np.array([[[1, 2, 3, 4],
[1, 2, 3, 4]],
[[1, 2, 3, 4],
[1, 2, 3, 4]]]), 2
yield np.arange(16.0).reshape(2, 2, 4), 2
yield np.arange(16.0).reshape(2, 2, 4), np.array([3, 6])
yield np.arange(16.0).reshape(2, 2, 4), [3, 6]
yield np.arange(16.0).reshape(2, 2, 4), (3, 6)
yield np.arange(8.0).reshape(2, 2, 2), 2
inputs = [inputs1D(), inputs2D(), inputs3D()]
for (f, mindim, name) in [(vsplit, 2, "vsplit"),
(hsplit, 1, "hsplit"),
(dsplit, 3, "dsplit")]:
pyfunc = f
cfunc = njit(pyfunc)
for i in range(mindim, 4):
for a, ind_or_sec in inputs[i - 1]:
self.assertPreciseEqual(pyfunc(a, ind_or_sec),
cfunc(a, ind_or_sec))
def test_vhdsplit_exception(self):
# Single test method for vsplit, hsplit and dsplit exceptions
for (f, mindim, name) in [(vsplit, 2, "vsplit"),
(hsplit, 1, "hsplit"),
(dsplit, 3, "dsplit")]:
cfunc = jit(nopython=True)(f)
self.disable_leak_check()
with self.assertRaises(TypingError) as raises:
cfunc(1, 2)
self.assertIn('The argument "ary" must be an array',
str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc("abc", 2)
self.assertIn('The argument "ary" must be an array',
str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc(np.array([[1, 2, 3, 4], [1, 2, 3, 4]]), "abc")
self.assertIn(('The argument "indices_or_sections" must be int or '
'1d-array'),
str(raises.exception))
with self.assertRaises(ValueError) as raises:
cfunc(np.array(1), 2)
self.assertIn(name + ' only works on arrays of ' + str(mindim) +
' or more dimensions',
str(raises.exception))
def test_roll_basic(self):
pyfunc = roll
cfunc = jit(nopython=True)(pyfunc)
def a_variations():
yield np.arange(7)
yield np.arange(3 * 4 * 5).reshape(3, 4, 5)
yield [1.1, 2.2, 3.3]
yield (True, False, True)
yield False
yield 4
yield (9,)
yield np.asfortranarray(np.array([[1.1, np.nan], [np.inf, 7.8]]))
yield np.array([])
yield ()
def shift_variations():
return itertools.chain.from_iterable(((True, False),
range(-10, 10)))
for a in a_variations():
for shift in shift_variations():
expected = pyfunc(a, shift)
got = cfunc(a, shift)
self.assertPreciseEqual(expected, got)
def test_roll_exceptions(self):
pyfunc = roll
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
for shift in 1.1, (1, 2):
with self.assertTypingError() as e:
cfunc(np.arange(10), shift)
msg = "shift must be an integer"
assert msg in str(e.exception)
def test_extract_basic(self):
pyfunc = extract
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc)
a = np.arange(10)
self.rnd.shuffle(a)
threshold_range = range(-1, 5) if REDUCED_TESTING else range(-3, 13)
for threshold in threshold_range:
cond = a > threshold
_check({'condition': cond, 'arr': a})
if REDUCED_TESTING:
a = np.arange(12).reshape(3, 4)
else:
a = np.arange(60).reshape(4, 5, 3)
cond = a > 5.2
_check({'condition': cond, 'arr': a})
a = ((1, 2, 3), (3, 4, 5), (4, 5, 6))
cond = np.eye(3).flatten()
_check({'condition': cond, 'arr': a})
a = [1.1, 2.2, 3.3, 4.4]
cond = [1, 1, 0, 1]
_check({'condition': cond, 'arr': a})
a = np.linspace(-2, 10, 6)
element_pool = (True, False, np.nan, -1, -1.0, -1.2, 1, 1.0, 1.5j)
if REDUCED_TESTING:
# Reduce combinations to limit memory usage
for cond in itertools.islice(
itertools.combinations_with_replacement(element_pool, 3),
10):
_check({'condition': cond, 'arr': a[:3]})
_check({'condition': np.array(cond), 'arr': a[:3]})
else:
for cond in itertools.combinations_with_replacement(
element_pool, 4):
_check({'condition': cond, 'arr': a})
_check({'condition': np.array(cond).reshape(2, 2), 'arr': a})
a = np.array([1, 2, 3])
cond = np.array([])
_check({'condition': cond, 'arr': a})
a = np.array([1, 2, 3])
cond = np.array([1, 0, 1, 0]) # but [1, 0, 1, 0, 1] raises
_check({'condition': cond, 'arr': a})
a = np.array([[1, 2, 3], [4, 5, 6]])
cond = [1, 0, 1, 0, 1, 0] # but [1, 0, 1, 0, 1, 0, 1] raises
_check({'condition': cond, 'arr': a})
a = np.array([[1, 2, 3], [4, 5, 6]])
cond = np.array([1, 0, 1, 0, 1, 0, 0, 0]).reshape(2, 2, 2)
_check({'condition': cond, 'arr': a})
a = np.asfortranarray(np.arange(60).reshape(3, 4, 5))
cond = np.repeat((0, 1), 30)
_check({'condition': cond, 'arr': a})
_check({'condition': cond, 'arr': a[::-1]})
a = np.array(4)
for cond in 0, 1:
_check({'condition': cond, 'arr': a})
a = 1
cond = 1
_check({'condition': cond, 'arr': a})
a = np.array(1)
cond = np.array([True, False])
_check({'condition': cond, 'arr': a})
a = np.arange(4)
cond = np.array([1, 0, 1, 0, 0, 0]).reshape(2, 3) * 1j
_check({'condition': cond, 'arr': a})
def test_extract_exceptions(self):
pyfunc = extract
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
a = np.array([])
cond = np.array([1, 2, 3])
with self.assertRaises(ValueError) as e:
cfunc(cond, a)
self.assertIn('Cannot extract from an empty array', str(e.exception))
def _check(cond, a):
msg = 'condition shape inconsistent with arr shape'
with self.assertRaises(ValueError) as e:
cfunc(cond, a)
self.assertIn(msg, str(e.exception))
a = np.array([[1, 2, 3], [1, 2, 3]])
cond = [1, 0, 1, 0, 1, 0, 1]
_check(cond, a)
a = np.array([1, 2, 3])
cond = np.array([1, 0, 1, 0, 1])
_check(cond, a)
a = np.array(60) # note, this is 0D
cond = 0, 1
_check(cond, a)
a = np.arange(4)
cond = np.array([True, False, False, False, True])
_check(cond, a)
a = np.arange(4)
cond = np.array([True, False, True, False, False, True, False])
_check(cond, a)
@unittest.skipUnless(IS_NUMPY_2, "New in numpy 2.0+")
def test_np_trapezoid_basic(self):
self.test_np_trapz_basic(pyfunc=np_trapezoid)
def test_np_trapz_basic(self, pyfunc=np_trapz):
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc)
y = [1, 2, 3]
_check({'y': y})
y = (3, 1, 2, 2, 2)
_check({'y': y})
y = np.arange(15).reshape(3, 5)
_check({'y': y})
y = np.linspace(-10, 10, 60).reshape(4, 3, 5)
_check({'y': y}, abs_tol=1e-13)
self.rnd.shuffle(y)
_check({'y': y}, abs_tol=1e-13)
y = np.array([])
_check({'y': y})
y = np.array([3.142, np.nan, np.inf, -np.inf, 5])
_check({'y': y})
y = np.arange(20) + np.linspace(0, 10, 20) * 1j
_check({'y': y})
y = np.array([], dtype=np.complex128)
_check({'y': y})
y = (True, False, True)
_check({'y': y})
@unittest.skipUnless(IS_NUMPY_2, "New in numpy 2.0+")
def test_np_trapezoid_x_basic(self):
self.test_np_trapz_x_basic(pyfunc=np_trapezoid_x)
def test_np_trapz_x_basic(self, pyfunc=np_trapz_x):
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc)
y = [1, 2, 3]
x = [4, 6, 8]
_check({'y': y, 'x': x})
y = [1, 2, 3, 4, 5]
x = (4, 6)
_check({'y': y, 'x': x})
y = (1, 2, 3, 4, 5)
x = [4, 5, 6, 7, 8]
_check({'y': y, 'x': x})
y = np.array([1, 2, 3, 4, 5])
x = [4, 4]
_check({'y': y, 'x': x})
y = np.array([])
x = np.array([2, 3])
_check({'y': y, 'x': x})
y = (1, 2, 3, 4, 5)
x = None
_check({'y': y, 'x': x})
y = np.arange(20).reshape(5, 4)
x = np.array([4, 5])
_check({'y': y, 'x': x})
y = np.arange(20).reshape(5, 4)
x = np.array([4, 5, 6, 7])
_check({'y': y, 'x': x})
y = np.arange(60).reshape(5, 4, 3)
x = np.array([4, 5])
_check({'y': y, 'x': x})
y = np.arange(60).reshape(5, 4, 3)
x = np.array([4, 5, 7])
_check({'y': y, 'x': x})
y = np.arange(60).reshape(5, 4, 3)
self.rnd.shuffle(y)
x = y + 1.1
self.rnd.shuffle(x)
_check({'y': y, 'x': x})
y = np.arange(20)
x = y + np.linspace(0, 10, 20) * 1j
_check({'y': y, 'x': x})
y = np.array([1, 2, 3])
x = np.array([1 + 1j, 1 + 2j])
_check({'y': y, 'x': x})
@unittest.skipUnless(IS_NUMPY_2, "New in numpy 2.0+")
def test_trapezoid_numpy_questionable(self):
self.test_trapz_numpy_questionable(pyfunc=np_trapezoid)
@unittest.skip('NumPy behaviour questionable')
def test_trapz_numpy_questionable(self, pyfunc=np_trapz):
# https://github.com/numpy/numpy/issues/12858
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc)
# passes (NumPy and Numba return 2.0)
y = np.array([True, False, True, True]).astype(int)
_check({'y': y})
# fails (NumPy returns 1.5; Numba returns 2.0)
y = np.array([True, False, True, True])
_check({'y': y})
@unittest.skipUnless(IS_NUMPY_2, "New in numpy 2.0+")
def test_np_trapezoid_dx_basic(self):
self.test_np_trapz_dx_basic(pyfunc=np_trapezoid_dx)
def test_np_trapz_dx_basic(self, pyfunc=np_trapz_dx):
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc)
y = [1, 2, 3]
dx = 2
_check({'y': y, 'dx': dx})
y = [1, 2, 3, 4, 5]
dx = [1, 4, 5, 6]
_check({'y': y, 'dx': dx})
y = [1, 2, 3, 4, 5]
dx = [1, 4, 5, 6]
_check({'y': y, 'dx': dx})
y = np.linspace(-2, 5, 10)
dx = np.nan
_check({'y': y, 'dx': dx})
y = np.linspace(-2, 5, 10)
dx = np.inf
_check({'y': y, 'dx': dx})
y = np.linspace(-2, 5, 10)
dx = np.linspace(-2, 5, 9)
_check({'y': y, 'dx': dx}, abs_tol=1e-13)
y = np.arange(60).reshape(4, 5, 3) * 1j
dx = np.arange(40).reshape(4, 5, 2)
_check({'y': y, 'dx': dx})
x = np.arange(-10, 10, .1)
r = cfunc(np.exp(-.5 * x ** 2) / np.sqrt(2 * np.pi), dx=0.1)
# check integral of normal equals 1
np.testing.assert_almost_equal(r, 1, 7)
y = np.arange(20)
dx = 1j
_check({'y': y, 'dx': dx})
y = np.arange(20)
dx = np.array([5])
_check({'y': y, 'dx': dx})
@unittest.skipUnless(IS_NUMPY_2, "New in numpy 2.0+")
def test_np_trapezoid_x_dx_basic(self):
self.test_np_trapz_x_dx_basic(pyfunc=np_trapezoid_x_dx)
def test_np_trapz_x_dx_basic(self, pyfunc=np_trapz_x_dx):
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc)
# dx should be ignored
for dx in (None, 2, np.array([1, 2, 3, 4, 5])):
y = [1, 2, 3]
x = [4, 6, 8]
_check({'y': y, 'x': x, 'dx': dx})
y = [1, 2, 3, 4, 5]
x = [4, 6]
_check({'y': y, 'x': x, 'dx': dx})
y = [1, 2, 3, 4, 5]
x = [4, 5, 6, 7, 8]
_check({'y': y, 'x': x, 'dx': dx})
y = np.arange(60).reshape(4, 5, 3)
self.rnd.shuffle(y)
x = y * 1.1
x[2, 2, 2] = np.nan
_check({'y': y, 'x': x, 'dx': dx})
@unittest.skipUnless(IS_NUMPY_2, "New in numpy 2.0+")
def test_np_trapezoid_x_dx_exceptions(self):
self.test_np_trapz_x_dx_exceptions(pyfunc=np_trapezoid_x_dx)
def test_np_trapz_x_dx_exceptions(self, pyfunc=np_trapz_x_dx):
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
def check_not_ok(params):
with self.assertRaises(ValueError) as e:
cfunc(*params)
self.assertIn('unable to broadcast', str(e.exception))
y = [1, 2, 3, 4, 5]
for x in [4, 5, 6, 7, 8, 9], [4, 5, 6]:
check_not_ok((y, x, 1.0))
y = np.arange(60).reshape(3, 4, 5)
x = np.arange(36).reshape(3, 4, 3)
check_not_ok((y, x, 1.0))
y = np.arange(60).reshape(3, 4, 5)
x = np.array([4, 5, 6, 7])
check_not_ok((y, x, 1.0))
y = [1, 2, 3, 4, 5]
dx = np.array([1.0, 2.0])
check_not_ok((y, None, dx))
y = np.arange(60).reshape(3, 4, 5)
dx = np.arange(60).reshape(3, 4, 5)
check_not_ok((y, None, dx))
with self.assertTypingError() as e:
y = np.array(4)
check_not_ok((y, None, 1.0))
self.assertIn('y cannot be 0D', str(e.exception))
for y in 5, False, np.nan:
with self.assertTypingError() as e:
cfunc(y, None, 1.0)
self.assertIn('y cannot be a scalar', str(e.exception))
def test_average(self):
#array of random numbers
N = 100
a = np.random.ranf(N) * 100
w = np.random.ranf(N) * 100
w0 = np.zeros(N)
#boolean array and weights
a_bool = np.random.ranf(N) > 0.5
w_bool = np.random.ranf(N) > 0.5
#array of random ints
a_int = np.random.randint(101, size=N)
w_int = np.random.randint(101, size=N)
#3D array of random numbers
d0 = 100
d1 = 50
d2 = 25
a_3d = np.random.rand(d0,d1,d2) * 100
w_3d = np.random.rand(d0,d1,d2) * 100
pyfunc = np_average
cfunc = jit(nopython=True)(pyfunc)
#test case for average with weights
#(number of elements in array and weight array are equal)
self.assertAlmostEqual( pyfunc(a,weights=w),
cfunc(a,weights=w), places=10)
self.assertAlmostEqual( pyfunc(a_3d,weights=w_3d),
cfunc(a_3d,weights=w_3d), places=10)
#test case for average with array and weights with
#int datatype (number of elements in array and weight array are equal)
self.assertAlmostEqual( pyfunc(a_int,weights=w_int),
cfunc(a_int,weights=w_int), places=10)
#test case for average with boolean weights
self.assertAlmostEqual( pyfunc(a,weights=w_bool),
cfunc(a,weights=w_bool), places=10)
self.assertAlmostEqual( pyfunc(a_bool,weights=w),
cfunc(a_bool,weights=w), places=10)
self.assertAlmostEqual( pyfunc(a_bool, weights=w_bool),
cfunc(a_bool, weights=w_bool), places=10)
#test case for average without weights
self.assertAlmostEqual(pyfunc(a), cfunc(a), places=10)
self.assertAlmostEqual(pyfunc(a_3d), cfunc(a_3d), places=10)
def test_weights_zero_sum(data, weights):
with self.assertRaises(ZeroDivisionError) as e:
cfunc(data, weights=weights)
err = e.exception
self.assertEqual(str(err),
"Weights sum to zero, can't be normalized.")
#test case when sum of weights is zero
test_weights_zero_sum(a, weights=w0)
def test_1D_weights(data, weights):
with self.assertRaises(TypeError) as e:
cfunc(data, weights=weights)
err = e.exception
self.assertEqual(str(err),
"1D weights expected when shapes of "
"a and weights differ.")
def test_1D_weights_axis(data, axis, weights):
with self.assertRaises(TypeError) as e:
cfunc(data, axis=axis, weights=weights)
err = e.exception
self.assertEqual(str(err),
"Numba does not support average with axis.")
def test_axis(data, axis):
with self.assertRaises(TypeError) as e:
cfunc(data, axis=axis)
err = e.exception
self.assertEqual(str(err),
"Numba does not support average with axis.")
#small case to test exceptions for 2D array and 1D weights
data = np.arange(6).reshape((3,2,1))
w = np.asarray([[1. / 4, 3. / 4]])
#test axis
test_axis(data, axis=1)
#test shape mismatch
test_1D_weights(data, weights=w)
#test axis and with weights provided
test_1D_weights_axis(data, axis=1, weights=w)
def test_allclose(self):
pyfunc = np_allclose
cfunc = jit(nopython=True)(pyfunc)
min_int = np.iinfo(np.int_).min
a = np.array([min_int], dtype=np.int_)
simple_data = [
(np.asarray([1e10, 1e-7]), np.asarray([1.00001e10, 1e-8])),
(np.asarray([1e10, 1e-8]), np.asarray([1.00001e10, 1e-9])),
(np.asarray([1e10, 1e-8]), np.asarray([1.0001e10, 1e-9])),
(np.asarray([1e10]), np.asarray([1.0001e10, 1e-9])),
(1.0, 1.0),
(np.array([np.inf, 1]), np.array([0, np.inf])),
(a, a)
]
for a, b in simple_data:
py_result = pyfunc(a, b)
c_result = cfunc(a, b)
self.assertEqual(py_result, c_result)
a = np.asarray([1.0, np.nan])
b = np.asarray([1.0, np.nan])
self.assertFalse(cfunc(a, b))
self.assertEqual(pyfunc(a, b, equal_nan=True),
cfunc(a, b, equal_nan=True))
b = np.asarray([np.nan, 1.0])
self.assertEqual(pyfunc(a, b), cfunc(a, b))
noise_levels = [1.0, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 0.0]
zero_array = np.zeros((25, 4))
a = np.random.ranf((25, 4))
for noise in noise_levels:
for rtol in noise_levels:
for atol in noise_levels:
py_result = pyfunc(zero_array, noise,
atol=atol, rtol=rtol)
c_result = cfunc(zero_array, noise,
atol=atol, rtol=rtol)
self.assertEqual(py_result, c_result)
py_result = pyfunc(noise, zero_array,
atol=atol, rtol=rtol)
c_result = cfunc(noise, zero_array,
atol=atol, rtol=rtol)
self.assertEqual(py_result, c_result)
py_result = pyfunc(np.asarray([noise]), zero_array,
atol=atol, rtol=rtol)
c_result = cfunc(np.asarray([noise]), zero_array,
atol=atol, rtol=rtol)
self.assertEqual(py_result, c_result)
py_result = pyfunc(a, a + noise, atol=atol, rtol=rtol)
c_result = cfunc(a, a + noise, atol=atol, rtol=rtol)
self.assertEqual(py_result, c_result)
py_result = pyfunc(a + noise, a, atol=atol, rtol=rtol)
c_result = cfunc(a + noise, a, atol=atol, rtol=rtol)
self.assertEqual(py_result, c_result)
def test_ip_allclose_numpy(self):
# https://github.com/numpy/numpy/blob/4adc87dff15a247e417d50f10cc4def8e1c17a03/numpy/core/tests/test_numeric.py#L2402-L2420 # noqa: E501
pyfunc = np_allclose
cfunc = jit(nopython=True)(pyfunc)
arr = np.array([100.0, 1000.0])
aran = np.arange(125).astype(dtype=np.float64).reshape((5, 5, 5))
atol = 1e-8
rtol = 1e-5
numpy_data = [
(np.asarray([1, 0]), np.asarray([1, 0])),
(np.asarray([atol]), np.asarray([0.0])),
(np.asarray([1.0]), np.asarray([1 + rtol + atol])),
(arr, arr + arr * rtol),
(arr, arr + arr * rtol + atol * 2),
(aran, aran + aran * rtol),
(np.inf, np.inf),
(np.inf, np.asarray([np.inf]))
]
for (x, y) in numpy_data:
self.assertEqual(pyfunc(x, y), cfunc(x, y))
def test_ip_not_allclose_numpy(self):
# https://github.com/numpy/numpy/blob/4adc87dff15a247e417d50f10cc4def8e1c17a03/numpy/core/tests/test_numeric.py#L2422-L2441 # noqa: E501
pyfunc = np_allclose
cfunc = jit(nopython=True)(pyfunc)
aran = np.arange(125).astype(dtype=np.float64).reshape((5, 5, 5))
atol = 1e-8
rtol = 1e-5
numpy_data = [
(np.asarray([np.inf, 0]), np.asarray([1.0, np.inf])),
(np.asarray([np.inf, 0]), np.asarray([1.0, 0])),
(np.asarray([np.inf, np.inf]), np.asarray([1.0, np.inf])),
(np.asarray([np.inf, np.inf]), np.asarray([1.0, 0.0])),
(np.asarray([-np.inf, 0.0]), np.asarray([np.inf, 0.0])),
(np.asarray([np.nan, 0.0]), np.asarray([np.nan, 0.0])),
(np.asarray([atol * 2]), np.asarray([0.0])),
(np.asarray([1.0]), np.asarray([1 + rtol + atol * 2])),
(aran, aran + aran * atol + atol * 2),
(np.array([np.inf, 1.0]), np.array([0.0, np.inf]))
]
for (x, y) in numpy_data:
self.assertEqual(pyfunc(x, y), cfunc(x, y))
def test_return_class_is_ndarray_numpy(self):
# https://github.com/numpy/numpy/blob/4adc87dff15a247e417d50f10cc4def8e1c17a03/numpy/core/tests/test_numeric.py#L2460-L2468 # noqa: E501
pyfunc = np_allclose
cfunc = jit(nopython=True)(pyfunc)
class Foo(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(cls)
a = Foo([1])
self.assertTrue(type(cfunc(a, a)) is bool)
def test_equalnan_numpy(self):
# https://github.com/numpy/numpy/blob/4adc87dff15a247e417d50f10cc4def8e1c17a03/numpy/core/tests/test_numeric.py#L2456-L2458 # noqa: E501
pyfunc = np_allclose
cfunc = jit(nopython=True)(pyfunc)
x = np.array([1.0, np.nan])
self.assertEqual(pyfunc(x, x, equal_nan=True),
cfunc(x, x, equal_nan=True))
def test_no_parameter_modification_numpy(self):
# https://github.com/numpy/numpy/blob/4adc87dff15a247e417d50f10cc4def8e1c17a03/numpy/core/tests/test_numeric.py#L2443-L2448 # noqa: E501
pyfunc = np_allclose
cfunc = jit(nopython=True)(pyfunc)
x = np.array([np.inf, 1])
y = np.array([0, np.inf])
cfunc(x, y)
np.testing.assert_array_equal(x, np.array([np.inf, 1]))
np.testing.assert_array_equal(y, np.array([0, np.inf]))
def test_min_int_numpy(self):
# https://github.com/numpy/numpy/blob/4adc87dff15a247e417d50f10cc4def8e1c17a03/numpy/core/tests/test_numeric.py#L2450-L2454 # noqa: E501
pyfunc = np_allclose
cfunc = jit(nopython=True)(pyfunc)
min_int = np.iinfo(np.int_).min
a = np.array([min_int], dtype=np.int_)
self.assertEqual(pyfunc(a, a), cfunc(a, a))
def test_allclose_exception(self):
self.disable_leak_check()
pyfunc = np_allclose
cfunc = jit(nopython=True)(pyfunc)
inps = [
(np.asarray([1e10, 1e-9, np.nan]),
np.asarray([1.0001e10, 1e-9]),
1e-05, 1e-08, False,
"shape mismatch: objects cannot be broadcast to a single shape",
ValueError),
('hello', 3, False, 1e-08, False,
'The first argument "a" must be array-like',
TypingError),
(3, 'hello', False, 1e-08, False,
'The second argument "b" must be array-like',
TypingError),
(2, 3, False, 1e-08, False,
'The third argument "rtol" must be a floating point',
TypingError),
(2, 3, 1e-05, False, False,
'The fourth argument "atol" must be a floating point',
TypingError),
(2, 3, 1e-05, 1e-08, 1,
'The fifth argument "equal_nan" must be a boolean',
TypingError),
]
for a, b, rtol, atol, equal_nan, exc_msg, exc in inps:
with self.assertRaisesRegex(exc, exc_msg):
cfunc(a, b, rtol, atol, equal_nan)
def test_interp_basic(self):
pyfunc = interp
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc, abs_tol=1e-10)
x = np.linspace(-5, 5, 25)
xp = np.arange(-4, 8)
fp = xp + 1.5
_check(params={'x': x, 'xp': xp, 'fp': fp})
self.rnd.shuffle(x)
_check(params={'x': x, 'xp': xp, 'fp': fp})
self.rnd.shuffle(fp)
_check(params={'x': x, 'xp': xp, 'fp': fp})
x[:5] = np.nan
x[-5:] = np.inf
self.rnd.shuffle(x)
_check(params={'x': x, 'xp': xp, 'fp': fp})
fp[:5] = np.nan
fp[-5:] = -np.inf
self.rnd.shuffle(fp)
_check(params={'x': x, 'xp': xp, 'fp': fp})
x = np.arange(-4, 8)
xp = x + 1
fp = x + 2
_check(params={'x': x, 'xp': xp, 'fp': fp})
x = (2.2, 3.3, -5.0)
xp = (2, 3, 4)
fp = (5, 6, 7)
_check(params={'x': x, 'xp': xp, 'fp': fp})
x = ((2.2, 3.3, -5.0), (1.2, 1.3, 4.0))
xp = np.linspace(-4, 4, 10)
fp = np.arange(-5, 5)
_check(params={'x': x, 'xp': xp, 'fp': fp})
x = np.array([1.4, np.nan, np.inf, -np.inf, 0.0, -9.1])
x = x.reshape(3, 2, order='F')
xp = np.linspace(-4, 4, 10)
fp = np.arange(-5, 5)
_check(params={'x': x, 'xp': xp, 'fp': fp})
for x in range(-2, 4):
xp = [0, 1, 2]
fp = (3, 4, 5)
_check(params={'x': x, 'xp': xp, 'fp': fp})
x = np.array([])
xp = [0, 1, 2]
fp = (3, 4, 5)
_check(params={'x': x, 'xp': xp, 'fp': fp})
x = np.linspace(0, 25, 60).reshape(3, 4, 5)
xp = np.arange(20)
fp = xp - 10
_check(params={'x': x, 'xp': xp, 'fp': fp})
x = np.nan
xp = np.arange(5)
fp = np.full(5, np.nan)
_check(params={'x': x, 'xp': xp, 'fp': fp})
x = np.nan
xp = [3]
fp = [4]
_check(params={'x': x, 'xp': xp, 'fp': fp})
x = np.arange(-4, 8)
xp = x
fp = x
_check(params={'x': x, 'xp': xp, 'fp': fp})
x = [True, False]
xp = np.arange(-4, 8)
fp = xp
_check(params={'x': x, 'xp': xp, 'fp': fp})
x = [-np.inf, -1.0, 0.0, 1.0, np.inf]
xp = np.arange(-4, 8)
fp = xp * 2.2
_check(params={'x': x, 'xp': xp, 'fp': fp})
x = np.linspace(-10, 10, 10)
xp = np.array([-np.inf, -1.0, 0.0, 1.0, np.inf])
fp = xp * 2.2
_check(params={'x': x, 'xp': xp, 'fp': fp})
x = self.rnd.randn(100)
xp = np.linspace(-3, 3, 100)
fp = np.full(100, fill_value=3.142)
_check(params={'x': x, 'xp': xp, 'fp': fp})
for factor in 1, -1:
x = np.array([5, 6, 7]) * factor
xp = [1, 2]
fp = [3, 4]
_check(params={'x': x, 'xp': xp, 'fp': fp})
x = 1
xp = [1]
fp = [True]
_check(params={'x': x, 'xp': xp, 'fp': fp})
x = np.linspace(0, 1, 5)
y = np.linspace(0, 1, 5)
x0 = np.linspace(0, 1, 50)
out = cfunc(x0, x, y)
np.testing.assert_almost_equal(out, x0)
x = np.array([1, 2, 3, 4])
xp = np.array([1, 2, 3, 4])
fp = np.array([1, 2, 3.01, 4])
_check(params={'x': x, 'xp': xp, 'fp': fp})
xp = [1]
fp = [np.inf]
_check(params={'x': 1, 'xp': xp, 'fp': fp})
x = np.array([1, 2, 2.5, 3, 4])
xp = np.array([1, 2, 3, 4])
fp = np.array([1, 2, np.nan, 4])
_check({'x': x, 'xp': xp, 'fp': fp})
x = np.array([1, 1.5, 2, 2.5, 3, 4, 4.5, 5, 5.5])
xp = np.array([1, 2, 3, 4, 5])
fp = np.array([np.nan, 2, np.nan, 4, np.nan])
_check({'x': x, 'xp': xp, 'fp': fp})
x = np.array([1, 2, 2.5, 3, 4])
xp = np.array([1, 2, 3, 4])
fp = np.array([1, 2, np.inf, 4])
_check({'x': x, 'xp': xp, 'fp': fp})
x = np.array([1, 1.5, np.nan, 2.5, -np.inf, 4, 4.5, 5, np.inf, 0, 7])
xp = np.array([1, 2, 3, 4, 5, 6])
fp = np.array([1, 2, np.nan, 4, 3, np.inf])
_check({'x': x, 'xp': xp, 'fp': fp})
x = np.array([3.10034867, 3.0999066, 3.10001529])
xp = np.linspace(0, 10, 1 + 20000)
fp = np.sin(xp / 2.0)
_check({'x': x, 'xp': xp, 'fp': fp})
x = self.rnd.uniform(0, 2 * np.pi, (100,))
xp = np.linspace(0, 2 * np.pi, 1000)
fp = np.cos(xp)
exact = np.cos(x)
got = cfunc(x, xp, fp)
np.testing.assert_allclose(exact, got, atol=1e-5)
# very dense calibration
x = self.rnd.randn(10)
xp = np.linspace(-10, 10, 1000)
fp = np.ones_like(xp)
_check({'x': x, 'xp': xp, 'fp': fp})
# very sparse calibration
x = self.rnd.randn(1000)
xp = np.linspace(-10, 10, 10)
fp = np.ones_like(xp)
_check({'x': x, 'xp': xp, 'fp': fp})
def _make_some_values_non_finite(self, a):
p = a.size // 100
np.put(a, self.rnd.choice(range(a.size), p, replace=False), np.nan)
np.put(a, self.rnd.choice(range(a.size), p, replace=False), -np.inf)
np.put(a, self.rnd.choice(range(a.size), p, replace=False), np.inf)
def arrays(self, ndata):
# much_finer_grid
yield np.linspace(2.0, 7.0, 1 + ndata * 5)
# finer_grid
yield np.linspace(2.0, 7.0, 1 + ndata)
# similar_grid
yield np.linspace(2.1, 6.8, 1 + ndata // 2)
# coarser_grid
yield np.linspace(2.1, 7.5, 1 + ndata // 2)
# much_coarser_grid
yield np.linspace(1.1, 9.5, 1 + ndata // 5)
# finer_stretched_grid
yield np.linspace(3.1, 5.3, 1 + ndata) * 1.09
# similar_stretched_grid
yield np.linspace(3.1, 8.3, 1 + ndata // 2) * 1.09
# finer_compressed_grid
yield np.linspace(3.1, 5.3, 1 + ndata) * 0.91
# similar_compressed_grid
yield np.linspace(3.1, 8.3, 1 + ndata // 2) * 0.91
# warped_grid
yield np.linspace(3.1, 5.3, 1 + ndata // 2) + 0.3 * np.sin(
np.arange(1 + ndata / 2) * np.pi / (1 + ndata / 2))
# very_low_noise_grid
yield np.linspace(3.1, 5.3, 1 + ndata) + self.rnd.normal(
size=1 + ndata, scale=0.5 / ndata)
# low_noise_grid
yield np.linspace(3.1, 5.3, 1 + ndata) + self.rnd.normal(
size=1 + ndata, scale=2.0 / ndata)
# med_noise_grid
yield np.linspace(3.1, 5.3, 1 + ndata) + self.rnd.normal(
size=1 + ndata, scale=5.0 / ndata)
# high_noise_grid
yield np.linspace(3.1, 5.3, 1 + ndata) + self.rnd.normal(
size=1 + ndata, scale=20.0 / ndata)
# very_high_noise_grid
yield np.linspace(3.1, 5.3, 1 + ndata) + self.rnd.normal(
size=1 + ndata, scale=50.0 / ndata)
# extreme_noise_grid
yield np.linspace(3.1, 5.3, 1 + ndata) + self.rnd.normal(
size=1 + ndata, scale=200.0 / ndata)
# random_fine_grid
yield self.rnd.rand(1 + ndata) * 9.0 + 0.6
# random_grid
yield self.rnd.rand(1 + ndata * 2) * 4.0 + 1.3
def test_interp_stress_tests(self):
pyfunc = interp
cfunc = jit(nopython=True)(pyfunc)
ndata = 20000
xp = np.linspace(0, 10, 1 + ndata)
fp = np.sin(xp / 2.0)
for x in self.arrays(ndata):
atol = 1e-14 # using abs_tol as otherwise fails on 32bit builds
expected = pyfunc(x, xp, fp)
got = cfunc(x, xp, fp)
self.assertPreciseEqual(expected, got, abs_tol=atol)
# no longer require xp to be monotonically increasing
# (in keeping with numpy) even if the output might not
# be meaningful; shuffle all inputs
self.rnd.shuffle(x)
expected = pyfunc(x, xp, fp)
got = cfunc(x, xp, fp)
self.assertPreciseEqual(expected, got, abs_tol=atol)
self.rnd.shuffle(xp)
expected = pyfunc(x, xp, fp)
got = cfunc(x, xp, fp)
self.assertPreciseEqual(expected, got, abs_tol=atol)
self.rnd.shuffle(fp)
expected = pyfunc(x, xp, fp)
got = cfunc(x, xp, fp)
self.assertPreciseEqual(expected, got, abs_tol=atol)
# add some values non finite
self._make_some_values_non_finite(x)
expected = pyfunc(x, xp, fp)
got = cfunc(x, xp, fp)
self.assertPreciseEqual(expected, got, abs_tol=atol)
self._make_some_values_non_finite(xp)
expected = pyfunc(x, xp, fp)
got = cfunc(x, xp, fp)
self.assertPreciseEqual(expected, got, abs_tol=atol)
self._make_some_values_non_finite(fp)
expected = pyfunc(x, xp, fp)
got = cfunc(x, xp, fp)
self.assertPreciseEqual(expected, got, abs_tol=atol)
@unittest.skipIf(IS_NUMPY_2 and IS_MACOS_ARM64, "NEP 50 interaction issue.")
def test_interp_complex_stress_tests(self):
pyfunc = interp
cfunc = jit(nopython=True)(pyfunc)
ndata = 2000
xp = np.linspace(0, 10, 1 + ndata)
real = np.sin(xp / 2.0)
real[:200] = self.rnd.choice([np.inf, -np.inf, np.nan], 200)
self.rnd.shuffle(real)
imag = np.cos(xp / 2.0)
imag[:200] = self.rnd.choice([np.inf, -np.inf, np.nan], 200)
self.rnd.shuffle(imag)
fp = real + 1j * imag
for x in self.arrays(ndata):
expected = pyfunc(x, xp, fp)
got = cfunc(x, xp, fp)
np.testing.assert_allclose(expected, got, equal_nan=True)
self.rnd.shuffle(x)
self.rnd.shuffle(xp)
self.rnd.shuffle(fp)
np.testing.assert_allclose(expected, got, equal_nan=True)
def test_interp_exceptions(self):
pyfunc = interp
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
x = np.array([1, 2, 3])
xp = np.array([])
fp = np.array([])
with self.assertRaises(ValueError) as e:
cfunc(x, xp, fp)
msg = "array of sample points is empty"
self.assertIn(msg, str(e.exception))
x = 1
xp = np.array([1, 2, 3])
fp = np.array([1, 2])
with self.assertRaises(ValueError) as e:
cfunc(x, xp, fp)
msg = "fp and xp are not of the same size."
self.assertIn(msg, str(e.exception))
x = 1
xp = np.arange(6).reshape(3, 2)
fp = np.arange(6)
with self.assertTypingError() as e:
cfunc(x, xp, fp)
msg = "xp must be 1D"
self.assertIn(msg, str(e.exception))
x = 1
xp = np.arange(6)
fp = np.arange(6).reshape(3, 2)
with self.assertTypingError() as e:
cfunc(x, xp, fp)
msg = "fp must be 1D"
self.assertIn(msg, str(e.exception))
x = 1 + 1j
xp = np.arange(6)
fp = np.arange(6)
with self.assertTypingError() as e:
cfunc(x, xp, fp)
complex_dtype_msg = (
"Cannot cast array data from complex dtype "
"to float64 dtype"
)
self.assertIn(complex_dtype_msg, str(e.exception))
x = 1
xp = (np.arange(6) + 1j).astype(np.complex64)
fp = np.arange(6)
with self.assertTypingError() as e:
cfunc(x, xp, fp)
self.assertIn(complex_dtype_msg, str(e.exception))
def test_interp_non_finite_calibration(self):
# examples from
# https://github.com/numpy/numpy/issues/12951
pyfunc = interp
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc)
xp = np.array([0, 1, 9, 10])
fp = np.array([-np.inf, 0.1, 0.9, np.inf])
x = np.array([0.2, 9.5])
params = {'x': x, 'xp': xp, 'fp': fp}
_check(params)
xp = np.array([-np.inf, 1, 9, np.inf])
fp = np.array([0, 0.1, 0.9, 1])
x = np.array([0.2, 9.5])
params = {'x': x, 'xp': xp, 'fp': fp}
_check(params)
def test_interp_supplemental_tests(self):
# inspired by class TestInterp
# https://github.com/numpy/numpy/blob/f5b6850f231/numpy/lib/tests/test_function_base.py # noqa: E501
pyfunc = interp
cfunc = jit(nopython=True)(pyfunc)
for size in range(1, 10):
xp = np.arange(size, dtype=np.double)
yp = np.ones(size, dtype=np.double)
incpts = np.array([-1, 0, size - 1, size], dtype=np.double)
decpts = incpts[::-1]
incres = cfunc(incpts, xp, yp)
decres = cfunc(decpts, xp, yp)
inctgt = np.array([1, 1, 1, 1], dtype=float)
dectgt = inctgt[::-1]
np.testing.assert_almost_equal(incres, inctgt)
np.testing.assert_almost_equal(decres, dectgt)
x = np.linspace(0, 1, 5)
y = np.linspace(0, 1, 5)
x0 = 0
np.testing.assert_almost_equal(cfunc(x0, x, y), x0)
x0 = 0.3
np.testing.assert_almost_equal(cfunc(x0, x, y), x0)
x0 = np.float32(0.3)
np.testing.assert_almost_equal(cfunc(x0, x, y), x0)
x0 = np.float64(0.3)
np.testing.assert_almost_equal(cfunc(x0, x, y), x0)
x0 = np.nan
np.testing.assert_almost_equal(cfunc(x0, x, y), x0)
x = np.linspace(0, 1, 5)
y = np.linspace(0, 1, 5)
x0 = np.array(0.3)
np.testing.assert_almost_equal(cfunc(x0, x, y), x0)
xp = np.arange(0, 10, 0.0001)
fp = np.sin(xp)
np.testing.assert_almost_equal(cfunc(np.pi, xp, fp), 0.0)
def test_interp_supplemental_complex_tests(self):
# inspired by class TestInterp
# https://github.com/numpy/numpy/blob/f5b6850f231/numpy/lib/tests/test_function_base.py # noqa: E501
pyfunc = interp
cfunc = jit(nopython=True)(pyfunc)
x = np.linspace(0, 1, 5)
y = np.linspace(0, 1, 5) + (1 + np.linspace(0, 1, 5)) * 1.0j
x0 = 0.3
y0 = x0 + (1 + x0) * 1.0j
np.testing.assert_almost_equal(cfunc(x0, x, y), y0)
def test_interp_float_precision_handled_per_numpy(self):
# test cases from https://github.com/numba/numba/issues/4890
pyfunc = interp
cfunc = jit(nopython=True)(pyfunc)
dtypes = [np.float32, np.float64, np.int32, np.int64]
for combo in itertools.combinations_with_replacement(dtypes, 3):
xp_dtype, fp_dtype, x_dtype = combo
xp = np.arange(10, dtype=xp_dtype)
fp = (xp ** 2).astype(fp_dtype)
x = np.linspace(2, 3, 10, dtype=x_dtype)
expected = pyfunc(x, xp, fp)
got = cfunc(x, xp, fp)
self.assertPreciseEqual(expected, got)
def test_isnat(self):
def values():
yield np.datetime64("2016-01-01")
yield np.datetime64("NaT")
yield np.datetime64('NaT', 'ms')
yield np.datetime64('NaT', 'ns')
yield np.datetime64('2038-01-19T03:14:07')
yield np.timedelta64('NaT', "ms")
yield np.timedelta64(34, "ms")
for unit in ['Y', 'M', 'W', 'D',
'h', 'm', 's', 'ms', 'us',
'ns', 'ps', 'fs', 'as']:
yield np.array([123, -321, "NaT"],
dtype='<datetime64[%s]' % unit)
yield np.array([123, -321, "NaT"],
dtype='<timedelta64[%s]' % unit)
pyfunc = isnat
cfunc = jit(nopython=True)(pyfunc)
for x in values():
expected = pyfunc(x)
got = cfunc(x)
if isinstance(x, np.ndarray):
self.assertPreciseEqual(expected, got, (x,))
else:
self.assertEqual(expected, got, x)
def test_asarray(self):
def input_variations():
"""
To quote from: https://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html # noqa: E501
Input data, in any form that can be converted to an array.
This includes:
* lists
* lists of tuples
* tuples
* tuples of tuples
* tuples of lists
* ndarrays
"""
yield 1j
yield 1.2
yield False
yield 1
yield [1, 2, 3]
yield [(1, 2, 3), (1, 2, 3)]
yield (1, 2, 3)
yield ((1, 2, 3), (1, 2, 3))
yield ([1, 2, 3], [1, 2, 3])
yield np.array([])
yield np.arange(4)
yield np.arange(12).reshape(3, 4)
yield np.arange(12).reshape(3, 4).T
# Test cases for `numba.typed.List`
def make_list(values):
a = List()
for i in values:
a.append(i)
return a
yield make_list((1, 2, 3))
yield make_list((1.0, 2.0, 3.0))
yield make_list((1j, 2j, 3j))
yield make_list((True, False, True))
# used to check that if the input is already an array and the dtype is
# the same as that of the input/omitted then the array itself is
# returned.
def check_pass_through(jitted, expect_same, params):
returned = jitted(**params)
if expect_same:
self.assertTrue(returned is params['a'])
else:
self.assertTrue(returned is not params['a'])
# should be numerically the same, just different dtype
np.testing.assert_allclose(returned, params['a'])
self.assertTrue(returned.dtype == params['dtype'])
for pyfunc in [asarray, asarray_kws]:
cfunc = jit(nopython=True)(pyfunc)
_check = partial(self._check_output, pyfunc, cfunc)
for x in input_variations():
params = {'a': x}
if 'kws' in pyfunc.__name__:
for dt in [None, np.complex128]:
params['dtype'] = dt
_check(params)
else:
_check(params)
# check the behaviour over a dtype change (or not!)
x = np.arange(10, dtype=np.float32)
params = {'a': x}
if 'kws' in pyfunc.__name__:
params['dtype'] = None
check_pass_through(cfunc, True, params)
params['dtype'] = np.complex128
check_pass_through(cfunc, False, params)
params['dtype'] = np.float32
check_pass_through(cfunc, True, params)
else:
check_pass_through(cfunc, True, params)
def test_asarray_literal(self):
def case1():
return np.asarray("hello world")
def case2(): # kind1
s = "hello world"
return np.asarray(s)
def case3(): # kind2
s = '大处 着眼,小处着手。大大大处'
return np.asarray(s)
def case4():
s = ''
return np.asarray(s)
funcs = [case1, case2, case3, case4]
for pyfunc in funcs:
cfunc = jit(nopython=True)(pyfunc)
expected = pyfunc()
got = cfunc()
self.assertPreciseEqual(expected, got)
def test_asarray_rejects_List_with_illegal_dtype(self):
self.disable_leak_check()
cfunc = jit(nopython=True)(asarray)
def test_reject(alist):
with self.assertRaises(TypingError) as e:
cfunc(alist)
self.assertIn(
"asarray support for List is limited "
"to Boolean and Number types",
str(e.exception))
def make_none_typed_list():
l = List()
l.append(None)
return l
def make_nested_list():
l = List()
m = List()
m.append(1)
l.append(m)
return l
def make_nested_list_with_dict():
l = List()
d = Dict()
d[1] = "a"
l.append(d)
return l
def make_unicode_list():
l = List()
for i in ("a", "bc", "def"):
l.append(i)
return l
test_reject(make_none_typed_list())
test_reject(make_nested_list())
test_reject(make_nested_list_with_dict())
test_reject(make_unicode_list())
@skip_if_numpy_2
def test_asfarray(self):
def inputs():
yield np.array([1, 2, 3]), None
yield np.array([2, 3], dtype=np.float32), np.float32
yield np.array([2, 3], dtype=np.int8), np.int8
yield np.array([2, 3], dtype=np.int8), np.complex64
yield np.array([2, 3], dtype=np.int8), np.complex128
pyfunc = asfarray
cfunc = jit(nopython=True)(pyfunc)
for arr, dt in inputs():
if dt is None:
expected = pyfunc(arr)
got = cfunc(arr)
else:
expected = pyfunc(arr, dtype=dt)
got = cfunc(arr, dtype=dt)
self.assertPreciseEqual(expected, got)
self.assertTrue(np.issubdtype(got.dtype, np.inexact), got.dtype)
# test default kwarg variant
pyfunc = asfarray_default_kwarg
cfunc = jit(nopython=True)(pyfunc)
arr = np.array([1, 2, 3])
expected = pyfunc(arr)
got = cfunc(arr)
self.assertPreciseEqual(expected, got)
self.assertTrue(np.issubdtype(got.dtype, np.inexact), got.dtype)
def test_repeat(self):
# np.repeat(a, repeats)
np_pyfunc = np_repeat
np_nbfunc = njit(np_pyfunc)
# a.repeat(repeats)
array_pyfunc = array_repeat
array_nbfunc = njit(array_pyfunc)
for pyfunc, nbfunc in ((np_pyfunc, np_nbfunc),
(array_pyfunc, array_nbfunc)):
def check(a, repeats):
self.assertPreciseEqual(pyfunc(a, repeats), nbfunc(a, repeats))
# test array arguments
if REDUCED_TESTING:
# Reduced test data for memory optimization
target_numpy_values = [
np.ones(1),
np.arange(10), # Much smaller than 1000
np.array([]),
]
target_numpy_types = [
np.float64,
np.complex128,
]
repeats_values = [0, 1, 2] # Fewer repeat values
else:
target_numpy_values = [
np.ones(1),
np.arange(1000),
np.array([[0, 1], [2, 3]]),
np.array([]),
np.array([[], []]),
]
target_numpy_types = [
np.uint32,
np.int32,
np.uint64,
np.int64,
np.float32,
np.float64,
np.complex64,
np.complex128,
]
repeats_values = [0, 1, 2, 3, 100]
target_numpy_inputs = (np.array(a,dtype=t) for a,t in
itertools.product(target_numpy_values,
target_numpy_types))
if REDUCED_TESTING:
target_non_numpy_inputs = [
1,
[0, 1, 2],
]
else:
target_non_numpy_inputs = [
1,
1.0,
True,
1j,
[0, 1, 2],
(0, 1, 2),
]
for i in itertools.chain(target_numpy_inputs,
target_non_numpy_inputs):
for repeats in repeats_values:
check(i, repeats=repeats)
# check broadcasting when repeats is an array/list
one = np.arange(1)
for i in ([0], [1], [2]):
check(one, repeats=i)
check(one, repeats=np.array(i))
two = np.arange(2)
for i in ([0, 0], [0, 1], [1, 0], [0, 1], [1, 2], [2, 1], [2, 2]):
check(two, repeats=i)
check(two, repeats=np.array(i))
check(two, repeats=np.array([2, 2], dtype=np.int32))
check(np.arange(10), repeats=np.arange(10))
def test_repeat_exception(self):
# np.repeat(a, repeats)
np_pyfunc = np_repeat
np_nbfunc = njit(np_pyfunc)
# a.repeat(repeats)
array_pyfunc = array_repeat
array_nbfunc = njit(array_pyfunc)
self.disable_leak_check()
for pyfunc, nbfunc in ((np_pyfunc, np_nbfunc),
(array_pyfunc, array_nbfunc)):
# negative repeat argument
with self.assertRaises(ValueError) as e:
nbfunc(np.ones(1), -1)
self.assertIn("negative dimensions are not allowed",
str(e.exception))
# float repeat argument has custom error message
with self.assertRaises(TypingError) as e:
nbfunc(np.ones(1), 1.0)
self.assertIn(
"The repeats argument must be an integer "
"or an array-like of integer dtype",
str(e.exception))
# negative repeat argument as array
with self.assertRaises(ValueError) as e:
nbfunc(np.ones(2), np.array([1, -1]))
self.assertIn("negative dimensions are not allowed",
str(e.exception))
# broadcasting error, repeats too large
with self.assertRaises(ValueError) as e:
nbfunc(np.ones(2), np.array([1, 1, 1]))
self.assertIn("operands could not be broadcast together",
str(e.exception))
# broadcasting error, repeats too small
with self.assertRaises(ValueError) as e:
nbfunc(np.ones(5), np.array([1, 1, 1, 1]))
self.assertIn("operands could not be broadcast together",
str(e.exception))
# float repeat argument has custom error message
with self.assertRaises(TypingError) as e:
nbfunc(np.ones(2), [1.0, 1.0])
self.assertIn(
"The repeats argument must be an integer "
"or an array-like of integer dtype",
str(e.exception))
for rep in [True, "a", "1"]:
with self.assertRaises(TypingError):
nbfunc(np.ones(1), rep)
def test_select(self):
np_pyfunc = np_select
np_nbfunc = njit(np_select)
test_cases = [
# Each test case below is one tuple.
# Each tuple is separated by a description of what's being tested
# test with arrays of length 3 instead of 2 and a different default
([np.array([False, False, False]),
np.array([False, True, False]),
np.array([False, False, True])],
[np.array([1, 2, 3]),
np.array([4, 5, 6]),
np.array([7, 8, 9])], 15.3),
# test with arrays of length 1 instead of 2
([np.array([True]),
np.array([False])], [np.array([1]), np.array([2])], 0),
# test with lists of length 100 of arrays of length 1
([np.array([False])] * 100, [np.array([1])] * 100, 0),
# passing arrays with NaNs
([np.isnan(np.array([1, 2, 3, np.nan, 5, 7]))] * 2,
[np.array([1, 2, 3, np.nan, 5, 7])] * 2, 0),
# passing lists with 2d arrays
([np.isnan(np.array([[1, 2, 3, np.nan, 5, 7]]))] * 2,
[np.array([[1, 2, 3, np.nan, 5, 7]])] * 2, 0),
# passing arrays with complex numbers
([np.isnan(np.array([1, 2, 3 + 2j, np.nan, 5, 7]))] * 2,
[np.array([1, 2, 3 + 2j, np.nan, 5, 7])] * 2, 0)
]
for x in (np.arange(10), np.arange(10).reshape((5, 2))):
# test with two lists
test_cases.append(([x < 3, x > 5], [x, x ** 2], 0))
# test with two tuples
test_cases.append(((x < 3, x > 5), (x, x ** 2), 0))
# test with one list and one tuple
test_cases.append(([x < 3, x > 5], (x, x ** 2), 0))
# test with one tuple and one list
test_cases.append(((x < 3, x > 5), [x, x ** 2], 0))
for condlist, choicelist, default in test_cases:
self.assertPreciseEqual(np_pyfunc(condlist, choicelist, default),
np_nbfunc(condlist, choicelist, default))
np_pyfunc_defaults = np_select_defaults
np_nbfunc_defaults = njit(np_select_defaults)
# check the defaults work, using whatever the last input was
self.assertPreciseEqual(np_pyfunc_defaults(condlist, choicelist),
np_nbfunc_defaults(condlist, choicelist))
def test_select_exception(self):
np_nbfunc = njit(np_select)
x = np.arange(10)
self.disable_leak_check()
for condlist, choicelist, default, expected_error, expected_text in [
# Each test case below is one tuple.
# Each tuple is separated by the description of the intended error
# passing condlist of dim zero
([np.array(True), np.array([False, True, False])],
[np.array(1), np.arange(12).reshape(4, 3)], 0,
TypingError, "condlist arrays must be of at least dimension 1"),
# condlist and choicelist with different dimensions
([np.array(True), np.array(False)], [np.array([1]), np.array([2])],
0, TypingError, "condlist and choicelist elements must have the "
"same number of dimensions"),
# condlist and choicelist with different dimensions
([np.array([True]), np.array([False])],
[np.array([[1]]), np.array([[2]])], 0, TypingError,
"condlist and choicelist elements must have the "
"same number of dimensions"),
# passing choicelist of dim zero
([np.array(True), np.array(False)], [np.array(1), np.array(2)], 0,
TypingError, "condlist arrays must be of at least dimension 1"),
# passing an array as condlist instead of a list or tuple
(np.isnan(np.array([1, 2, 3, np.nan, 5, 7])),
np.array([1, 2, 3, np.nan, 5, 7]), 0, TypingError,
"condlist must be a List or a Tuple"),
# default is a list
([True], [0], [0], TypingError,
"default must be a scalar"),
# condlist with ints instead of booleans
([(x < 3).astype(int), (x > 5).astype(int)], [x, x ** 2], 0,
TypingError, "condlist arrays must contain booleans"),
# condlist and choicelist of different length
([x > 9, x > 8, x > 7, x > 6], [x, x**2, x], 0, ValueError,
"list of cases must be same length as list of conditions"),
# condlist contains tuples instead of arrays
# if in the future numba's np.where accepts tuples, the
# implementation of np.select should also accept them and
# the following two test cases should be normal tests
# instead of negative tests
# test with lists of length 100 of tuples of length 1 for condlist
([(False,)] * 100, [np.array([1])] * 100, 0, TypingError,
'items of condlist must be arrays'),
# test with lists of length 100 of tuples of length 1 for choicelist
([np.array([False])] * 100, [(1,)] * 100, 0, TypingError,
'items of choicelist must be arrays'),
]:
with self.assertRaises(expected_error) as e:
np_nbfunc(condlist, choicelist, default)
self.assertIn(expected_text, str(e.exception))
def test_windowing(self):
def check_window(func):
np_pyfunc = func
np_nbfunc = njit(func)
for M in [0, 1, 5, 12]:
expected = np_pyfunc(M)
got = np_nbfunc(M)
self.assertPreciseEqual(expected, got, prec='double')
for M in ['a', 1.1, 1j]:
with self.assertRaises(TypingError) as raises:
np_nbfunc(1.1)
self.assertIn("M must be an integer", str(raises.exception))
check_window(np_bartlett)
check_window(np_blackman)
check_window(np_hamming)
check_window(np_hanning)
# Test np.kaiser separately
np_pyfunc = np_kaiser
np_nbfunc = njit(np_kaiser)
for M in [0, 1, 5, 12]:
for beta in [0.0, 5.0, 14.0]:
expected = np_pyfunc(M, beta)
got = np_nbfunc(M, beta)
if IS_32BITS or platform.machine() in ['ppc64le', 'aarch64']:
self.assertPreciseEqual(expected,
got, prec='double', ulps=2)
else:
self.assertPreciseEqual(expected, got, prec='double',
ulps=2)
for M in ['a', 1.1, 1j]:
with self.assertRaises(TypingError) as raises:
np_nbfunc(M, 1.0)
self.assertIn("M must be an integer", str(raises.exception))
for beta in ['a', 1j]:
with self.assertRaises(TypingError) as raises:
np_nbfunc(5, beta)
self.assertIn("beta must be an integer or float",
str(raises.exception))
def test_cross(self):
pyfunc = np_cross
cfunc = jit(nopython=True)(pyfunc)
pairs = [
# 3x3 (n-dims)
(
np.array([[1, 2, 3], [4, 5, 6]]),
np.array([[4, 5, 6], [1, 2, 3]])
),
# 2x3 array-like (n-dims)
(
np.array([[1, 2, 3], [4, 5, 6]]),
((4, 5), (1, 2))
),
# 3x3 (1-dim) with type promotion
(
np.array([1, 2, 3], dtype=np.int64),
np.array([4, 5, 6], dtype=np.float64)
),
# 3x3 array-like (1-dim)
(
(1, 2, 3),
(4, 5, 6)
),
# 2x3 (1-dim)
(
np.array([1, 2]),
np.array([4, 5, 6])
),
# 3x3 (with broadcasting 1d x 2d)
(
np.array([1, 2, 3]),
np.array([[4, 5, 6], [1, 2, 3]])
),
# 3x3 (with broadcasting 2d x 1d)
(
np.array([[1, 2, 3], [4, 5, 6]]),
np.array([1, 2, 3])
),
# 3x2 (with higher order broadcasting)
(
np.arange(36).reshape(6, 2, 3),
np.arange(4).reshape(2, 2)
)
]
for x, y in pairs:
expected = pyfunc(x, y)
got = cfunc(x, y)
self.assertPreciseEqual(expected, got)
def test_cross_exceptions(self):
pyfunc = np_cross
cfunc = jit(nopython=True)(pyfunc)
self.disable_leak_check()
# test incompatible dimensions for ndim == 1
with self.assertRaises(ValueError) as raises:
cfunc(
np.arange(4),
np.arange(3)
)
self.assertIn(
'Incompatible dimensions for cross product',
str(raises.exception)
)
# test 2d cross product error for ndim == 1
with self.assertRaises(ValueError) as raises:
cfunc(
np.array((1, 2)),
np.array((3, 4))
)
self.assertIn(
'Dimensions for both inputs is 2.',
str(raises.exception)
)
self.assertIn(
'`cross2d(a, b)` from `numba.np.extensions`.',
str(raises.exception)
)
# test incompatible dimensions for ndim > 1
with self.assertRaises(ValueError) as raises:
cfunc(
np.arange(8).reshape((2, 4)),
np.arange(6)[::-1].reshape((2, 3))
)
self.assertIn(
'Incompatible dimensions for cross product',
str(raises.exception)
)
# test 2d cross product error for ndim == 1
with self.assertRaises(ValueError) as raises:
cfunc(
np.arange(8).reshape((4, 2)),
np.arange(8)[::-1].reshape((4, 2))
)
self.assertIn(
'Dimensions for both inputs is 2',
str(raises.exception)
)
# test non-array-like input
with self.assertRaises(TypingError) as raises:
cfunc(
set([1, 2, 3]),
set([4, 5, 6])
)
self.assertIn(
'Inputs must be array-like.',
str(raises.exception)
)
def test_cross2d(self):
pyfunc = np_cross
cfunc = njit(nb_cross2d)
pairs = [
# 2x2 (n-dims)
(
np.array([[1, 2], [4, 5]]),
np.array([[4, 5], [1, 2]])
),
# 2x2 array-like (n-dims)
(
np.array([[1, 2], [4, 5]]),
((4, 5), (1, 2))
),
# 2x2 (1-dim) with type promotion
(
np.array([1, 2], dtype=np.int64),
np.array([4, 5], dtype=np.float64)
),
# 2x2 array-like (1-dim)
(
(1, 2),
(4, 5)
),
# 2x2 (with broadcasting 1d x 2d)
(
np.array([1, 2]),
np.array([[4, 5], [1, 2]])
),
# 2x2 (with broadcasting 2d x 1d)
(
np.array([[1, 2], [4, 5]]),
np.array([1, 2])
),
# 2x2 (with higher order broadcasting)
(
np.arange(36).reshape(6, 3, 2),
np.arange(6).reshape(3, 2)
)
]
for x, y in pairs:
expected = pyfunc(x, y)
got = cfunc(x, y)
self.assertPreciseEqual(expected, got)
def test_cross2d_exceptions(self):
cfunc = njit(nb_cross2d)
self.disable_leak_check()
# test incompatible dimensions for ndim == 1
with self.assertRaises(ValueError) as raises:
cfunc(
np.array((1, 2, 3)),
np.array((4, 5, 6))
)
self.assertIn(
'Incompatible dimensions for 2D cross product',
str(raises.exception)
)
# test incompatible dimensions for ndim > 1
with self.assertRaises(ValueError) as raises:
cfunc(
np.arange(6).reshape((2, 3)),
np.arange(6)[::-1].reshape((2, 3))
)
self.assertIn(
'Incompatible dimensions for 2D cross product',
str(raises.exception)
)
# test non-array-like input
with self.assertRaises(TypingError) as raises:
cfunc(
set([1, 2]),
set([4, 5])
)
self.assertIn(
'Inputs must be array-like.',
str(raises.exception)
)
def test_trim_zeros(self):
def arrays():
yield np.array([])
yield np.zeros(5)
yield np.zeros(1)
yield np.array([1, 2, 3])
yield np.array([0, 1, 2, 3])
yield np.array([0., 1., 2., np.nan, 0.])
yield np.array(['0', 'Hello', 'world'])
def explicit_trim():
yield np.array([0, 1, 2, 0, 0]), 'FB'
yield np.array([0, 1, 2]), 'B'
yield np.array([np.nan, 0., 1.2, 2.3, 0.]), 'b'
yield np.array([0, 0, 1, 2, 5]), 'f'
if numpy_version < (2, 2):
# abf and d are not supported in numpy >= 2.2
yield np.array([0, 1, 2, 0]), 'abf'
yield np.array([0, 4, 0]), 'd'
yield np.array(['\0', '1', '2']), 'f'
pyfunc = np_trim_zeros
cfunc = jit(nopython=True)(pyfunc)
for arr in arrays():
expected = pyfunc(arr)
got = cfunc(arr)
self.assertPreciseEqual(expected, got)
for arr, trim in explicit_trim():
expected = pyfunc(arr, trim)
got = cfunc(arr, trim)
self.assertPreciseEqual(expected, got)
def test_trim_zeros_numpy(self):
# https://github.com/numpy/numpy/blob/9d8d46ad615a7e13256b930146ac369f651016c0/numpy/lib/tests/test_function_base.py#L1251-L1313
a = np.array([0, 0, 1, 0, 2, 3, 4, 0])
b = a.astype(float)
c = a.astype(complex)
# d = a.astype(object)
values = [a, b, c]
# test_basic
slc = np.s_[2:-1]
for arr in values:
res = np_trim_zeros(arr)
self.assertPreciseEqual(res, arr[slc])
# test_leading_skip
slc = np.s_[:-1]
for arr in values:
res = np_trim_zeros(arr, trim='b')
self.assertPreciseEqual(res, arr[slc])
# test_trailing_skip
slc = np.s_[2:]
for arr in values:
res = np_trim_zeros(arr, trim='F')
self.assertPreciseEqual(res, arr[slc])
# test_all_zero
for _arr in values:
arr = np.zeros_like(_arr, dtype=_arr.dtype)
res1 = np_trim_zeros(arr, trim='B')
assert len(res1) == 0
res2 = np_trim_zeros(arr, trim='f')
assert len(res2) == 0
# test_size_zero
arr = np.zeros(0)
res = np_trim_zeros(arr)
self.assertPreciseEqual(arr, res)
# test_overflow
for arr in [np.array([0, 2**62, 0]), np.array([0, 2**63, 0]),
np.array([0, 2**64, 0])]:
slc = np.s_[1:2]
res = np_trim_zeros(arr)
self.assertPreciseEqual(res, arr[slc])
# test_no_trim
arr = np.array([None, 1, None])
res = np_trim_zeros(arr)
self.assertPreciseEqual(arr, res)
# test_list_to_list
res = np_trim_zeros(a.tolist())
assert isinstance(res, list)
def test_trim_zeros_exceptions(self):
self.disable_leak_check()
cfunc = jit(nopython=True)(np_trim_zeros)
with self.assertRaises(TypingError) as raises:
cfunc(np.array([[1, 2, 3], [4, 5, 6]]))
self.assertIn(
'array must be 1D',
str(raises.exception)
)
with self.assertRaises(TypingError) as raises:
cfunc(3)
self.assertIn(
'The first argument must be an array',
str(raises.exception)
)
with self.assertRaises(TypingError) as raises:
cfunc({0, 1, 2})
self.assertIn(
'The first argument must be an array',
str(raises.exception)
)
with self.assertRaises(TypingError) as raises:
cfunc(np.array([0, 1, 2]), 1)
self.assertIn(
'The second argument must be a string',
str(raises.exception)
)
def test_union1d(self):
pyfunc = np_union1d
cfunc = jit(nopython=True)(pyfunc)
arrays = [
# Test 1d arrays
(
np.array([1, 2, 3]),
np.array([2, 3, 4])
),
# Test 2d with 1d array
(
np.array([[1, 2, 3], [2, 3, 4]]),
np.array([2, 5, 6])
),
# Test 3d with 1d array
(
np.arange(0, 20).reshape(2,2,5),
np.array([1, 20, 21])
),
# Test 2d with 3d array
(
np.arange(0, 10).reshape(2,5),
np.arange(0, 20).reshape(2,5,2)
),
# Test other array-like
(
np.array([False, True, 7]),
np.array([1, 2, 3])
)
]
for a, b in arrays:
expected = pyfunc(a,b)
got = cfunc(a,b)
self.assertPreciseEqual(expected, got)
def test_union1d_exceptions(self):
cfunc = jit(nopython=True)(np_union1d)
self.disable_leak_check()
# Test inputs not array-like
with self.assertRaises(TypingError) as raises:
cfunc("Hello", np.array([1,2]))
self.assertIn(
"The arguments to np.union1d must be array-like",
str(raises.exception)
)
with self.assertRaises(TypingError) as raises:
cfunc(np.array([1,2]), "Hello")
self.assertIn(
"The arguments to np.union1d must be array-like",
str(raises.exception)
)
with self.assertRaises(TypingError) as raises:
cfunc("Hello", "World")
self.assertIn(
"The arguments to np.union1d must be array-like",
str(raises.exception)
)
# Test Unicode array exceptions
with self.assertRaises(TypingError) as raises:
cfunc(np.array(['hello', 'world']), np.array(['a', 'b']))
self.assertIn(
"For Unicode arrays, arrays must have same dtype",
str(raises.exception)
)
with self.assertRaises(TypingError) as raises:
cfunc(np.array(['c', 'd']), np.array(['foo', 'bar']))
self.assertIn(
"For Unicode arrays, arrays must have same dtype",
str(raises.exception)
)
with self.assertRaises(TypingError) as raises:
cfunc(np.array(['c', 'd']), np.array([1, 2]))
self.assertIn(
"For Unicode arrays, arrays must have same dtype",
str(raises.exception)
)
with self.assertRaises(TypingError) as raises:
cfunc(np.array(['c', 'd']), np.array([1.1, 2.5]))
self.assertIn(
"For Unicode arrays, arrays must have same dtype",
str(raises.exception)
)
def test_asarray_chkfinite(self):
pyfunc = np_asarray_chkfinite
cfunc = jit(nopython=True)(pyfunc)
self.disable_leak_check()
pairs = [
#1D array with all args
(
np.array([1, 2, 3]),
np.float32,
),
#1D array
(
np.array([1, 2, 3]),
),
#1D array-like
(
[1, 2, 3, 4],
),
# 2x2 (n-dims)
(
np.array([[1, 2], [3, 4]]),
np.float32,
),
# 2x2 array-like (n-dims)
(
((1, 2), (3, 4)),
np.int64
),
# 2x2 (1-dim) with type promotion
(
np.array([1, 2], dtype=np.int64),
),
# 3x2 (with higher order broadcasting)
(
np.arange(36).reshape(6, 2, 3),
),
]
for pair in pairs:
expected = pyfunc(*pair)
got = cfunc(*pair)
self.assertPreciseEqual(expected, got)
def test_asarray_chkfinite_exceptions(self):
cfunc = jit(nopython=True)(np_asarray_chkfinite)
self.disable_leak_check()
#test for single value
with self.assertRaises(TypingError) as e:
cfunc(2)
msg = "The argument to np.asarray_chkfinite must be array-like"
self.assertIn(msg, str(e.exception))
#test for NaNs
with self.assertRaises(ValueError) as e:
cfunc(np.array([2, 4, np.nan, 5]))
self.assertIn("array must not contain infs or NaNs", str(e.exception))
#test for infs
with self.assertRaises(ValueError) as e:
cfunc(np.array([1, 2, np.inf, 4]))
self.assertIn("array must not contain infs or NaNs", str(e.exception))
#test for dtype
with self.assertRaises(TypingError) as e:
cfunc(np.array([1, 2, 3, 4]), 'float32')
self.assertIn("dtype must be a valid Numpy dtype", str(e.exception))
def test_unwrap_basic(self):
pyfunc = unwrap
cfunc = njit(pyfunc)
pyfunc1 = unwrap1
cfunc1 = njit(pyfunc1)
pyfunc13 = unwrap13
cfunc13 = njit(pyfunc13)
pyfunc123 = unwrap123
cfunc123 = njit(pyfunc123)
# Based on tests from https://github.com/numpy/numpy/blob/3032e84ff34f20def2ef4ebf9f8695947af3fd24/numpy/lib/tests/test_function_base.py#L1979-L2003 # noqa: E501
# Additional tests are included to ensure proper support for
# higher dimensional arrays
# p only
def inputs1():
yield np.array([1, 1 + 2 * np.pi])
phase = np.linspace(0, np.pi, num=5)
phase[3:] += np.pi
yield phase
yield np.arange(16).reshape((4,4))
yield np.arange(160, step=10).reshape((4,4))
yield np.arange(240, step=10).reshape((2,3,4))
for p in inputs1():
self.assertPreciseEqual(pyfunc1(p), cfunc1(p))
uneven_seq = np.array([0, 75, 150, 225, 300, 430])
wrap_uneven = np.mod(uneven_seq, 250)
# p and period only
def inputs13():
yield np.array([1, 1 + 256]), 255
yield np.array([0, 75, 150, 225, 300]), 255
yield np.array([0, 1, 2, -1, 0]), 4
yield np.array([2, 3, 4, 5, 2, 3, 4, 5]), 4
yield wrap_uneven, 250
# check that you can set axis=-1 without errors
self.assertPreciseEqual(pyfunc(wrap_uneven, axis=-1, period=250),
cfunc(wrap_uneven, axis=-1, period=250))
for p, period in inputs13():
self.assertPreciseEqual(pyfunc13(p, period=period),
cfunc13(p, period=period))
# p, period and discont
def inputs123():
yield wrap_uneven, 250, 140
for p, period, discont in inputs123():
self.assertPreciseEqual(pyfunc123(p, period=period,
discont=discont),
cfunc123(p, period=period,
discont=discont))
def test_unwrap_exception(self):
cfunc = njit(unwrap)
self.disable_leak_check()
with self.assertRaises(TypingError) as e:
cfunc('abc')
self.assertIn('The argument "p" must be array-like',
str(e.exception))
with self.assertRaises(TypingError) as e:
cfunc(np.array([1, 2]), 'abc')
self.assertIn('The argument "discont" must be a scalar',
str(e.exception))
with self.assertRaises(TypingError) as e:
cfunc(np.array([1, 2]), 3, period='abc')
self.assertIn('The argument "period" must be a scalar',
str(e.exception))
with self.assertRaises(TypingError) as e:
cfunc(np.array([1, 2]), 3, axis='abc')
self.assertIn('The argument "axis" must be an integer',
str(e.exception))
with self.assertRaises(ValueError) as e:
cfunc(np.array([1, 2]), 3, axis=2)
self.assertIn('Value for argument "axis" is not supported',
str(e.exception))
def test_swapaxes_basic(self):
pyfunc = swapaxes
cfunc = jit(nopython=True)(pyfunc)
def a_variations():
yield np.arange(10)
yield np.arange(10).reshape(2, 5)
yield np.arange(60).reshape(5, 4, 3)
for a in a_variations():
for a1 in range(-a.ndim, a.ndim):
for a2 in range(-a.ndim, a.ndim):
expected = pyfunc(a, a1, a2)
got = cfunc(a, a1, a2)
self.assertPreciseEqual(expected, got)
def test_swapaxes_exception(self):
pyfunc = swapaxes
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
with self.assertRaises(TypingError) as raises:
cfunc('abc', 0, 0)
self.assertIn('The first argument "a" must be an array',
str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc(np.arange(4), 'abc', 0)
self.assertIn('The second argument "axis1" must be an integer',
str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc(np.arange(4), 0, 'abc')
self.assertIn('The third argument "axis2" must be an integer',
str(raises.exception))
with self.assertRaises(ValueError) as raises:
cfunc(np.arange(4), 1, 0)
self.assertIn('np.swapaxes: Argument axis1 out of bounds',
str(raises.exception))
with self.assertRaises(ValueError) as raises:
cfunc(np.arange(8).reshape(2, 4), 0, -3)
self.assertIn('np.swapaxes: Argument axis2 out of bounds',
str(raises.exception))
def test_take_along_axis(self):
a = np.arange(24).reshape((3, 1, 4, 2))
# For now axis must be literal, test explicitly defined implementations
@njit
def axis_none(a, i):
return np.take_along_axis(a, i, axis=None)
indices = np.array([1, 2], dtype=np.uint64)
self.assertPreciseEqual(axis_none(a, indices),
axis_none.py_func(a, indices))
def gen(axis):
@njit
def impl(a, i):
return np.take_along_axis(a, i, axis)
return impl
for i in range(-1, a.ndim):
jfunc = gen(i)
ai = np.argsort(a, axis=i)
self.assertPreciseEqual(jfunc(a, ai), jfunc.py_func(a, ai))
def test_take_along_axis_broadcasting(self):
# Based on
# https://github.com/numpy/numpy/blob/v1.21.0/numpy/lib/tests/test_shape_base.py#L74-L79
# This demonstrates that arrays are broadcast before the algorithm is
# applied.
arr = np.ones((3, 4, 1))
ai = np.ones((1, 2, 5), dtype=np.intp)
def gen(axis):
@njit
def impl(a, i):
return np.take_along_axis(a, i, axis)
return impl
# Check same axis but expressed as positive/negative value
for i in (1, -2):
check = gen(i)
expected = check.py_func(arr, ai)
actual = check(arr, ai)
self.assertPreciseEqual(expected, actual)
self.assertEqual(actual.shape, (3, 2, 5))
def test_take_along_axis_exceptions(self):
arr2d = np.arange(8).reshape(2, 4)
# Valid indices when axis=None is passed to take_along_axis:
indices_none = np.array([0, 1], dtype=np.uint64)
indices = np.ones((2, 4), dtype=np.uint64)
# For now axis must be literal, so we need to construct functions with
# explicit axis:
def gen(axis):
@njit
def impl(a, i):
return np.take_along_axis(a, i, axis)
return impl
with self.assertRaises(TypingError) as raises:
gen("a")(arr2d, indices)
self.assertIn("axis must be an integer", str(raises.exception))
with self.assertRaises(TypingError) as raises:
gen(-3)(arr2d, indices)
self.assertIn("axis is out of bounds", str(raises.exception))
with self.assertRaises(TypingError) as raises:
gen(2)(arr2d, indices)
self.assertIn("axis is out of bounds", str(raises.exception))
with self.assertRaises(TypingError) as raises:
gen(None)(12, indices_none)
self.assertIn('"arr" must be an array', str(raises.exception))
with self.assertRaises(TypingError) as raises:
gen(None)(arr2d, 5)
self.assertIn('"indices" must be an array', str(raises.exception))
with self.assertRaises(TypingError) as raises:
gen(None)(arr2d, np.array([0.0, 1.0]))
self.assertIn(
'indices array must contain integers',
str(raises.exception)
)
@njit
def not_literal_axis(a, i, axis):
return np.take_along_axis(a, i, axis)
with self.assertRaises(TypingError) as raises:
not_literal_axis(arr2d, indices, 0)
self.assertIn("axis must be a literal value", str(raises.exception))
with self.assertRaises(TypingError) as raises:
gen(0)(arr2d, np.array([0, 1], dtype=np.uint64))
self.assertIn("must have the same number of dimensions",
str(raises.exception))
# With axis None, array's ndim is implicitly 1.
with self.assertRaises(TypingError) as raises:
gen(None)(arr2d, arr2d)
self.assertIn("must have the same number of dimensions",
str(raises.exception))
with self.assertRaises(ValueError) as raises:
gen(0)(arr2d, np.ones((2, 3), dtype=np.uint64))
self.assertIn("dimensions don't match", str(raises.exception))
# Exceptions leak references
self.disable_leak_check()
def test_nan_to_num(self):
# Test cases are from
# https://github.com/numpy/numpy/blob/8ff45c5bb520db04af8720bf1d34a392a8d2561a/numpy/lib/tests/test_type_check.py#L350-L452
values = [
np.nan,
1,
1.1,
1 + 1j,
complex(-np.inf, np.nan),
complex(np.nan, np.nan),
np.array([1], dtype=int),
np.array([complex(-np.inf, np.inf), complex(1, np.nan),
complex(np.nan, 1), complex(np.inf, -np.inf)]),
np.array([0.1, 1.0, 0.4]),
np.array([1, 2, 3]),
np.array([[0.1, 1.0, 0.4], [0.4, 1.2, 4.0]]),
np.array([0.1, np.nan, 0.4]),
np.array([[0.1, np.nan, 0.4], [np.nan, 1.2, 4.0]]),
np.array([-np.inf, np.nan, np.inf]),
np.array([-np.inf, np.nan, np.inf], dtype=np.float32)
]
nans = [0.0, 10]
posinfs = [None, 1000.0]
neginfs = [None, -1000.0]
pyfunc = nan_to_num
cfunc = njit(nan_to_num)
for value, nan, posinf, neginf in product(
values, nans, posinfs, neginfs
):
expected = pyfunc(value, nan=nan, posinf=posinf, neginf=neginf)
got = cfunc(value, nan=nan, posinf=posinf, neginf=neginf)
self.assertPreciseEqual(expected, got)
def test_nan_to_num_copy_false(self):
# Check that copy=False operates in-place.
cfunc = njit(nan_to_num)
x = np.array([0.1, 0.4, np.nan, np.inf, -np.inf])
expected = np.array([1.0, 1000.0, -1000.0])
cfunc(
x,
copy=False,
nan=expected[0],
posinf=expected[1],
neginf=expected[2]
)
self.assertPreciseEqual(x[-3:], expected)
x_complex = np.array(
[
0.1,
0.4,
complex(np.nan, np.nan),
complex(np.inf, np.nan),
complex(np.nan, -np.inf)
]
)
cfunc(
x_complex,
copy=False,
nan=expected[0],
posinf=expected[1],
neginf=expected[2]
)
self.assertPreciseEqual(
x_complex[-3:],
np.array([1. + 1.j, 1e3 + 1.j, 1. - 1000.j])
)
def test_nan_to_num_invalid_argument(self):
cfunc = njit(nan_to_num)
with self.assertTypingError() as raises:
cfunc("invalid_input")
self.assertIn("The first argument must be a scalar or an array-like",
str(raises.exception))
def test_diagflat_basic(self):
pyfunc1 = diagflat1
cfunc1 = njit(pyfunc1)
pyfunc2 = diagflat2
cfunc2 = njit(pyfunc2)
def inputs():
yield np.array([1,2]), 1
yield np.array([[1,2],[3,4]]), -2
yield np.arange(8).reshape((2,2,2)), 2
yield [1, 2], 1
yield np.array([]), 1
for v, k in inputs():
self.assertPreciseEqual(pyfunc1(v), cfunc1(v))
self.assertPreciseEqual(pyfunc2(v, k), cfunc2(v, k))
def test_diagflat1_exception(self):
pyfunc = diagflat1
cfunc = njit(pyfunc)
self.disable_leak_check()
with self.assertRaises(TypingError) as raises:
cfunc("abc")
self.assertIn('The argument "v" must be array-like',
str(raises.exception))
def test_diagflat2_exception(self):
pyfunc = diagflat2
cfunc = njit(pyfunc)
self.disable_leak_check()
with self.assertRaises(TypingError) as raises:
cfunc("abc", 2)
self.assertIn('The argument "v" must be array-like',
str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc([1, 2], "abc")
self.assertIn('The argument "k" must be an integer',
str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc([1, 2], 3.0)
self.assertIn('The argument "k" must be an integer',
str(raises.exception))
@staticmethod
def _setxor_arrays():
yield (List.empty_list(types.float64),
List.empty_list(types.float64)) # two empty arrays
yield [1], List.empty_list(types.float64) # empty right
yield List.empty_list(types.float64), [1] # empty left
yield [1], [2] # singletons - xor == union
yield [1], [1] # singletons - xor == nothing
yield [1, 2], [1]
yield [1, 2, 2], [2, 2]
yield [1, 2, 2], [2, 2, 3]
yield [1, 2], [2, 1]
yield [1, 2, 3], [1, 2, 3]
yield [2, 3, 4, 0], [1, 3]
# from numpy:
# https://github.com/numpy/numpy/blob/b0371ef240560e78b651a5d7c9407ae3212a3d56/numpy/lib/tests/test_arraysetops.py#L86 # noqa: E501
yield [5, 7, 1, 2], [2, 4, 3, 1, 5]
yield [1, 2, 3], [6, 5, 4]
yield [1, 8, 2, 3], [1, 2, 3, 4, 5, 6]
def test_setxor1d_2(self):
np_pyfunc = np_setxor1d_2
np_nbfunc = njit(np_pyfunc)
def check(ar1, ar2):
if isinstance(ar1, list):
ar1 = List(ar1)
if isinstance(ar2, list):
ar2 = List(ar2)
expected = np_pyfunc(ar1, ar2)
got = np_nbfunc(ar1, ar2)
self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}")
for a, b in self._setxor_arrays():
check(a, b)
def test_setxor1d_3(self):
np_pyfunc = np_setxor1d_3
np_nbfunc = njit(np_pyfunc)
def check(ar1, ar2, assume_unique=False):
if isinstance(ar1, list):
ar1 = List(ar1)
if isinstance(ar2, list):
ar2 = List(ar2)
expected = np_pyfunc(ar1, ar2, assume_unique)
got = np_nbfunc(ar1, ar2, assume_unique)
self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}")
for a, b in self._setxor_arrays():
check(a, b)
if len(np.unique(a)) == len(a) and len(np.unique(b)) == len(b):
check(a, b, True)
def test_setxor1d_errors(self):
np_pyfunc = np_setxor1d_3
np_nbfunc = njit(np_pyfunc)
a = np.array([1])
b = np.array([2])
self.disable_leak_check()
with self.assertRaises(TypingError):
np_nbfunc(a, b, "foo")
with self.assertRaises(TypingError):
np_nbfunc("foo", b, True)
with self.assertRaises(TypingError):
np_nbfunc(a, "foo", True)
@staticmethod
def _setdiff_arrays():
yield (List.empty_list(types.float64),
List.empty_list(types.float64)) # two empty arrays
yield [1], List.empty_list(types.float64) # empty right
yield List.empty_list(types.float64), [1] # empty left
yield [1], [2] # singletons - diff == [1]
yield [1], [1] # singletons - diff == nothing
yield [1, 2], [1]
yield [1, 2, 2], [2, 2]
yield [1, 2, 2], [2, 2, 3]
yield [1, 2], [2, 1]
yield [1, 2, 3], [1, 2, 3]
yield [2, 3, 4, 0], [1, 3]
# https://github.com/numpy/numpy/blob/b0371ef240560e78b651a5d7c9407ae3212a3d56/numpy/lib/tests/test_arraysetops.py#L558 # noqa: E501
yield (np.array([6, 5, 4, 7, 1, 2, 7, 4]),
np.array([2, 4, 3, 3, 2, 1, 5]))
yield np.arange(21), np.arange(19)
yield np.array([3, 2, 1]), np.array([7, 5, 2])
def test_setdiff1d_2(self):
np_pyfunc = np_setdiff1d_2
np_nbfunc = njit(np_pyfunc)
def check(ar1, ar2):
if isinstance(ar1, list):
ar1 = List(ar1)
if isinstance(ar2, list):
ar2 = List(ar2)
expected = np_pyfunc(ar1, ar2)
got = np_nbfunc(ar1, ar2)
self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}")
for a, b in self._setdiff_arrays():
check(a, b)
def test_setdiff1d_3(self):
np_pyfunc = np_setdiff1d_3
np_nbfunc = njit(np_pyfunc)
def check(ar1, ar2, assume_unique=False):
if isinstance(ar1, list):
ar1 = List(ar1)
if isinstance(ar2, list):
ar2 = List(ar2)
expected = np_pyfunc(ar1, ar2, assume_unique)
got = np_nbfunc(ar1, ar2, assume_unique)
self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}")
for a, b in self._setdiff_arrays():
check(a, b)
if len(np.unique(a)) == len(a) and len(np.unique(b)) == len(b):
check(a, b, True)
def test_setdiff1d_errors(self):
np_pyfunc = np_setdiff1d_3
np_nbfunc = njit(np_pyfunc)
a = np.array([1])
b = np.array([2])
self.disable_leak_check()
with self.assertRaises(TypingError):
np_nbfunc(a, b, "foo")
with self.assertRaises(TypingError):
np_nbfunc("foo", b, True)
with self.assertRaises(TypingError):
np_nbfunc(a, "foo", True)
@staticmethod
def _in1d_arrays():
yield (List.empty_list(types.float64),
List.empty_list(types.float64)) # two empty arrays
yield [1], List.empty_list(types.float64) # empty right
yield List.empty_list(types.float64), [1] # empty left
yield [1], [2] # singletons - False
yield [1], [1] # singletons - True
yield [1, 2], [1]
yield [1, 2, 2], [2, 2]
yield [1, 2, 2], [2, 2, 3]
yield [1, 2], [2, 1]
yield [1, 2, 3], [1, 2, 3]
yield [2, 3, 4, 0], [3, 1]
yield [2, 3], np.arange(20) # Test the "sorting" method.
yield [2, 3], np.tile(np.arange(5), 4)
def test_in1d_2(self):
np_pyfunc = np_in1d_2
np_nbfunc = njit(np_pyfunc)
def check(ar1, ar2):
if isinstance(ar1, list):
ar1 = List(ar1)
if isinstance(ar2, list):
ar2 = List(ar2)
expected = np_pyfunc(ar1, ar2)
got = np_nbfunc(ar1, ar2)
self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}")
for a, b in self._in1d_arrays():
check(a, b)
def test_in1d_3a(self):
np_pyfunc = np_in1d_3a
np_nbfunc = njit(np_pyfunc)
def check(ar1, ar2, assume_unique=False):
if isinstance(ar1, list):
ar1 = List(ar1)
if isinstance(ar2, list):
ar2 = List(ar2)
expected = np_pyfunc(ar1, ar2, assume_unique)
got = np_nbfunc(ar1, ar2, assume_unique)
self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}")
for a, b in self._in1d_arrays():
check(a, b)
if len(np.unique(a)) == len(a) and len(np.unique(b)) == len(b):
check(a, b, assume_unique=True)
def test_in1d_3b(self):
np_pyfunc = np_in1d_3b
np_nbfunc = njit(np_pyfunc)
def check(ar1, ar2, invert=False):
if isinstance(ar1, list):
ar1 = List(ar1)
if isinstance(ar2, list):
ar2 = List(ar2)
expected = np_pyfunc(ar1, ar2, invert)
got = np_nbfunc(ar1, ar2, invert)
self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}")
for a, b in self._in1d_arrays():
check(a, b, invert=False)
check(a, b, invert=True)
def test_in1d_4(self):
np_pyfunc = np_in1d_4
np_nbfunc = njit(np_pyfunc)
def check(ar1, ar2, assume_unique=False, invert=False):
if isinstance(ar1, list):
ar1 = List(ar1)
if isinstance(ar2, list):
ar2 = List(ar2)
expected = np_pyfunc(ar1, ar2, assume_unique, invert)
got = np_nbfunc(ar1, ar2, assume_unique, invert)
self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}")
for a, b in self._in1d_arrays():
check(a, b, invert=False)
check(a, b, invert=True)
if len(np.unique(a)) == len(a) and len(np.unique(b)) == len(b):
check(a, b, assume_unique=True, invert=False)
check(a, b, assume_unique=True, invert=True)
def test_in1d_errors(self):
np_pyfunc = np_in1d_4
np_nbfunc = njit(np_pyfunc)
a = np.array([1])
b = np.array([2])
x = np_nbfunc(a, b)
self.assertPreciseEqual(x, np.array([False]))
self.disable_leak_check()
with self.assertRaises(TypingError):
np_nbfunc(a, b, "foo", False)
with self.assertRaises(TypingError):
np_nbfunc(a, b, False, "foo")
with self.assertRaises(TypingError):
np_nbfunc("foo", b, True, False)
with self.assertRaises(TypingError):
np_nbfunc(a, "foo", True, False)
@njit()
def np_in1d_kind(a, b, kind):
return np.in1d(a, b, kind=kind)
with self.assertRaises(TypingError):
np_in1d_kind(a, b, kind=None)
with self.assertRaises(TypingError):
np_in1d_kind(a, b, kind="table")
@classmethod
def _isin_arrays(cls):
if REDUCED_TESTING:
return cls._isin_arrays_reduced()
else:
return cls._isin_arrays_full()
@staticmethod
def _isin_arrays_reduced():
# Minimal test cases for memory optimization
yield [1], [1] # singletons - True
yield [1], [2] # singletons - False
yield [2, 3], [3, 4] # basic arrays
# One numpy array test
a = np.arange(4).reshape([2, 2])
b = np.array([2, 3])
yield a, b
@staticmethod
def _isin_arrays_full():
yield (List.empty_list(types.float64),
List.empty_list(types.float64)) # two empty arrays
yield (np.zeros((1, 0), dtype=np.int64),
List.empty_list(types.int64)) # two-dim array - shape (1, 0)
yield (np.zeros((0, 0), dtype=np.int64),
List.empty_list(types.int64))
yield (np.zeros((0, 1), dtype=np.int64),
List.empty_list(types.int64))
yield [1], List.empty_list(types.float64) # empty right
yield List.empty_list(types.float64), [1] # empty left
yield [1], [2] # singletons - False
yield [1], [1] # singletons - True
yield [1, 2], [1]
yield [1, 2, 2], [2, 2]
yield [1, 2, 2], [2, 2, 3]
yield [1, 2], [2, 1]
yield [2, 3], np.arange(20) # Test the "sorting" method.
yield [2, 3], np.tile(np.arange(5), 4)
yield np.arange(30).reshape(2, 3, 5), [5, 7, 10, 15] # 3d
# from numpy
# https://github.com/numpy/numpy/blob/b0371ef240560e78b651a5d7c9407ae3212a3d56/numpy/lib/tests/test_arraysetops.py#L200 # noqa: E501
a = np.arange(24).reshape([2, 3, 4])
b = np.array([[10, 20, 30], [0, 1, 3], [11, 22, 33]])
yield a, b
yield np.array(3), b
yield a, np.array(3)
yield np.array(3), np.array(3)
yield 5, b
yield a, 6
yield 5, 6
yield List.empty_list(types.int64), b
yield a, List.empty_list(types.int64)
for dtype in [bool, np.int64, np.float64]:
if dtype in {np.int64, np.float64}:
ar = np.array([10, 20, 30], dtype=dtype)
elif dtype in {bool}:
ar = np.array([True, False, False])
empty_array = np.array([], dtype=dtype)
yield empty_array, ar
yield ar, empty_array
yield empty_array, empty_array
for mult in (1, 10):
yield [5, 7, 1, 2], [2, 4, 3, 1, 5] * mult
yield [8, 7, 1, 2], [2, 4, 3, 1, 5] * mult
yield [4, 7, 1, 8], [2, 4, 3, 1, 5] * mult
a = [5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5]
yield a, [2, 3, 4] * mult
yield a, [2, 3, 4] * mult + [5, 5, 4] * mult
yield np.array([5, 7, 1, 2]), np.array([2, 4, 3, 1, 5] * mult)
yield np.array([5, 7, 1, 1, 2]), np.array([2, 4, 3, 3, 1, 5] * mult)
yield np.array([5, 5]), np.array([2, 2] * mult)
yield np.array([5]), np.array([2])
yield np.array([True, False]), np.array([False, False, False])
for dtype1, dtype2 in [
(np.int8, np.int16),
(np.int16, np.int8),
(np.uint8, np.uint16),
(np.uint16, np.uint8),
(np.uint8, np.int16),
(np.int16, np.uint8),
]:
is_dtype2_signed = np.issubdtype(dtype2, np.signedinteger)
ar1 = np.array([0, 0, 1, 1], dtype=dtype1)
if is_dtype2_signed:
ar2 = np.array([-128, 0, 127], dtype=dtype2)
else:
ar2 = np.array([127, 0, 255], dtype=dtype2)
yield ar1, ar2
for dtype in np.typecodes["AllInteger"]:
a = np.array([True, False, False], dtype=bool)
b = np.array([0, 0, 0, 0], dtype=dtype)
yield a, b
yield b, a
def test_isin_2(self):
np_pyfunc = np_isin_2
np_nbfunc = njit(np_pyfunc)
def check(ar1, ar2):
expected = np_pyfunc(ar1, ar2)
if isinstance(ar1, list):
ar1 = List(ar1)
if isinstance(ar2, list):
ar2 = List(ar2)
got = np_nbfunc(ar1, ar2)
self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}")
for a, b in self._isin_arrays():
check(a, b)
@skip_if_reduced_testing
def test_isin_3a(self):
np_pyfunc = np_isin_3a
np_nbfunc = njit(np_pyfunc)
def check(ar1, ar2, assume_unique=False):
expected = np_pyfunc(ar1, ar2, assume_unique)
if isinstance(ar1, list):
ar1 = List(ar1)
if isinstance(ar2, list):
ar2 = List(ar2)
got = np_nbfunc(ar1, ar2, assume_unique)
self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}")
for a, b in self._isin_arrays():
check(a, b)
try:
len_a = len(a)
except TypeError:
len_a = 1
try:
len_b = len(b)
except TypeError:
len_b = 1
if len(np.unique(a)) == len_a and len(np.unique(b)) == len_b:
check(a, b, assume_unique=True)
@skip_if_reduced_testing
def test_isin_3b(self):
np_pyfunc = np_isin_3b
np_nbfunc = njit(np_pyfunc)
def check(ar1, ar2, invert=False):
expected = np_pyfunc(ar1, ar2, invert)
if isinstance(ar1, list):
ar1 = List(ar1)
if isinstance(ar2, list):
ar2 = List(ar2)
got = np_nbfunc(ar1, ar2, invert)
self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}")
for a, b in self._isin_arrays():
check(a, b, invert=False)
check(a, b, invert=True)
@skip_if_reduced_testing
def test_isin_4(self):
np_pyfunc = np_isin_4
np_nbfunc = njit(np_pyfunc)
def check(ar1, ar2, assume_unique=False, invert=False):
expected = np_pyfunc(ar1, ar2, assume_unique, invert)
if isinstance(ar1, list):
ar1 = List(ar1)
if isinstance(ar2, list):
ar2 = List(ar2)
got = np_nbfunc(ar1, ar2, assume_unique, invert)
self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}")
for a, b in self._isin_arrays():
check(a, b, invert=False)
check(a, b, invert=True)
try:
len_a = len(a)
except TypeError:
len_a = 1
try:
len_b = len(b)
except TypeError:
len_b = 1
if len(np.unique(a)) == len_a and len(np.unique(b)) == len_b:
check(a, b, assume_unique=True, invert=False)
check(a, b, assume_unique=True, invert=True)
def test_isin_errors(self):
np_pyfunc = np_isin_4
np_nbfunc = njit(np_pyfunc)
a = np.array([1])
b = np.array([2])
x = np_nbfunc(a, b)
self.assertPreciseEqual(x, np.array([False]))
self.disable_leak_check()
with self.assertRaises(TypingError):
np_nbfunc(a, b, "foo", False)
with self.assertRaises(TypingError):
np_nbfunc(a, b, False, "foo")
with self.assertRaises(TypingError):
np_nbfunc("foo", b, True, False)
with self.assertRaises(TypingError):
np_nbfunc(a, "foo", True, False)
@njit()
def np_isin_kind(a, b, kind):
return np.isin(a, b, kind=kind)
with self.assertRaises(TypingError):
np_isin_kind(a, b, kind=None)
with self.assertRaises(TypingError):
np_isin_kind(a, b, kind="table")
def test_setops_manyways(self):
# https://github.com/numpy/numpy/blob/b0371ef240560e78b651a5d7c9407ae3212a3d56/numpy/lib/tests/test_arraysetops.py#L588 # noqa: E501
nb_setxor1d = njit(np_setxor1d_2)
nb_intersect1d = njit(intersect1d_2)
nb_union1d = njit(np_union1d)
nb_setdiff1d = njit(np_setdiff1d_2)
a = np.array([5, 7, 1, 2, 8])
b = np.array([9, 8, 2, 4, 3, 1, 5])
c1 = nb_setxor1d(a, b)
aux1 = nb_intersect1d(a, b)
aux2 = nb_union1d(a, b)
c2 = nb_setdiff1d(aux2, aux1)
self.assertPreciseEqual(c1, c2)
|
TestNPFunctions
|
python
|
pytorch__pytorch
|
test/distributed/elastic/multiprocessing/redirects_test.py
|
{
"start": 550,
"end": 4749
}
|
class ____(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.mkdtemp(prefix=f"{self.__class__.__name__}_")
def tearDown(self):
shutil.rmtree(self.test_dir)
def test_redirect_invalid_std(self):
with self.assertRaises(ValueError):
with redirect("stdfoo", os.path.join(self.test_dir, "stdfoo.log")):
pass
def test_redirect_stdout(self):
stdout_log = os.path.join(self.test_dir, "stdout.log")
# printing to stdout before redirect should go to console not stdout.log
print("foo first from python")
libc.printf(b"foo first from c\n")
os.system("echo foo first from cmd")
with redirect_stdout(stdout_log):
print("foo from python")
libc.printf(b"foo from c\n")
os.system("echo foo from cmd")
# make sure stdout is restored
print("foo again from python")
libc.printf(b"foo again from c\n")
os.system("echo foo again from cmd")
with open(stdout_log) as f:
# since we print from python, c, cmd -> the stream is not ordered
# do a set comparison
lines = set(f.readlines())
self.assertEqual(
{"foo from python\n", "foo from c\n", "foo from cmd\n"}, lines
)
def test_redirect_stderr(self):
stderr_log = os.path.join(self.test_dir, "stderr.log")
print("bar first from python")
libc.fprintf(c_stderr, b"bar first from c\n")
os.system("echo bar first from cmd 1>&2")
with redirect_stderr(stderr_log):
print("bar from python", file=sys.stderr)
libc.fprintf(c_stderr, b"bar from c\n")
os.system("echo bar from cmd 1>&2")
print("bar again from python")
libc.fprintf(c_stderr, b"bar again from c\n")
os.system("echo bar again from cmd 1>&2")
with open(stderr_log) as f:
lines = set(f.readlines())
self.assertEqual(
{"bar from python\n", "bar from c\n", "bar from cmd\n"}, lines
)
def test_redirect_both(self):
stdout_log = os.path.join(self.test_dir, "stdout.log")
stderr_log = os.path.join(self.test_dir, "stderr.log")
print("first stdout from python")
libc.printf(b"first stdout from c\n")
print("first stderr from python", file=sys.stderr)
libc.fprintf(c_stderr, b"first stderr from c\n")
with redirect_stdout(stdout_log), redirect_stderr(stderr_log):
print("redir stdout from python")
print("redir stderr from python", file=sys.stderr)
libc.printf(b"redir stdout from c\n")
libc.fprintf(c_stderr, b"redir stderr from c\n")
print("again stdout from python")
libc.fprintf(c_stderr, b"again stderr from c\n")
with open(stdout_log) as f:
lines = set(f.readlines())
self.assertEqual(
{"redir stdout from python\n", "redir stdout from c\n"}, lines
)
with open(stderr_log) as f:
lines = set(f.readlines())
self.assertEqual(
{"redir stderr from python\n", "redir stderr from c\n"}, lines
)
def _redirect_large_buffer(self, print_fn, num_lines=500_000):
stdout_log = os.path.join(self.test_dir, "stdout.log")
with redirect_stdout(stdout_log):
for i in range(num_lines):
print_fn(i)
with open(stdout_log) as fp:
actual = {int(line.split(":")[1]) for line in fp}
expected = set(range(num_lines))
self.assertSetEqual(expected, actual)
def test_redirect_large_buffer_py(self):
def py_print(i):
print(f"py:{i}")
self._redirect_large_buffer(py_print)
def test_redirect_large_buffer_c(self):
def c_print(i):
libc.printf(bytes(f"c:{i}\n", "utf-8"))
self._redirect_large_buffer(c_print)
if __name__ == "__main__":
raise RuntimeError(
"This test is not currently used and should be "
"enabled in discover_tests.py if required."
)
|
RedirectsTest
|
python
|
ray-project__ray
|
python/ray/_private/thirdparty/pynvml/pynvml.py
|
{
"start": 67873,
"end": 68134
}
|
class ____(_PrintableStructure):
_fields_ = [
('pid', c_uint),
('timeStamp', c_ulonglong),
('smUtil', c_uint),
('memUtil', c_uint),
('encUtil', c_uint),
('decUtil', c_uint),
]
|
c_nvmlProcessUtilizationSample_t
|
python
|
encode__django-rest-framework
|
tests/schemas/views.py
|
{
"start": 901,
"end": 1225
}
|
class ____(APIView):
"""
get: A description of my GET operation.
post: A description of my POST operation.
"""
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def get(self, *args, **kwargs):
pass
def post(self, request, *args, **kwargs):
pass
|
DocStringExampleListView
|
python
|
boto__boto3
|
tests/functional/test_s3.py
|
{
"start": 8518,
"end": 12573
}
|
class ____(BaseTransferTest):
def setUp(self):
super().setUp()
self.contents = io.BytesIO(b'foo\n')
def stub_put_object(self):
put_object_response = {
"ETag": self.etag,
"ResponseMetadata": {"HTTPStatusCode": 200},
}
expected_params = {
"Bucket": self.bucket,
"Key": self.key,
"Body": botocore.stub.ANY,
"ChecksumAlgorithm": DEFAULT_CHECKSUM_ALGORITHM,
}
self.stubber.add_response(
method='put_object',
service_response=put_object_response,
expected_params=expected_params,
)
def stub_upload_part(self, part_number):
upload_part_response = {
'ETag': self.etag,
'ResponseMetadata': {'HTTPStatusCode': 200},
'ChecksumCRC32': f'sum{part_number}==',
}
expected_params = {
"Bucket": self.bucket,
"Key": self.key,
"Body": botocore.stub.ANY,
"PartNumber": part_number,
"UploadId": self.upload_id,
'ChecksumAlgorithm': 'CRC32',
}
self.stubber.add_response(
method='upload_part',
service_response=upload_part_response,
expected_params=expected_params,
)
def stub_multipart_upload(self, num_parts):
self.stub_create_multipart_upload(
extra_expected_params={
"ChecksumAlgorithm": DEFAULT_CHECKSUM_ALGORITHM,
}
)
# Add the responses for each UploadPartCopy
parts = []
for i in range(num_parts):
# Fill in the parts
part_number = i + 1
self.stub_upload_part(part_number=part_number)
parts.append(
{
'ETag': self.etag,
'PartNumber': part_number,
'ChecksumCRC32': f'sum{part_number}==',
}
)
self.stub_complete_multipart_upload(parts)
def test_client_upload(self):
self.stub_put_object()
with self.stubber:
# The stubber will assert that all the right parameters are called.
self.s3.meta.client.upload_fileobj(
Fileobj=self.contents, Bucket=self.bucket, Key=self.key
)
self.stubber.assert_no_pending_responses()
def test_raises_value_error_on_invalid_fileobj(self):
with self.stubber:
with pytest.raises(ValueError):
self.s3.meta.client.upload_fileobj(
Fileobj='foo', Bucket=self.bucket, Key=self.key
)
def test_bucket_upload(self):
self.stub_put_object()
bucket = self.s3.Bucket(self.bucket)
with self.stubber:
# The stubber will assert that all the right parameters are called.
bucket.upload_fileobj(Fileobj=self.contents, Key=self.key)
self.stubber.assert_no_pending_responses()
def test_object_upload(self):
self.stub_put_object()
obj = self.s3.Object(self.bucket, self.key)
with self.stubber:
# The stubber will assert that all the right parameters are called.
obj.upload_fileobj(Fileobj=self.contents)
self.stubber.assert_no_pending_responses()
def test_multipart_upload(self):
chunksize = 8 * (1024**2)
contents = io.BytesIO(b'0' * (chunksize * 3))
self.stub_multipart_upload(num_parts=3)
transfer_config = TransferConfig(
multipart_chunksize=chunksize,
multipart_threshold=1,
max_concurrency=1,
)
with self.stubber:
# The stubber will assert that all the right parameters are called.
self.s3.meta.client.upload_fileobj(
Fileobj=contents,
Bucket=self.bucket,
Key=self.key,
Config=transfer_config,
)
self.stubber.assert_no_pending_responses()
|
TestUploadFileobj
|
python
|
doocs__leetcode
|
solution/0400-0499/0474.Ones and Zeroes/Solution.py
|
{
"start": 0,
"end": 539
}
|
class ____:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
sz = len(strs)
f = [[[0] * (n + 1) for _ in range(m + 1)] for _ in range(sz + 1)]
for i, s in enumerate(strs, 1):
a, b = s.count("0"), s.count("1")
for j in range(m + 1):
for k in range(n + 1):
f[i][j][k] = f[i - 1][j][k]
if j >= a and k >= b:
f[i][j][k] = max(f[i][j][k], f[i - 1][j - a][k - b] + 1)
return f[sz][m][n]
|
Solution
|
python
|
pytorch__pytorch
|
torch/fx/experimental/const_fold.py
|
{
"start": 324,
"end": 14300
}
|
class ____(torch.fx.GraphModule):
"""
FoldedGraphModule is a GraphModule which also contains another
`const_subgraph_module` representing a subgraph which has all const attr
inputs and which can be run once before running the main standard
`graph`. The `const_output_names` are the ordered list names of attrs which
represent what each respective output from the const_subgraph should be set
on which attrs.
"""
def __init__(
self,
root: torch.nn.Module,
graph: torch.fx.Graph,
const_subgraph: Optional[torch.fx.Graph] = None,
fx_const_folded_attrs_name: Optional[str] = None,
device_for_folded_attrs: str = "cuda",
):
super().__init__(root, graph)
self.const_subgraph_module = (
None
if const_subgraph is None
else torch.fx.GraphModule(root, const_subgraph)
)
self.has_folding_been_run = False
self.fx_const_folded_attrs_name = fx_const_folded_attrs_name
self.device_for_folded_attrs = device_for_folded_attrs
def __call__(self, *args, **kwargs):
if not self.has_folding_been_run:
self.run_folding()
return super().__call__(*args)
def run_folding(self):
# If there's no const subgraph module or attr output names to use, return
# early as there is no const folding to perform.
if (
self.const_subgraph_module is None
or self.fx_const_folded_attrs_name is None
):
return
assert not self.has_folding_been_run
self.has_folding_been_run = True
# Actually run const folding subgraph. Note that single attr const fold
# subgraphs output a single Tensor while multiple outputs are returned as
# Tuple[Tensor,].
folded_attrs = self.const_subgraph_module()
def _create_param(i):
return torch.nn.Parameter(
i.detach().clone()
if not isinstance(i, int)
else torch.Tensor([i]).to(device=self.device_for_folded_attrs),
requires_grad=i.requires_grad if isinstance(i, torch.Tensor) else False,
)
params = (
torch.nn.ParameterList([_create_param(i) for i in folded_attrs])
if isinstance(folded_attrs, tuple)
else _create_param(folded_attrs)
)
setattr(self, self.fx_const_folded_attrs_name, params)
def _inline_module(gm: torch.fx.GraphModule, inline_mod_name: str):
"""
Given `gm` and some graph module which is called with target name `inline_mod_name`,
this helper will inline all of the nodes from that called graph module into `gm`.
"""
# Fetch the inner graph module that we want to inline inside `gm`.
inline_mod = dict(gm.named_modules())[inline_mod_name]
assert isinstance(inline_mod, torch.fx.GraphModule)
call_mod_node_to_replace = None
for node in gm.graph.nodes:
if node.op == "call_module" and node.target == inline_mod_name:
call_mod_node_to_replace = node
break
assert call_mod_node_to_replace is not None
# Now actually do the swap. Note that we have to keep track of new nodes that are
# copied into `gm` -- we do this via replacement_mapping.
call_mod_args = call_mod_node_to_replace.args
call_mod_kwargs = call_mod_node_to_replace.kwargs
replacement_mapping: dict[torch.fx.Node, torch.fx.Node] = {}
ph_count = 0
def replacement_fn(node):
new_node = replacement_mapping[node]
new_node.meta = node.meta.copy()
return new_node
for inline_node in inline_mod.graph.nodes:
if inline_node.op == "placeholder":
replacement_mapping[inline_node] = (
call_mod_kwargs[inline_node.name]
if inline_node.name in call_mod_kwargs
else call_mod_args[ph_count]
)
ph_count += 1
continue
if inline_node.op == "output":
outputs = inline_node.args[0]
output_replacements = map_arg(outputs, replacement_fn)
call_mod_node_to_replace.replace_all_uses_with(output_replacements)
continue
with gm.graph.inserting_before(call_mod_node_to_replace):
new_node = gm.graph.node_copy(inline_node, replacement_fn)
replacement_mapping[inline_node] = new_node
# Explicitly remove the module that was just inlined,
# this module may contain impure ops so cannot be dead code eliminated,
# this module is unneeded as it's just inlined back to main graph.
gm.graph.erase_node(call_mod_node_to_replace)
gm.graph.eliminate_dead_code()
def get_unique_attr_name_in_module(mod_traced: torch.fx.GraphModule, name: str) -> str:
"""
Make sure the name is unique (in a module) and can represents an attr.
"""
# Delete all characters that are illegal in a Python identifier.
name = re.sub("[^0-9a-zA-Z_]+", "_", name)
if name[0].isdigit():
name = f"_{name}"
# Now make sure it is in fact unique to the module by incrementing suffix value.
while hasattr(mod_traced, name):
match = re.match(r"(.*)_(\d+)$", name)
if match is None:
name = name + "_1"
else:
base, num = match.group(1, 2)
name = f"{base}_{int(num) + 1}"
return name
def split_const_subgraphs(
module: Union[torch.nn.Module, torch.fx.GraphModule],
skip_folding_node_fn: Optional[Callable[[torch.fx.Node], bool]] = None,
device_for_folded_attrs: str = "cpu",
) -> FoldedGraphModule:
"""
Looks through `module` for any nodes that have all constant attribute inputs
and separates them out into their own constant subgraph, and returns a
FoldedGraphModule which runs that constant subgraph on the first run to set
attributes on the module prior to running the non-constant portion of the
graph.
"""
import sympy
if not isinstance(module, torch.fx.GraphModule):
mod_traced = torch.fx.symbolic_trace(module)
else:
mod_traced = module
def _subgraph_has_impure_ops(module: torch.fx.GraphModule) -> bool:
"""
Return True if a GraphModule type subgraph contains any impure op, else False.
"""
assert isinstance(module, torch.fx.GraphModule), (
"caller should only pass GraphModule to subgraph_has_impure_ops check"
)
for node in module.graph.nodes:
if node.op == "call_function" and node.is_impure():
return True
if (
# pyrefly: ignore [invalid-argument]
node.op == "call_module"
# pyrefly: ignore [not-callable]
and (submodule := module.get_submodule(node.target))
and isinstance(submodule, torch.fx.GraphModule)
):
return _subgraph_has_impure_ops(submodule)
return False
# Build up a list of const_nodes, defined as nodes that are themselves
# get_attrs, or have all get_attr or other constant node inputs.
const_nodes: set[torch.fx.Node] = set()
found_const_folding = False
for node in mod_traced.graph.nodes:
# Skip over placeholders/outputs because they can't be const folded and
# we don't want to add tags to them.
if node.op in {"placeholder", "output"}:
continue
# If the node itself is constant, or all of its inputs are constant,
# then tag it as constant.
if node.op != "get_attr" and not set(node.all_input_nodes).issubset(
const_nodes
):
continue
# If provided skip folding function says to skip, then skip.
if skip_folding_node_fn and skip_folding_node_fn(node):
continue
# Skip folding side-effectful functions
if node.is_impure():
continue
# Skip folding nodes that have symbolic fill_value
if isinstance(node.kwargs.get("fill_value", None), sympy.Expr):
continue
# Skip folding submodules that have impure ops
if (
# pyrefly: ignore [invalid-argument]
node.op == "call_module"
# pyrefly: ignore [not-callable]
and (target_mod := mod_traced.get_submodule(node.target))
and isinstance(target_mod, torch.fx.GraphModule)
and _subgraph_has_impure_ops(target_mod)
):
continue
# Must be a constant foldable node at this point.
const_nodes.add(node)
if node.op != "get_attr":
found_const_folding = True
# If we did not find any const folding then return early without a const fold subgraph.
if not found_const_folding:
return FoldedGraphModule(mod_traced, mod_traced.graph)
# Partition the module into two: submod_0 for constant folding subgraph, and
# submod_1 for the rest.
def mod_partition(node: torch.fx.Node):
return 0 if node in const_nodes else 1
split = split_module(mod_traced, module, mod_partition)
const_mod_name, non_const_mod_name = "submod_0", "submod_1"
# Safely get submod_1 in case there are no non-const nodes
const_gm, non_const_gm = split.submod_0, getattr(split, non_const_mod_name, None)
# The module that a call_module node refers to gets copied to submodules during split.
# The path to the module also gets inlined, i.e. mod.a.b -> mod_a_b. Here we need to
# attach inlined modules to `split` as it's the owning module now.
for node in non_const_gm.graph.nodes if non_const_gm else []:
if node.op == "call_module":
setattr(split, node.target, getattr(non_const_gm, node.target))
for node in const_gm.graph.nodes:
if node.op == "call_module":
setattr(split, node.target, getattr(const_gm, node.target))
# split_module currently does not use get_attrs for attrs. Instead it passes
# them in as args from the parent module, which used get_attrs. Here we set
# them as get_attrs inside const_gm, allowing for running folding without
# somehow a priori knowing the attrs that should be passed as args. We can
# unconditionally do this for all placeholders because we know all
# placeholders to const_gm must be constants accessible via get_attr.
call_const_gm_args = None
for node in split.graph.nodes:
if node.op == "call_module":
if node.target == const_mod_name:
call_const_gm_args = node.args
break
assert call_const_gm_args is not None
# Here we do the actual replacement of placeholders to get_attrs. Note that here we
# set the const_gm.graph into a new root_const_gm with split as the root module,
# because we are fetching attributes directly from the root module, instead of
# fetching them from const_gm. Example: The const_gm must have some format like:
# graph():
# %inp : [num_users=1] = placeholder[target=const_inp]
# %add : [num_users=1] = call_function[target=operator.add](args = (%inp, %inp), kwargs = {})
# return add
# We replace that with the following, which does not have any placeholders:
# graph():
# %inp_1 : [num_users=1] = get_attr[target=const_inp]
# %add : [num_users=1] = call_function[target=operator.add](args = (%inp_1, %inp_1), kwargs = {})
# return add
root_const_gm = torch.fx.GraphModule(split, const_gm.graph)
# The order of placeholders in the const_gm graph should match the order of
# args in the outer module, so we can simply use an index for the
# placeholder mapping
ph_idx = 0
for node in root_const_gm.graph.nodes:
if node.op == "output":
multiple_outputs = isinstance(node.args[0], tuple)
continue
if node.op != "placeholder":
continue
assert ph_idx < len(call_const_gm_args)
in_node = call_const_gm_args[ph_idx]
ph_idx += 1
assert in_node.op == "get_attr"
with root_const_gm.graph.inserting_before(node):
new_node = root_const_gm.graph.get_attr(in_node.target)
new_node.meta = node.meta.copy()
node.replace_all_uses_with(new_node)
root_const_gm.graph.erase_node(node)
assert "multiple_outputs" in locals()
# Now find the call to const_gm inside split, and replace it with a getattr to the
# folded tensor(s) that result from constant folding. Note that we don't need to
# worry about whether this is one or more tensors because the original graph
# correctly uses getitem to extract individual tensors if there are multiple folded.
fx_const_folded_attrs_name = get_unique_attr_name_in_module(
mod_traced, "_FX_CONST_FOLDED_ATTRS"
)
setattr(
split,
fx_const_folded_attrs_name,
torch.nn.ParameterList() if multiple_outputs else torch.nn.Parameter(), # type: ignore[possibly-undefined]
)
for node in split.graph.nodes:
if node.op == "call_module" and node.target == const_mod_name:
with node.graph.inserting_before(node):
folded_attrs = node.graph.get_attr(fx_const_folded_attrs_name)
folded_attrs.meta = node.meta.copy()
node.replace_all_uses_with(folded_attrs)
break
# Finally, inline the non-constant submod (if it exists) into the split submod.
# This is so that the original caller who may have passed in a graph module will
# get back out a graph module whose graph is traced to the same granularity.
if hasattr(split, non_const_mod_name):
_inline_module(split, non_const_mod_name)
split.graph.eliminate_dead_code()
return FoldedGraphModule(
split,
split.graph,
root_const_gm.graph,
fx_const_folded_attrs_name,
device_for_folded_attrs,
)
|
FoldedGraphModule
|
python
|
sqlalchemy__sqlalchemy
|
test/base/test_utils.py
|
{
"start": 39973,
"end": 40979
}
|
class ____(fixtures.TestBase):
def test_lru(self):
class item:
def __init__(self, id_):
self.id = id_
def __str__(self):
return "item id %d" % self.id
lru = util.LRUCache(10, threshold=0.2)
for id_ in range(1, 20):
lru[id_] = item(id_)
# first couple of items should be gone
assert 1 not in lru
assert 2 not in lru
# next batch over the threshold of 10 should be present
for id_ in range(11, 20):
assert id_ in lru
lru[12]
lru[15]
lru[23] = item(23)
lru[24] = item(24)
lru[25] = item(25)
lru[26] = item(26)
lru[27] = item(27)
assert 11 not in lru
assert 13 not in lru
for id_ in (25, 24, 23, 14, 12, 19, 18, 17, 16, 15):
assert id_ in lru
lru[25]
i2 = item(25)
lru[25] = i2
assert 25 in lru
assert lru[25] is i2
|
LRUTest
|
python
|
apache__airflow
|
providers/fab/tests/unit/fab/auth_manager/test_security.py
|
{
"start": 4194,
"end": 43022
}
|
class ____(BaseView):
route_base = ""
@expose("/some_action")
@has_access
def some_action(self):
return "action!"
def _clear_db_dag_and_runs():
clear_db_runs()
clear_db_dags()
clear_db_dag_bundles()
def _delete_dag_permissions(dag_id, security_manager):
dag_resource_name = _resource_name(dag_id, permissions.RESOURCE_DAG)
for dag_action_name in security_manager.DAG_ACTIONS:
security_manager.delete_permission(dag_action_name, dag_resource_name)
def _create_dag_bundle(bundle_name, session):
bundle = DagBundleModel(name=bundle_name)
session.add(bundle)
session.commit()
return bundle
def _delete_dag_bundle(bundle_name, session):
session.execute(delete(DagBundleModel).where(DagBundleModel.name == bundle_name))
session.commit()
def _create_dag_model(dag_id, bundle_name, session, security_manager):
dag_model = DagModel(dag_id=dag_id, bundle_name=bundle_name)
session.add(dag_model)
session.commit()
security_manager.sync_perm_for_dag(dag_id, access_control=None)
return dag_model
def _delete_dag_model(dag_model, session, security_manager):
session.delete(dag_model)
session.commit()
_delete_dag_permissions(dag_model.dag_id, security_manager)
def _can_read_dag(dag_id: str, user) -> bool:
from airflow.api_fastapi.auth.managers.models.resource_details import DagDetails
return get_auth_manager().is_authorized_dag(method="GET", details=DagDetails(id=dag_id), user=user)
def _can_edit_dag(dag_id: str, user) -> bool:
from airflow.api_fastapi.auth.managers.models.resource_details import DagDetails
return get_auth_manager().is_authorized_dag(method="PUT", details=DagDetails(id=dag_id), user=user)
def _can_delete_dag(dag_id: str, user) -> bool:
from airflow.api_fastapi.auth.managers.models.resource_details import DagDetails
return get_auth_manager().is_authorized_dag(method="DELETE", details=DagDetails(id=dag_id), user=user)
def _has_all_dags_access(user) -> bool:
return get_auth_manager().is_authorized_dag(
method="GET", user=user
) or get_auth_manager().is_authorized_dag(method="PUT", user=user)
@contextlib.contextmanager
def _create_dag_model_context(dag_id, session, security_manager):
bundle_name = "testing"
_create_dag_bundle(bundle_name, session)
dag = _create_dag_model(dag_id, bundle_name, session, security_manager)
yield dag
_delete_dag_model(dag, session, security_manager)
_delete_dag_bundle(bundle_name, session)
@pytest.fixture(scope="module", autouse=True)
def clear_db_after_suite():
yield None
_clear_db_dag_and_runs()
@pytest.fixture(autouse=True)
def clear_db_before_test():
_clear_db_dag_and_runs()
@pytest.fixture(scope="module")
def app():
with conf_vars(
{
(
"core",
"auth_manager",
): "airflow.providers.fab.auth_manager.fab_auth_manager.FabAuthManager",
}
):
_app = application.create_app(enable_plugins=False)
_app.config["WTF_CSRF_ENABLED"] = False
with _app.app_context():
yield _app
@pytest.fixture(scope="module")
def app_builder(app):
app_builder = app.appbuilder
app_builder.add_view(SomeBaseView, "SomeBaseView", category="BaseViews")
app_builder.add_view(SomeModelView, "SomeModelView", category="ModelViews")
return app.appbuilder
@pytest.fixture(scope="module")
def security_manager(app_builder):
return app_builder.sm
@pytest.fixture(scope="module")
def session(app_builder):
return app_builder.session
@pytest.fixture
def role(request, app, security_manager):
params = request.param
_role = None
params["mock_roles"] = [{"role": params["name"], "perms": params["permissions"]}]
if params.get("create", True):
security_manager.bulk_sync_roles(params["mock_roles"])
_role = security_manager.find_role(params["name"])
yield _role, params
delete_role(app, params["name"])
@pytest.fixture
def mock_dag_models(request, session, security_manager):
dags_ids = request.param
bundle_name = "testing"
_create_dag_bundle(bundle_name, session)
dags = [_create_dag_model(dag_id, bundle_name, session, security_manager) for dag_id in dags_ids]
yield dags_ids
for dag in dags:
_delete_dag_model(dag, session, security_manager)
_delete_dag_bundle(bundle_name, session)
@pytest.fixture
def sample_dags(security_manager):
dags = [
DAG("has_access_control", schedule=None, access_control={"Public": {permissions.ACTION_CAN_READ}}),
DAG("no_access_control", schedule=None),
]
yield dags
for dag in dags:
_delete_dag_permissions(dag.dag_id, security_manager)
@pytest.fixture(scope="module")
def has_dag_perm(security_manager):
def _has_dag_perm(perm, dag_id, user):
from airflow.api_fastapi.auth.managers.models.resource_details import DagDetails
return get_auth_manager().is_authorized_dag(method=perm, details=DagDetails(id=dag_id), user=user)
return _has_dag_perm
@pytest.fixture(scope="module")
def assert_user_has_dag_perms(has_dag_perm):
def _assert_user_has_dag_perms(perms, dag_id, user=None):
for perm in perms:
assert has_dag_perm(perm, dag_id, user), f"User should have '{perm}' on DAG '{dag_id}'"
return _assert_user_has_dag_perms
@pytest.fixture(scope="module")
def assert_user_does_not_have_dag_perms(has_dag_perm):
def _assert_user_does_not_have_dag_perms(dag_id, perms, user=None):
for perm in perms:
assert not has_dag_perm(perm, dag_id, user), f"User should not have '{perm}' on DAG '{dag_id}'"
return _assert_user_does_not_have_dag_perms
@pytest.mark.parametrize(
"role",
[{"name": "MyRole3", "permissions": [("can_some_action", "SomeBaseView")]}],
indirect=True,
)
def test_bulk_sync_roles_baseview(app, security_manager, role):
_role, params = role
assert _role is not None
assert len(_role.permissions) == len(params["permissions"])
@pytest.mark.parametrize(
"role",
[
{
"name": "MyRole2",
"permissions": [
("can_list", "SomeModelView"),
("can_show", "SomeModelView"),
("can_add", "SomeModelView"),
(permissions.ACTION_CAN_EDIT, "SomeModelView"),
(permissions.ACTION_CAN_DELETE, "SomeModelView"),
],
}
],
indirect=True,
)
def test_bulk_sync_roles_modelview(app, security_manager, role):
_role, params = role
assert role is not None
assert len(_role.permissions) == len(params["permissions"])
# Check short circuit works
with assert_queries_count(2): # One for Permission, one for roles
security_manager.bulk_sync_roles(params["mock_roles"])
@pytest.mark.parametrize(
"role",
[{"name": "Test_Role", "permissions": []}],
indirect=True,
)
def test_update_and_verify_permission_role(app, security_manager, role):
_role, params = role
perm = security_manager.get_permission(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_ROLE)
security_manager.add_permission_to_role(_role, perm)
role_perms_len = len(_role.permissions)
security_manager.bulk_sync_roles(params["mock_roles"])
new_role_perms_len = len(_role.permissions)
assert role_perms_len == new_role_perms_len
assert new_role_perms_len == 1
def test_verify_public_role_has_no_permissions(security_manager):
public = security_manager.find_role("Public")
assert public.permissions == []
@patch.object(FabAuthManager, "is_logged_in")
def test_verify_default_anon_user_has_no_accessible_dag_ids(
mock_is_logged_in, app, session, security_manager
):
with app.app_context():
mock_is_logged_in.return_value = False
user = AnonymousUser()
app.config["AUTH_ROLE_PUBLIC"] = "Public"
assert security_manager.get_user_roles(user) == [security_manager.get_public_role()]
with _create_dag_model_context("test_dag_id", session, security_manager):
security_manager.sync_roles()
assert get_auth_manager().get_authorized_dag_ids(user=user) == set()
def test_verify_default_anon_user_has_no_access_to_specific_dag(app, session, security_manager, has_dag_perm):
with app.app_context():
user = AnonymousUser()
app.config["AUTH_ROLE_PUBLIC"] = "Public"
assert security_manager.get_user_roles(user) == [security_manager.get_public_role()]
dag_id = "test_dag_id"
with _create_dag_model_context(dag_id, session, security_manager):
security_manager.sync_roles()
assert _can_read_dag(dag_id, user) is False
assert _can_edit_dag(dag_id, user) is False
assert has_dag_perm("GET", dag_id, user) is False
assert has_dag_perm("PUT", dag_id, user) is False
@patch.object(FabAuthManager, "is_logged_in")
@pytest.mark.parametrize(
"mock_dag_models",
[["test_dag_id_1", "test_dag_id_2", "test_dag_id_3"]],
indirect=True,
)
def test_verify_anon_user_with_admin_role_has_all_dag_access(
mock_is_logged_in, app, security_manager, mock_dag_models
):
test_dag_ids = mock_dag_models
with app.app_context():
app.config["AUTH_ROLE_PUBLIC"] = "Admin"
mock_is_logged_in.return_value = False
user = AnonymousUser()
assert security_manager.get_user_roles(user) == [security_manager.get_public_role()]
security_manager.sync_roles()
assert get_auth_manager().get_authorized_dag_ids(user=user) == set(test_dag_ids)
def test_verify_anon_user_with_admin_role_has_access_to_each_dag(
app, session, security_manager, has_dag_perm
):
with app.app_context():
user = AnonymousUser()
app.config["AUTH_ROLE_PUBLIC"] = "Admin"
# Call `.get_user_roles` bc `user` is a mock and the `user.roles` prop needs to be set.
user.roles = security_manager.get_user_roles(user)
assert user.roles == [security_manager.get_public_role()]
test_dag_ids = ["test_dag_id_1", "test_dag_id_2", "test_dag_id_3", "test_dag_id_4.with_dot"]
for dag_id in test_dag_ids:
with _create_dag_model_context(dag_id, session, security_manager):
security_manager.sync_roles()
assert _can_read_dag(dag_id, user) is True
assert _can_edit_dag(dag_id, user) is True
assert has_dag_perm("GET", dag_id, user) is True
assert has_dag_perm("PUT", dag_id, user) is True
def test_get_user_roles(app_builder, security_manager):
user = mock.MagicMock()
roles = app_builder.sm.find_role("Admin")
user.roles = [roles]
assert security_manager.get_user_roles(user) == [roles]
def test_get_user_roles_for_anonymous_user(app, security_manager):
viewer_role_perms = {
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_DEPENDENCIES),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_CODE),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_VERSION),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_WARNING),
(permissions.ACTION_CAN_READ, RESOURCE_ASSET),
(permissions.ACTION_CAN_READ, RESOURCE_ASSET_ALIAS),
(permissions.ACTION_CAN_READ, RESOURCE_BACKFILL),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_CLUSTER_ACTIVITY),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_IMPORT_ERROR),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_JOB),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_POOL),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_SLA_MISS),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK_INSTANCE),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK_LOG),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_XCOM),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_HITL_DETAIL),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_WEBSITE),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_MY_PASSWORD),
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_MY_PASSWORD),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_MY_PROFILE),
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_MY_PROFILE),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_BROWSE_MENU),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_DAG),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_DAG_DEPENDENCIES),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_DAG_RUN),
(permissions.ACTION_CAN_ACCESS_MENU, RESOURCE_ASSET),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_CLUSTER_ACTIVITY),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_JOB),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_SLA_MISS),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_TASK_INSTANCE),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_DOCS_MENU),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_DOCS),
}
app.config["AUTH_ROLE_PUBLIC"] = "Viewer"
with app.app_context():
user = AnonymousUser()
perms_views = set()
for role in security_manager.get_user_roles(user):
perms_views.update({(perm.action.name, perm.resource.name) for perm in role.permissions})
assert perms_views == viewer_role_perms
def test_get_current_user_permissions(app):
action = "can_some_action"
resource = "SomeBaseView"
with app.app_context():
with create_user_scope(
app,
username="get_current_user_permissions",
role_name="MyRole5",
permissions=[
(action, resource),
],
) as user:
assert user.perms == {(action, resource)}
with create_user_scope(
app,
username="no_perms",
) as user:
assert len(user.perms) == 0
@patch.object(FabAuthManager, "is_logged_in")
def test_get_accessible_dag_ids(mock_is_logged_in, app, security_manager, session, testing_dag_bundle):
role_name = "MyRole1"
permission_action = [permissions.ACTION_CAN_READ]
dag_id = "dag_id"
username = "ElUser"
with app.app_context():
with create_user_scope(
app,
username=username,
role_name=role_name,
permissions=[
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG),
],
) as user:
mock_is_logged_in.return_value = True
if hasattr(DagModel, "schedule_interval"): # Airflow 2 compat.
dag_model = DagModel(
dag_id=dag_id,
bundle_name="testing",
fileloc="/tmp/dag_.py",
schedule_interval="2 2 * * *",
)
else: # Airflow 3.
dag_model = DagModel(
dag_id=dag_id,
bundle_name="testing",
fileloc="/tmp/dag_.py",
timetable_summary="2 2 * * *",
)
session.add(dag_model)
session.commit()
security_manager.sync_perm_for_dag(dag_id, access_control={role_name: permission_action})
assert get_auth_manager().get_authorized_dag_ids(user=user) == {"dag_id"}
@patch.object(FabAuthManager, "is_logged_in")
def test_dont_get_inaccessible_dag_ids_for_dag_resource_permission(
mock_is_logged_in, app, security_manager, session, testing_dag_bundle
):
# In this test case,
# get_authorized_dag_ids() don't return DAGs to which the user has CAN_EDIT action
username = "Monsieur User"
role_name = "MyRole1"
permission_action = [permissions.ACTION_CAN_EDIT]
dag_id = "dag_id"
with app.app_context():
with create_user_scope(
app,
username=username,
role_name=role_name,
permissions=[
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_DAG),
],
) as user:
mock_is_logged_in.return_value = True
if hasattr(DagModel, "schedule_interval"): # Airflow 2 compat.
dag_model = DagModel(
dag_id=dag_id,
bundle_name="testing",
fileloc="/tmp/dag_.py",
schedule_interval="2 2 * * *",
)
else: # Airflow 3.
dag_model = DagModel(
dag_id=dag_id,
bundle_name="testing",
fileloc="/tmp/dag_.py",
timetable_summary="2 2 * * *",
)
session.add(dag_model)
session.commit()
security_manager.sync_perm_for_dag(dag_id, access_control={role_name: permission_action})
assert get_auth_manager().get_authorized_dag_ids(user=user) == set()
def test_has_access(security_manager):
user = mock.MagicMock()
action_name = ACTION_CAN_READ
resource_name = "resource"
user.perms = [(action_name, resource_name)]
assert security_manager.has_access(action_name, resource_name, user)
def test_sync_perm_for_dag_creates_permissions_on_resources(security_manager):
test_dag_id = "TEST_DAG"
prefixed_test_dag_id = f"DAG:{test_dag_id}"
security_manager.sync_perm_for_dag(test_dag_id, access_control=None)
assert security_manager.get_permission(permissions.ACTION_CAN_READ, prefixed_test_dag_id) is not None
assert security_manager.get_permission(permissions.ACTION_CAN_EDIT, prefixed_test_dag_id) is not None
def test_sync_perm_for_dag_creates_permissions_for_specified_roles(app, security_manager):
test_dag_id = "TEST_DAG"
test_role = "limited-role"
security_manager.bulk_sync_roles([{"role": test_role, "perms": []}])
with app.app_context():
with create_user_scope(
app,
username="test_user",
role_name=test_role,
permissions=[],
) as user:
security_manager.sync_perm_for_dag(
test_dag_id, access_control={test_role: {"can_read", "can_edit"}}
)
assert _can_read_dag(test_dag_id, user)
assert _can_edit_dag(test_dag_id, user)
assert not _can_delete_dag(test_dag_id, user)
def test_sync_perm_for_dag_removes_existing_permissions_if_empty(app, security_manager):
test_dag_id = "TEST_DAG"
test_role = "limited-role"
with app.app_context():
with create_user_scope(
app,
username="test_user",
role_name=test_role,
permissions=[],
) as user:
security_manager.bulk_sync_roles(
[
{
"role": test_role,
"perms": [
(permissions.ACTION_CAN_READ, f"DAG:{test_dag_id}"),
(permissions.ACTION_CAN_EDIT, f"DAG:{test_dag_id}"),
(permissions.ACTION_CAN_DELETE, f"DAG:{test_dag_id}"),
],
}
]
)
assert _can_read_dag(test_dag_id, user)
assert _can_edit_dag(test_dag_id, user)
assert _can_delete_dag(test_dag_id, user)
# Need to clear cache on user perms
user._perms = None
security_manager.sync_perm_for_dag(test_dag_id, access_control={test_role: {}})
assert not _can_read_dag(test_dag_id, user)
assert not _can_edit_dag(test_dag_id, user)
assert not _can_delete_dag(test_dag_id, user)
def test_sync_perm_for_dag_removes_permissions_from_other_roles(app, security_manager):
test_dag_id = "TEST_DAG"
test_role = "limited-role"
with app.app_context():
with create_user_scope(
app,
username="test_user",
role_name=test_role,
permissions=[],
) as user:
security_manager.bulk_sync_roles(
[
{
"role": test_role,
"perms": [
(permissions.ACTION_CAN_READ, f"DAG:{test_dag_id}"),
(permissions.ACTION_CAN_EDIT, f"DAG:{test_dag_id}"),
(permissions.ACTION_CAN_DELETE, f"DAG:{test_dag_id}"),
],
},
{"role": "other_role", "perms": []},
]
)
assert _can_read_dag(test_dag_id, user)
assert _can_edit_dag(test_dag_id, user)
assert _can_delete_dag(test_dag_id, user)
# Need to clear cache on user perms
user._perms = None
security_manager.sync_perm_for_dag(test_dag_id, access_control={"other_role": {"can_read"}})
assert not _can_read_dag(test_dag_id, user)
assert not _can_edit_dag(test_dag_id, user)
assert not _can_delete_dag(test_dag_id, user)
def test_sync_perm_for_dag_does_not_prune_roles_when_access_control_unset(app, security_manager):
test_dag_id = "TEST_DAG"
test_role = "limited-role"
with app.app_context():
with create_user_scope(
app,
username="test_user",
role_name=test_role,
permissions=[],
) as user:
security_manager.bulk_sync_roles(
[
{
"role": test_role,
"perms": [
(permissions.ACTION_CAN_READ, f"DAG:{test_dag_id}"),
(permissions.ACTION_CAN_EDIT, f"DAG:{test_dag_id}"),
],
},
]
)
assert _can_read_dag(test_dag_id, user)
assert _can_edit_dag(test_dag_id, user)
# Need to clear cache on user perms
user._perms = None
security_manager.sync_perm_for_dag(test_dag_id, access_control=None)
assert _can_read_dag(test_dag_id, user)
assert _can_edit_dag(test_dag_id, user)
def test_has_all_dag_access(app, security_manager):
for role_name in ["Admin", "Viewer", "Op", "User"]:
with app.app_context():
with create_user_scope(
app,
username="user",
role_name=role_name,
) as user:
assert _has_all_dags_access(user)
with app.app_context():
with create_user_scope(
app,
username="user",
role_name="read_all",
permissions=[(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG)],
) as user:
assert _has_all_dags_access(user)
with app.app_context():
with create_user_scope(
app,
username="user",
role_name="edit_all",
permissions=[(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_DAG)],
) as user:
assert _has_all_dags_access(user)
with app.app_context():
with create_user_scope(
app,
username="user",
role_name="nada",
permissions=[],
) as user:
assert not _has_all_dags_access(user)
def test_access_control_with_non_existent_role(security_manager):
with pytest.raises(AirflowException) as ctx:
security_manager._sync_dag_view_permissions(
dag_id="access-control-test",
access_control={
"this-role-does-not-exist": [permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_READ]
},
)
assert "role does not exist" in str(ctx.value)
def test_access_control_with_non_allowed_resource(security_manager):
with pytest.raises(AirflowException) as ctx:
security_manager._sync_dag_view_permissions(
dag_id="access-control-test",
access_control={
"Public": {
permissions.RESOURCE_POOL: {permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_READ}
}
},
)
assert "invalid resource name" in str(ctx.value)
def test_all_dag_access_doesnt_give_non_dag_access(app, security_manager):
username = "dag_access_user"
role_name = "dag_access_role"
with app.app_context():
with create_user_scope(
app,
username=username,
role_name=role_name,
permissions=[
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG),
],
) as user:
assert security_manager.has_access(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG, user)
assert not security_manager.has_access(
permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK_INSTANCE, user
)
def test_access_control_with_invalid_permission(app, security_manager):
invalid_actions = [
"can_varimport", # a real action, but not a member of DAG_ACTIONS
"can_eat_pudding", # clearly not a real action
]
username = "LaUser"
rolename = "team-a"
with create_user_scope(
app,
username=username,
role_name=rolename,
):
for action in invalid_actions:
with pytest.raises(AirflowException) as ctx:
security_manager._sync_dag_view_permissions(
"access_control_test",
access_control={rolename: {action}},
)
assert "invalid permissions" in str(ctx.value)
if hasattr(permissions, "resource_name"):
assert "invalid permission" in str(ctx.value)
else:
# Test with old airflow running new FAB
assert "invalid resource name" in str(ctx.value)
def test_access_control_is_set_on_init(
app,
security_manager,
assert_user_has_dag_perms,
assert_user_does_not_have_dag_perms,
):
username = "access_control_is_set_on_init"
role_name = "team-a"
negated_role = "NOT-team-a"
with app.app_context():
with create_user_scope(
app,
username=username,
role_name=role_name,
permissions=[],
) as user:
security_manager._sync_dag_view_permissions(
"access_control_test",
access_control={role_name: [permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_READ]},
)
assert_user_has_dag_perms(
perms=["PUT", "GET"],
dag_id="access_control_test",
user=user,
)
security_manager.bulk_sync_roles([{"role": negated_role, "perms": []}])
set_user_single_role(app, user, role_name=negated_role)
assert_user_does_not_have_dag_perms(
perms=["PUT", "GET"],
dag_id="access_control_test",
user=user,
)
@pytest.mark.parametrize(
("access_control_before", "access_control_after"),
[
(READ_WRITE, READ_ONLY),
# old access control format
({permissions.ACTION_CAN_READ, permissions.ACTION_CAN_EDIT}, {permissions.ACTION_CAN_READ}),
],
ids=["new_access_control_format", "old_access_control_format"],
)
def test_access_control_stale_perms_are_revoked(
app,
security_manager,
assert_user_has_dag_perms,
assert_user_does_not_have_dag_perms,
access_control_before,
access_control_after,
):
username = "access_control_stale_perms_are_revoked"
role_name = "team-a"
with app.app_context():
with create_user_scope(
app,
username=username,
role_name=role_name,
permissions=[],
) as user:
set_user_single_role(app, user, role_name="team-a")
security_manager._sync_dag_view_permissions(
"access_control_test", access_control={"team-a": access_control_before}
)
assert_user_has_dag_perms(perms=["GET", "PUT"], dag_id="access_control_test", user=user)
security_manager._sync_dag_view_permissions(
"access_control_test", access_control={"team-a": access_control_after}
)
# Clear the cache, to make it pick up new rol perms
user._perms = None
assert_user_has_dag_perms(perms=["GET"], dag_id="access_control_test", user=user)
assert_user_does_not_have_dag_perms(perms=["PUT"], dag_id="access_control_test", user=user)
def test_override_role_vm(app_builder):
test_security_manager = MockSecurityManager(appbuilder=app_builder)
assert len(test_security_manager.VIEWER_VMS) == 1
assert {"Airflow"} == test_security_manager.VIEWER_VMS
@pytest.mark.skipif(AIRFLOW_V_3_1_PLUS, reason="Different dag bag setup")
def test_create_dag_specific_permissions_airflow2(security_manager, monkeypatch, sample_dags):
access_control = (
{"Public": {"DAGs": {permissions.ACTION_CAN_READ}}}
if hasattr(permissions, "resource_name")
else {"Public": {permissions.ACTION_CAN_READ}}
)
collect_dags_from_db_mock = mock.Mock()
dagbag_mock = mock.Mock()
dagbag_mock.dags = {dag.dag_id: dag for dag in sample_dags}
dagbag_mock.collect_dags_from_db = collect_dags_from_db_mock
dagbag_class_mock = mock.Mock()
dagbag_class_mock.return_value = dagbag_mock
import airflow.providers.fab.auth_manager.security_manager
monkeypatch.setitem(
airflow.providers.fab.auth_manager.security_manager.override.__dict__, "DagBag", dagbag_class_mock
)
security_manager._sync_dag_view_permissions = mock.Mock()
for dag in sample_dags:
dag_resource_name = _resource_name(dag.dag_id, permissions.RESOURCE_DAG)
all_perms = security_manager.get_all_permissions()
assert ("can_read", dag_resource_name) not in all_perms
assert ("can_edit", dag_resource_name) not in all_perms
security_manager.create_dag_specific_permissions()
dagbag_class_mock.assert_called_once_with(read_dags_from_db=True)
collect_dags_from_db_mock.assert_called_once_with()
for dag in sample_dags:
dag_resource_name = _resource_name(dag.dag_id, permissions.RESOURCE_DAG)
all_perms = security_manager.get_all_permissions()
assert ("can_read", dag_resource_name) in all_perms
assert ("can_edit", dag_resource_name) in all_perms
security_manager._sync_dag_view_permissions.assert_called_once_with(
"has_access_control",
access_control,
)
del dagbag_mock.dags["has_access_control"]
with assert_queries_count(2): # two query to get all perms; dagbag is mocked
# The extra query happens at permission check
security_manager.create_dag_specific_permissions()
@pytest.mark.skipif(not AIRFLOW_V_3_1_PLUS, reason="Different dag bag setup")
def test_create_dag_specific_permissions_airflow3(session, security_manager, monkeypatch, sample_dags):
access_control = (
{"Public": {"DAGs": {permissions.ACTION_CAN_READ}}}
if hasattr(permissions, "resource_name")
else {"Public": {permissions.ACTION_CAN_READ}}
)
import airflow.providers.fab.auth_manager.security_manager
_iter_dags_mock = mock.Mock(return_value=sample_dags)
monkeypatch.setitem(
airflow.providers.fab.auth_manager.security_manager.override.__dict__, "_iter_dags", _iter_dags_mock
)
security_manager._sync_dag_view_permissions = mock.Mock()
for dag in sample_dags:
dag_resource_name = _resource_name(dag.dag_id, permissions.RESOURCE_DAG)
all_perms = security_manager.get_all_permissions()
assert ("can_read", dag_resource_name) not in all_perms
assert ("can_edit", dag_resource_name) not in all_perms
security_manager.create_dag_specific_permissions()
assert _iter_dags_mock.mock_calls == [mock.call()]
for dag in sample_dags:
dag_resource_name = _resource_name(dag.dag_id, permissions.RESOURCE_DAG)
all_perms = security_manager.get_all_permissions()
assert ("can_read", dag_resource_name) in all_perms
assert ("can_edit", dag_resource_name) in all_perms
security_manager._sync_dag_view_permissions.assert_called_once_with(
"has_access_control",
access_control,
)
_iter_dags_mock.reset_mock(return_value=True)
_iter_dags_mock.return_value = (d for d in sample_dags if d.dag_id != "has_access_control")
with assert_queries_count(2): # two query to get all perms; dagbag is mocked
# The extra query happens at permission check
security_manager.create_dag_specific_permissions()
def test_get_all_permissions(security_manager):
with assert_queries_count(1):
perms = security_manager.get_all_permissions()
assert isinstance(perms, set)
for perm in perms:
assert len(perm) == 2
assert ("can_read", "Connections") in perms
def test_get_all_non_dag_permissions(security_manager):
with assert_queries_count(1):
pvs = security_manager._get_all_non_dag_permissions()
assert isinstance(pvs, dict)
for (perm_name, viewmodel_name), perm in pvs.items():
assert isinstance(perm_name, str)
assert isinstance(viewmodel_name, str)
assert isinstance(perm, security_manager.permission_model)
assert ("can_read", "Connections") in pvs
def test_get_all_roles_with_permissions(security_manager):
with assert_queries_count(1):
roles = security_manager._get_all_roles_with_permissions()
assert isinstance(roles, dict)
for role_name, role in roles.items():
assert isinstance(role_name, str)
assert isinstance(role, security_manager.role_model)
assert "Admin" in roles
def test_permissions_work_for_dags_with_dot_in_dagname(
app,
security_manager,
assert_user_has_dag_perms,
assert_user_does_not_have_dag_perms,
session,
testing_dag_bundle,
):
username = "dag_permission_user"
role_name = "dag_permission_role"
dag_id = "dag_id_1"
dag_id_2 = "dag_id_1.with_dot"
bundle_name = "testing"
with app.app_context():
mock_roles = [
{
"role": role_name,
"perms": [
(permissions.ACTION_CAN_READ, f"DAG:{dag_id}"),
(permissions.ACTION_CAN_EDIT, f"DAG:{dag_id}"),
],
}
]
with create_user_scope(
app,
username=username,
role_name=role_name,
) as user:
dag1 = DagModel(dag_id=dag_id, bundle_name=bundle_name)
dag2 = DagModel(dag_id=dag_id_2, bundle_name=bundle_name)
session.add_all([dag1, dag2])
session.commit()
security_manager.bulk_sync_roles(mock_roles)
security_manager.sync_perm_for_dag(dag1.dag_id, access_control={role_name: READ_WRITE})
security_manager.sync_perm_for_dag(dag2.dag_id, access_control={role_name: READ_WRITE})
assert_user_has_dag_perms(perms=["GET", "PUT"], dag_id=dag_id, user=user)
assert_user_does_not_have_dag_perms(perms=["GET", "PUT"], dag_id=dag_id_2, user=user)
# Clean up DAG models and bundle
session.execute(delete(DagModel))
session.execute(delete(DagBundleModel).where(DagBundleModel.name == bundle_name))
session.commit()
@pytest.fixture
def mock_security_manager(app_builder):
mocked_security_manager = MockSecurityManager(appbuilder=app_builder)
mocked_security_manager.update_user = mock.MagicMock()
return mocked_security_manager
@pytest.fixture
def new_user():
user = mock.MagicMock()
user.login_count = None
user.fail_login_count = None
user.last_login = None
return user
@pytest.fixture
def old_user():
user = mock.MagicMock()
user.login_count = 42
user.fail_login_count = 9
user.last_login = datetime.datetime(1984, 12, 1, 0, 0, 0)
return user
@time_machine.travel(datetime.datetime(1985, 11, 5, 1, 24, 0), tick=False)
def test_update_user_auth_stat_first_successful_auth(mock_security_manager, new_user):
mock_security_manager.update_user_auth_stat(new_user, success=True)
assert new_user.login_count == 1
assert new_user.fail_login_count == 0
mock_security_manager.update_user.assert_called_once_with(new_user)
@time_machine.travel(datetime.datetime(1985, 11, 5, 1, 24, 0), tick=False)
def test_update_user_auth_stat_subsequent_successful_auth(mock_security_manager, old_user):
mock_security_manager.update_user_auth_stat(old_user, success=True)
assert old_user.login_count == 43
assert old_user.fail_login_count == 0
mock_security_manager.update_user.assert_called_once_with(old_user)
@time_machine.travel(datetime.datetime(1985, 11, 5, 1, 24, 0), tick=False)
def test_update_user_auth_stat_first_unsuccessful_auth(mock_security_manager, new_user):
mock_security_manager.update_user_auth_stat(new_user, success=False)
assert new_user.login_count == 0
assert new_user.fail_login_count == 1
assert new_user.last_login is None
mock_security_manager.update_user.assert_called_once_with(new_user)
@time_machine.travel(datetime.datetime(1985, 11, 5, 1, 24, 0), tick=False)
def test_update_user_auth_stat_subsequent_unsuccessful_auth(mock_security_manager, old_user):
mock_security_manager.update_user_auth_stat(old_user, success=False)
assert old_user.login_count == 42
assert old_user.fail_login_count == 10
assert old_user.last_login == datetime.datetime(1984, 12, 1, 0, 0, 0)
mock_security_manager.update_user.assert_called_once_with(old_user)
def test_users_can_be_found(app, security_manager, session, caplog):
"""Test that usernames are case insensitive"""
create_user(app, "Test")
create_user(app, "test")
create_user(app, "TEST")
create_user(app, "TeSt")
assert security_manager.find_user("Test")
users = security_manager.get_all_users()
assert len(users) == 1
delete_user(app, "Test")
assert "Error adding new user to database" in caplog.text
|
SomeBaseView
|
python
|
pytorch__pytorch
|
test/test_dataloader.py
|
{
"start": 119915,
"end": 120555
}
|
class ____(Dataset):
from collections import namedtuple
Batch = namedtuple("Batch", ["data", "label", "random_tensor"])
Data = namedtuple("Data", ["positive", "negative"])
def __len__(self):
return 4
def __getitem__(self, ndx):
return self.Batch(
data=self.Data(positive=ndx, negative=-ndx),
label=str(ndx),
random_tensor=torch.randn(3),
)
@unittest.skipIf(
TEST_WITH_TSAN,
"Fails with TSAN with the following error: starting new threads after multi-threaded "
"fork is not supported. Dying (set die_after_fork=0 to override)",
)
|
NamedTupleDataset
|
python
|
kamyu104__LeetCode-Solutions
|
Python/n-ary-tree-preorder-traversal.py
|
{
"start": 146,
"end": 581
}
|
class ____(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
result, stack = [], [root]
while stack:
node = stack.pop()
result.append(node.val)
for child in reversed(node.children):
if child:
stack.append(child)
return result
|
Solution
|
python
|
marshmallow-code__marshmallow
|
src/marshmallow/fields.py
|
{
"start": 48746,
"end": 49503
}
|
class ____(_TemporalField[dt.time]):
"""A formatted time string.
Example: ``'03:12:58.019077'``
:param format: Either ``"iso"`` (for ISO8601) or a date format string.
If `None`, defaults to "iso".
:param kwargs: The same keyword arguments that :class:`Field` receives.
"""
SERIALIZATION_FUNCS = {
"iso": dt.time.isoformat,
"iso8601": dt.time.isoformat,
}
DESERIALIZATION_FUNCS = {
"iso": dt.time.fromisoformat,
"iso8601": dt.time.fromisoformat,
}
DEFAULT_FORMAT = "iso"
OBJ_TYPE = "time"
SCHEMA_OPTS_VAR_NAME = "timeformat"
@staticmethod
def _make_object_from_format(value, data_format):
return dt.datetime.strptime(value, data_format).time()
|
Time
|
python
|
tensorflow__tensorflow
|
tensorflow/python/ops/image_ops_test.py
|
{
"start": 93741,
"end": 108904
}
|
class ____(test_util.TensorFlowTestCase):
def _testSampleDistortedBoundingBox(self, image, bounding_box,
min_object_covered, aspect_ratio_range,
area_range):
original_area = float(np.prod(image.shape))
bounding_box_area = float((bounding_box[3] - bounding_box[1]) *
(bounding_box[2] - bounding_box[0]))
image_size_np = np.array(image.shape, dtype=np.int32)
bounding_box_np = (
np.array(bounding_box, dtype=np.float32).reshape([1, 1, 4]))
aspect_ratios = []
area_ratios = []
fraction_object_covered = []
num_iter = 1000
with self.cached_session():
image_tf = constant_op.constant(image, shape=image.shape)
image_size_tf = constant_op.constant(
image_size_np, shape=image_size_np.shape)
bounding_box_tf = constant_op.constant(
bounding_box_np, dtype=dtypes.float32, shape=bounding_box_np.shape)
begin, size, _ = image_ops.sample_distorted_bounding_box(
image_size=image_size_tf,
bounding_boxes=bounding_box_tf,
min_object_covered=min_object_covered,
aspect_ratio_range=aspect_ratio_range,
area_range=area_range)
y = array_ops.strided_slice(image_tf, begin, begin + size)
for _ in range(num_iter):
y_tf = self.evaluate(y)
crop_height = y_tf.shape[0]
crop_width = y_tf.shape[1]
aspect_ratio = float(crop_width) / float(crop_height)
area = float(crop_width * crop_height)
aspect_ratios.append(aspect_ratio)
area_ratios.append(area / original_area)
fraction_object_covered.append(float(np.sum(y_tf)) / bounding_box_area)
# min_object_covered as tensor
min_object_covered_t = ops.convert_to_tensor(min_object_covered)
begin, size, _ = image_ops.sample_distorted_bounding_box(
image_size=image_size_tf,
bounding_boxes=bounding_box_tf,
min_object_covered=min_object_covered_t,
aspect_ratio_range=aspect_ratio_range,
area_range=area_range)
y = array_ops.strided_slice(image_tf, begin, begin + size)
for _ in range(num_iter):
y_tf = self.evaluate(y)
crop_height = y_tf.shape[0]
crop_width = y_tf.shape[1]
aspect_ratio = float(crop_width) / float(crop_height)
area = float(crop_width * crop_height)
aspect_ratios.append(aspect_ratio)
area_ratios.append(area / original_area)
fraction_object_covered.append(float(np.sum(y_tf)) / bounding_box_area)
# Ensure that each entry is observed within 3 standard deviations.
# num_bins = 10
# aspect_ratio_hist, _ = np.histogram(aspect_ratios,
# bins=num_bins,
# range=aspect_ratio_range)
# mean = np.mean(aspect_ratio_hist)
# stddev = np.sqrt(mean)
# TODO(wicke, shlens, dga): Restore this test so that it is no longer flaky.
# TODO(irving): Since the rejection probability is not independent of the
# aspect ratio, the aspect_ratio random value is not exactly uniformly
# distributed in [min_aspect_ratio, max_aspect_ratio). This test should be
# fixed to reflect the true statistical property, then tightened to enforce
# a stricter bound. Or, ideally, the sample_distorted_bounding_box Op
# be fixed to not use rejection sampling and generate correctly uniform
# aspect ratios.
# self.assertAllClose(aspect_ratio_hist,
# [mean] * num_bins, atol=3.6 * stddev)
# The resulting crop will not be uniformly distributed in area. In practice,
# we find that the area skews towards the small sizes. Instead, we perform
# a weaker test to ensure that the area ratios are merely within the
# specified bounds.
self.assertLessEqual(max(area_ratios), area_range[1])
self.assertGreaterEqual(min(area_ratios), area_range[0])
# For reference, here is what the distribution of area ratios look like.
area_ratio_hist, _ = np.histogram(area_ratios, bins=10, range=area_range)
print("area_ratio_hist ", area_ratio_hist)
# Ensure that fraction_object_covered is satisfied.
# TODO(wicke, shlens, dga): Restore this test so that it is no longer flaky.
# self.assertGreaterEqual(min(fraction_object_covered), min_object_covered)
def testWholeImageBoundingBox(self):
height = 40
width = 50
image_size = [height, width, 1]
bounding_box = [0.0, 0.0, 1.0, 1.0]
image = np.arange(
0, np.prod(image_size), dtype=np.int32).reshape(image_size)
self._testSampleDistortedBoundingBox(
image,
bounding_box,
min_object_covered=0.1,
aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0))
def testWithBoundingBox(self):
height = 40
width = 50
x_shape = [height, width, 1]
image = np.zeros(x_shape, dtype=np.int32)
# Create an object with 1's in a region with area A and require that
# the total pixel values >= 0.1 * A.
min_object_covered = 0.1
xmin = 2
ymin = 3
xmax = 12
ymax = 13
for x in np.arange(xmin, xmax + 1, 1):
for y in np.arange(ymin, ymax + 1, 1):
image[x, y] = 1
# Bounding box is specified as (ymin, xmin, ymax, xmax) in
# relative coordinates.
bounding_box = (float(ymin) / height, float(xmin) / width,
float(ymax) / height, float(xmax) / width)
self._testSampleDistortedBoundingBox(
image,
bounding_box=bounding_box,
min_object_covered=min_object_covered,
aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0))
def testSampleDistortedBoundingBoxShape(self):
# Shape function requires placeholders and a graph.
with ops.Graph().as_default():
with self.cached_session():
image_size = constant_op.constant(
[40, 50, 1], shape=[3], dtype=dtypes.int32)
bounding_box = constant_op.constant(
[[[0.0, 0.0, 1.0, 1.0]]],
shape=[1, 1, 4],
dtype=dtypes.float32,
)
begin, end, bbox_for_drawing = image_ops.sample_distorted_bounding_box(
image_size=image_size,
bounding_boxes=bounding_box,
min_object_covered=0.1,
aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0))
# Test that the shapes are correct.
self.assertAllEqual([3], begin.get_shape().as_list())
self.assertAllEqual([3], end.get_shape().as_list())
self.assertAllEqual([1, 1, 4], bbox_for_drawing.get_shape().as_list())
# Actual run to make sure shape is correct inside Compute().
begin = self.evaluate(begin)
end = self.evaluate(end)
bbox_for_drawing = self.evaluate(bbox_for_drawing)
begin, end, bbox_for_drawing = image_ops.sample_distorted_bounding_box(
image_size=image_size,
bounding_boxes=bounding_box,
min_object_covered=array_ops.placeholder(dtypes.float32),
aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0))
# Test that the shapes are correct.
self.assertAllEqual([3], begin.get_shape().as_list())
self.assertAllEqual([3], end.get_shape().as_list())
self.assertAllEqual([1, 1, 4], bbox_for_drawing.get_shape().as_list())
def testDefaultMinObjectCovered(self):
# By default min_object_covered=0.1 if not provided
with self.cached_session():
image_size = constant_op.constant(
[40, 50, 1], shape=[3], dtype=dtypes.int32)
bounding_box = constant_op.constant(
[[[0.0, 0.0, 1.0, 1.0]]],
shape=[1, 1, 4],
dtype=dtypes.float32,
)
begin, end, bbox_for_drawing = image_ops.sample_distorted_bounding_box(
image_size=image_size,
bounding_boxes=bounding_box,
aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0))
self.assertAllEqual([3], begin.get_shape().as_list())
self.assertAllEqual([3], end.get_shape().as_list())
self.assertAllEqual([1, 1, 4], bbox_for_drawing.get_shape().as_list())
# Actual run to make sure shape is correct inside Compute().
begin = self.evaluate(begin)
end = self.evaluate(end)
bbox_for_drawing = self.evaluate(bbox_for_drawing)
def _testStatelessSampleDistortedBoundingBox(self, image, bounding_box,
min_object_covered,
aspect_ratio_range, area_range):
with test_util.use_gpu():
original_area = float(np.prod(image.shape))
bounding_box_area = float((bounding_box[3] - bounding_box[1]) *
(bounding_box[2] - bounding_box[0]))
image_size_np = np.array(image.shape, dtype=np.int32)
bounding_box_np = (
np.array(bounding_box, dtype=np.float32).reshape([1, 1, 4]))
iterations = 2
test_seeds = [(1, 2), (3, 4), (5, 6)]
for seed in test_seeds:
aspect_ratios = []
area_ratios = []
fraction_object_covered = []
for _ in range(iterations):
image_tf = constant_op.constant(image, shape=image.shape)
image_size_tf = constant_op.constant(
image_size_np, shape=image_size_np.shape)
bounding_box_tf = constant_op.constant(bounding_box_np,
dtype=dtypes.float32,
shape=bounding_box_np.shape)
begin, size, _ = image_ops.stateless_sample_distorted_bounding_box(
image_size=image_size_tf,
bounding_boxes=bounding_box_tf,
seed=seed,
min_object_covered=min_object_covered,
aspect_ratio_range=aspect_ratio_range,
area_range=area_range)
y = array_ops.strided_slice(image_tf, begin, begin + size)
y_tf = self.evaluate(y)
crop_height = y_tf.shape[0]
crop_width = y_tf.shape[1]
aspect_ratio = float(crop_width) / float(crop_height)
area = float(crop_width * crop_height)
aspect_ratios.append(aspect_ratio)
area_ratio = area / original_area
area_ratios.append(area_ratio)
fraction_object_covered.append(
float(np.sum(y_tf)) / bounding_box_area)
# Check that `area_ratio` is within valid range.
self.assertLessEqual(area_ratio, area_range[1])
self.assertGreaterEqual(area_ratio, area_range[0])
# Each array should consist of one value just repeated `iteration` times
# because the same seed is used.
self.assertEqual(len(set(aspect_ratios)), 1)
self.assertEqual(len(set(area_ratios)), 1)
self.assertEqual(len(set(fraction_object_covered)), 1)
# TODO(b/162345082): stateless random op generates different random number
# with xla_gpu. Update tests such that there is a single ground truth result
# to test against.
def testWholeImageBoundingBoxStateless(self):
height = 40
width = 50
image_size = [height, width, 1]
bounding_box = [0.0, 0.0, 1.0, 1.0]
image = np.arange(
0, np.prod(image_size), dtype=np.int32).reshape(image_size)
for min_obj_covered in [0.1, constant_op.constant(0.1)]:
self._testStatelessSampleDistortedBoundingBox(
image,
bounding_box,
min_object_covered=min_obj_covered,
aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0))
# TODO(b/162345082): stateless random op generates different random number
# with xla_gpu. Update tests such that there is a single ground truth result
# to test against.
def testWithBoundingBoxStateless(self):
height = 40
width = 50
x_shape = [height, width, 1]
image = np.zeros(x_shape, dtype=np.int32)
xmin = 2
ymin = 3
xmax = 12
ymax = 13
for x in np.arange(xmin, xmax + 1, 1):
for y in np.arange(ymin, ymax + 1, 1):
image[x, y] = 1
# Bounding box is specified as (ymin, xmin, ymax, xmax) in
# relative coordinates.
bounding_box = (float(ymin) / height, float(xmin) / width,
float(ymax) / height, float(xmax) / width)
# Test both scalar and tensor input for `min_object_covered`.
for min_obj_covered in [0.1, constant_op.constant(0.1)]:
self._testStatelessSampleDistortedBoundingBox(
image,
bounding_box=bounding_box,
min_object_covered=min_obj_covered,
aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0))
def testSampleDistortedBoundingBoxShapeStateless(self):
with test_util.use_gpu():
image_size = constant_op.constant(
[40, 50, 1], shape=[3], dtype=dtypes.int32)
bounding_box = constant_op.constant(
[[[0.0, 0.0, 1.0, 1.0]]],
shape=[1, 1, 4],
dtype=dtypes.float32,
)
bbox_func = functools.partial(
image_ops.stateless_sample_distorted_bounding_box,
image_size=image_size,
bounding_boxes=bounding_box,
min_object_covered=0.1,
aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0))
# Check error is raised with wrong seed shapes.
for seed in [1, (1, 2, 3)]:
with self.assertRaises((ValueError, errors.InvalidArgumentError)):
begin, end, bbox_for_drawing = bbox_func(seed=seed)
test_seed = (1, 2)
begin, end, bbox_for_drawing = bbox_func(seed=test_seed)
# Test that the shapes are correct.
self.assertAllEqual([3], begin.get_shape().as_list())
self.assertAllEqual([3], end.get_shape().as_list())
self.assertAllEqual([1, 1, 4], bbox_for_drawing.get_shape().as_list())
# Actual run to make sure shape is correct inside Compute().
begin = self.evaluate(begin)
end = self.evaluate(end)
bbox_for_drawing = self.evaluate(bbox_for_drawing)
self.assertAllEqual([3], begin.shape)
self.assertAllEqual([3], end.shape)
self.assertAllEqual([1, 1, 4], bbox_for_drawing.shape)
def testDeterminismExceptionThrowing(self):
with test_util.deterministic_ops():
with self.assertRaisesRegex(
ValueError, "requires a non-zero seed to be passed in when "
"determinism is enabled"):
image_ops_impl.sample_distorted_bounding_box_v2(
image_size=[50, 50, 1],
bounding_boxes=[[[0., 0., 1., 1.]]],
)
image_ops_impl.sample_distorted_bounding_box_v2(
image_size=[50, 50, 1], bounding_boxes=[[[0., 0., 1., 1.]]], seed=1)
with self.assertRaisesRegex(
ValueError, 'requires "seed" or "seed2" to be non-zero when '
"determinism is enabled"):
image_ops_impl.sample_distorted_bounding_box(
image_size=[50, 50, 1], bounding_boxes=[[[0., 0., 1., 1.]]])
image_ops_impl.sample_distorted_bounding_box(
image_size=[50, 50, 1], bounding_boxes=[[[0., 0., 1., 1.]]], seed=1)
|
SelectDistortedCropBoxTest
|
python
|
langchain-ai__langchain
|
libs/langchain_v1/langchain/agents/middleware/types.py
|
{
"start": 8930,
"end": 9798
}
|
class ____:
"""Response from model execution including messages and optional structured output.
The result will usually contain a single `AIMessage`, but may include an additional
`ToolMessage` if the model used a tool for structured output.
"""
result: list[BaseMessage]
"""List of messages from model execution."""
structured_response: Any = None
"""Parsed structured output if `response_format` was specified, `None` otherwise."""
# Type alias for middleware return type - allows returning either full response or just AIMessage
ModelCallResult: TypeAlias = "ModelResponse | AIMessage"
"""`TypeAlias` for model call handler return value.
Middleware can return either:
- `ModelResponse`: Full response with messages and optional structured output
- `AIMessage`: Simplified return for simple use cases
"""
@dataclass
|
ModelResponse
|
python
|
keras-team__keras
|
keras/src/losses/losses_test.py
|
{
"start": 71807,
"end": 74324
}
|
class ____(testing.TestCase):
def test_config(self):
self.run_class_serialization_test(losses.Tversky(name="mytversky"))
def test_correctness(self):
y_true = np.array(([[1, 2], [1, 2]]))
y_pred = np.array(([[4, 1], [6, 1]]))
output = losses.Tversky()(y_true, y_pred)
self.assertAllClose(output, -0.55555546)
def test_correctness_custom_coefficients(self):
y_true = np.array(([[1, 2], [1, 2]]))
y_pred = np.array(([[4, 1], [6, 1]]))
output = losses.Tversky(alpha=0.2, beta=0.8)(y_true, y_pred)
self.assertAllClose(output, -0.29629636)
def test_binary_segmentation(self):
y_true = np.array(
([[1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1]])
)
y_pred = np.array(
([[0, 1, 0, 1], [1, 0, 1, 1], [0, 1, 0, 1], [1, 0, 1, 1]])
)
output = losses.Tversky()(y_true, y_pred)
self.assertAllClose(output, 0.77777773)
def test_binary_segmentation_with_axis(self):
y_true = np.array(
[[[[1.0], [1.0]], [[0.0], [0.0]]], [[[1.0], [1.0]], [[0.0], [0.0]]]]
)
y_pred = np.array(
[[[[0.0], [1.0]], [[0.0], [1.0]]], [[[0.4], [0.0]], [[0.0], [0.9]]]]
)
output = losses.Tversky(axis=(1, 2, 3), reduction=None)(y_true, y_pred)
self.assertAllClose(output, [0.5, 0.75757575])
def test_binary_segmentation_custom_coefficients(self):
y_true = np.array(
([[1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1]])
)
y_pred = np.array(
([[0, 1, 0, 1], [1, 0, 1, 1], [0, 1, 0, 1], [1, 0, 1, 1]])
)
output = losses.Tversky(alpha=0.2, beta=0.8)(y_true, y_pred)
self.assertAllClose(output, 0.7916667)
def test_binary_segmentation_custom_coefficients_with_axis(self):
y_true = np.array(
[[[[1.0], [1.0]], [[0.0], [0.0]]], [[[1.0], [1.0]], [[0.0], [0.0]]]]
)
y_pred = np.array(
[[[[0.0], [1.0]], [[0.0], [1.0]]], [[[0.4], [0.0]], [[0.0], [0.9]]]]
)
output = losses.Tversky(
alpha=0.2, beta=0.8, axis=(1, 2, 3), reduction=None
)(y_true, y_pred)
self.assertAllClose(output, [0.5, 0.7222222])
def test_dtype_arg(self):
y_true = np.array(([[1, 2], [1, 2]]))
y_pred = np.array(([[4, 1], [6, 1]]))
output = losses.Tversky(dtype="bfloat16")(y_true, y_pred)
self.assertDType(output, "bfloat16")
|
TverskyTest
|
python
|
run-llama__llama_index
|
llama-index-integrations/readers/llama-index-readers-feishu-docs/llama_index/readers/feishu_docs/base.py
|
{
"start": 805,
"end": 3779
}
|
class ____(BaseReader):
"""
Feishu Docs reader.
Reads a page from Google Docs
"""
host = "https://open.feishu.cn"
documents_raw_content_url_path = "/open-apis/docx/v1/documents/{}/raw_content"
tenant_access_token_internal_url_path = (
"/open-apis/auth/v3/tenant_access_token/internal"
)
def __init__(self, app_id, app_secret) -> None:
"""
Args:
app_id: The unique identifier of the application is obtained after the application is created.
app_secret: Application key, obtained after creating the application.
"""
super().__init__()
self.app_id = app_id
self.app_secret = app_secret
self.tenant_access_token = ""
self.expire = 0
def load_data(self, document_ids: List[str]) -> List[Document]:
"""
Load data from the input directory.
Args:
document_ids (List[str]): a list of document ids.
"""
if document_ids is None:
raise ValueError('Must specify a "document_ids" in `load_kwargs`.')
results = []
for document_id in document_ids:
doc = self._load_doc(document_id)
results.append(Document(text=doc, extra_info={"document_id": document_id}))
return results
def _load_doc(self, document_id) -> str:
"""
Load a document from Feishu Docs.
Args:
document_id: the document id.
Returns:
The document text.
"""
url = self.host + self.documents_raw_content_url_path.format(document_id)
if self.tenant_access_token == "" or self.expire < time.time():
self._update_tenant_access_token()
headers = {
"Authorization": f"Bearer {self.tenant_access_token}",
"Content-Type": "application/json; charset=utf-8",
}
response = requests.get(url, headers=headers)
return response.json()["data"]["content"]
def _update_tenant_access_token(self):
"""For update tenant_access_token."""
url = self.host + self.tenant_access_token_internal_url_path
headers = {"Content-Type": "application/json; charset=utf-8"}
data = {"app_id": self.app_id, "app_secret": self.app_secret}
response = requests.post(url, data=json.dumps(data), headers=headers)
self.tenant_access_token = response.json()["tenant_access_token"]
self.expire = time.time() + response.json()["expire"]
def set_lark_domain(self):
"""The default API endpoints are for Feishu, in order to switch to Lark, we should use set_lark_domain."""
self.host = "https://open.larksuite.com"
if __name__ == "__main__":
app_id = os.environ.get("FEISHU_APP_ID")
app_secret = os.environ.get("FEISHU_APP_SECRET")
reader = FeishuDocsReader(app_id, app_secret)
print(reader.load_data(document_ids=[os.environ.get("FEISHU_DOC_ID")]))
|
FeishuDocsReader
|
python
|
kamyu104__LeetCode-Solutions
|
Python/minimum-operations-to-form-subsequence-with-target-sum.py
|
{
"start": 1049,
"end": 1790
}
|
class ____(object):
def minOperations(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
total = sum(nums)
if total < target:
return -1
nums.sort()
result = 0
while target:
x = nums.pop()
if x <= target:
target -= x
total -= x
elif total-x >= target:
total -= x
else:
nums.append(x//2)
nums.append(x//2)
result += 1
return result
# Time: O(nlogn)
# Space: O(n)
import heapq
# codeforces, https://codeforces.com/problemset/problem/1303/D
# heap, greedy
|
Solution2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.