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 | pandas-dev__pandas | pandas/core/methods/selectn.py | {
"start": 1913,
"end": 5069
} | class ____(SelectN[Series]):
"""
Implement n largest/smallest for Series
Parameters
----------
obj : Series
n : int
keep : {'first', 'last'}, default 'first'
Returns
-------
nordered : Series
"""
def compute(self, method: str) -> Series:
from pandas.core.reshape.concat import concat
n = self.n
dtype = self.obj.dtype
if not self.is_valid_dtype_n_method(dtype):
raise TypeError(f"Cannot use method '{method}' with dtype {dtype}")
if n <= 0:
return self.obj[[]]
# Save index and reset to default index to avoid performance impact
# from when index contains duplicates
original_index: Index = self.obj.index
default_index = self.obj.reset_index(drop=True)
# Slower method used when taking the full length of the series
# In this case, it is equivalent to a sort.
if n >= len(default_index):
ascending = method == "nsmallest"
result = default_index.sort_values(ascending=ascending, kind="stable").head(
n
)
result.index = original_index.take(result.index)
return result
# Fast method used in the general case
dropped = default_index.dropna()
nan_index = default_index.drop(dropped.index)
new_dtype = dropped.dtype
# Similar to algorithms._ensure_data
arr = dropped._values
if needs_i8_conversion(arr.dtype):
arr = arr.view("i8")
elif isinstance(arr.dtype, BaseMaskedDtype):
arr = arr._data
else:
arr = np.asarray(arr)
if arr.dtype.kind == "b":
arr = arr.view(np.uint8)
if method == "nlargest":
arr = -arr
if is_integer_dtype(new_dtype):
# GH 21426: ensure reverse ordering at boundaries
arr -= 1
elif is_bool_dtype(new_dtype):
# GH 26154: ensure False is smaller than True
arr = 1 - (-arr)
if self.keep == "last":
arr = arr[::-1]
nbase = n
narr = len(arr)
n = min(n, narr)
# arr passed into kth_smallest must be contiguous. We copy
# here because kth_smallest will modify its input
# avoid OOB access with kth_smallest_c when n <= 0
if len(arr) > 0:
kth_val = libalgos.kth_smallest(arr.copy(order="C"), n - 1)
else:
kth_val = np.nan
(ns,) = np.nonzero(arr <= kth_val)
inds = ns[arr[ns].argsort(kind="stable")]
if self.keep != "all":
inds = inds[:n]
findex = nbase
else:
if len(inds) < nbase <= len(nan_index) + len(inds):
findex = len(nan_index) + len(inds)
else:
findex = len(inds)
if self.keep == "last":
# reverse indices
inds = narr - 1 - inds
result = concat([dropped.iloc[inds], nan_index]).iloc[:findex]
result.index = original_index.take(result.index)
return result
| SelectNSeries |
python | plotly__plotly.py | plotly/graph_objs/scatter3d/_error_y.py | {
"start": 233,
"end": 14881
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter3d"
_path_str = "scatter3d.error_y"
_valid_props = {
"array",
"arrayminus",
"arrayminussrc",
"arraysrc",
"color",
"copy_zstyle",
"symmetric",
"thickness",
"traceref",
"tracerefminus",
"type",
"value",
"valueminus",
"visible",
"width",
}
@property
def array(self):
"""
Sets the data corresponding the length of each error bar.
Values are plotted relative to the underlying data.
The 'array' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["array"]
@array.setter
def array(self, val):
self["array"] = val
@property
def arrayminus(self):
"""
Sets the data corresponding the length of each error bar in the
bottom (left) direction for vertical (horizontal) bars Values
are plotted relative to the underlying data.
The 'arrayminus' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["arrayminus"]
@arrayminus.setter
def arrayminus(self, val):
self["arrayminus"] = val
@property
def arrayminussrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`arrayminus`.
The 'arrayminussrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["arrayminussrc"]
@arrayminussrc.setter
def arrayminussrc(self, val):
self["arrayminussrc"] = val
@property
def arraysrc(self):
"""
Sets the source reference on Chart Studio Cloud for `array`.
The 'arraysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["arraysrc"]
@arraysrc.setter
def arraysrc(self, val):
self["arraysrc"] = val
@property
def color(self):
"""
Sets the stroke color of the error bars.
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 copy_zstyle(self):
"""
The 'copy_zstyle' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["copy_zstyle"]
@copy_zstyle.setter
def copy_zstyle(self, val):
self["copy_zstyle"] = val
@property
def symmetric(self):
"""
Determines whether or not the error bars have the same length
in both direction (top/bottom for vertical bars, left/right for
horizontal bars.
The 'symmetric' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["symmetric"]
@symmetric.setter
def symmetric(self, val):
self["symmetric"] = val
@property
def thickness(self):
"""
Sets the thickness (in px) of the error bars.
The 'thickness' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["thickness"]
@thickness.setter
def thickness(self, val):
self["thickness"] = val
@property
def traceref(self):
"""
The 'traceref' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
"""
return self["traceref"]
@traceref.setter
def traceref(self, val):
self["traceref"] = val
@property
def tracerefminus(self):
"""
The 'tracerefminus' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
"""
return self["tracerefminus"]
@tracerefminus.setter
def tracerefminus(self, val):
self["tracerefminus"] = val
@property
def type(self):
"""
Determines the rule used to generate the error bars. If
"constant", the bar lengths are of a constant value. Set this
constant in `value`. If "percent", the bar lengths correspond
to a percentage of underlying data. Set this percentage in
`value`. If "sqrt", the bar lengths correspond to the square of
the underlying data. If "data", the bar lengths are set with
data set `array`.
The 'type' property is an enumeration that may be specified as:
- One of the following enumeration values:
['percent', 'constant', 'sqrt', 'data']
Returns
-------
Any
"""
return self["type"]
@type.setter
def type(self, val):
self["type"] = val
@property
def value(self):
"""
Sets the value of either the percentage (if `type` is set to
"percent") or the constant (if `type` is set to "constant")
corresponding to the lengths of the error bars.
The 'value' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["value"]
@value.setter
def value(self, val):
self["value"] = val
@property
def valueminus(self):
"""
Sets the value of either the percentage (if `type` is set to
"percent") or the constant (if `type` is set to "constant")
corresponding to the lengths of the error bars in the bottom
(left) direction for vertical (horizontal) bars
The 'valueminus' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["valueminus"]
@valueminus.setter
def valueminus(self, val):
self["valueminus"] = val
@property
def visible(self):
"""
Determines whether or not this set of error bars is visible.
The 'visible' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["visible"]
@visible.setter
def visible(self, val):
self["visible"] = val
@property
def width(self):
"""
Sets the width (in px) of the cross-bar at both ends of the
error bars.
The 'width' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["width"]
@width.setter
def width(self, val):
self["width"] = val
@property
def _prop_descriptions(self):
return """\
array
Sets the data corresponding the length of each error
bar. Values are plotted relative to the underlying
data.
arrayminus
Sets the data corresponding the length of each error
bar in the bottom (left) direction for vertical
(horizontal) bars Values are plotted relative to the
underlying data.
arrayminussrc
Sets the source reference on Chart Studio Cloud for
`arrayminus`.
arraysrc
Sets the source reference on Chart Studio Cloud for
`array`.
color
Sets the stroke color of the error bars.
copy_zstyle
symmetric
Determines whether or not the error bars have the same
length in both direction (top/bottom for vertical bars,
left/right for horizontal bars.
thickness
Sets the thickness (in px) of the error bars.
traceref
tracerefminus
type
Determines the rule used to generate the error bars. If
"constant", the bar lengths are of a constant value.
Set this constant in `value`. If "percent", the bar
lengths correspond to a percentage of underlying data.
Set this percentage in `value`. If "sqrt", the bar
lengths correspond to the square of the underlying
data. If "data", the bar lengths are set with data set
`array`.
value
Sets the value of either the percentage (if `type` is
set to "percent") or the constant (if `type` is set to
"constant") corresponding to the lengths of the error
bars.
valueminus
Sets the value of either the percentage (if `type` is
set to "percent") or the constant (if `type` is set to
"constant") corresponding to the lengths of the error
bars in the bottom (left) direction for vertical
(horizontal) bars
visible
Determines whether or not this set of error bars is
visible.
width
Sets the width (in px) of the cross-bar at both ends of
the error bars.
"""
def __init__(
self,
arg=None,
array=None,
arrayminus=None,
arrayminussrc=None,
arraysrc=None,
color=None,
copy_zstyle=None,
symmetric=None,
thickness=None,
traceref=None,
tracerefminus=None,
type=None,
value=None,
valueminus=None,
visible=None,
width=None,
**kwargs,
):
"""
Construct a new ErrorY object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatter3d.ErrorY`
array
Sets the data corresponding the length of each error
bar. Values are plotted relative to the underlying
data.
arrayminus
Sets the data corresponding the length of each error
bar in the bottom (left) direction for vertical
(horizontal) bars Values are plotted relative to the
underlying data.
arrayminussrc
Sets the source reference on Chart Studio Cloud for
`arrayminus`.
arraysrc
Sets the source reference on Chart Studio Cloud for
`array`.
color
Sets the stroke color of the error bars.
copy_zstyle
symmetric
Determines whether or not the error bars have the same
length in both direction (top/bottom for vertical bars,
left/right for horizontal bars.
thickness
Sets the thickness (in px) of the error bars.
traceref
tracerefminus
type
Determines the rule used to generate the error bars. If
"constant", the bar lengths are of a constant value.
Set this constant in `value`. If "percent", the bar
lengths correspond to a percentage of underlying data.
Set this percentage in `value`. If "sqrt", the bar
lengths correspond to the square of the underlying
data. If "data", the bar lengths are set with data set
`array`.
value
Sets the value of either the percentage (if `type` is
set to "percent") or the constant (if `type` is set to
"constant") corresponding to the lengths of the error
bars.
valueminus
Sets the value of either the percentage (if `type` is
set to "percent") or the constant (if `type` is set to
"constant") corresponding to the lengths of the error
bars in the bottom (left) direction for vertical
(horizontal) bars
visible
Determines whether or not this set of error bars is
visible.
width
Sets the width (in px) of the cross-bar at both ends of
the error bars.
Returns
-------
ErrorY
"""
super().__init__("error_y")
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.scatter3d.ErrorY
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatter3d.ErrorY`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("array", arg, array)
self._set_property("arrayminus", arg, arrayminus)
self._set_property("arrayminussrc", arg, arrayminussrc)
self._set_property("arraysrc", arg, arraysrc)
self._set_property("color", arg, color)
self._set_property("copy_zstyle", arg, copy_zstyle)
self._set_property("symmetric", arg, symmetric)
self._set_property("thickness", arg, thickness)
self._set_property("traceref", arg, traceref)
self._set_property("tracerefminus", arg, tracerefminus)
self._set_property("type", arg, type)
self._set_property("value", arg, value)
self._set_property("valueminus", arg, valueminus)
self._set_property("visible", arg, visible)
self._set_property("width", arg, width)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| ErrorY |
python | doocs__leetcode | solution/2400-2499/2478.Number of Beautiful Partitions/Solution.py | {
"start": 0,
"end": 687
} | class ____:
def beautifulPartitions(self, s: str, k: int, minLength: int) -> int:
primes = '2357'
if s[0] not in primes or s[-1] in primes:
return 0
mod = 10**9 + 7
n = len(s)
f = [[0] * (k + 1) for _ in range(n + 1)]
g = [[0] * (k + 1) for _ in range(n + 1)]
f[0][0] = g[0][0] = 1
for i, c in enumerate(s, 1):
if i >= minLength and c not in primes and (i == n or s[i] in primes):
for j in range(1, k + 1):
f[i][j] = g[i - minLength][j - 1]
for j in range(k + 1):
g[i][j] = (g[i - 1][j] + f[i][j]) % mod
return f[n][k]
| Solution |
python | openai__openai-python | tests/api_resources/beta/threads/runs/test_steps.py | {
"start": 6465,
"end": 12850
} | class ____:
parametrize = pytest.mark.parametrize(
"async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"]
)
@parametrize
async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None:
with pytest.warns(DeprecationWarning):
step = await async_client.beta.threads.runs.steps.retrieve(
step_id="step_id",
thread_id="thread_id",
run_id="run_id",
)
assert_matches_type(RunStep, step, path=["response"])
@parametrize
async def test_method_retrieve_with_all_params(self, async_client: AsyncOpenAI) -> None:
with pytest.warns(DeprecationWarning):
step = await async_client.beta.threads.runs.steps.retrieve(
step_id="step_id",
thread_id="thread_id",
run_id="run_id",
include=["step_details.tool_calls[*].file_search.results[*].content"],
)
assert_matches_type(RunStep, step, path=["response"])
@parametrize
async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None:
with pytest.warns(DeprecationWarning):
response = await async_client.beta.threads.runs.steps.with_raw_response.retrieve(
step_id="step_id",
thread_id="thread_id",
run_id="run_id",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
step = response.parse()
assert_matches_type(RunStep, step, path=["response"])
@parametrize
async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None:
with pytest.warns(DeprecationWarning):
async with async_client.beta.threads.runs.steps.with_streaming_response.retrieve(
step_id="step_id",
thread_id="thread_id",
run_id="run_id",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
step = await response.parse()
assert_matches_type(RunStep, step, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None:
with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"):
await async_client.beta.threads.runs.steps.with_raw_response.retrieve(
step_id="step_id",
thread_id="",
run_id="run_id",
)
with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"):
await async_client.beta.threads.runs.steps.with_raw_response.retrieve(
step_id="step_id",
thread_id="thread_id",
run_id="",
)
with pytest.raises(ValueError, match=r"Expected a non-empty value for `step_id` but received ''"):
await async_client.beta.threads.runs.steps.with_raw_response.retrieve(
step_id="",
thread_id="thread_id",
run_id="run_id",
)
@parametrize
async def test_method_list(self, async_client: AsyncOpenAI) -> None:
with pytest.warns(DeprecationWarning):
step = await async_client.beta.threads.runs.steps.list(
run_id="run_id",
thread_id="thread_id",
)
assert_matches_type(AsyncCursorPage[RunStep], step, path=["response"])
@parametrize
async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None:
with pytest.warns(DeprecationWarning):
step = await async_client.beta.threads.runs.steps.list(
run_id="run_id",
thread_id="thread_id",
after="after",
before="before",
include=["step_details.tool_calls[*].file_search.results[*].content"],
limit=0,
order="asc",
)
assert_matches_type(AsyncCursorPage[RunStep], step, path=["response"])
@parametrize
async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None:
with pytest.warns(DeprecationWarning):
response = await async_client.beta.threads.runs.steps.with_raw_response.list(
run_id="run_id",
thread_id="thread_id",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
step = response.parse()
assert_matches_type(AsyncCursorPage[RunStep], step, path=["response"])
@parametrize
async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None:
with pytest.warns(DeprecationWarning):
async with async_client.beta.threads.runs.steps.with_streaming_response.list(
run_id="run_id",
thread_id="thread_id",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
step = await response.parse()
assert_matches_type(AsyncCursorPage[RunStep], step, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
async def test_path_params_list(self, async_client: AsyncOpenAI) -> None:
with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"):
await async_client.beta.threads.runs.steps.with_raw_response.list(
run_id="run_id",
thread_id="",
)
with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"):
await async_client.beta.threads.runs.steps.with_raw_response.list(
run_id="",
thread_id="thread_id",
)
| TestAsyncSteps |
python | pypa__warehouse | tests/unit/email/test_init.py | {
"start": 133306,
"end": 136172
} | class ____:
def test_removed_as_collaborator_email(
self, db_request, pyramid_config, monkeypatch
):
removed_user = UserFactory.create()
EmailFactory.create(primary=True, verified=True, public=True, user=removed_user)
submitter_user = UserFactory.create()
EmailFactory.create(
primary=True, verified=True, public=True, user=submitter_user
)
db_request.user = submitter_user
subject_renderer = pyramid_config.testing_add_renderer(
"email/removed-as-collaborator/subject.txt"
)
subject_renderer.string_response = "Email Subject"
body_renderer = pyramid_config.testing_add_renderer(
"email/removed-as-collaborator/body.txt"
)
body_renderer.string_response = "Email Body"
html_renderer = pyramid_config.testing_add_renderer(
"email/removed-as-collaborator/body.html"
)
html_renderer.string_response = "Email HTML Body"
send_email = pretend.stub(
delay=pretend.call_recorder(lambda *args, **kwargs: None)
)
db_request.task = pretend.call_recorder(lambda *args, **kwargs: send_email)
monkeypatch.setattr(email, "send_email", send_email)
result = email.send_removed_as_collaborator_email(
db_request,
removed_user,
submitter=submitter_user,
project_name="test_project",
)
assert result == {
"project": "test_project",
"submitter": submitter_user.username,
}
subject_renderer.assert_()
body_renderer.assert_(submitter=submitter_user.username)
body_renderer.assert_(project="test_project")
html_renderer.assert_(submitter=submitter_user.username)
html_renderer.assert_(project="test_project")
assert db_request.task.calls == [pretend.call(send_email)]
assert send_email.delay.calls == [
pretend.call(
f"{removed_user.name} <{removed_user.primary_email.email}>",
{
"sender": None,
"subject": "Email Subject",
"body_text": "Email Body",
"body_html": (
"<html>\n<head></head>\n"
"<body><p>Email HTML Body</p></body>\n</html>\n"
),
},
{
"tag": "account:email:sent",
"user_id": removed_user.id,
"additional": {
"from_": None,
"to": removed_user.primary_email.email,
"subject": "Email Subject",
"redact_ip": True,
},
},
)
]
| TestRemovedAsCollaboratorEmail |
python | python-pillow__Pillow | Tests/test_image_access.py | {
"start": 3199,
"end": 6667
} | class ____:
@staticmethod
def color(mode: str) -> int | tuple[int, ...]:
bands = Image.getmodebands(mode)
if bands == 1:
return 1
return tuple(range(1, bands + 1))
def check(self, mode: str, expected_color_int: int | None = None) -> None:
expected_color = (
self.color(mode) if expected_color_int is None else expected_color_int
)
# Check putpixel
im = Image.new(mode, (1, 1), None)
im.putpixel((0, 0), expected_color)
actual_color = im.getpixel((0, 0))
assert actual_color == expected_color, (
f"put/getpixel roundtrip failed for mode {mode}, "
f"expected {expected_color} got {actual_color}"
)
# Check putpixel negative index
im.putpixel((-1, -1), expected_color)
actual_color = im.getpixel((-1, -1))
assert actual_color == expected_color, (
f"put/getpixel roundtrip negative index failed for mode {mode}, "
f"expected {expected_color} got {actual_color}"
)
# Check 0x0 image with None initial color
im = Image.new(mode, (0, 0), None)
assert im.load() is not None
with pytest.raises(IndexError):
im.putpixel((0, 0), expected_color)
with pytest.raises(IndexError):
im.getpixel((0, 0))
# Check negative index
with pytest.raises(IndexError):
im.putpixel((-1, -1), expected_color)
with pytest.raises(IndexError):
im.getpixel((-1, -1))
# Check initial color
im = Image.new(mode, (1, 1), expected_color)
actual_color = im.getpixel((0, 0))
assert actual_color == expected_color, (
f"initial color failed for mode {mode}, "
f"expected {expected_color} got {actual_color}"
)
# Check initial color negative index
actual_color = im.getpixel((-1, -1))
assert actual_color == expected_color, (
f"initial color failed with negative index for mode {mode}, "
f"expected {expected_color} got {actual_color}"
)
# Check 0x0 image with initial color
im = Image.new(mode, (0, 0), expected_color)
with pytest.raises(IndexError):
im.getpixel((0, 0))
# Check negative index
with pytest.raises(IndexError):
im.getpixel((-1, -1))
@pytest.mark.parametrize("mode", Image.MODES)
def test_basic(self, mode: str) -> None:
self.check(mode)
def test_list(self) -> None:
im = hopper()
assert im.getpixel([0, 0]) == (20, 20, 70)
@pytest.mark.parametrize("mode", ("I;16", "I;16B"))
@pytest.mark.parametrize("expected_color", (2**15 - 1, 2**15, 2**15 + 1, 2**16 - 1))
def test_signedness(self, mode: str, expected_color: int) -> None:
# See https://github.com/python-pillow/Pillow/issues/452
# pixelaccess is using signed int* instead of uint*
self.check(mode, expected_color)
@pytest.mark.parametrize("mode", ("P", "PA"))
@pytest.mark.parametrize("color", ((255, 0, 0), (255, 0, 0, 255)))
def test_p_putpixel_rgb_rgba(self, mode: str, color: tuple[int, ...]) -> None:
im = Image.new(mode, (1, 1))
im.putpixel((0, 0), color)
alpha = color[3] if len(color) == 4 and mode == "PA" else 255
assert im.convert("RGBA").getpixel((0, 0)) == (255, 0, 0, alpha)
| TestImageGetPixel |
python | Farama-Foundation__Gymnasium | gymnasium/envs/toy_text/taxi.py | {
"start": 445,
"end": 25178
} | class ____(Env):
"""
The Taxi Problem involves navigating to passengers in a grid world, picking them up and dropping them
off at one of four locations.
## Description
There are four designated pick-up and drop-off locations (Red, Green, Yellow and Blue) in the
5x5 grid world. The taxi starts off at a random square and the passenger at one of the
designated locations.
The goal is move the taxi to the passenger's location, pick up the passenger,
move to the passenger's desired destination, and
drop off the passenger. Once the passenger is dropped off, the episode ends.
The player receives positive rewards for successfully dropping-off the passenger at the correct
location. Negative rewards for incorrect attempts to pick-up/drop-off passenger and
for each step where another reward is not received.
Map:
+---------+
|R: | : :G|
| : | : : |
| : : : : |
| | : | : |
|Y| : |B: |
+---------+
From "Hierarchical Reinforcement Learning with the MAXQ Value Function Decomposition"
by Tom Dietterich [<a href="#taxi_ref">1</a>].
## Action Space
The action shape is `(1,)` in the range `{0, 5}` indicating
which direction to move the taxi or to pickup/drop off passengers.
- 0: Move south (down)
- 1: Move north (up)
- 2: Move east (right)
- 3: Move west (left)
- 4: Pickup passenger
- 5: Drop off passenger
## Observation Space
There are 500 discrete states since there are 25 taxi positions, 5 possible
locations of the passenger (including the case when the passenger is in the
taxi), and 4 destination locations.
Destination on the map are represented with the first letter of the color.
Passenger locations:
- 0: Red
- 1: Green
- 2: Yellow
- 3: Blue
- 4: In taxi
Destinations:
- 0: Red
- 1: Green
- 2: Yellow
- 3: Blue
An observation is returned as an `int()` that encodes the corresponding state, calculated by
`((taxi_row * 5 + taxi_col) * 5 + passenger_location) * 4 + destination`
Note that there are 400 states that can actually be reached during an
episode. The missing states correspond to situations in which the passenger
is at the same location as their destination, as this typically signals the
end of an episode. Four additional states can be observed right after a
successful episodes, when both the passenger and the taxi are at the destination.
This gives a total of 404 reachable discrete states.
## Starting State
The initial state is sampled uniformly from the possible states
where the passenger is neither at their destination nor inside the taxi.
There are 300 possible initial states: 25 taxi positions, 4 passenger locations (excluding inside the taxi)
and 3 destinations (excluding the passenger's current location).
## Rewards
- -1 per step unless other reward is triggered.
- +20 delivering passenger.
- -10 executing "pickup" and "drop-off" actions illegally.
An action that results a noop, like moving into a wall, will incur the time step
penalty. Noops can be avoided by sampling the `action_mask` returned in `info`.
## Episode End
The episode ends if the following happens:
- Termination:
1. The taxi drops off the passenger.
- Truncation (when using the time_limit wrapper):
1. The length of the episode is 200.
## Information
`step()` and `reset()` return a dict with the following keys:
- p - transition probability for the state.
- action_mask - if actions will cause a transition to a new state.
For some cases, taking an action will have no effect on the state of the episode.
In v0.25.0, ``info["action_mask"]`` contains a np.ndarray for each of the actions specifying
if the action will change the state.
To sample a modifying action, use ``action = env.action_space.sample(info["action_mask"])``
Or with a Q-value based algorithm ``action = np.argmax(q_values[obs, np.where(info["action_mask"] == 1)[0]])``.
## Arguments
```python
import gymnasium as gym
gym.make('Taxi-v3')
```
<a id="is_raining"></a>`is_raining=False`: If True the cab will move in intended direction with
probability of 80% else will move in either left or right of target direction with
equal probability of 10% in both directions.
<a id="fickle_passenger"></a>`fickle_passenger=False`: If true the passenger has a 30% chance of changing
destinations when the cab has moved one square away from the passenger's source location. Passenger fickleness
only happens on the first pickup and successful movement. If the passenger is dropped off at the source location
and picked up again, it is not triggered again.
## References
<a id="taxi_ref"></a>[1] T. G. Dietterich, “Hierarchical Reinforcement Learning with the MAXQ Value Function Decomposition,”
Journal of Artificial Intelligence Research, vol. 13, pp. 227–303, Nov. 2000, doi: 10.1613/jair.639.
## Version History
* v3: Map Correction + Cleaner Domain Description, v0.25.0 action masking added to the reset and step information
- In Gymnasium `1.2.0` the `is_rainy` and `fickle_passenger` arguments were added to align with Dietterich, 2000
* v2: Disallow Taxi start location = goal location, Update Taxi observations in the rollout, Update Taxi reward threshold.
* v1: Remove (3,2) from locs, add passidx<4 check
* v0: Initial version release
"""
metadata = {
"render_modes": ["human", "ansi", "rgb_array"],
"render_fps": 4,
}
def _pickup(self, taxi_loc, pass_idx, reward):
"""Computes the new location and reward for pickup action."""
if pass_idx < 4 and taxi_loc == self.locs[pass_idx]:
new_pass_idx = 4
new_reward = reward
else: # passenger not at location
new_pass_idx = pass_idx
new_reward = -10
return new_pass_idx, new_reward
def _dropoff(self, taxi_loc, pass_idx, dest_idx, default_reward):
"""Computes the new location and reward for return dropoff action."""
if (taxi_loc == self.locs[dest_idx]) and pass_idx == 4:
new_pass_idx = dest_idx
new_terminated = True
new_reward = 20
elif (taxi_loc in self.locs) and pass_idx == 4:
new_pass_idx = self.locs.index(taxi_loc)
new_terminated = False
new_reward = default_reward
else: # dropoff at wrong location
new_pass_idx = pass_idx
new_terminated = False
new_reward = -10
return new_pass_idx, new_reward, new_terminated
def _build_dry_transitions(self, row, col, pass_idx, dest_idx, action):
"""Computes the next action for a state (row, col, pass_idx, dest_idx) and action."""
state = self.encode(row, col, pass_idx, dest_idx)
taxi_loc = (row, col)
new_row, new_col, new_pass_idx = row, col, pass_idx
reward = -1 # default reward when there is no pickup/dropoff
terminated = False
if action == 0:
new_row = min(row + 1, self.max_row)
elif action == 1:
new_row = max(row - 1, 0)
if action == 2 and self.desc[1 + row, 2 * col + 2] == b":":
new_col = min(col + 1, self.max_col)
elif action == 3 and self.desc[1 + row, 2 * col] == b":":
new_col = max(col - 1, 0)
elif action == 4: # pickup
new_pass_idx, reward = self._pickup(taxi_loc, new_pass_idx, reward)
elif action == 5: # dropoff
new_pass_idx, reward, terminated = self._dropoff(
taxi_loc, new_pass_idx, dest_idx, reward
)
new_state = self.encode(new_row, new_col, new_pass_idx, dest_idx)
self.P[state][action].append((1.0, new_state, reward, terminated))
def _calc_new_position(self, row, col, movement, offset=0):
"""Calculates the new position for a row and col to the movement."""
dr, dc = movement
new_row = max(0, min(row + dr, self.max_row))
new_col = max(0, min(col + dc, self.max_col))
if self.desc[1 + new_row, 2 * new_col + offset] == b":":
return new_row, new_col
else: # Default to current position if not traversable
return row, col
def _build_rainy_transitions(self, row, col, pass_idx, dest_idx, action):
"""Computes the next action for a state (row, col, pass_idx, dest_idx) and action for `is_rainy`."""
state = self.encode(row, col, pass_idx, dest_idx)
taxi_loc = left_pos = right_pos = (row, col)
new_row, new_col, new_pass_idx = row, col, pass_idx
reward = -1 # default reward when there is no pickup/dropoff
terminated = False
moves = {
0: ((1, 0), (0, -1), (0, 1)), # Down
1: ((-1, 0), (0, -1), (0, 1)), # Up
2: ((0, 1), (1, 0), (-1, 0)), # Right
3: ((0, -1), (1, 0), (-1, 0)), # Left
}
# Check if movement is allowed
if (
action in {0, 1}
or (action == 2 and self.desc[1 + row, 2 * col + 2] == b":")
or (action == 3 and self.desc[1 + row, 2 * col] == b":")
):
dr, dc = moves[action][0]
new_row = max(0, min(row + dr, self.max_row))
new_col = max(0, min(col + dc, self.max_col))
left_pos = self._calc_new_position(row, col, moves[action][1], offset=2)
right_pos = self._calc_new_position(row, col, moves[action][2])
elif action == 4: # pickup
new_pass_idx, reward = self._pickup(taxi_loc, new_pass_idx, reward)
elif action == 5: # dropoff
new_pass_idx, reward, terminated = self._dropoff(
taxi_loc, new_pass_idx, dest_idx, reward
)
intended_state = self.encode(new_row, new_col, new_pass_idx, dest_idx)
if action <= 3:
left_state = self.encode(left_pos[0], left_pos[1], new_pass_idx, dest_idx)
right_state = self.encode(
right_pos[0], right_pos[1], new_pass_idx, dest_idx
)
self.P[state][action].append((0.8, intended_state, -1, terminated))
self.P[state][action].append((0.1, left_state, -1, terminated))
self.P[state][action].append((0.1, right_state, -1, terminated))
else:
self.P[state][action].append((1.0, intended_state, reward, terminated))
def __init__(
self,
render_mode: str | None = None,
is_rainy: bool = False,
fickle_passenger: bool = False,
):
self.desc = np.asarray(MAP, dtype="c")
self.locs = locs = [(0, 0), (0, 4), (4, 0), (4, 3)]
self.locs_colors = [(255, 0, 0), (0, 255, 0), (255, 255, 0), (0, 0, 255)]
num_states = 500
num_rows = 5
num_columns = 5
self.max_row = num_rows - 1
self.max_col = num_columns - 1
self.initial_state_distrib = np.zeros(num_states)
num_actions = 6
self.P = {
state: {action: [] for action in range(num_actions)}
for state in range(num_states)
}
for row in range(num_rows):
for col in range(num_columns):
for pass_idx in range(len(locs) + 1): # +1 for being inside taxi
for dest_idx in range(len(locs)):
state = self.encode(row, col, pass_idx, dest_idx)
if pass_idx < 4 and pass_idx != dest_idx:
self.initial_state_distrib[state] += 1
for action in range(num_actions):
if is_rainy:
self._build_rainy_transitions(
row,
col,
pass_idx,
dest_idx,
action,
)
else:
self._build_dry_transitions(
row,
col,
pass_idx,
dest_idx,
action,
)
self.initial_state_distrib /= self.initial_state_distrib.sum()
self.action_space = spaces.Discrete(num_actions)
self.observation_space = spaces.Discrete(num_states)
self.render_mode = render_mode
self.fickle_passenger = fickle_passenger
self.fickle_step = self.fickle_passenger and self.np_random.random() < 0.3
# pygame utils
self.window = None
self.clock = None
self.cell_size = (
WINDOW_SIZE[0] / self.desc.shape[1],
WINDOW_SIZE[1] / self.desc.shape[0],
)
self.taxi_imgs = None
self.taxi_orientation = 0
self.passenger_img = None
self.destination_img = None
self.median_horiz = None
self.median_vert = None
self.background_img = None
def encode(self, taxi_row, taxi_col, pass_loc, dest_idx):
# (5) 5, 5, 4
i = taxi_row
i *= 5
i += taxi_col
i *= 5
i += pass_loc
i *= 4
i += dest_idx
return i
def decode(self, i):
out = []
out.append(i % 4)
i = i // 4
out.append(i % 5)
i = i // 5
out.append(i % 5)
i = i // 5
out.append(i)
assert 0 <= i < 5
return reversed(out)
def action_mask(self, state: int):
"""Computes an action mask for the action space using the state information."""
mask = np.zeros(6, dtype=np.int8)
taxi_row, taxi_col, pass_loc, dest_idx = self.decode(state)
if taxi_row < 4:
mask[0] = 1
if taxi_row > 0:
mask[1] = 1
if taxi_col < 4 and self.desc[taxi_row + 1, 2 * taxi_col + 2] == b":":
mask[2] = 1
if taxi_col > 0 and self.desc[taxi_row + 1, 2 * taxi_col] == b":":
mask[3] = 1
if pass_loc < 4 and (taxi_row, taxi_col) == self.locs[pass_loc]:
mask[4] = 1
if pass_loc == 4 and (
(taxi_row, taxi_col) == self.locs[dest_idx]
or (taxi_row, taxi_col) in self.locs
):
mask[5] = 1
return mask
def step(self, a):
transitions = self.P[self.s][a]
i = categorical_sample([t[0] for t in transitions], self.np_random)
p, s, r, t = transitions[i]
self.lastaction = a
shadow_row, shadow_col, shadow_pass_loc, shadow_dest_idx = self.decode(self.s)
taxi_row, taxi_col, pass_loc, _ = self.decode(s)
# If we are in the fickle step, the passenger has been in the vehicle for at least a step and this step the
# position changed
if (
self.fickle_passenger
and self.fickle_step
and shadow_pass_loc == 4
and (taxi_row != shadow_row or taxi_col != shadow_col)
):
self.fickle_step = False
possible_destinations = [
i for i in range(len(self.locs)) if i != shadow_dest_idx
]
dest_idx = self.np_random.choice(possible_destinations)
s = self.encode(taxi_row, taxi_col, pass_loc, dest_idx)
self.s = s
if self.render_mode == "human":
self.render()
# truncation=False as the time limit is handled by the `TimeLimit` wrapper added during `make`
return int(s), r, t, False, {"prob": p, "action_mask": self.action_mask(s)}
def reset(
self,
*,
seed: int | None = None,
options: dict | None = None,
):
super().reset(seed=seed)
self.s = categorical_sample(self.initial_state_distrib, self.np_random)
self.lastaction = None
self.fickle_step = self.fickle_passenger and self.np_random.random() < 0.3
self.taxi_orientation = 0
if self.render_mode == "human":
self.render()
return int(self.s), {"prob": 1.0, "action_mask": self.action_mask(self.s)}
def render(self):
if self.render_mode is None:
assert self.spec is not None
gym.logger.warn(
"You are calling render method without specifying any render mode. "
"You can specify the render_mode at initialization, "
f'e.g. gym.make("{self.spec.id}", render_mode="rgb_array")'
)
return
elif self.render_mode == "ansi":
return self._render_text()
else: # self.render_mode in {"human", "rgb_array"}:
return self._render_gui(self.render_mode)
def _render_gui(self, mode):
try:
import pygame # dependency to pygame only if rendering with human
except ImportError as e:
raise DependencyNotInstalled(
'pygame is not installed, run `pip install "gymnasium[toy-text]"`'
) from e
if self.window is None:
pygame.init()
pygame.display.set_caption("Taxi")
if mode == "human":
self.window = pygame.display.set_mode(WINDOW_SIZE)
elif mode == "rgb_array":
self.window = pygame.Surface(WINDOW_SIZE)
assert (
self.window is not None
), "Something went wrong with pygame. This should never happen."
if self.clock is None:
self.clock = pygame.time.Clock()
if self.taxi_imgs is None:
file_names = [
path.join(path.dirname(__file__), "img/cab_front.png"),
path.join(path.dirname(__file__), "img/cab_rear.png"),
path.join(path.dirname(__file__), "img/cab_right.png"),
path.join(path.dirname(__file__), "img/cab_left.png"),
]
self.taxi_imgs = [
pygame.transform.scale(pygame.image.load(file_name), self.cell_size)
for file_name in file_names
]
if self.passenger_img is None:
file_name = path.join(path.dirname(__file__), "img/passenger.png")
self.passenger_img = pygame.transform.scale(
pygame.image.load(file_name), self.cell_size
)
if self.destination_img is None:
file_name = path.join(path.dirname(__file__), "img/hotel.png")
self.destination_img = pygame.transform.scale(
pygame.image.load(file_name), self.cell_size
)
self.destination_img.set_alpha(170)
if self.median_horiz is None:
file_names = [
path.join(path.dirname(__file__), "img/gridworld_median_left.png"),
path.join(path.dirname(__file__), "img/gridworld_median_horiz.png"),
path.join(path.dirname(__file__), "img/gridworld_median_right.png"),
]
self.median_horiz = [
pygame.transform.scale(pygame.image.load(file_name), self.cell_size)
for file_name in file_names
]
if self.median_vert is None:
file_names = [
path.join(path.dirname(__file__), "img/gridworld_median_top.png"),
path.join(path.dirname(__file__), "img/gridworld_median_vert.png"),
path.join(path.dirname(__file__), "img/gridworld_median_bottom.png"),
]
self.median_vert = [
pygame.transform.scale(pygame.image.load(file_name), self.cell_size)
for file_name in file_names
]
if self.background_img is None:
file_name = path.join(path.dirname(__file__), "img/taxi_background.png")
self.background_img = pygame.transform.scale(
pygame.image.load(file_name), self.cell_size
)
desc = self.desc
for y in range(0, desc.shape[0]):
for x in range(0, desc.shape[1]):
cell = (x * self.cell_size[0], y * self.cell_size[1])
self.window.blit(self.background_img, cell)
if desc[y][x] == b"|" and (y == 0 or desc[y - 1][x] != b"|"):
self.window.blit(self.median_vert[0], cell)
elif desc[y][x] == b"|" and (
y == desc.shape[0] - 1 or desc[y + 1][x] != b"|"
):
self.window.blit(self.median_vert[2], cell)
elif desc[y][x] == b"|":
self.window.blit(self.median_vert[1], cell)
elif desc[y][x] == b"-" and (x == 0 or desc[y][x - 1] != b"-"):
self.window.blit(self.median_horiz[0], cell)
elif desc[y][x] == b"-" and (
x == desc.shape[1] - 1 or desc[y][x + 1] != b"-"
):
self.window.blit(self.median_horiz[2], cell)
elif desc[y][x] == b"-":
self.window.blit(self.median_horiz[1], cell)
for cell, color in zip(self.locs, self.locs_colors):
color_cell = pygame.Surface(self.cell_size)
color_cell.set_alpha(128)
color_cell.fill(color)
loc = self.get_surf_loc(cell)
self.window.blit(color_cell, (loc[0], loc[1] + 10))
taxi_row, taxi_col, pass_idx, dest_idx = self.decode(self.s)
if pass_idx < 4:
self.window.blit(self.passenger_img, self.get_surf_loc(self.locs[pass_idx]))
if self.lastaction in [0, 1, 2, 3]:
self.taxi_orientation = self.lastaction
dest_loc = self.get_surf_loc(self.locs[dest_idx])
taxi_location = self.get_surf_loc((taxi_row, taxi_col))
if dest_loc[1] <= taxi_location[1]:
self.window.blit(
self.destination_img,
(dest_loc[0], dest_loc[1] - self.cell_size[1] // 2),
)
self.window.blit(self.taxi_imgs[self.taxi_orientation], taxi_location)
else: # change blit order for overlapping appearance
self.window.blit(self.taxi_imgs[self.taxi_orientation], taxi_location)
self.window.blit(
self.destination_img,
(dest_loc[0], dest_loc[1] - self.cell_size[1] // 2),
)
if mode == "human":
pygame.event.pump()
pygame.display.update()
self.clock.tick(self.metadata["render_fps"])
elif mode == "rgb_array":
return np.transpose(
np.array(pygame.surfarray.pixels3d(self.window)), axes=(1, 0, 2)
)
def get_surf_loc(self, map_loc):
return (map_loc[1] * 2 + 1) * self.cell_size[0], (
map_loc[0] + 1
) * self.cell_size[1]
def _render_text(self):
desc = self.desc.copy().tolist()
outfile = StringIO()
out = [[c.decode("utf-8") for c in line] for line in desc]
taxi_row, taxi_col, pass_idx, dest_idx = self.decode(self.s)
def ul(x):
return "_" if x == " " else x
if pass_idx < 4:
out[1 + taxi_row][2 * taxi_col + 1] = utils.colorize(
out[1 + taxi_row][2 * taxi_col + 1], "yellow", highlight=True
)
pi, pj = self.locs[pass_idx]
out[1 + pi][2 * pj + 1] = utils.colorize(
out[1 + pi][2 * pj + 1], "blue", bold=True
)
else: # passenger in taxi
out[1 + taxi_row][2 * taxi_col + 1] = utils.colorize(
ul(out[1 + taxi_row][2 * taxi_col + 1]), "green", highlight=True
)
di, dj = self.locs[dest_idx]
out[1 + di][2 * dj + 1] = utils.colorize(out[1 + di][2 * dj + 1], "magenta")
outfile.write("\n".join(["".join(row) for row in out]) + "\n")
if self.lastaction is not None:
outfile.write(
f" ({['South', 'North', 'East', 'West', 'Pickup', 'Dropoff'][self.lastaction]})\n"
)
else:
outfile.write("\n")
with closing(outfile):
return outfile.getvalue()
def close(self):
if self.window is not None:
import pygame
pygame.display.quit()
pygame.quit()
# Taxi rider from https://franuka.itch.io/rpg-asset-pack
# All other assets by Mel Tillery http://www.cyaneus.com/
| TaxiEnv |
python | spack__spack | lib/spack/spack/test/cmd/repo.py | {
"start": 4167,
"end": 4367
} | class ____(Package):
pass
"""
NEW_7ZIP = b"""\
# some comment
from spack_repo.builtin.build_systems.generic import Package
from spack.package import *
from ..blt.package import linker_helpers
| _7zip |
python | falconry__falcon | falcon/util/mediatypes.py | {
"start": 3873,
"end": 4306
} | class ____:
main_type: str
subtype: str
params: dict
# NOTE(vytas): Using __slots__ with dataclasses is tricky, but it seems to
# work here since we are not using any default values in the definition.
__slots__ = ('main_type', 'subtype', 'params')
@classmethod
def parse(cls, media_type: str) -> _MediaType:
return cls(*_parse_media_type_header(media_type))
@dataclasses.dataclass
| _MediaType |
python | langchain-ai__langchain | libs/core/langchain_core/prompts/chat.py | {
"start": 11259,
"end": 11338
} | class ____(TypedDict, total=False):
image_url: str | dict
| _ImageTemplateParam |
python | dagster-io__dagster | python_modules/automation/automation/dagster_docs/watcher.py | {
"start": 10158,
"end": 11492
} | class ____:
"""Watches a file for changes and triggers docstring validation."""
def __init__(
self, target_file: Path, validation_callback: Callable[[], None], verbose: bool = False
) -> None:
"""Initialize the file watcher.
Args:
target_file: The file to watch for changes
validation_callback: Function to call when the file changes
verbose: Whether to print debug information about file events
"""
self.target_file = target_file.resolve()
self.validation_callback = validation_callback
self.observer = Observer()
self.handler = DocstringValidationHandler(target_file, validation_callback, verbose)
def start_watching(self) -> None:
"""Start watching the file for changes."""
if not self.target_file.exists():
raise FileNotFoundError(f"Target file does not exist: {self.target_file}")
# Watch the parent directory since we need to catch modifications to the file
watch_dir = self.target_file.parent
self.observer.schedule(self.handler, str(watch_dir), recursive=False)
self.observer.start()
def stop_watching(self) -> None:
"""Stop watching the file for changes."""
self.observer.stop()
self.observer.join()
| DocstringFileWatcher |
python | huggingface__transformers | src/transformers/models/recurrent_gemma/modeling_recurrent_gemma.py | {
"start": 14352,
"end": 15006
} | class ____(torch.autograd.Function):
"""Computes a square root with a gradient clipped at `_MAX_SQRT_GRADIENT`."""
@staticmethod
def forward(ctx, x: torch.Tensor) -> torch.Tensor:
"""The forward pass, which is a normal `sqrt`."""
ctx.save_for_backward(x)
return torch.sqrt(x)
@staticmethod
def backward(ctx, grad_output: torch.Tensor) -> torch.Tensor:
"""The backward pass, which clips the `sqrt` gradient."""
(x,) = ctx.saved_tensors
clipped_x_times_4 = torch.clip(4.0 * x, min=1 / (_MAX_SQRT_GRADIENT**2))
return grad_output / torch.sqrt(clipped_x_times_4)
| SqrtBoundDerivative |
python | realpython__materials | python-property/circle_v5.py | {
"start": 25,
"end": 479
} | class ____:
def __init__(self, radius):
self.radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
self._diameter = None
self._radius = value
@property
def diameter(self):
if self._diameter is None:
sleep(0.5) # Simulate a costly computation
self._diameter = self._radius * 2
return self._diameter
| Circle |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/list_files_test.py | {
"start": 1414,
"end": 9115
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
def setUp(self):
super(ListFilesTest, self).setUp()
self.tmp_dir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tmp_dir, ignore_errors=True)
super(ListFilesTest, self).tearDown()
def _touchTempFiles(self, filenames):
for filename in filenames:
open(path.join(self.tmp_dir, filename), 'a').close()
@combinations.generate(test_base.default_test_combinations())
def testEmptyDirectory(self):
with self.assertRaisesWithPredicateMatch(errors.InvalidArgumentError,
'No files matched'):
dataset = dataset_ops.Dataset.list_files(path.join(self.tmp_dir, '*'))
# We need requires_initialization=True so that getNext uses
# make_initializable_iterator instead of make_one_shot_iterator.
# make_one_shot_iterator has an issue where it fails to capture control
# dependencies when capturing the dataset, so it loses the assertion that
# list_files matches at least one file.
# TODO(b/140837601): Make this work with make_one_shot_iterator.
self.getNext(dataset, requires_initialization=True)
@combinations.generate(test_base.default_test_combinations())
def testSimpleDirectory(self):
filenames = ['a', 'b', 'c']
self._touchTempFiles(filenames)
dataset = dataset_ops.Dataset.list_files(path.join(self.tmp_dir, '*'))
self.assertDatasetProduces(
dataset,
expected_output=[
compat.as_bytes(path.join(self.tmp_dir, filename))
for filename in filenames
],
assert_items_equal=True)
@combinations.generate(test_base.default_test_combinations())
def testSimpleDirectoryNotShuffled(self):
filenames = ['b', 'c', 'a']
self._touchTempFiles(filenames)
dataset = dataset_ops.Dataset.list_files(
path.join(self.tmp_dir, '*'), shuffle=False)
self.assertDatasetProduces(
dataset,
expected_output=[
compat.as_bytes(path.join(self.tmp_dir, filename))
for filename in sorted(filenames)
])
def testFixedSeedResultsInRepeatableOrder(self):
filenames = ['a', 'b', 'c']
self._touchTempFiles(filenames)
def dataset_fn():
return dataset_ops.Dataset.list_files(
path.join(self.tmp_dir, '*'), shuffle=True, seed=37)
expected_filenames = [
compat.as_bytes(path.join(self.tmp_dir, filename))
for filename in filenames
]
all_actual_filenames = []
for _ in range(3):
actual_filenames = []
next_element = self.getNext(dataset_fn(), requires_initialization=True)
try:
while True:
actual_filenames.append(self.evaluate(next_element()))
except errors.OutOfRangeError:
pass
all_actual_filenames.append(actual_filenames)
# Each run should produce the same set of filenames, which may be
# different from the order of `expected_filenames`.
self.assertCountEqual(expected_filenames, all_actual_filenames[0])
# However, the different runs should produce filenames in the same order
# as each other.
self.assertEqual(all_actual_filenames[0], all_actual_filenames[1])
self.assertEqual(all_actual_filenames[0], all_actual_filenames[2])
@combinations.generate(test_base.default_test_combinations())
def tesEmptyDirectoryInitializer(self):
def dataset_fn():
return dataset_ops.Dataset.list_files(path.join(self.tmp_dir, '*'))
self.assertDatasetProduces(
dataset_fn(),
expected_error=(errors.InvalidArgumentError,
'No files matched pattern'),
requires_initialization=True)
@combinations.generate(test_base.default_test_combinations())
def testSimpleDirectoryInitializer(self):
filenames = ['a', 'b', 'c']
self._touchTempFiles(filenames)
dataset = dataset_ops.Dataset.list_files(path.join(self.tmp_dir, '*'))
self.assertDatasetProduces(
dataset,
expected_output=[
compat.as_bytes(path.join(self.tmp_dir, filename))
for filename in filenames
],
assert_items_equal=True)
@combinations.generate(test_base.default_test_combinations())
def testFileSuffixes(self):
filenames = ['a.txt', 'b.py', 'c.py', 'd.pyc']
self._touchTempFiles(filenames)
dataset = dataset_ops.Dataset.list_files(path.join(self.tmp_dir, '*.py'))
self.assertDatasetProduces(
dataset,
expected_output=[
compat.as_bytes(path.join(self.tmp_dir, filename))
for filename in filenames[1:-1]
],
assert_items_equal=True)
@combinations.generate(test_base.default_test_combinations())
def testFileMiddles(self):
filenames = ['a.txt', 'b.py', 'c.pyc']
self._touchTempFiles(filenames)
dataset = dataset_ops.Dataset.list_files(path.join(self.tmp_dir, '*.py*'))
self.assertDatasetProduces(
dataset,
expected_output=[
compat.as_bytes(path.join(self.tmp_dir, filename))
for filename in filenames[1:]
],
assert_items_equal=True)
@combinations.generate(test_base.default_test_combinations())
def testNoShuffle(self):
filenames = ['a', 'b', 'c']
self._touchTempFiles(filenames)
# Repeat the list twice and ensure that the order is the same each time.
# NOTE(mrry): This depends on an implementation detail of `list_files()`,
# which is that the list of files is captured when the iterator is
# initialized. Otherwise, or if e.g. the iterator were initialized more than
# once, it's possible that the non-determinism of `tf.matching_files()`
# would cause this test to fail. However, it serves as a useful confirmation
# that the `shuffle=False` argument is working as intended.
# TODO(b/73959787): Provide some ordering guarantees so that this test is
# more meaningful.
dataset = dataset_ops.Dataset.list_files(
path.join(self.tmp_dir, '*'), shuffle=False).repeat(2)
next_element = self.getNext(dataset)
expected_filenames = []
actual_filenames = []
for filename in filenames * 2:
expected_filenames.append(
compat.as_bytes(path.join(self.tmp_dir, filename)))
actual_filenames.append(compat.as_bytes(self.evaluate(next_element())))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(next_element())
self.assertCountEqual(expected_filenames, actual_filenames)
self.assertEqual(actual_filenames[:len(filenames)],
actual_filenames[len(filenames):])
@combinations.generate(test_base.default_test_combinations())
def testMultiplePatternsAsList(self):
filenames = ['a.txt', 'b.py', 'c.py', 'd.pyc']
self._touchTempFiles(filenames)
patterns = [path.join(self.tmp_dir, pat) for pat in ['*.py', '*.txt']]
dataset = dataset_ops.Dataset.list_files(patterns)
self.assertDatasetProduces(
dataset,
expected_output=[
compat.as_bytes(path.join(self.tmp_dir, filename))
for filename in filenames[:-1]
],
assert_items_equal=True)
@combinations.generate(test_base.default_test_combinations())
def testMultiplePatternsAsTensor(self):
filenames = ['a.txt', 'b.py', 'c.py', 'd.pyc']
self._touchTempFiles(filenames)
dataset = dataset_ops.Dataset.list_files(
[path.join(self.tmp_dir, pat) for pat in ['*.py', '*.txt']])
self.assertDatasetProduces(
dataset,
expected_output=[
compat.as_bytes(path.join(self.tmp_dir, filename))
for filename in filenames[:-1]
],
assert_items_equal=True)
| ListFilesTest |
python | coleifer__peewee | peewee.py | {
"start": 275561,
"end": 282044
} | class ____(collections.namedtuple('_PrefetchQuery', (
'query', 'fields', 'is_backref', 'rel_models', 'field_to_name', 'model'))):
def __new__(cls, query, fields=None, is_backref=None, rel_models=None,
field_to_name=None, model=None):
if fields:
if is_backref:
if rel_models is None:
rel_models = [field.model for field in fields]
foreign_key_attrs = [field.rel_field.name for field in fields]
else:
if rel_models is None:
rel_models = [field.rel_model for field in fields]
foreign_key_attrs = [field.name for field in fields]
field_to_name = list(zip(fields, foreign_key_attrs))
model = query.model
return super(PrefetchQuery, cls).__new__(
cls, query, fields, is_backref, rel_models, field_to_name, model)
def populate_instance(self, instance, id_map):
if self.is_backref:
for field in self.fields:
identifier = instance.__data__[field.name]
key = (field, identifier)
if key in id_map:
setattr(instance, field.name, id_map[key])
else:
for field, attname in self.field_to_name:
identifier = instance.__data__[field.rel_field.name]
key = (field, identifier)
rel_instances = id_map.get(key, [])
for inst in rel_instances:
setattr(inst, attname, instance)
inst._dirty.clear()
setattr(instance, field.backref, rel_instances)
def store_instance(self, instance, id_map):
for field, attname in self.field_to_name:
identity = field.rel_field.python_value(instance.__data__[attname])
key = (field, identity)
if self.is_backref:
id_map[key] = instance
else:
id_map.setdefault(key, [])
id_map[key].append(instance)
def prefetch_add_subquery(sq, subqueries, prefetch_type):
fixed_queries = [PrefetchQuery(sq)]
for i, subquery in enumerate(subqueries):
if isinstance(subquery, tuple):
subquery, target_model = subquery
else:
target_model = None
if not isinstance(subquery, Query) and is_model(subquery) or \
isinstance(subquery, ModelAlias):
subquery = subquery.select()
subquery_model = subquery.model
for j in reversed(range(i + 1)):
fks = backrefs = None
fixed = fixed_queries[j]
last_query = fixed.query
last_model = last_obj = fixed.model
if isinstance(last_model, ModelAlias):
last_model = last_model.model
rels = subquery_model._meta.model_refs.get(last_model, [])
if rels:
fks = [getattr(subquery_model, fk.name) for fk in rels]
pks = [getattr(last_obj, fk.rel_field.name) for fk in rels]
else:
backrefs = subquery_model._meta.model_backrefs.get(last_model)
if (fks or backrefs) and ((target_model is last_obj) or
(target_model is None)):
break
else:
tgt_err = ' using %s' % target_model if target_model else ''
raise AttributeError('Error: unable to find foreign key for '
'query: %s%s' % (subquery, tgt_err))
dest = (target_model,) if target_model else None
if fks:
if prefetch_type == PREFETCH_TYPE.WHERE:
expr = reduce(operator.or_, [
(fk << last_query.select(pk))
for (fk, pk) in zip(fks, pks)])
subquery = subquery.where(expr)
elif prefetch_type == PREFETCH_TYPE.JOIN:
expr = []
select_pks = set()
for fk, pk in zip(fks, pks):
expr.append(getattr(last_query.c, pk.column_name) == fk)
select_pks.add(pk)
subquery = subquery.distinct().join(
last_query.select(*select_pks),
on=reduce(operator.or_, expr))
fixed_queries.append(PrefetchQuery(subquery, fks, False, dest))
elif backrefs:
expr = []
fields = []
for backref in backrefs:
rel_field = getattr(subquery_model, backref.rel_field.name)
fk_field = getattr(last_obj, backref.name)
fields.append((rel_field, fk_field))
if prefetch_type == PREFETCH_TYPE.WHERE:
for rel_field, fk_field in fields:
expr.append(rel_field << last_query.select(fk_field))
subquery = subquery.where(reduce(operator.or_, expr))
elif prefetch_type == PREFETCH_TYPE.JOIN:
select_fks = []
for rel_field, fk_field in fields:
select_fks.append(fk_field)
target = getattr(last_query.c, fk_field.column_name)
expr.append(rel_field == target)
subquery = subquery.distinct().join(
last_query.select(*select_fks),
on=reduce(operator.or_, expr))
fixed_queries.append(PrefetchQuery(subquery, backrefs, True, dest))
return fixed_queries
def prefetch(sq, *subqueries, **kwargs):
if not subqueries:
return sq
prefetch_type = kwargs.pop('prefetch_type', PREFETCH_TYPE.WHERE)
if kwargs:
raise ValueError('Unrecognized arguments: %s' % kwargs)
fixed_queries = prefetch_add_subquery(sq, subqueries, prefetch_type)
deps = {}
rel_map = {}
for pq in reversed(fixed_queries):
query_model = pq.model
if pq.fields:
for rel_model in pq.rel_models:
rel_map.setdefault(rel_model, [])
rel_map[rel_model].append(pq)
deps.setdefault(query_model, {})
id_map = deps[query_model]
has_relations = bool(rel_map.get(query_model))
for instance in pq.query:
if pq.fields:
pq.store_instance(instance, id_map)
if has_relations:
for rel in rel_map[query_model]:
rel.populate_instance(instance, deps[rel.model])
return list(pq.query)
| PrefetchQuery |
python | huggingface__transformers | tests/pipelines/test_pipelines_video_classification.py | {
"start": 1149,
"end": 4550
} | class ____(unittest.TestCase):
model_mapping = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING
example_video_filepath = None
@classmethod
def _load_dataset(cls):
# Lazy loading of the dataset. Because it is a class method, it will only be loaded once per pytest process.
if cls.example_video_filepath is None:
cls.example_video_filepath = hf_hub_download(
repo_id="nateraw/video-demo", filename="archery.mp4", repo_type="dataset"
)
def get_test_pipeline(
self,
model,
tokenizer=None,
image_processor=None,
feature_extractor=None,
processor=None,
dtype="float32",
):
self._load_dataset()
video_classifier = VideoClassificationPipeline(
model=model,
tokenizer=tokenizer,
feature_extractor=feature_extractor,
image_processor=image_processor,
processor=processor,
dtype=dtype,
top_k=2,
)
examples = [
self.example_video_filepath,
# TODO: re-enable this once we have a stable hub solution for CI
# "https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4",
]
return video_classifier, examples
def run_pipeline_test(self, video_classifier, examples):
for example in examples:
outputs = video_classifier(example)
self.assertEqual(
outputs,
[
{"score": ANY(float), "label": ANY(str)},
{"score": ANY(float), "label": ANY(str)},
],
)
for element in outputs:
compare_pipeline_output_to_hub_spec(element, VideoClassificationOutputElement)
@require_torch
def test_small_model_pt(self):
small_model = "hf-internal-testing/tiny-random-VideoMAEForVideoClassification"
small_feature_extractor = VideoMAEImageProcessor(
size={"shortest_edge": 10}, crop_size={"height": 10, "width": 10}
)
video_classifier = pipeline(
"video-classification", model=small_model, feature_extractor=small_feature_extractor, frame_sampling_rate=4
)
video_file_path = hf_hub_download(repo_id="nateraw/video-demo", filename="archery.mp4", repo_type="dataset")
output = video_classifier(video_file_path, top_k=2)
self.assertEqual(
nested_simplify(output, decimals=4),
[{"score": 0.5199, "label": "LABEL_0"}, {"score": 0.4801, "label": "LABEL_1"}],
)
for element in output:
compare_pipeline_output_to_hub_spec(element, VideoClassificationOutputElement)
outputs = video_classifier(
[
video_file_path,
video_file_path,
],
top_k=2,
)
self.assertEqual(
nested_simplify(outputs, decimals=4),
[
[{"score": 0.5199, "label": "LABEL_0"}, {"score": 0.4801, "label": "LABEL_1"}],
[{"score": 0.5199, "label": "LABEL_0"}, {"score": 0.4801, "label": "LABEL_1"}],
],
)
for output in outputs:
for element in output:
compare_pipeline_output_to_hub_spec(element, VideoClassificationOutputElement)
| VideoClassificationPipelineTests |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/visitors.py | {
"start": 14288,
"end": 14415
} | class ____(Protocol):
def __call__(s, self: object, visitor: HasTraversalDispatch) -> Any: ...
| _InternalTraversalDispatchType |
python | python__mypy | mypyc/irbuild/targets.py | {
"start": 279,
"end": 657
} | class ____(AssignmentTarget):
"""Register as an assignment target.
This is used for local variables and some temporaries.
"""
def __init__(self, register: Register) -> None:
self.register = register
self.type = register.type
def __repr__(self) -> str:
return f"AssignmentTargetRegister({self.register.name})"
| AssignmentTargetRegister |
python | python-pillow__Pillow | src/PIL/PdfParser.py | {
"start": 1617,
"end": 1909
} | class ____(RuntimeError):
"""An error that probably indicates a syntactic or semantic error in the
PDF file structure"""
pass
def check_format_condition(condition: bool, error_message: str) -> None:
if not condition:
raise PdfFormatError(error_message)
| PdfFormatError |
python | huggingface__transformers | src/transformers/models/qwen2_vl/modeling_qwen2_vl.py | {
"start": 13566,
"end": 15535
} | class ____(nn.Module):
def __init__(self, dim: int, hidden_dim: int, hidden_act: str) -> None:
super().__init__()
self.fc1 = nn.Linear(dim, hidden_dim)
self.act = ACT2FN[hidden_act]
self.fc2 = nn.Linear(hidden_dim, dim)
def forward(self, x) -> torch.Tensor:
return self.fc2(self.act(self.fc1(x)))
# Copied from transformers.models.llama.modeling_llama.repeat_kv
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
"""
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
scaling: float,
dropout: float = 0.0,
**kwargs,
):
key_states = repeat_kv(key, module.num_key_value_groups)
value_states = repeat_kv(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
if attention_mask is not None:
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
attn_weights = attn_weights + causal_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value_states)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
| VisionMlp |
python | django__django | tests/serializers/models/data.py | {
"start": 1331,
"end": 1404
} | class ____(models.Model):
data = models.FloatField(null=True)
| FloatData |
python | ipython__ipython | IPython/extensions/tests/test_deduperreload.py | {
"start": 18252,
"end": 19215
} | class ____:
def __init__(self):
self.ns = {}
self.user_ns = self.ns
self.user_ns_hidden = {}
self.auto_magics = AutoreloadMagics(shell=self)
@staticmethod
def pre_run_cell(obj):
try_with_arg = False
try:
obj.pre_run_cell()
except TypeError:
try_with_arg = True
if try_with_arg:
obj.pre_run_cell(None)
@staticmethod
def post_run_cell(obj):
try_with_arg = False
try:
obj.post_run_cell()
except TypeError:
try_with_arg = True
if try_with_arg:
obj.post_run_cell(None)
def run_code(self, code):
self.pre_run_cell(self.auto_magics)
exec(code, self.user_ns)
self.auto_magics.post_execute_hook()
def push(self, items):
self.ns.update(items)
def magic_autoreload(self, parameter):
self.auto_magics.autoreload(parameter)
| FakeShell |
python | dask__dask | dask/dataframe/dask_expr/_quantiles.py | {
"start": 386,
"end": 2546
} | class ____(Expr):
_parameters = ["frame", "input_npartitions", "upsample", "random_state"]
_defaults = {"upsample": 1.0, "random_state": None}
@functools.cached_property
def _meta(self):
return self.frame._meta
@property
def npartitions(self):
return 1
def _divisions(self):
return 0.0, 1.0
def __dask_postcompute__(self):
return toolz.first, ()
def _layer(self):
import pandas as pd
qs = np.linspace(0, 1, self.input_npartitions + 1)
if self.random_state is None:
random_state = int(tokenize(self.operands), 16) % np.iinfo(np.int32).max
else:
random_state = self.random_state
state_data = random_state_data(self.frame.npartitions, random_state)
keys = self.frame.__dask_keys__()
dtype_dsk = {(self._name, 0, 0): (dtype_info, keys[0])}
percentiles_dsk = {
(self._name, 1, i): (
percentiles_summary,
key,
self.frame.npartitions,
self.input_npartitions,
self.upsample,
state,
)
for i, (state, key) in enumerate(zip(state_data, keys))
}
merge_dsk = create_merge_tree(
merge_and_compress_summaries, sorted(percentiles_dsk), self._name, 2
)
if not merge_dsk:
# Compress the data even if we only have one partition
merge_dsk = {
(self._name, 2, 0): (
merge_and_compress_summaries,
[list(percentiles_dsk)[0]],
)
}
merged_key = max(merge_dsk)
last_dsk = {
(self._name, 0): (
pd.Series,
(
process_val_weights,
merged_key,
self.input_npartitions,
(self._name, 0, 0),
),
qs,
None,
self.frame._meta.name,
)
}
return {**dtype_dsk, **percentiles_dsk, **merge_dsk, **last_dsk}
| RepartitionQuantiles |
python | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 178423,
"end": 178742
} | class ____:
def test_subclass_op(self):
class simple(np.ndarray):
def __new__(subtype, shape):
self = np.ndarray.__new__(subtype, shape, dtype=object)
self.fill(0)
return self
a = simple((3, 4))
assert_equal(a + a, a)
| TestSubclass |
python | astropy__astropy | astropy/time/formats.py | {
"start": 35085,
"end": 36804
} | class ____(TimeFromEpoch):
"""
Input for a `~matplotlib.axes.Axes` object with ax.xaxis.axis_date():
1 + number of days from 0001-01-01 00:00:00 UTC.
This can be used as follow::
>>> import matplotlib.pyplot as plt
>>> jyear = np.linspace(2000, 2001, 20)
>>> t = Time(jyear, format='jyear', scale='utc')
>>> fig, ax = plt.subplots()
>>> ax.xaxis.axis_date()
>>> ax.scatter(t.plot_date, jyear)
>>> fig.autofmt_xdate() # orient date labels at a slant
>>> fig.show()
For example, 730120.0003703703 is midnight on January 1, 2000.
"""
# This corresponds to the zero reference time for matplotlib plot_date().
# Note that TAI and UTC are equivalent at the reference time.
name = "plot_date"
unit = 1.0
epoch_val = 1721424.5 # Time('0001-01-01 00:00:00', scale='tai').jd - 1
epoch_val2 = None
epoch_scale = "utc"
epoch_format = "jd"
@lazyproperty
def epoch(self):
"""Reference epoch time from which the time interval is measured."""
if HAS_MATPLOTLIB:
from matplotlib.dates import get_epoch
# Get the matplotlib date epoch as an ISOT string in UTC
epoch_utc = get_epoch()
from erfa import ErfaWarning
with warnings.catch_warnings():
# Catch possible dubious year warnings from erfa
warnings.filterwarnings("ignore", category=ErfaWarning)
_epoch = Time(epoch_utc, scale="utc", format="isot")
_epoch.format = "jd"
else:
# If matplotlib is not installed then the epoch is '0001-01-01'
_epoch = self._epoch
return _epoch
| TimePlotDate |
python | pandas-dev__pandas | pandas/tests/arrays/test_datetimelike.py | {
"start": 20354,
"end": 31421
} | class ____(SharedTests):
index_cls = DatetimeIndex
array_cls = DatetimeArray
scalar_type = Timestamp
example_dtype = "M8[ns]"
@pytest.fixture
def arr1d(self, tz_naive_fixture, freqstr):
"""
Fixture returning DatetimeArray with parametrized frequency and
timezones
"""
tz = tz_naive_fixture
dti = pd.date_range(
"2016-01-01 01:01:00", periods=5, freq=freqstr, tz=tz, unit="ns"
)
dta = dti._data
return dta
def test_round(self, arr1d):
# GH#24064
dti = self.index_cls(arr1d)
result = dti.round(freq="2min")
expected = dti - pd.Timedelta(minutes=1)
expected = expected._with_freq(None)
tm.assert_index_equal(result, expected)
dta = dti._data
result = dta.round(freq="2min")
expected = expected._data._with_freq(None)
tm.assert_datetime_array_equal(result, expected)
def test_array_interface(self, datetime_index):
arr = datetime_index._data
copy_false = None if np_version_gt2 else False
# default asarray gives the same underlying data (for tz naive)
result = np.asarray(arr)
expected = arr._ndarray
assert result is expected
tm.assert_numpy_array_equal(result, expected)
result = np.array(arr, copy=copy_false)
assert result is expected
tm.assert_numpy_array_equal(result, expected)
# specifying M8[ns] gives the same result as default
result = np.asarray(arr, dtype="datetime64[ns]")
expected = arr._ndarray
assert result is expected
tm.assert_numpy_array_equal(result, expected)
result = np.array(arr, dtype="datetime64[ns]", copy=copy_false)
assert result is expected
tm.assert_numpy_array_equal(result, expected)
result = np.array(arr, dtype="datetime64[ns]")
if not np_version_gt2:
# TODO: GH 57739
assert result is not expected
tm.assert_numpy_array_equal(result, expected)
# to object dtype
result = np.asarray(arr, dtype=object)
expected = np.array(list(arr), dtype=object)
tm.assert_numpy_array_equal(result, expected)
# to other dtype always copies
result = np.asarray(arr, dtype="int64")
assert result is not arr.asi8
assert not np.may_share_memory(arr, result)
expected = arr.asi8.copy()
tm.assert_numpy_array_equal(result, expected)
# other dtypes handled by numpy
for dtype in ["float64", str]:
result = np.asarray(arr, dtype=dtype)
expected = np.asarray(arr).astype(dtype)
tm.assert_numpy_array_equal(result, expected)
def test_array_object_dtype(self, arr1d):
# GH#23524
arr = arr1d
dti = self.index_cls(arr1d)
expected = np.array(list(dti))
result = np.array(arr, dtype=object)
tm.assert_numpy_array_equal(result, expected)
# also test the DatetimeIndex method while we're at it
result = np.array(dti, dtype=object)
tm.assert_numpy_array_equal(result, expected)
def test_array_tz(self, arr1d):
# GH#23524
arr = arr1d
dti = self.index_cls(arr1d)
copy_false = None if np_version_gt2 else False
expected = dti.asi8.view("M8[ns]")
result = np.array(arr, dtype="M8[ns]")
tm.assert_numpy_array_equal(result, expected)
result = np.array(arr, dtype="datetime64[ns]")
tm.assert_numpy_array_equal(result, expected)
# check that we are not making copies when setting copy=copy_false
result = np.array(arr, dtype="M8[ns]", copy=copy_false)
assert result.base is expected.base
assert result.base is not None
result = np.array(arr, dtype="datetime64[ns]", copy=copy_false)
assert result.base is expected.base
assert result.base is not None
def test_array_i8_dtype(self, arr1d):
arr = arr1d
dti = self.index_cls(arr1d)
copy_false = None if np_version_gt2 else False
expected = dti.asi8
result = np.array(arr, dtype="i8")
tm.assert_numpy_array_equal(result, expected)
result = np.array(arr, dtype=np.int64)
tm.assert_numpy_array_equal(result, expected)
# check that we are still making copies when setting copy=copy_false
result = np.array(arr, dtype="i8", copy=copy_false)
assert result.base is not expected.base
assert result.base is None
def test_from_array_keeps_base(self):
# Ensure that DatetimeArray._ndarray.base isn't lost.
arr = np.array(["2000-01-01", "2000-01-02"], dtype="M8[ns]")
dta = DatetimeArray._from_sequence(arr, dtype=arr.dtype)
assert dta._ndarray is arr
dta = DatetimeArray._from_sequence(arr[:0], dtype=arr.dtype)
assert dta._ndarray.base is arr
def test_from_dti(self, arr1d):
arr = arr1d
dti = self.index_cls(arr1d)
assert list(dti) == list(arr)
# Check that Index.__new__ knows what to do with DatetimeArray
dti2 = pd.Index(arr)
assert isinstance(dti2, DatetimeIndex)
assert list(dti2) == list(arr)
def test_astype_object(self, arr1d):
arr = arr1d
dti = self.index_cls(arr1d)
asobj = arr.astype("O")
assert isinstance(asobj, np.ndarray)
assert asobj.dtype == "O"
assert list(asobj) == list(dti)
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
def test_to_period(self, datetime_index, freqstr):
dti = datetime_index
arr = dti._data
freqstr = PeriodDtype(to_offset(freqstr))._freqstr
expected = dti.to_period(freq=freqstr)
result = arr.to_period(freq=freqstr)
assert isinstance(result, PeriodArray)
tm.assert_equal(result, expected._data)
def test_to_period_2d(self, arr1d):
arr2d = arr1d.reshape(1, -1)
warn = None if arr1d.tz is None else UserWarning
with tm.assert_produces_warning(warn, match="will drop timezone information"):
result = arr2d.to_period("D")
expected = arr1d.to_period("D").reshape(1, -1)
tm.assert_period_array_equal(result, expected)
@pytest.mark.parametrize("propname", DatetimeArray._bool_ops)
def test_bool_properties(self, arr1d, propname):
# in this case _bool_ops is just `is_leap_year`
dti = self.index_cls(arr1d)
arr = arr1d
assert dti.freq == arr.freq
result = getattr(arr, propname)
expected = np.array(getattr(dti, propname), dtype=result.dtype)
tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("propname", DatetimeArray._field_ops)
def test_int_properties(self, arr1d, propname):
dti = self.index_cls(arr1d)
arr = arr1d
result = getattr(arr, propname)
expected = np.array(getattr(dti, propname), dtype=result.dtype)
tm.assert_numpy_array_equal(result, expected)
def test_take_fill_valid(self, arr1d, fixed_now_ts):
arr = arr1d
dti = self.index_cls(arr1d)
now = fixed_now_ts.tz_localize(dti.tz)
result = arr.take([-1, 1], allow_fill=True, fill_value=now)
assert result[0] == now
msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
with pytest.raises(TypeError, match=msg):
# fill_value Timedelta invalid
arr.take([-1, 1], allow_fill=True, fill_value=now - now)
with pytest.raises(TypeError, match=msg):
# fill_value Period invalid
arr.take([-1, 1], allow_fill=True, fill_value=Period("2014Q1"))
tz = None if dti.tz is not None else "US/Eastern"
now = fixed_now_ts.tz_localize(tz)
msg = "Cannot compare tz-naive and tz-aware datetime-like objects"
with pytest.raises(TypeError, match=msg):
# Timestamp with mismatched tz-awareness
arr.take([-1, 1], allow_fill=True, fill_value=now)
value = NaT._value
msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got"
with pytest.raises(TypeError, match=msg):
# require NaT, not iNaT, as it could be confused with an integer
arr.take([-1, 1], allow_fill=True, fill_value=value)
value = np.timedelta64("NaT", "ns")
with pytest.raises(TypeError, match=msg):
# require appropriate-dtype if we have a NA value
arr.take([-1, 1], allow_fill=True, fill_value=value)
if arr.tz is not None:
# GH#37356
# Assuming here that arr1d fixture does not include Australia/Melbourne
value = fixed_now_ts.tz_localize("Australia/Melbourne")
result = arr.take([-1, 1], allow_fill=True, fill_value=value)
expected = arr.take(
[-1, 1],
allow_fill=True,
fill_value=value.tz_convert(arr.dtype.tz),
)
tm.assert_equal(result, expected)
def test_concat_same_type_invalid(self, arr1d):
# different timezones
arr = arr1d
if arr.tz is None:
other = arr.tz_localize("UTC")
else:
other = arr.tz_localize(None)
with pytest.raises(ValueError, match="to_concat must have the same"):
arr._concat_same_type([arr, other])
def test_concat_same_type_different_freq(self, unit):
# we *can* concatenate DTI with different freqs.
a = pd.date_range("2000", periods=2, freq="D", tz="US/Central", unit=unit)._data
b = pd.date_range("2000", periods=2, freq="h", tz="US/Central", unit=unit)._data
result = DatetimeArray._concat_same_type([a, b])
expected = (
pd.to_datetime(
[
"2000-01-01 00:00:00",
"2000-01-02 00:00:00",
"2000-01-01 00:00:00",
"2000-01-01 01:00:00",
]
)
.tz_localize("US/Central")
.as_unit(unit)
._data
)
tm.assert_datetime_array_equal(result, expected)
def test_strftime(self, arr1d, using_infer_string):
arr = arr1d
result = arr.strftime("%Y %b")
expected = np.array([ts.strftime("%Y %b") for ts in arr], dtype=object)
if using_infer_string:
expected = pd.array(expected, dtype=pd.StringDtype(na_value=np.nan))
tm.assert_equal(result, expected)
def test_strftime_nat(self, using_infer_string):
# GH 29578
arr = DatetimeIndex(["2019-01-01", NaT])._data
result = arr.strftime("%Y-%m-%d")
expected = np.array(["2019-01-01", np.nan], dtype=object)
if using_infer_string:
expected = pd.array(expected, dtype=pd.StringDtype(na_value=np.nan))
tm.assert_equal(result, expected)
| TestDatetimeArray |
python | donnemartin__system-design-primer | solutions/object_oriented_design/parking_lot/parking_lot.py | {
"start": 141,
"end": 654
} | class ____(metaclass=ABCMeta):
def __init__(self, vehicle_size, license_plate, spot_size):
self.vehicle_size = vehicle_size
self.license_plate = license_plate
self.spot_size
self.spots_taken = []
def clear_spots(self):
for spot in self.spots_taken:
spot.remove_vehicle(self)
self.spots_taken = []
def take_spot(self, spot):
self.spots_taken.append(spot)
@abstractmethod
def can_fit_in_spot(self, spot):
pass
| Vehicle |
python | Farama-Foundation__Gymnasium | gymnasium/wrappers/numpy_to_torch.py | {
"start": 847,
"end": 2342
} | class ____(ArrayConversion):
"""Wraps a NumPy-based environment such that it can be interacted with PyTorch Tensors.
Actions must be provided as PyTorch Tensors and observations will be returned as PyTorch Tensors.
A vector version of the wrapper exists, :class:`gymnasium.wrappers.vector.NumpyToTorch`.
Note:
For ``rendered`` this is returned as a NumPy array not a pytorch Tensor.
Example:
>>> import torch
>>> import gymnasium as gym
>>> env = gym.make("CartPole-v1")
>>> env = NumpyToTorch(env)
>>> obs, _ = env.reset(seed=123)
>>> type(obs)
<class 'torch.Tensor'>
>>> action = torch.tensor(env.action_space.sample())
>>> obs, reward, terminated, truncated, info = env.step(action)
>>> type(obs)
<class 'torch.Tensor'>
>>> type(reward)
<class 'float'>
>>> type(terminated)
<class 'bool'>
>>> type(truncated)
<class 'bool'>
Change logs:
* v1.0.0 - Initially added
"""
def __init__(self, env: gym.Env, device: Device | None = None):
"""Wrapper class to change inputs and outputs of environment to PyTorch tensors.
Args:
env: The NumPy-based environment to wrap
device: The device the torch Tensors should be moved to
"""
super().__init__(env=env, env_xp=np, target_xp=torch, target_device=device)
self.device: Device | None = device
| NumpyToTorch |
python | walkccc__LeetCode | solutions/3196. Maximize Total Cost of Alternating Subarrays/3196.py | {
"start": 0,
"end": 387
} | class ____:
def maximumTotalCost(self, nums: list[int]) -> int:
keep = nums[0] # the maximum cost if the last number is kept
flip = nums[0] # the maximum cost if the last number is flipped
for i in range(1, len(nums)):
keepCurr = max(keep, flip) + nums[i]
flipCurr = keep - nums[i]
keep = keepCurr
flip = flipCurr
return max(keep, flip)
| Solution |
python | python__mypy | mypyc/irbuild/prepare.py | {
"start": 26978,
"end": 30611
} | class ____(TraverserVisitor):
current_path: str
def __init__(self, errors: Errors) -> None:
super().__init__()
# Map of main singledispatch function to list of registered implementations
self.singledispatch_impls: defaultdict[FuncDef, list[RegisterImplInfo]] = defaultdict(list)
# Map of decorated function to the indices of any decorators to remove
self.decorators_to_remove: dict[FuncDef, list[int]] = {}
self.errors: Errors = errors
self.func_stack_depth = 0
def visit_func_def(self, o: FuncDef) -> None:
self.func_stack_depth += 1
super().visit_func_def(o)
self.func_stack_depth -= 1
def visit_decorator(self, dec: Decorator) -> None:
if dec.decorators:
decorators_to_store = dec.decorators.copy()
decorators_to_remove: list[int] = []
# the index of the last non-register decorator before finding a register decorator
# when going through decorators from top to bottom
last_non_register: int | None = None
for i, d in enumerate(decorators_to_store):
impl = get_singledispatch_register_call_info(d, dec.func)
if impl is not None:
if self.func_stack_depth > 0:
self.errors.error(
"Registering nested functions not supported", self.current_path, d.line
)
self.singledispatch_impls[impl.singledispatch_func].append(
(impl.dispatch_type, dec.func)
)
decorators_to_remove.append(i)
if last_non_register is not None:
# found a register decorator after a non-register decorator, which we
# don't support because we'd have to make a copy of the function before
# calling the decorator so that we can call it later, which complicates
# the implementation for something that is probably not commonly used
self.errors.error(
"Calling decorator after registering function not supported",
self.current_path,
decorators_to_store[last_non_register].line,
)
else:
if refers_to_fullname(d, "functools.singledispatch"):
if self.func_stack_depth > 0:
self.errors.error(
"Nested singledispatch functions not supported",
self.current_path,
d.line,
)
decorators_to_remove.append(i)
# make sure that we still treat the function as a singledispatch function
# even if we don't find any registered implementations (which might happen
# if all registered implementations are registered dynamically)
self.singledispatch_impls.setdefault(dec.func, [])
last_non_register = i
if decorators_to_remove:
# calling register on a function that tries to dispatch based on type annotations
# raises a TypeError because compiled functions don't have an __annotations__
# attribute
self.decorators_to_remove[dec.func] = decorators_to_remove
super().visit_decorator(dec)
| SingledispatchVisitor |
python | euske__pdfminer | pdfminer/layout.py | {
"start": 21450,
"end": 21826
} | class ____(LTLayoutContainer):
def __init__(self, pageid, bbox, rotate=0):
LTLayoutContainer.__init__(self, bbox)
self.pageid = pageid
self.rotate = rotate
return
def __repr__(self):
return ('<%s(%r) %s rotate=%r>' %
(self.__class__.__name__, self.pageid,
bbox2str(self.bbox), self.rotate))
| LTPage |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_clear_thinking_20251015_edit_response.py | {
"start": 214,
"end": 543
} | class ____(BaseModel):
cleared_input_tokens: int
"""Number of input tokens cleared by this edit."""
cleared_thinking_turns: int
"""Number of thinking turns that were cleared."""
type: Literal["clear_thinking_20251015"]
"""The type of context management edit applied."""
| BetaClearThinking20251015EditResponse |
python | gevent__gevent | src/gevent/threadpool.py | {
"start": 1378,
"end": 9189
} | class ____(RawGreenlet):
# Exists to produce a more useful repr for worker pool
# threads/greenlets, and manage the communication of the worker
# thread with the threadpool.
# Inform the gevent.util.GreenletTree that this should be
# considered the root (for printing purposes)
greenlet_tree_is_root = True
_thread_ident = 0
_exc_info = sys.exc_info
_get_hub_if_exists = staticmethod(get_hub_if_exists)
# We capture the hub each time through the loop in case its created
# so we can destroy it after a fork.
_hub_of_worker = None
# The hub of the threadpool we're working for. Just for info.
_hub = None
# A cookie passed to task_queue.get()
_task_queue_cookie = None
# If not -1, how long to block waiting for a task before we
# exit.
_idle_task_timeout = -1
def __init__(self, threadpool):
# Construct in the main thread (owner of the threadpool)
# The parent greenlet and thread identifier will be set once the
# new thread begins running.
RawGreenlet.__init__(self)
self._hub = threadpool.hub
# Avoid doing any imports in the background thread if it's not
# necessary (monkey.get_original imports if not patched).
# Background imports can hang Python 2 (gevent's thread resolver runs in the BG,
# and resolving may have to import the idna module, which needs an import lock, so
# resolving at module scope)
if monkey.is_module_patched('sys'):
stderr = monkey.get_original('sys', 'stderr')
else:
stderr = sys.stderr
self._stderr = stderr
# We can capture the task_queue; even though it can change if the threadpool
# is re-innitted, we won't be running in that case
self._task_queue = threadpool.task_queue # type:gevent._threading.Queue
self._task_queue_cookie = self._task_queue.allocate_cookie()
self._unregister_worker = threadpool._unregister_worker
self._idle_task_timeout = threadpool._idle_task_timeout
threadpool._register_worker(self)
try:
start_new_thread(self._begin, ())
except:
self._unregister_worker(self)
raise
def _begin(self, _get_c=getcurrent, _get_ti=get_thread_ident):
# Pass arguments to avoid accessing globals during module shutdown.
# we're in the new thread (but its root greenlet). Establish invariants and get going
# by making this the current greenlet.
self.parent = _get_c() # pylint:disable=attribute-defined-outside-init
self._thread_ident = _get_ti()
# ignore the parent attribute. (We can't set parent to None.)
self.parent.greenlet_tree_is_ignored = True
try:
self.switch() # goto run()
except: # pylint:disable=bare-except
# run() will attempt to print any exceptions, but that might
# not work during shutdown. sys.excepthook and such may be gone,
# so things might not get printed at all except for a cryptic
# message. This is especially true on Python 2 (doesn't seem to be
# an issue on Python 3).
pass
def __fixup_hub_before_block(self):
hub = self._get_hub_if_exists() # Don't create one; only set if a worker function did it
if hub is not None:
hub.name = 'ThreadPool Worker Hub'
# While we block, don't let the monitoring thread, if any,
# report us as blocked. Indeed, so long as we never
# try to switch greenlets, don't report us as blocked---
# the threadpool is *meant* to run blocking tasks
if hub is not None and hub.periodic_monitoring_thread is not None:
hub.periodic_monitoring_thread.ignore_current_greenlet_blocking()
self._hub_of_worker = hub
@staticmethod
def __print_tb(tb, stderr):
# Extracted from traceback to avoid accessing any module
# globals (these sometimes happen during interpreter shutdown;
# see test__subprocess_interrupted)
while tb is not None:
f = tb.tb_frame
lineno = tb.tb_lineno
co = f.f_code
filename = co.co_filename
name = co.co_name
print(' File "%s", line %d, in %s' % (filename, lineno, name),
file=stderr)
tb = tb.tb_next
def _before_run_task(self, func, args, kwargs, thread_result,
_sys=sys,
_get_thread_profile=_get_thread_profile,
_get_thread_trace=_get_thread_trace):
# pylint:disable=unused-argument
_sys.setprofile(_get_thread_profile())
_sys.settrace(_get_thread_trace())
def _after_run_task(self, func, args, kwargs, thread_result, _sys=sys):
# pylint:disable=unused-argument
_sys.setprofile(None)
_sys.settrace(None)
def __run_task(self, func, args, kwargs, thread_result):
self._before_run_task(func, args, kwargs, thread_result)
try:
thread_result.set(func(*args, **kwargs))
except: # pylint:disable=bare-except
thread_result.handle_error((self, func), self._exc_info())
finally:
self._after_run_task(func, args, kwargs, thread_result)
del func, args, kwargs, thread_result
def run(self):
# pylint:disable=too-many-branches
task = None
exc_info = sys.exc_info
fixup_hub_before_block = self.__fixup_hub_before_block
task_queue_get = self._task_queue.get
task_queue_cookie = self._task_queue_cookie
run_task = self.__run_task
task_queue_done = self._task_queue.task_done
idle_task_timeout = self._idle_task_timeout
try: # pylint:disable=too-many-nested-blocks
while 1: # tiny bit faster than True on Py2
fixup_hub_before_block()
try:
task = task_queue_get(task_queue_cookie, idle_task_timeout)
except EmptyTimeout:
# Nothing to do, exit the thread. Do not
# go into the next block where we would call
# queue.task_done(), because we didn't actually
# take a task.
return
try:
if task is None:
return
run_task(*task)
except:
task = repr(task)
raise
finally:
task = None if not isinstance(task, str) else task
task_queue_done()
except Exception as e: # pylint:disable=broad-except
print(
"Failed to run worker thread. Task=%r Exception=%r" % (
task, e
),
file=self._stderr)
self.__print_tb(exc_info()[-1], self._stderr)
finally:
# Re-check for the hub in case the task created it but then
# failed.
self.cleanup(self._get_hub_if_exists())
def cleanup(self, hub_of_worker):
if self._hub is not None:
self._hub = None
self._unregister_worker(self)
self._unregister_worker = lambda _: None
self._task_queue = None
self._task_queue_cookie = None
if hub_of_worker is not None:
hub_of_worker.destroy(True)
def __repr__(self, _format_hub=_format_hub):
return "<ThreadPoolWorker at 0x%x thread_ident=0x%x threadpool-hub=%s>" % (
id(self),
self._thread_ident,
_format_hub(self._hub)
)
| _WorkerGreenlet |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/profiling.py | {
"start": 1171,
"end": 10237
} | class ____:
"""Store per-platform/fn profiling results in a file.
There was no json module available when this was written, but now
the file format which is very deterministically line oriented is kind of
handy in any case for diffs and merges.
"""
def __init__(self, filename, sort="cumulative", dump=None):
self.force_write = (
config.options is not None and config.options.force_write_profiles
)
self.write = self.force_write or (
config.options is not None and config.options.write_profiles
)
self.fname = os.path.abspath(filename)
self.short_fname = os.path.split(self.fname)[-1]
self.data = collections.defaultdict(
lambda: collections.defaultdict(dict)
)
self.dump = dump
self.sort = sort
self._read()
if self.write:
# rewrite for the case where features changed,
# etc.
self._write()
@property
def platform_key(self):
dbapi_key = config.db.name + "_" + config.db.driver
if config.db.name == "sqlite" and config.db.dialect._is_url_file_db(
config.db.url
):
dbapi_key += "_file"
# keep it at 2.7, 3.1, 3.2, etc. for now.
py_version = ".".join([str(v) for v in sys.version_info[0:2]])
if freethreading:
py_version += "t"
platform_tokens = [
platform.machine(),
platform.system().lower(),
platform.python_implementation().lower(),
py_version,
dbapi_key,
]
platform_tokens.append("dbapiunicode")
_has_cext = has_compiled_ext()
platform_tokens.append(_has_cext and "cextensions" or "nocextensions")
return "_".join(platform_tokens)
def has_stats(self):
test_key = _current_test
return (
test_key in self.data and self.platform_key in self.data[test_key]
)
def result(self, callcount):
test_key = _current_test
per_fn = self.data[test_key]
per_platform = per_fn[self.platform_key]
if "counts" not in per_platform:
per_platform["counts"] = counts = []
else:
counts = per_platform["counts"]
if "current_count" not in per_platform:
per_platform["current_count"] = current_count = 0
else:
current_count = per_platform["current_count"]
has_count = len(counts) > current_count
if not has_count:
counts.append(callcount)
if self.write:
self._write()
result = None
else:
result = per_platform["lineno"], counts[current_count]
per_platform["current_count"] += 1
return result
def reset_count(self):
test_key = _current_test
# since self.data is a defaultdict, don't access a key
# if we don't know it's there first.
if test_key not in self.data:
return
per_fn = self.data[test_key]
if self.platform_key not in per_fn:
return
per_platform = per_fn[self.platform_key]
if "counts" in per_platform:
per_platform["counts"][:] = []
def replace(self, callcount):
test_key = _current_test
per_fn = self.data[test_key]
per_platform = per_fn[self.platform_key]
counts = per_platform["counts"]
current_count = per_platform["current_count"]
if current_count < len(counts):
counts[current_count - 1] = callcount
else:
counts[-1] = callcount
if self.write:
self._write()
def _header(self):
return (
"# %s\n"
"# This file is written out on a per-environment basis.\n"
"# For each test in aaa_profiling, the corresponding "
"function and \n"
"# environment is located within this file. "
"If it doesn't exist,\n"
"# the test is skipped.\n"
"# If a callcount does exist, it is compared "
"to what we received. \n"
"# assertions are raised if the counts do not match.\n"
"# \n"
"# To add a new callcount test, apply the function_call_count \n"
"# decorator and re-run the tests using the --write-profiles \n"
"# option - this file will be rewritten including the new count.\n"
"# \n"
) % (self.fname)
def _read(self):
try:
profile_f = open(self.fname)
except OSError:
return
for lineno, line in enumerate(profile_f):
line = line.strip()
if not line or line.startswith("#"):
continue
test_key, platform_key, counts = line.split()
per_fn = self.data[test_key]
per_platform = per_fn[platform_key]
c = [int(count) for count in counts.split(",")]
per_platform["counts"] = c
per_platform["lineno"] = lineno + 1
per_platform["current_count"] = 0
profile_f.close()
def _write(self):
print("Writing profile file %s" % self.fname)
profile_f = open(self.fname, "w")
profile_f.write(self._header())
for test_key in sorted(self.data):
per_fn = self.data[test_key]
profile_f.write("\n# TEST: %s\n\n" % test_key)
for platform_key in sorted(per_fn):
per_platform = per_fn[platform_key]
c = ",".join(str(count) for count in per_platform["counts"])
profile_f.write("%s %s %s\n" % (test_key, platform_key, c))
profile_f.close()
def function_call_count(variance=0.05, times=1, warmup=0):
"""Assert a target for a test case's function call count.
The main purpose of this assertion is to detect changes in
callcounts for various functions - the actual number is not as important.
Callcounts are stored in a file keyed to Python version and OS platform
information. This file is generated automatically for new tests,
and versioned so that unexpected changes in callcounts will be detected.
"""
# use signature-rewriting decorator function so that pytest fixtures
# still work on py27. In Py3, update_wrapper() alone is good enough,
# likely due to the introduction of __signature__.
from sqlalchemy.util import decorator
@decorator
def wrap(fn, *args, **kw):
for warm in range(warmup):
fn(*args, **kw)
timerange = range(times)
with count_functions(variance=variance):
for time in timerange:
rv = fn(*args, **kw)
return rv
return wrap
@contextlib.contextmanager
def count_functions(variance=0.05):
if cProfile is None:
raise config._skip_test_exception("cProfile is not installed")
if not _profile_stats.has_stats() and not _profile_stats.write:
config.skip_test(
"No profiling stats available on this "
"platform for this function. Run tests with "
"--write-profiles to add statistics to %s for "
"this platform." % _profile_stats.short_fname
)
gc_collect()
pr = cProfile.Profile()
pr.enable()
# began = time.time()
yield
# ended = time.time()
pr.disable()
# s = StringIO()
stats = pstats.Stats(pr, stream=sys.stdout)
# timespent = ended - began
callcount = stats.total_calls
expected = _profile_stats.result(callcount)
if expected is None:
expected_count = None
else:
line_no, expected_count = expected
print("Pstats calls: %d Expected %s" % (callcount, expected_count))
stats.sort_stats(*re.split(r"[, ]", _profile_stats.sort))
stats.print_stats()
if _profile_stats.dump:
base, ext = os.path.splitext(_profile_stats.dump)
test_name = _current_test.split(".")[-1]
dumpfile = "%s_%s%s" % (base, test_name, ext or ".profile")
stats.dump_stats(dumpfile)
print("Dumped stats to file %s" % dumpfile)
# stats.print_callers()
if _profile_stats.force_write:
_profile_stats.replace(callcount)
elif expected_count:
deviance = int(callcount * variance)
failed = abs(callcount - expected_count) > deviance
if failed:
if _profile_stats.write:
_profile_stats.replace(callcount)
else:
raise AssertionError(
"Adjusted function call count %s not within %s%% "
"of expected %s, platform %s. Rerun with "
"--write-profiles to "
"regenerate this callcount."
% (
callcount,
(variance * 100),
expected_count,
_profile_stats.platform_key,
)
)
| ProfileStatsFile |
python | plotly__plotly.py | _plotly_utils/png.py | {
"start": 10716,
"end": 10758
} | class ____(FormatError):
pass
| ChunkError |
python | getsentry__sentry | src/sentry/api/paginator.py | {
"start": 28535,
"end": 28629
} | class ____(Protocol):
def __call__(self, limit: int, offset: int) -> list[Any]: ...
| Callback |
python | readthedocs__readthedocs.org | readthedocs/organizations/views/private.py | {
"start": 7436,
"end": 7634
} | class ____(
PrivateViewMixin, OrganizationTeamMemberView, DeleteViewWithMessage
):
success_message = _("Member removed from team")
http_method_names = ["post"]
| DeleteOrganizationTeamMember |
python | PrefectHQ__prefect | src/integrations/prefect-dbt/prefect_dbt/cloud/exceptions.py | {
"start": 426,
"end": 523
} | class ____(DbtCloudException):
"""Raised when a triggered job run fails"""
| DbtCloudJobRunFailed |
python | bokeh__bokeh | tests/unit/bokeh/server/test_auth_provider.py | {
"start": 1592,
"end": 2508
} | class ____:
def test_endpoints(self, null_auth: bsa.NullAuth) -> None:
assert null_auth.endpoints == []
def test_get_user(self, null_auth: bsa.NullAuth) -> None:
assert null_auth.get_user is None
async def test_get_user_async(self, null_auth: bsa.NullAuth) -> None:
assert null_auth.get_user_async is None
def test_login_url(self, null_auth: bsa.NullAuth) -> None:
assert null_auth.login_url is None
def test_get_login_url(self, null_auth: bsa.NullAuth) -> None:
assert null_auth.get_login_url is None
def test_login_handler(self, null_auth: bsa.NullAuth) -> None:
assert null_auth.login_handler is None
def test_logout_url(self, null_auth: bsa.NullAuth) -> None:
assert null_auth.logout_url is None
def test_logout_handler(self, null_auth: bsa.NullAuth) -> None:
assert null_auth.logout_handler is None
| TestNullAuth |
python | mlflow__mlflow | mlflow/models/auth_policy.py | {
"start": 1351,
"end": 2305
} | class ____:
"""
Specifies the authentication policy for the model, which includes two key
components.
System Auth Policy: A list of resources required to serve this model
User Auth Policy: A minimal list of scopes that the user should
have access to, in order to invoke this model
"""
def __init__(
self,
user_auth_policy: UserAuthPolicy | None = None,
system_auth_policy: SystemAuthPolicy | None = None,
):
self.user_auth_policy = user_auth_policy
self.system_auth_policy = system_auth_policy
def to_dict(self):
"""
Serialize Auth Policy to a dictionary
"""
return {
"system_auth_policy": self.system_auth_policy.to_dict()
if self.system_auth_policy
else {},
"user_auth_policy": self.user_auth_policy.to_dict() if self.user_auth_policy else {},
}
| AuthPolicy |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-mixpanel/source_mixpanel/streams.py | {
"start": 6310,
"end": 6855
} | class ____(MixpanelStream, ABC):
def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, any]:
updated_state = latest_record.get(self.cursor_field)
if updated_state:
state_value = current_stream_state.get(self.cursor_field)
if state_value:
updated_state = max(updated_state, state_value)
current_stream_state[self.cursor_field] = updated_state
return current_stream_state
| IncrementalMixpanelStream |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_logging_sink.py | {
"start": 1963,
"end": 5903
} | class ____(GoogleCloudBaseOperator):
"""
Creates a Cloud Logging export sink in a GCP project.
This operator creates a sink that exports log entries from Cloud Logging
to destinations like Cloud Storage, BigQuery, or Pub/Sub.
:param project_id: Required. ID of the Google Cloud project where the sink will be created.
:param sink_config: Required. The full sink configuration as a dictionary or a LogSink object.
See: https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks
:param unique_writer_identity: If True, creates a unique service account for the sink.
If False, uses the default Google-managed service account.
:param gcp_conn_id: Optional. The connection ID used to connect to Google Cloud. Defaults to "google_cloud_default".
: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).
"""
template_fields: Sequence[str] = (
"project_id",
"sink_config",
"gcp_conn_id",
"impersonation_chain",
"unique_writer_identity",
)
def __init__(
self,
project_id: str,
sink_config: dict | LogSink,
unique_writer_identity: bool = False,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
):
super().__init__(**kwargs)
self.project_id = project_id
self.sink_config = sink_config
self.unique_writer_identity = unique_writer_identity
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
def execute(self, context: Context) -> dict[str, Any]:
"""Execute the operator."""
_validate_inputs(self, required_fields=["project_id", "sink_config"])
hook = CloudLoggingHook(gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain)
try:
self.log.info(
"Creating log sink '%s' in project '%s'",
_get_field(self.sink_config, "name"),
self.project_id,
)
self.log.info("Destination: %s", _get_field(self.sink_config, "destination"))
response = hook.create_sink(
sink=self.sink_config,
unique_writer_identity=self.unique_writer_identity,
project_id=self.project_id,
)
self.log.info("Log sink created successfully: %s", response.name)
if self.unique_writer_identity and hasattr(response, "writer_identity"):
self.log.info("Writer identity: %s", response.writer_identity)
self.log.info("Remember to grant appropriate permissions to the writer identity")
return LogSink.to_dict(response)
except AlreadyExists:
self.log.info(
"Already existed log sink, sink_name=%s, project_id=%s",
_get_field(self.sink_config, "name"),
self.project_id,
)
existing_sink = hook.get_sink(
sink_name=_get_field(self.sink_config, "name"), project_id=self.project_id
)
return LogSink.to_dict(existing_sink)
except google.cloud.exceptions.GoogleCloudError as e:
self.log.error("An error occurred. Exiting.")
raise e
| CloudLoggingCreateSinkOperator |
python | fastapi__sqlmodel | docs_src/tutorial/select/tutorial003.py | {
"start": 100,
"end": 1141
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def create_heroes():
hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson")
hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)
with Session(engine) as session:
session.add(hero_1)
session.add(hero_2)
session.add(hero_3)
session.commit()
def select_heroes():
with Session(engine) as session:
statement = select(Hero)
results = session.exec(statement)
heroes = results.all()
print(heroes)
def main():
create_db_and_tables()
create_heroes()
select_heroes()
if __name__ == "__main__":
main()
| Hero |
python | django__django | tests/urlpatterns/tests.py | {
"start": 10932,
"end": 13565
} | class ____(SimpleTestCase):
def test_matching_urls(self):
def no_converter(x):
return x
test_data = (
("int", {"0", "1", "01", 1234567890}, int),
("str", {"abcxyz"}, no_converter),
("path", {"allows.ANY*characters"}, no_converter),
("slug", {"abcxyz-ABCXYZ_01234567890"}, no_converter),
("uuid", {"39da9369-838e-4750-91a5-f7805cd82839"}, uuid.UUID),
)
for url_name, url_suffixes, converter in test_data:
for url_suffix in url_suffixes:
url = "/%s/%s/" % (url_name, url_suffix)
with self.subTest(url=url):
match = resolve(url)
self.assertEqual(match.url_name, url_name)
self.assertEqual(match.kwargs, {url_name: converter(url_suffix)})
# reverse() works with string parameters.
string_kwargs = {url_name: url_suffix}
self.assertEqual(reverse(url_name, kwargs=string_kwargs), url)
# reverse() also works with native types (int, UUID, etc.).
if converter is not no_converter:
# The converted value might be different for int (a
# leading zero is lost in the conversion).
converted_value = match.kwargs[url_name]
converted_url = "/%s/%s/" % (url_name, converted_value)
self.assertEqual(
reverse(url_name, kwargs={url_name: converted_value}),
converted_url,
)
def test_nonmatching_urls(self):
test_data = (
("int", {"-1", "letters"}),
("str", {"", "/"}),
("path", {""}),
("slug", {"", "stars*notallowed"}),
(
"uuid",
{
"",
"9da9369-838e-4750-91a5-f7805cd82839",
"39da9369-838-4750-91a5-f7805cd82839",
"39da9369-838e-475-91a5-f7805cd82839",
"39da9369-838e-4750-91a-f7805cd82839",
"39da9369-838e-4750-91a5-f7805cd8283",
},
),
)
for url_name, url_suffixes in test_data:
for url_suffix in url_suffixes:
url = "/%s/%s/" % (url_name, url_suffix)
with self.subTest(url=url), self.assertRaises(Resolver404):
resolve(url)
@override_settings(ROOT_URLCONF="urlpatterns.path_same_name_urls")
| ConverterTests |
python | doocs__leetcode | solution/1900-1999/1908.Game of Nim/Solution.py | {
"start": 0,
"end": 413
} | class ____:
def nimGame(self, piles: List[int]) -> bool:
@cache
def dfs(st):
lst = list(st)
for i, x in enumerate(lst):
for j in range(1, x + 1):
lst[i] -= j
if not dfs(tuple(lst)):
return True
lst[i] += j
return False
return dfs(tuple(piles))
| Solution |
python | urllib3__urllib3 | test/with_dummyserver/test_socketlevel.py | {
"start": 87740,
"end": 89810
} | class ____(SocketDummyServerTestCase):
def test_multipart_assert_header_parsing_no_defects(self) -> None:
quit_event = threading.Event()
def socket_handler(listener: socket.socket) -> None:
for _ in range(2):
listener.settimeout(LONG_TIMEOUT)
while True:
if quit_event and quit_event.is_set():
return
try:
sock = listener.accept()[0]
break
except (TimeoutError, socket.timeout):
continue
sock.settimeout(LONG_TIMEOUT)
while True:
if quit_event and quit_event.is_set():
sock.close()
return
if sock.recv(65536).endswith(b"\r\n\r\n"):
break
sock.sendall(
b"HTTP/1.1 404 Not Found\r\n"
b"Server: example.com\r\n"
b"Content-Type: multipart/mixed; boundary=36eeb8c4e26d842a\r\n"
b"Content-Length: 73\r\n"
b"\r\n"
b"--36eeb8c4e26d842a\r\n"
b"Content-Type: text/plain\r\n"
b"\r\n"
b"1\r\n"
b"--36eeb8c4e26d842a--\r\n",
)
sock.close()
self._start_server(socket_handler, quit_event=quit_event)
from urllib3.connectionpool import log
with mock.patch.object(log, "warning") as log_warning:
with HTTPConnectionPool(self.host, self.port, timeout=LONG_TIMEOUT) as pool:
resp = pool.urlopen("GET", "/")
assert resp.status == 404
assert (
resp.headers["content-type"]
== "multipart/mixed; boundary=36eeb8c4e26d842a"
)
assert len(resp.data) == 73
log_warning.assert_not_called()
| TestMultipartResponse |
python | getsentry__sentry | src/sentry/seer/endpoints/seer_rpc.py | {
"start": 4823,
"end": 4901
} | class ____(TypedDict):
name: str
type: str
descending: bool
| SortDict |
python | wntrblm__nox | nox/logger.py | {
"start": 1275,
"end": 1700
} | class ____(logging.Formatter):
def __init__(self, *, add_timestamp: bool = False) -> None:
super().__init__(fmt=_get_format(colorlog=False, add_timestamp=add_timestamp))
self._simple_fmt = logging.Formatter("%(message)s")
def format(self, record: Any) -> str:
if record.levelname == "OUTPUT":
return self._simple_fmt.format(record)
return super().format(record)
| NoxFormatter |
python | neetcode-gh__leetcode | python/0525-contiguous-array.py | {
"start": 0,
"end": 549
} | class ____:
def findMaxLength(self, nums: List[int]) -> int:
zero, one = 0, 0
res = 0
diff_index = {}
for i, n in enumerate(nums):
if n == 0:
zero += 1
else:
one += 1
if one - zero not in diff_index:
diff_index[one - zero] = i
if one == zero:
res = one + zero
else:
idx = diff_index[one - zero]
res = max(res, i - idx)
return res
| Solution |
python | numpy__numpy | numpy/_core/tests/test_arraymethod.py | {
"start": 2565,
"end": 3223
} | class ____:
def test_class_getitem(self, cls: type[np.ndarray]) -> None:
"""Test `ndarray.__class_getitem__`."""
alias = cls[Any, Any]
assert isinstance(alias, types.GenericAlias)
assert alias.__origin__ is cls
@pytest.mark.parametrize("arg_len", range(4))
def test_subscript_tup(self, cls: type[np.ndarray], arg_len: int) -> None:
arg_tup = (Any,) * arg_len
if arg_len in (1, 2):
assert cls[arg_tup]
else:
match = f"Too {'few' if arg_len == 0 else 'many'} arguments"
with pytest.raises(TypeError, match=match):
cls[arg_tup]
| TestClassGetItem |
python | miyuchina__mistletoe | mistletoe/markdown_renderer.py | {
"start": 223,
"end": 633
} | class ____(block_token.BlockToken):
"""
Blank line token. Represents a single blank line.
This is a leaf block token without children.
"""
pattern = re.compile(r"\s*\n$")
def __init__(self, _):
self.children = []
@classmethod
def start(cls, line):
return cls.pattern.match(line)
@classmethod
def read(cls, lines):
return [next(lines)]
| BlankLine |
python | kubernetes-client__python | kubernetes/client/models/v2_pods_metric_source.py | {
"start": 383,
"end": 4387
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'metric': 'V2MetricIdentifier',
'target': 'V2MetricTarget'
}
attribute_map = {
'metric': 'metric',
'target': 'target'
}
def __init__(self, metric=None, target=None, local_vars_configuration=None): # noqa: E501
"""V2PodsMetricSource - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._metric = None
self._target = None
self.discriminator = None
self.metric = metric
self.target = target
@property
def metric(self):
"""Gets the metric of this V2PodsMetricSource. # noqa: E501
:return: The metric of this V2PodsMetricSource. # noqa: E501
:rtype: V2MetricIdentifier
"""
return self._metric
@metric.setter
def metric(self, metric):
"""Sets the metric of this V2PodsMetricSource.
:param metric: The metric of this V2PodsMetricSource. # noqa: E501
:type: V2MetricIdentifier
"""
if self.local_vars_configuration.client_side_validation and metric is None: # noqa: E501
raise ValueError("Invalid value for `metric`, must not be `None`") # noqa: E501
self._metric = metric
@property
def target(self):
"""Gets the target of this V2PodsMetricSource. # noqa: E501
:return: The target of this V2PodsMetricSource. # noqa: E501
:rtype: V2MetricTarget
"""
return self._target
@target.setter
def target(self, target):
"""Sets the target of this V2PodsMetricSource.
:param target: The target of this V2PodsMetricSource. # noqa: E501
:type: V2MetricTarget
"""
if self.local_vars_configuration.client_side_validation and target is None: # noqa: E501
raise ValueError("Invalid value for `target`, must not be `None`") # noqa: E501
self._target = target
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V2PodsMetricSource):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V2PodsMetricSource):
return True
return self.to_dict() != other.to_dict()
| V2PodsMetricSource |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1462412,
"end": 1463473
} | class ____(sgqlc.types.Type, Node):
"""An invitation for a user to be added to a repository."""
__schema__ = github_schema
__field_names__ = ("email", "invitee", "inviter", "permalink", "permission", "repository")
email = sgqlc.types.Field(String, graphql_name="email")
"""The email address that received the invitation."""
invitee = sgqlc.types.Field("User", graphql_name="invitee")
"""The user who received the invitation."""
inviter = sgqlc.types.Field(sgqlc.types.non_null("User"), graphql_name="inviter")
"""The user who created the invitation."""
permalink = sgqlc.types.Field(sgqlc.types.non_null(URI), graphql_name="permalink")
"""The permalink for this repository invitation."""
permission = sgqlc.types.Field(sgqlc.types.non_null(RepositoryPermission), graphql_name="permission")
"""The permission granted on this repository by this invitation."""
repository = sgqlc.types.Field(RepositoryInfo, graphql_name="repository")
"""The Repository the user is invited to."""
| RepositoryInvitation |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 212694,
"end": 215479
} | class ____(Request):
"""
Move datasets to a project
:param ids: Datasets to move
:type ids: Sequence[str]
:param project: Target project ID. If not provided, `project_name` must be
provided. Use null for the root project
:type project: str
:param project_name: Target project name. If provided and a project with this
name does not exist, a new project will be created. If not provided, `project`
must be provided.
:type project_name: str
"""
_service = "datasets"
_action = "move"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"ids": {
"description": "Datasets to move",
"items": {"type": "string"},
"type": "array",
},
"project": {
"description": (
"Target project ID. If not provided, `project_name` must be provided. Use null for the root project"
),
"type": "string",
},
"project_name": {
"description": (
"Target project name. If provided and a project with this name does not exist, a new project will"
" be created. If not provided, `project` must be provided."
),
"type": "string",
},
},
"required": ["ids"],
"type": "object",
}
def __init__(self, ids, project=None, project_name=None, **kwargs):
super(MoveRequest, self).__init__(**kwargs)
self.ids = ids
self.project = project
self.project_name = project_name
@schema_property("ids")
def ids(self):
return self._property_ids
@ids.setter
def ids(self, value):
if value is None:
self._property_ids = None
return
self.assert_isinstance(value, "ids", (list, tuple))
self.assert_isinstance(value, "ids", six.string_types, is_array=True)
self._property_ids = value
@schema_property("project")
def project(self):
return self._property_project
@project.setter
def project(self, value):
if value is None:
self._property_project = None
return
self.assert_isinstance(value, "project", six.string_types)
self._property_project = value
@schema_property("project_name")
def project_name(self):
return self._property_project_name
@project_name.setter
def project_name(self, value):
if value is None:
self._property_project_name = None
return
self.assert_isinstance(value, "project_name", six.string_types)
self._property_project_name = value
| MoveRequest |
python | celery__celery | celery/apps/beat.py | {
"start": 929,
"end": 5724
} | class ____:
"""Beat as a service."""
Service = beat.Service
app: Celery = None
def __init__(self, max_interval: int | None = None, app: Celery | None = None,
socket_timeout: int = 30, pidfile: str | None = None, no_color: bool | None = None,
loglevel: str = 'WARN', logfile: str | None = None, schedule: str | None = None,
scheduler: str | None = None,
scheduler_cls: str | None = None, # XXX use scheduler
redirect_stdouts: bool | None = None,
redirect_stdouts_level: str | None = None,
quiet: bool = False, **kwargs: Any) -> None:
self.app = app = app or self.app
either = self.app.either
self.loglevel = loglevel
self.logfile = logfile
self.schedule = either('beat_schedule_filename', schedule)
self.scheduler_cls = either(
'beat_scheduler', scheduler, scheduler_cls)
self.redirect_stdouts = either(
'worker_redirect_stdouts', redirect_stdouts)
self.redirect_stdouts_level = either(
'worker_redirect_stdouts_level', redirect_stdouts_level)
self.quiet = quiet
self.max_interval = max_interval
self.socket_timeout = socket_timeout
self.no_color = no_color
self.colored = app.log.colored(
self.logfile,
enabled=not no_color if no_color is not None else no_color,
)
self.pidfile = pidfile
if not isinstance(self.loglevel, numbers.Integral):
self.loglevel = LOG_LEVELS[self.loglevel.upper()]
def run(self) -> None:
if not self.quiet:
print(str(self.colored.cyan(
f'celery beat v{VERSION_BANNER} is starting.')))
self.init_loader()
self.set_process_title()
self.start_scheduler()
def setup_logging(self, colorize: bool | None = None) -> None:
if colorize is None and self.no_color is not None:
colorize = not self.no_color
self.app.log.setup(self.loglevel, self.logfile,
self.redirect_stdouts, self.redirect_stdouts_level,
colorize=colorize)
def start_scheduler(self) -> None:
if self.pidfile:
platforms.create_pidlock(self.pidfile)
service = self.Service(
app=self.app,
max_interval=self.max_interval,
scheduler_cls=self.scheduler_cls,
schedule_filename=self.schedule,
)
if not self.quiet:
print(self.banner(service))
self.setup_logging()
if self.socket_timeout:
logger.debug('Setting default socket timeout to %r',
self.socket_timeout)
socket.setdefaulttimeout(self.socket_timeout)
try:
self.install_sync_handler(service)
service.start()
except Exception as exc:
logger.critical('beat raised exception %s: %r',
exc.__class__, exc,
exc_info=True)
raise
def banner(self, service: beat.Service) -> str:
c = self.colored
return str(
c.blue('__ ', c.magenta('-'),
c.blue(' ... __ '), c.magenta('-'),
c.blue(' _\n'),
c.reset(self.startup_info(service))),
)
def init_loader(self) -> None:
# Run the worker init handler.
# (Usually imports task modules and such.)
self.app.loader.init_worker()
self.app.finalize()
def startup_info(self, service: beat.Service) -> str:
scheduler = service.get_scheduler(lazy=True)
return STARTUP_INFO_FMT.format(
conninfo=self.app.connection().as_uri(),
timestamp=datetime.now().replace(microsecond=0),
logfile=self.logfile or '[stderr]',
loglevel=LOG_LEVELS[self.loglevel],
loader=qualname(self.app.loader),
scheduler=qualname(scheduler),
scheduler_info=scheduler.info,
hmax_interval=humanize_seconds(scheduler.max_interval),
max_interval=scheduler.max_interval,
)
def set_process_title(self) -> None:
arg_start = 'manage' in sys.argv[0] and 2 or 1
platforms.set_process_title(
'celery beat', info=' '.join(sys.argv[arg_start:]),
)
def install_sync_handler(self, service: beat.Service) -> None:
"""Install a `SIGTERM` + `SIGINT` handler saving the schedule."""
def _sync(signum: Signals, frame: FrameType) -> None:
service.sync()
raise SystemExit()
platforms.signals.update(SIGTERM=_sync, SIGINT=_sync)
| Beat |
python | kamyu104__LeetCode-Solutions | Python/kth-ancestor-of-a-tree-node.py | {
"start": 257,
"end": 1225
} | class ____(object):
def __init__(self, n, parent):
"""
:type n: int
:type parent: List[int]
"""
par = [[p] if p != -1 else [] for p in parent]
q = [par[i] for i, p in enumerate(parent) if p != -1]
i = 0
while q:
new_q = []
for p in q:
if not (i < len(par[p[i]])):
continue
p.append(par[p[i]][i])
new_q.append(p)
q = new_q
i += 1
self.__parent = par
def getKthAncestor(self, node, k):
"""
:type node: int
:type k: int
:rtype: int
"""
par, i, pow_i_of_2 = self.__parent, 0, 1
while pow_i_of_2 <= k:
if k & pow_i_of_2:
if not (i < len(par[node])):
return -1
node = par[node][i]
i += 1
pow_i_of_2 *= 2
return node
| TreeAncestor |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 47464,
"end": 48379
} | class ____(themeable):
"""
x-axis major-tick length
Parameters
----------
theme_element : float | complex
Value in points. A negative value creates the ticks
inside the plot panel. A complex value (e.g. `3j`)
creates ticks that span both in and out of the panel.
"""
def apply_ax(self, ax: Axes):
super().apply_ax(ax)
value: float | complex = self.properties["value"]
try:
visible = ax.xaxis.get_major_ticks()[0].tick1line.get_visible()
except IndexError:
value = 0
else:
if not visible:
value = 0
if isinstance(value, (float, int)):
tickdir = "in" if value < 0 else "out"
else:
tickdir = "inout"
ax.xaxis.set_tick_params(
which="major", length=abs(value), tickdir=tickdir
)
| axis_ticks_length_major_x |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/util.py | {
"start": 11799,
"end": 67444
} | class ____(UserDict):
"""Normal dict except it returns a case-insensitive string for any `name` key values."""
def __init__(self, data: dict[str, Any]):
self.data = data
@override
def __getitem__(self, key: Any) -> Any:
item = self.data[key]
if key == "name":
logger.debug(f"CaseInsensitiveNameDict.__getitem__ - {key}:{item}")
return CaseInsensitiveString(item)
return item
def get_sqlalchemy_column_metadata( # noqa: C901 # FIXME CoP
execution_engine: SqlAlchemyExecutionEngine,
table_selectable: sqlalchemy.Select,
schema_name: Optional[str] = None,
) -> Sequence[Mapping[str, Any]] | None:
try:
columns: Sequence[Dict[str, Any]]
engine = execution_engine.engine
inspector = execution_engine.get_inspector()
try:
# if a custom query was passed
if sqlalchemy.TextClause and isinstance(table_selectable, sqlalchemy.TextClause): # type: ignore[truthy-function]
if hasattr(table_selectable, "selected_columns"):
# New in version 1.4.
columns = table_selectable.selected_columns.columns
else:
# Implicit subquery for columns().column was deprecated in SQLAlchemy 1.4
# We must explicitly create a subquery
columns = table_selectable.columns().subquery().columns
elif sqlalchemy.quoted_name and isinstance(table_selectable, sqlalchemy.quoted_name): # type: ignore[truthy-function]
columns = inspector.get_columns(
table_name=table_selectable,
schema=schema_name,
)
else:
logger.warning("unexpected table_selectable type")
columns = inspector.get_columns( # type: ignore[assignment]
table_name=str(table_selectable),
schema=schema_name,
)
except (
KeyError,
AttributeError,
sa.exc.NoSuchTableError,
sa.exc.ProgrammingError,
) as exc:
logger.debug(f"{type(exc).__name__} while introspecting columns", exc_info=exc)
logger.info(f"While introspecting columns {exc!r}; attempting reflection fallback")
# we will get a KeyError for temporary tables, since
# reflection will not find the temporary schema
columns = column_reflection_fallback(
selectable=table_selectable,
dialect=engine.dialect,
sqlalchemy_engine=engine,
)
# Use fallback because for mssql and trino reflection mechanisms do not throw an error but return an empty list # noqa: E501 # FIXME CoP
if len(columns) == 0:
columns = column_reflection_fallback(
selectable=table_selectable,
dialect=engine.dialect,
sqlalchemy_engine=engine,
)
dialect_name = execution_engine.dialect.name
if dialect_name in [
GXSqlDialect.DATABRICKS,
GXSqlDialect.POSTGRESQL,
GXSqlDialect.SNOWFLAKE,
GXSqlDialect.TRINO,
]:
# WARNING: Do not alter columns in place, as they are cached on the inspector
columns_copy = [column.copy() for column in columns]
for column in columns_copy:
if column.get("type"):
# When using column_reflection_fallback, we might not be able to
# extract the column type, and only have the column name
compiled_type = column["type"].compile(dialect=execution_engine.dialect)
# Make the type case-insensitive
column["type"] = CaseInsensitiveString(str(compiled_type))
# Wrap all columns in CaseInsensitiveNameDict for all three dialects
return [CaseInsensitiveNameDict(column) for column in columns_copy]
return columns
except AttributeError as e:
logger.debug(f"Error while introspecting columns: {e!r}", exc_info=e)
return None
def column_reflection_fallback( # noqa: C901, PLR0912, PLR0915 # FIXME CoP
selectable: sqlalchemy.Select,
dialect: sqlalchemy.Dialect,
sqlalchemy_engine: sqlalchemy.Engine,
) -> List[Dict[str, str]]:
"""If we can't reflect the table, use a query to at least get column names."""
if isinstance(sqlalchemy_engine.engine, sqlalchemy.Engine):
connection = sqlalchemy_engine.engine.connect()
else:
connection = sqlalchemy_engine.engine
# with sqlalchemy_engine.begin() as connection:
with connection:
col_info_dict_list: List[Dict[str, str]]
# noinspection PyUnresolvedReferences
if dialect.name.lower() == "mssql":
# Get column names and types from the database
# Reference: https://dataedo.com/kb/query/sql-server/list-table-columns-in-database
tables_table_clause: sqlalchemy.TableClause = sa.table( # type: ignore[assignment] # FIXME CoP
"tables",
sa.column("object_id"),
sa.column("schema_id"),
sa.column("name"),
schema="sys",
).alias("sys_tables_table_clause")
tables_table_query: sqlalchemy.Select = (
sa.select( # type: ignore[assignment] # FIXME CoP
tables_table_clause.columns.object_id.label("object_id"),
sa.func.schema_name(tables_table_clause.columns.schema_id).label("schema_name"),
tables_table_clause.columns.name.label("table_name"),
)
.select_from(tables_table_clause)
.alias("sys_tables_table_subquery")
)
columns_table_clause: sqlalchemy.TableClause = sa.table( # type: ignore[assignment] # FIXME CoP
"columns",
sa.column("object_id"),
sa.column("user_type_id"),
sa.column("column_id"),
sa.column("name"),
sa.column("max_length"),
sa.column("precision"),
schema="sys",
).alias("sys_columns_table_clause")
columns_table_query: sqlalchemy.Select = (
sa.select( # type: ignore[assignment] # FIXME CoP
columns_table_clause.columns.object_id.label("object_id"),
columns_table_clause.columns.user_type_id.label("user_type_id"),
columns_table_clause.columns.column_id.label("column_id"),
columns_table_clause.columns.name.label("column_name"),
columns_table_clause.columns.max_length.label("column_max_length"),
columns_table_clause.columns.precision.label("column_precision"),
)
.select_from(columns_table_clause)
.alias("sys_columns_table_subquery")
)
types_table_clause: sqlalchemy.TableClause = sa.table( # type: ignore[assignment] # FIXME CoP
"types",
sa.column("user_type_id"),
sa.column("name"),
schema="sys",
).alias("sys_types_table_clause")
types_table_query: sqlalchemy.Select = (
sa.select( # type: ignore[assignment] # FIXME CoP
types_table_clause.columns.user_type_id.label("user_type_id"),
types_table_clause.columns.name.label("column_data_type"),
)
.select_from(types_table_clause)
.alias("sys_types_table_subquery")
)
inner_join_conditions: sqlalchemy.BinaryExpression = sa.and_( # type: ignore[assignment] # FIXME CoP
*(tables_table_query.c.object_id == columns_table_query.c.object_id,)
)
outer_join_conditions: sqlalchemy.BinaryExpression = sa.and_( # type: ignore[assignment] # FIXME CoP
*(
columns_table_query.columns.user_type_id
== types_table_query.columns.user_type_id,
)
)
col_info_query = (
sa.select(
tables_table_query.c.schema_name,
tables_table_query.c.table_name,
columns_table_query.c.column_id,
columns_table_query.c.column_name,
types_table_query.c.column_data_type,
columns_table_query.c.column_max_length,
columns_table_query.c.column_precision,
)
.select_from(
tables_table_query.join( # type: ignore[call-arg,arg-type] # FIXME CoP
right=columns_table_query,
onclause=inner_join_conditions,
isouter=False,
).join(
right=types_table_query,
onclause=outer_join_conditions,
isouter=True,
)
)
.where(tables_table_query.c.table_name == selectable.name) # type: ignore[attr-defined] # FIXME CoP
.order_by(
tables_table_query.c.schema_name.asc(),
tables_table_query.c.table_name.asc(),
columns_table_query.c.column_id.asc(),
)
)
col_info_tuples_list: List[tuple] = connection.execute(col_info_query).fetchall() # type: ignore[assignment] # FIXME CoP
col_info_dict_list = [
{
"name": column_name,
# "type": getattr(type_module, column_data_type.upper())(),
"type": column_data_type.upper(),
}
for schema_name, table_name, column_id, column_name, column_data_type, column_max_length, column_precision in col_info_tuples_list # noqa: E501 # FIXME CoP
]
elif dialect.name.lower() == "trino":
try:
table_name = selectable.name # type: ignore[attr-defined] # FIXME CoP
except AttributeError:
table_name = selectable
if str(table_name).lower().startswith("select"):
rx = re.compile(r"^.* from ([\S]+)", re.I)
match = rx.match(str(table_name).replace("\n", ""))
if match:
table_name = match.group(1)
schema_name = sqlalchemy_engine.dialect.default_schema_name
tables_table: sa.Table = sa.Table(
"tables",
sa.MetaData(),
schema="information_schema",
)
tables_table_query = (
sa.select( # type: ignore[assignment] # FIXME CoP
sa.column("table_schema").label("schema_name"),
sa.column("table_name").label("table_name"),
)
.select_from(tables_table)
.alias("information_schema_tables_table")
)
columns_table: sa.Table = sa.Table(
"columns",
sa.MetaData(),
schema="information_schema",
)
columns_table_query = (
sa.select( # type: ignore[assignment] # FIXME CoP
sa.column("column_name").label("column_name"),
sa.column("table_name").label("table_name"),
sa.column("table_schema").label("schema_name"),
sa.column("data_type").label("column_data_type"),
)
.select_from(columns_table)
.alias("information_schema_columns_table")
)
conditions = sa.and_(
*(
tables_table_query.c.table_name == columns_table_query.c.table_name,
tables_table_query.c.schema_name == columns_table_query.c.schema_name,
)
)
col_info_query = (
sa.select( # type: ignore[assignment] # FIXME CoP
tables_table_query.c.schema_name,
tables_table_query.c.table_name,
columns_table_query.c.column_name,
columns_table_query.c.column_data_type,
)
.select_from(
tables_table_query.join( # type: ignore[call-arg,arg-type] # FIXME CoP
right=columns_table_query, onclause=conditions, isouter=False
)
)
.where(
sa.and_(
*(
tables_table_query.c.table_name == table_name,
tables_table_query.c.schema_name == schema_name,
)
)
)
.order_by(
tables_table_query.c.schema_name.asc(),
tables_table_query.c.table_name.asc(),
columns_table_query.c.column_name.asc(),
)
.alias("column_info")
)
# in sqlalchemy > 2.0.0 this is a Subquery, which we need to convert into a Selectable
if not col_info_query.supports_execution:
col_info_query = sa.select(col_info_query) # type: ignore[call-overload] # FIXME CoP
col_info_tuples_list = connection.execute(col_info_query).fetchall() # type: ignore[assignment] # FIXME CoP
col_info_dict_list = [
{
"name": column_name,
"type": column_data_type.upper(),
}
for schema_name, table_name, column_name, column_data_type in col_info_tuples_list
]
else:
# if a custom query was passed
if sqlalchemy.TextClause and isinstance(selectable, sqlalchemy.TextClause): # type: ignore[truthy-function] # FIXME CoP
query: sqlalchemy.TextClause = selectable
elif sqlalchemy.Table and isinstance(selectable, sqlalchemy.Table): # type: ignore[truthy-function] # FIXME CoP
query = sa.select(sa.text("*")).select_from(selectable).limit(1)
else: # noqa: PLR5501 # FIXME CoP
# noinspection PyUnresolvedReferences
if dialect.name.lower() == GXSqlDialect.REDSHIFT:
# Redshift needs temp tables to be declared as text
query = sa.select(sa.text("*")).select_from(sa.text(selectable)).limit(1) # type: ignore[assignment,arg-type] # FIXME CoP
else:
query = sa.select(sa.text("*")).select_from(sa.text(selectable)).limit(1) # type: ignore[assignment,arg-type] # FIXME CoP
result_object = connection.execute(query)
# noinspection PyProtectedMember
col_names: List[str] = result_object._metadata.keys # type: ignore[assignment] # FIXME CoP
col_info_dict_list = [{"name": col_name} for col_name in col_names]
return col_info_dict_list
def get_dbms_compatible_metric_domain_kwargs(
metric_domain_kwargs: dict,
batch_columns_list: Sequence[str | sqlalchemy.quoted_name],
) -> dict:
"""
This method checks "metric_domain_kwargs" and updates values of "Domain" keys based on actual "Batch" columns. If
column name in "Batch" column list is quoted, then corresponding column name in "metric_domain_kwargs" is also quoted.
Args:
metric_domain_kwargs: Original "metric_domain_kwargs" dictionary of attribute key-value pairs.
batch_columns_list: Actual "Batch" column list (e.g., output of "table.columns" metric).
Returns:
metric_domain_kwargs: Updated "metric_domain_kwargs" dictionary with quoted column names, where appropriate.
""" # noqa: E501 # FIXME CoP
column_names: List[str | sqlalchemy.quoted_name]
if "column" in metric_domain_kwargs:
column_name: str | sqlalchemy.quoted_name = get_dbms_compatible_column_names(
column_names=metric_domain_kwargs["column"],
batch_columns_list=batch_columns_list,
)
metric_domain_kwargs["column"] = column_name
elif "column_A" in metric_domain_kwargs and "column_B" in metric_domain_kwargs:
column_A_name: str | sqlalchemy.quoted_name = metric_domain_kwargs["column_A"]
column_B_name: str | sqlalchemy.quoted_name = metric_domain_kwargs["column_B"]
column_names = [
column_A_name,
column_B_name,
]
column_names = get_dbms_compatible_column_names(
column_names=column_names,
batch_columns_list=batch_columns_list,
)
(
metric_domain_kwargs["column_A"],
metric_domain_kwargs["column_B"],
) = column_names
elif "column_list" in metric_domain_kwargs:
column_names = metric_domain_kwargs["column_list"]
column_names = get_dbms_compatible_column_names(
column_names=column_names,
batch_columns_list=batch_columns_list,
)
metric_domain_kwargs["column_list"] = column_names
return metric_domain_kwargs
@overload
def get_dbms_compatible_column_names(
column_names: str,
batch_columns_list: Sequence[str | sqlalchemy.quoted_name],
error_message_template: str = ...,
) -> str | sqlalchemy.quoted_name: ...
@overload
def get_dbms_compatible_column_names(
column_names: List[str],
batch_columns_list: Sequence[str | sqlalchemy.quoted_name],
error_message_template: str = ...,
) -> List[str | sqlalchemy.quoted_name]: ...
def get_dbms_compatible_column_names(
column_names: List[str] | str,
batch_columns_list: Sequence[str | sqlalchemy.quoted_name],
error_message_template: str = 'Error: The column "{column_name:s}" in BatchData does not exist.', # noqa: E501 # FIXME CoP
) -> List[str | sqlalchemy.quoted_name] | str | sqlalchemy.quoted_name:
"""
Case non-sensitivity is expressed in upper case by common DBMS backends and in lower case by SQLAlchemy, with any
deviations enclosed with double quotes.
SQLAlchemy enables correct translation to/from DBMS backends through "sqlalchemy.sql.elements.quoted_name" class
where necessary by insuring that column names of correct type (i.e., "str" or "sqlalchemy.sql.elements.quoted_name")
are returned by "sqlalchemy.inspect(sqlalchemy.engine.Engine).get_columns(table_name, schema)" ("table.columns"
metric is based on this method). Columns of precise type (string or "quoted_name" as appropriate) are returned.
Args:
column_names: Single string-valued column name or list of string-valued column names
batch_columns_list: Properly typed column names (output of "table.columns" metric)
error_message_template: String template to output error message if any column cannot be found in "Batch" object.
Returns:
Single property-typed column name object or list of property-typed column name objects (depending on input).
""" # noqa: E501 # FIXME CoP
normalized_typed_batch_columns_mappings: List[Tuple[str, str | sqlalchemy.quoted_name]] = (
_verify_column_names_exist_and_get_normalized_typed_column_names_map(
column_names=column_names,
batch_columns_list=batch_columns_list,
error_message_template=error_message_template,
)
or []
)
element: Tuple[str, str | sqlalchemy.quoted_name]
typed_batch_column_names_list: List[str | sqlalchemy.quoted_name] = [
element[1] for element in normalized_typed_batch_columns_mappings
]
if isinstance(column_names, list):
return typed_batch_column_names_list
return typed_batch_column_names_list[0]
def verify_column_names_exist(
column_names: List[str] | str,
batch_columns_list: List[str | sqlalchemy.quoted_name],
error_message_template: str = 'Error: The column "{column_name:s}" in BatchData does not exist.', # noqa: E501 # FIXME CoP
) -> None:
_ = _verify_column_names_exist_and_get_normalized_typed_column_names_map(
column_names=column_names,
batch_columns_list=batch_columns_list,
error_message_template=error_message_template,
verify_only=True,
)
def _verify_column_names_exist_and_get_normalized_typed_column_names_map( # noqa: C901 # FIXME CoP
column_names: List[str] | str,
batch_columns_list: Sequence[str | sqlalchemy.quoted_name],
error_message_template: str = 'Error: The column "{column_name:s}" in BatchData does not exist.', # noqa: E501 # FIXME CoP
verify_only: bool = False,
) -> List[Tuple[str, str | sqlalchemy.quoted_name]] | None:
"""
Insures that column name or column names (supplied as argument using "str" representation) exist in "Batch" object.
Args:
column_names: Single string-valued column name or list of string-valued column names
batch_columns_list: Properly typed column names (output of "table.columns" metric)
verify_only: Perform verification only (do not return normalized typed column names)
error_message_template: String template to output error message if any column cannot be found in "Batch" object.
Returns:
List of tuples having mapping from string-valued column name to typed column name; None if "verify_only" is set.
""" # noqa: E501 # FIXME CoP
column_names_list: List[str]
if isinstance(column_names, list):
column_names_list = column_names
else:
column_names_list = [column_names]
def _get_normalized_column_name_mapping_if_exists(
column_name: str,
) -> Tuple[str, str | sqlalchemy.quoted_name] | None:
typed_column_name_cursor: str | sqlalchemy.quoted_name
for typed_column_name_cursor in batch_columns_list:
if (
(type(typed_column_name_cursor) == str) # noqa: E721 # FIXME CoP
and (column_name.casefold() == typed_column_name_cursor.casefold())
) or (column_name == str(typed_column_name_cursor)):
return column_name, typed_column_name_cursor
# use explicit identifier if passed in by user
if isinstance(typed_column_name_cursor, str) and (
(column_name.casefold().strip('"') == typed_column_name_cursor.casefold())
or (column_name.casefold().strip("[]") == typed_column_name_cursor.casefold())
or (column_name.casefold().strip("`") == typed_column_name_cursor.casefold())
):
return column_name, column_name
return None
normalized_batch_columns_mappings: List[Tuple[str, str | sqlalchemy.quoted_name]] = []
normalized_column_name_mapping: Tuple[str, str | sqlalchemy.quoted_name] | None
column_name: str
for column_name in column_names_list:
normalized_column_name_mapping = _get_normalized_column_name_mapping_if_exists(
column_name=column_name
)
if normalized_column_name_mapping is None:
raise gx_exceptions.InvalidMetricAccessorDomainKwargsKeyError(
message=error_message_template.format(column_name=column_name)
)
else: # noqa: PLR5501 # FIXME CoP
if not verify_only:
normalized_batch_columns_mappings.append(normalized_column_name_mapping)
return None if verify_only else normalized_batch_columns_mappings
def parse_value_set(value_set: Iterable) -> list:
parsed_value_set = [parse(value) if isinstance(value, str) else value for value in value_set]
return parsed_value_set
def get_dialect_like_pattern_expression( # noqa: C901, PLR0912, PLR0915 # FIXME CoP
column: sa.Column, dialect: ModuleType, like_pattern: str, positive: bool = True
) -> sa.BinaryExpression | None:
dialect_supported: bool = False
try:
# Bigquery
if hasattr(dialect, "BigQueryDialect"):
dialect_supported = True
except (
AttributeError,
TypeError,
): # TypeError can occur if the driver was not installed and so is None
pass
if hasattr(dialect, "dialect"):
try:
if issubclass(dialect.dialect, sa.dialects.sqlite.dialect):
dialect_supported = True
except AttributeError:
pass
try:
if issubclass(dialect.dialect, sa.dialects.postgresql.dialect):
dialect_supported = True
except AttributeError:
pass
try:
if issubclass(dialect.dialect, sa.dialects.mysql.dialect):
dialect_supported = True
except AttributeError:
pass
try:
if issubclass(dialect.dialect, sa.dialects.mssql.dialect):
dialect_supported = True
except AttributeError:
pass
if _is_databricks_dialect(dialect):
dialect_supported = True
try:
if hasattr(dialect, "RedshiftDialect"):
dialect_supported = True
except (AttributeError, TypeError):
pass
# noinspection PyUnresolvedReferences
if aws.redshiftdialect and isinstance(dialect, aws.redshiftdialect.RedshiftDialect):
dialect_supported = True
else:
pass
try:
# noinspection PyUnresolvedReferences
if hasattr(dialect, "TrinoDialect") or (
trino.trinodialect and isinstance(dialect, trino.trinodialect.TrinoDialect)
):
dialect_supported = True
except (AttributeError, TypeError):
pass
try:
# noinspection PyUnresolvedReferences
if hasattr(dialect, "ClickHouseDialect") or isinstance(
dialect, clickhouse_sqlalchemy.drivers.base.ClickHouseDialect
):
dialect_supported = True
except (AttributeError, TypeError):
pass
try:
if hasattr(dialect, "SnowflakeDialect"):
dialect_supported = True
except (AttributeError, TypeError):
pass
try:
if hasattr(dialect, "DremioDialect"):
dialect_supported = True
except (AttributeError, TypeError):
pass
try:
if issubclass(dialect.dialect, teradatasqlalchemy.dialect.TeradataDialect):
dialect_supported = True
except (AttributeError, TypeError):
pass
if dialect_supported:
try:
if positive:
return column.like(sqlalchemy.literal(like_pattern))
else:
return sa.not_(column.like(sqlalchemy.literal(like_pattern)))
except AttributeError:
pass
return None
def validate_distribution_parameters( # noqa: C901, PLR0912, PLR0915 # FIXME CoP
distribution, params
):
"""Ensures that necessary parameters for a distribution are present and that all parameters are sensical.
If parameters necessary to construct a distribution are missing or invalid, this function raises ValueError\
with an informative description. Note that 'loc' and 'scale' are optional arguments, and that 'scale'\
must be positive.
Args:
distribution (string): \
The scipy distribution name, e.g. normal distribution is 'norm'.
params (dict or list): \
The distribution shape parameters in a named dictionary or positional list form following the scipy \
cdf argument scheme.
params={'mean': 40, 'std_dev': 5} or params=[40, 5]
Exceptions:
ValueError: \
With an informative description, usually when necessary parameters are omitted or are invalid.
""" # noqa: E501 # FIXME CoP
norm_msg = "norm distributions require 0 parameters and optionally 'mean', 'std_dev'."
beta_msg = "beta distributions require 2 positive parameters 'alpha', 'beta' and optionally 'loc', 'scale'." # noqa: E501 # FIXME CoP
gamma_msg = (
"gamma distributions require 1 positive parameter 'alpha' and optionally 'loc','scale'."
)
# poisson_msg = "poisson distributions require 1 positive parameter 'lambda' and optionally 'loc'." # noqa: E501 # FIXME CoP
uniform_msg = "uniform distributions require 0 parameters and optionally 'loc', 'scale'."
chi2_msg = "chi2 distributions require 1 positive parameter 'df' and optionally 'loc', 'scale'."
expon_msg = "expon distributions require 0 parameters and optionally 'loc', 'scale'."
if distribution not in [
"norm",
"beta",
"gamma",
"poisson",
"uniform",
"chi2",
"expon",
]:
raise AttributeError(f"Unsupported distribution provided: {distribution}") # noqa: TRY003 # FIXME CoP
if isinstance(params, dict):
# `params` is a dictionary
if params.get("std_dev", 1) <= 0 or params.get("scale", 1) <= 0:
raise ValueError("std_dev and scale must be positive.") # noqa: TRY003 # FIXME CoP
# alpha and beta are required and positive
if distribution == "beta" and (params.get("alpha", -1) <= 0 or params.get("beta", -1) <= 0):
raise ValueError(f"Invalid parameters: {beta_msg}") # noqa: TRY003 # FIXME CoP
# alpha is required and positive
elif distribution == "gamma" and params.get("alpha", -1) <= 0:
raise ValueError(f"Invalid parameters: {gamma_msg}") # noqa: TRY003 # FIXME CoP
# lambda is a required and positive
# elif distribution == 'poisson' and params.get('lambda', -1) <= 0:
# raise ValueError("Invalid parameters: %s" %poisson_msg)
# df is necessary and required to be positive
elif distribution == "chi2" and params.get("df", -1) <= 0:
raise ValueError(f"Invalid parameters: {chi2_msg}:") # noqa: TRY003 # FIXME CoP
elif isinstance(params, (tuple, list)):
scale = None
# `params` is a tuple or a list
if distribution == "beta":
if len(params) < 2: # noqa: PLR2004 # FIXME CoP
raise ValueError(f"Missing required parameters: {beta_msg}") # noqa: TRY003 # FIXME CoP
if params[0] <= 0 or params[1] <= 0:
raise ValueError(f"Invalid parameters: {beta_msg}") # noqa: TRY003 # FIXME CoP
if len(params) == 4: # noqa: PLR2004 # FIXME CoP
scale = params[3]
elif len(params) > 4: # noqa: PLR2004 # FIXME CoP
raise ValueError(f"Too many parameters provided: {beta_msg}") # noqa: TRY003 # FIXME CoP
elif distribution == "norm":
if len(params) > 2: # noqa: PLR2004 # FIXME CoP
raise ValueError(f"Too many parameters provided: {norm_msg}") # noqa: TRY003 # FIXME CoP
if len(params) == 2: # noqa: PLR2004 # FIXME CoP
scale = params[1]
elif distribution == "gamma":
if len(params) < 1:
raise ValueError(f"Missing required parameters: {gamma_msg}") # noqa: TRY003 # FIXME CoP
if len(params) == 3: # noqa: PLR2004 # FIXME CoP
scale = params[2]
if len(params) > 3: # noqa: PLR2004 # FIXME CoP
raise ValueError(f"Too many parameters provided: {gamma_msg}") # noqa: TRY003 # FIXME CoP
elif params[0] <= 0:
raise ValueError(f"Invalid parameters: {gamma_msg}") # noqa: TRY003 # FIXME CoP
# elif distribution == 'poisson':
# if len(params) < 1:
# raise ValueError("Missing required parameters: %s" %poisson_msg)
# if len(params) > 2:
# raise ValueError("Too many parameters provided: %s" %poisson_msg)
# elif params[0] <= 0:
# raise ValueError("Invalid parameters: %s" %poisson_msg)
elif distribution == "uniform":
if len(params) == 2: # noqa: PLR2004 # FIXME CoP
scale = params[1]
if len(params) > 2: # noqa: PLR2004 # FIXME CoP
raise ValueError(f"Too many arguments provided: {uniform_msg}") # noqa: TRY003 # FIXME CoP
elif distribution == "chi2":
if len(params) < 1:
raise ValueError(f"Missing required parameters: {chi2_msg}") # noqa: TRY003 # FIXME CoP
elif len(params) == 3: # noqa: PLR2004 # FIXME CoP
scale = params[2]
elif len(params) > 3: # noqa: PLR2004 # FIXME CoP
raise ValueError(f"Too many arguments provided: {chi2_msg}") # noqa: TRY003 # FIXME CoP
if params[0] <= 0:
raise ValueError(f"Invalid parameters: {chi2_msg}") # noqa: TRY003 # FIXME CoP
elif distribution == "expon":
if len(params) == 2: # noqa: PLR2004 # FIXME CoP
scale = params[1]
if len(params) > 2: # noqa: PLR2004 # FIXME CoP
raise ValueError(f"Too many arguments provided: {expon_msg}") # noqa: TRY003 # FIXME CoP
if scale is not None and scale <= 0:
raise ValueError("std_dev and scale must be positive.") # noqa: TRY003 # FIXME CoP
else:
raise ValueError( # noqa: TRY003, TRY004 # FIXME CoP
"params must be a dict or list, or use great_expectations.dataset.util.infer_distribution_parameters(data, distribution)" # noqa: E501 # FIXME CoP
)
def _scipy_distribution_positional_args_from_dict(distribution, params):
"""Helper function that returns positional arguments for a scipy distribution using a dict of parameters.
See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\
to see an example of scipy's positional arguments. This function returns the arguments specified by the \
scipy.stat.distribution.cdf() for that distribution.
Args:
distribution (string): \
The scipy distribution name.
params (dict): \
A dict of named parameters.
Raises:
AttributeError: \
If an unsupported distribution is provided.
""" # noqa: E501 # FIXME CoP
params["loc"] = params.get("loc", 0)
if "scale" not in params:
params["scale"] = 1
if distribution == "norm":
return params["mean"], params["std_dev"]
elif distribution == "beta":
return params["alpha"], params["beta"], params["loc"], params["scale"]
elif distribution == "gamma":
return params["alpha"], params["loc"], params["scale"]
# elif distribution == 'poisson':
# return params['lambda'], params['loc']
elif distribution == "uniform":
return params["min"], params["max"]
elif distribution == "chi2":
return params["df"], params["loc"], params["scale"]
elif distribution == "expon":
return params["loc"], params["scale"]
def is_valid_continuous_partition_object(partition_object):
"""Tests whether a given object is a valid continuous partition object. See :ref:`partition_object`.
:param partition_object: The partition_object to evaluate
:return: Boolean
""" # noqa: E501 # FIXME CoP
if (
(partition_object is None)
or ("weights" not in partition_object)
or ("bins" not in partition_object)
):
return False
if "tail_weights" in partition_object:
if len(partition_object["tail_weights"]) != 2: # noqa: PLR2004 # FIXME CoP
return False
comb_weights = partition_object["tail_weights"] + partition_object["weights"]
else:
comb_weights = partition_object["weights"]
## TODO: Consider adding this check to migrate to the tail_weights structure of partition objects # noqa: E501 # FIXME CoP
# if (partition_object['bins'][0] == -np.inf) or (partition_object['bins'][-1] == np.inf):
# return False
# Expect one more bin edge than weight; all bin edges should be monotonically increasing; weights should sum to one # noqa: E501 # FIXME CoP
return (
(len(partition_object["bins"]) == (len(partition_object["weights"]) + 1))
and np.all(np.diff(partition_object["bins"]) > 0)
and np.allclose(np.sum(comb_weights), 1.0)
)
def _substitute_positional_parameters(query_template: str, compiled: SQLCompiler) -> str:
"""
Substitute positional (?) parameters in query template.
"""
param_values = [compiled.params[name] for name in compiled.positiontup or []]
params = (repr(val) for val in param_values)
query_as_string = re.sub(r"\?", lambda m: next(params), query_template)
return query_as_string
def _substitute_pyformat_parameters(query_template: str, compiled: Compiled) -> str:
"""Substitute %(param_name)s parameters in query template."""
query_as_string = query_template
for param_name, param_value in compiled.params.items():
# Match %(name)s or %(name:TYPE)s - BigQuery includes type annotations
pattern = rf"%\({re.escape(param_name)}(?::[^)]+)?\)s"
query_as_string = re.sub(pattern, repr(param_value), query_as_string)
return query_as_string
def _substitute_colon_parameters(query_template: str, compiled: Compiled) -> str:
"""Substitute :param_name parameters in query template."""
query_as_string = query_template
for param_name, param_value in compiled.params.items():
query_as_string = query_as_string.replace(f":{param_name}", repr(param_value))
return query_as_string
def _detect_parameter_style(
query_template: str, compiled: Compiled
) -> Literal["positional", "pyformat", "colon", "none_or_other"]:
"""
Detect the SQL parameter placeholder style used in the compiled query.
Returns one of: "positional", "pyformat", "colon", or "none_or_other"
"""
if hasattr(compiled, "positiontup") and compiled.positiontup:
return "positional"
elif compiled.params and any(f"%({name}" in query_template for name in compiled.params):
return "pyformat"
elif compiled.params and any(f":{name}" in query_template for name in compiled.params):
return "colon"
else:
return "none_or_other"
def _check_has_unsubstituted_params(
query_as_string: str,
compiled: Compiled,
) -> bool:
"""
Check if any parameters are still unsubstituted in the query.
Checks if all parameter values appear in the query (as their repr() forms).
Also checks if parameter names appear in the query (for named placeholders),
accounting for names that might appear within the substituted values.
"""
if not compiled.params:
return False
# Check if all parameter values are present in the query
for value in compiled.params.values():
value_repr = repr(value)
if value_repr not in query_as_string:
# Value not found in query - substitution failed
return True
# Additional check: if parameter names appear in query (outside of any values),
# this indicates named placeholders weren't substituted
for name in compiled.params:
if name in query_as_string:
# Check if this name appears in ANY of the parameter values
name_in_any_value = any(name in repr(value) for value in compiled.params.values())
if not name_in_any_value:
# Parameter name is in query but not in any value - it's unsubstituted
return True
return False
def _substitute_with_render_postcompile(
engine: SqlAlchemyExecutionEngine,
select_statement: sqlalchemy.Select,
) -> Tuple[str, Compiled]:
"""
Compile SQL with render_postcompile and manually substitute parameters.
Pros:
- Produces queries directly copy-pasteable into SQL query editors
Cons:
- Requires manual parameter style detection and substitution logic
- May fail for unknown bind parameter styles
Returns:
Tuple of (query_string, compiled_object)
"""
compiled = select_statement.compile(
engine.engine,
compile_kwargs={"render_postcompile": True},
)
query_template = str(compiled)
# Detect parameter style and substitute parameters
parameter_style = _detect_parameter_style(query_template, compiled)
if parameter_style == "positional":
# Positional placeholders (?) - e.g. SQLite, Trino, MSSQL
query_as_string = _substitute_positional_parameters(query_template, compiled)
elif parameter_style == "pyformat":
# Named parameters with %(param_name)s syntax - e.g. PostgreSQL, MySQL, BigQuery
# BigQuery includes type annotations like %(name:FLOAT64)s
query_as_string = _substitute_pyformat_parameters(query_template, compiled)
elif parameter_style == "colon":
# Named parameters with :param_name syntax - e.g. Databricks, Oracle
query_as_string = _substitute_colon_parameters(query_template, compiled)
else: # parameter_style == "none_or_other"
# No parameters to substitute, or unknown parameter style
query_as_string = query_template
return query_as_string, compiled
def _fallback_to_literal_binds(
engine: SqlAlchemyExecutionEngine,
select_statement: sqlalchemy.Select,
) -> str:
"""
Fall back to literal_binds compilation.
Pros:
- Guaranteed to substitute bind parameters for all SQLAlchemy-supported dialects
Cons:
- Requires post-processing for SQL editor compatibility
- May fail for unknown DB-API vs SQL editor syntax incompatibilities
"""
compiled = select_statement.compile(
engine.engine,
compile_kwargs={"literal_binds": True},
)
query_as_string = str(compiled)
# Unescape %% to % for SQL editor compatibility
# PostgreSQL (psycopg2) and MySQL (mysqlclient) escape % as %% for Python driver
dialect_name: str = engine.dialect_name
if dialect_name in (GXSqlDialect.POSTGRESQL, GXSqlDialect.MYSQL, GXSqlDialect.REDSHIFT):
query_as_string = query_as_string.replace("%%", "%")
return query_as_string
def sqlalchemy_select_to_sql_string(
engine: SqlAlchemyExecutionEngine, select_statement: sqlalchemy.Select
) -> str:
"""
Compile SQL select statement with bound parameters rendered as literal values. Append semicolon.
This function exists because SQLAlchemy does not guarantee a way to produce a
valid SQL syntax string. SQLAlchemy's built-in literal_binds produces queries
with driver-specific escaping that is intended for Python DB-API drivers, not SQL
query editors. For example, psycopg2 (PostgreSQL driver) escapes '%' as '%%' for
Python string formatting, so LIKE '%pattern%' becomes LIKE '%%pattern%%'. This is
correct for Python but invalid SQL syntax.
We use a two-step approach:
1. Try render_postcompile with manual parameter substitution (produces SQL editor syntax)
2. Fall back to literal_binds with post-processing if manual substitution fails
This ensures users can copy-paste the resulting query directly into their SQL query
editor without modification.
Args:
engine: SqlAlchemyExecutionEngine with connection to backend.
select_statement: Select statement to compile into string.
Returns:
String representation of select_statement with parameters inlined,
suitable for copy-pasting into a SQL query editor.
"""
# Try render_postcompile with manual substitution first (avoids %% escaping)
query_as_string, compiled = _substitute_with_render_postcompile(engine, select_statement)
# Check if substitution failed and fall back to literal_binds if needed
if _check_has_unsubstituted_params(query_as_string, compiled):
query_as_string = _fallback_to_literal_binds(engine, select_statement)
return query_as_string + ";"
def get_sqlalchemy_source_table_and_schema(
engine: SqlAlchemyExecutionEngine,
) -> sa.Table:
"""
Util method to return table name that is associated with current batch.
This is used by `_sqlalchemy_map_condition_query()` which returns a query that allows users to return
unexpected_index_values.
Args:
engine (SqlAlchemyExecutionEngine): Engine that is currently being used to calculate the Metrics
Returns:
SqlAlchemy Table that is the source table and schema.
""" # noqa: E501 # FIXME CoP
assert isinstance(engine.batch_manager.active_batch_data, SqlAlchemyBatchData), (
"`active_batch_data` not SqlAlchemyBatchData"
)
schema_name = engine.batch_manager.active_batch_data.source_schema_name
table_name = engine.batch_manager.active_batch_data.source_table_name
if table_name:
return sa.Table(
table_name,
sa.MetaData(),
schema=schema_name,
)
else:
return engine.batch_manager.active_batch_data.selectable
def get_unexpected_indices_for_multiple_pandas_named_indices( # noqa: C901 # FIXME CoP
domain_records_df: pd.DataFrame,
unexpected_index_column_names: List[str],
expectation_domain_column_list: List[str],
exclude_unexpected_values: bool = False,
) -> UnexpectedIndexList:
"""
Builds unexpected_index_list for Pandas Dataframe in situation where the named
columns is also a named index. This method handles the case when there are multiple named indices.
Args:
domain_records_df: reference to Pandas dataframe
unexpected_index_column_names: column_names for indices, either named index or unexpected_index_columns
expectation_domain_column_list: list of columns that Expectation is being run on.
Returns:
List of Dicts that contain ID/PK values
""" # noqa: E501 # FIXME CoP
if not expectation_domain_column_list:
raise gx_exceptions.MetricResolutionError(
message="Error: The list of domain columns is currently empty. Please check your configuration.", # noqa: E501 # FIXME CoP
failed_metrics=["unexpected_index_list"],
)
domain_records_df_index_names: List[str] = domain_records_df.index.names # type: ignore[assignment] # FIXME
unexpected_indices: List[tuple[int | str, ...]] = list(domain_records_df.index)
tuple_index: Dict[str, int] = dict()
for column_name in unexpected_index_column_names:
if column_name not in domain_records_df_index_names:
raise gx_exceptions.MetricResolutionError(
message=f"Error: The column {column_name} does not exist in the named indices. "
f"Please check your configuration.",
failed_metrics=["unexpected_index_list"],
)
else:
tuple_index[column_name] = domain_records_df_index_names.index(column_name, 0)
unexpected_index_list: UnexpectedIndexList = []
if exclude_unexpected_values and len(unexpected_indices) != 0:
primary_key_dict_list: dict[str, List[Any]] = {
idx_col: [] for idx_col in unexpected_index_column_names
}
for index in unexpected_indices:
for column_name in unexpected_index_column_names:
primary_key_dict_list[column_name].append(index[tuple_index[column_name]])
unexpected_index_list.append(primary_key_dict_list)
else:
for index in unexpected_indices:
primary_key_dict: Dict[str, Any] = dict()
for domain_column_name in expectation_domain_column_list:
primary_key_dict[domain_column_name] = domain_records_df.at[
index, domain_column_name
]
for column_name in unexpected_index_column_names:
primary_key_dict[column_name] = index[tuple_index[column_name]]
unexpected_index_list.append(primary_key_dict)
return unexpected_index_list
def get_unexpected_indices_for_single_pandas_named_index(
domain_records_df: pd.DataFrame,
unexpected_index_column_names: List[str],
expectation_domain_column_list: List[str],
exclude_unexpected_values: bool = False,
) -> UnexpectedIndexList:
"""
Builds unexpected_index_list for Pandas Dataframe in situation where the named
columns is also a named index. This method handles the case when there is a single named index.
Args:
domain_records_df: reference to Pandas dataframe
unexpected_index_column_names: column_names for indices, either named index or unexpected_index_columns
expectation_domain_column_list: list of columns that Expectation is being run on.
Returns:
List of Dicts that contain ID/PK values
""" # noqa: E501 # FIXME CoP
if not expectation_domain_column_list:
return []
unexpected_index_values_by_named_index: List[int | str] = list(domain_records_df.index)
unexpected_index_list: UnexpectedIndexList = []
if not (
len(unexpected_index_column_names) == 1
and unexpected_index_column_names[0] == domain_records_df.index.name
):
raise gx_exceptions.MetricResolutionError(
message=f"Error: The column {unexpected_index_column_names[0] if unexpected_index_column_names else '<no column specified>'} does not exist in the named indices. Please check your configuration", # noqa: E501 # FIXME CoP
failed_metrics=["unexpected_index_list"],
)
if exclude_unexpected_values and len(unexpected_index_values_by_named_index) != 0:
primary_key_dict_list: dict[str, List[Any]] = {unexpected_index_column_names[0]: []}
for index in unexpected_index_values_by_named_index:
primary_key_dict_list[unexpected_index_column_names[0]].append(index)
unexpected_index_list.append(primary_key_dict_list)
else:
for index in unexpected_index_values_by_named_index:
primary_key_dict: Dict[str, Any] = dict()
for domain_column in expectation_domain_column_list:
primary_key_dict[domain_column] = domain_records_df.at[index, domain_column]
column_name: str = unexpected_index_column_names[0]
primary_key_dict[column_name] = index
unexpected_index_list.append(primary_key_dict)
return unexpected_index_list
def compute_unexpected_pandas_indices( # noqa: C901 # FIXME CoP
domain_records_df: pd.DataFrame,
expectation_domain_column_list: List[str],
result_format: Dict[str, Any],
execution_engine: PandasExecutionEngine,
metrics: Dict[str, Any],
) -> UnexpectedIndexList:
"""
Helper method to compute unexpected_index_list for PandasExecutionEngine. Handles logic needed for named indices.
Args:
domain_records_df: DataFrame of data we are currently running Expectation on.
expectation_domain_column_list: list of columns that we are running Expectation on. It can be one column.
result_format: configuration that contains `unexpected_index_column_names`
expectation_domain_column_list: list of columns that we are running Expectation on. It can be one column.
execution_engine: PandasExecutionEngine
metrics: dict of currently available metrics
Returns:
list of unexpected_index_list values. It can either be a list of dicts or a list of numbers (if using default index).
""" # noqa: E501 # FIXME CoP
unexpected_index_column_names: List[str]
unexpected_index_list: UnexpectedIndexList
exclude_unexpected_values: bool = result_format.get("exclude_unexpected_values", False)
if domain_records_df.index.name is not None:
unexpected_index_column_names = result_format.get(
"unexpected_index_column_names", [domain_records_df.index.name]
)
unexpected_index_list = get_unexpected_indices_for_single_pandas_named_index(
domain_records_df=domain_records_df,
unexpected_index_column_names=unexpected_index_column_names,
expectation_domain_column_list=expectation_domain_column_list,
exclude_unexpected_values=exclude_unexpected_values,
)
# multiple named indices
elif domain_records_df.index.names[0] is not None:
unexpected_index_column_names = result_format.get(
"unexpected_index_column_names", list(domain_records_df.index.names)
)
unexpected_index_list = get_unexpected_indices_for_multiple_pandas_named_indices(
domain_records_df=domain_records_df,
unexpected_index_column_names=unexpected_index_column_names,
expectation_domain_column_list=expectation_domain_column_list,
exclude_unexpected_values=exclude_unexpected_values,
)
# named columns
elif result_format.get("unexpected_index_column_names"):
unexpected_index_column_names = result_format["unexpected_index_column_names"]
unexpected_index_list = []
unexpected_indices: List[int | str] = list(domain_records_df.index)
if (
exclude_unexpected_values
and len(unexpected_indices) != 0
and len(unexpected_index_column_names) != 0
):
primary_key_dict_list: dict[str, List[Any]] = {
idx_col: [] for idx_col in unexpected_index_column_names
}
for index in unexpected_indices:
for column_name in unexpected_index_column_names:
column_name = get_dbms_compatible_column_names( # noqa: PLW2901 # FIXME CoP
column_names=column_name,
batch_columns_list=metrics["table.columns"],
error_message_template='Error: The unexpected_index_column "{column_name:s}" does not exist in Dataframe. Please check your configuration and try again.', # noqa: E501 # FIXME CoP
)
primary_key_dict_list[column_name].append(
domain_records_df.at[index, column_name]
)
unexpected_index_list.append(primary_key_dict_list)
else:
for index in unexpected_indices:
primary_key_dict: Dict[str, Any] = dict()
assert expectation_domain_column_list, (
"`expectation_domain_column_list` was not provided"
)
for domain_column_name in expectation_domain_column_list:
primary_key_dict[domain_column_name] = domain_records_df.at[
index, domain_column_name
]
for column_name in unexpected_index_column_names:
column_name = get_dbms_compatible_column_names( # noqa: PLW2901 # FIXME CoP
column_names=column_name,
batch_columns_list=metrics["table.columns"],
error_message_template='Error: The unexpected_index_column "{column_name:s}" does not exist in Dataframe. Please check your configuration and try again.', # noqa: E501 # FIXME CoP
)
primary_key_dict[column_name] = domain_records_df.at[index, column_name]
unexpected_index_list.append(primary_key_dict)
else:
unexpected_index_list = list(domain_records_df.index)
return unexpected_index_list
| CaseInsensitiveNameDict |
python | PrefectHQ__prefect | src/integrations/prefect-docker/prefect_docker/deployments/steps.py | {
"start": 2066,
"end": 14631
} | class ____(TypedDict):
"""
The result of a `push_docker_image` step.
Attributes:
image_name: The name of the pushed image.
tag: The tag of the pushed image.
image: The name and tag of the pushed image.
additional_tags: The additional tags on the image, in addition to `tag`.
"""
image_name: str
tag: Optional[str]
image: str
additional_tags: Optional[List[str]]
def _make_hashable(obj: Any) -> Any:
if isinstance(obj, dict):
return json.dumps(obj, sort_keys=True)
elif isinstance(obj, list):
return tuple(_make_hashable(v) for v in obj)
return obj
def cacheable(func: Callable[P, T]) -> Callable[P, T]:
@wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
if ignore_cache := kwargs.pop("ignore_cache", False):
logger.debug(f"Ignoring `@cacheable` decorator for {func.__name__}.")
key = (
func.__name__,
tuple(_make_hashable(arg) for arg in args),
tuple((k, _make_hashable(v)) for k, v in sorted(kwargs.items())),
)
if ignore_cache or key not in STEP_OUTPUT_CACHE:
logger.debug(f"Cache miss for {func.__name__}, running function.")
STEP_OUTPUT_CACHE[key] = func(*args, **kwargs)
else:
logger.debug(f"Cache hit for {func.__name__}, returning cached value.")
return STEP_OUTPUT_CACHE[key]
return wrapper
@cacheable
def build_docker_image(
image_name: str,
dockerfile: str = "Dockerfile",
tag: str | None = None,
additional_tags: list[str] | None = None,
ignore_cache: bool = False,
persist_dockerfile: bool = False,
dockerfile_output_path: str = "Dockerfile.generated",
**build_kwargs: Any,
) -> BuildDockerImageResult:
"""
Builds a Docker image for a Prefect deployment.
Can be used within a `prefect.yaml` file to build a Docker
image prior to creating or updating a deployment.
Args:
image_name: The name of the Docker image to build, including the registry and
repository.
dockerfile: The path to the Dockerfile used to build the image. If "auto" is
passed, a temporary Dockerfile will be created to build the image.
tag: The tag to apply to the built image.
additional_tags: Additional tags on the image, in addition to `tag`, to apply to the built image.
persist_dockerfile: If True and dockerfile="auto", the generated Dockerfile will be saved
instead of deleted after the build.
dockerfile_output_path: Optional path where the auto-generated Dockerfile should be saved
(e.g., "Dockerfile.generated"). Only used if `persist_dockerfile` is True.
**build_kwargs: Additional keyword arguments to pass to Docker when building
the image. Available options can be found in the [`docker-py`](https://docker-py.readthedocs.io/en/stable/images.html#docker.models.images.ImageCollection.build)
documentation.
Returns:
A dictionary containing the image name and tag of the
built image.
Example:
Build a Docker image prior to creating a deployment:
```yaml
build:
- prefect_docker.deployments.steps.build_docker_image:
requires: prefect-docker
image_name: repo-name/image-name
tag: dev
```
Build a Docker image with multiple tags:
```yaml
build:
- prefect_docker.deployments.steps.build_docker_image:
requires: prefect-docker
image_name: repo-name/image-name
tag: dev
additional_tags:
- v0.1.0,
- dac9ccccedaa55a17916eef14f95cc7bdd3c8199
```
Build a Docker image using an auto-generated Dockerfile:
```yaml
build:
- prefect_docker.deployments.steps.build_docker_image:
requires: prefect-docker
image_name: repo-name/image-name
tag: dev
dockerfile: auto
```
Build a Docker image for a different platform:
```yaml
build:
- prefect_docker.deployments.steps.build_docker_image:
requires: prefect-docker
image_name: repo-name/image-name
tag: dev
dockerfile: Dockerfile
platform: amd64
```
Save the auto-generated Dockerfile to disk:
```yaml
build:
- prefect_docker.deployments.steps.build_docker_image:
requires: prefect-docker
image_name: repo-name/image-name
tag: dev
dockerfile: auto
persist_dockerfile: true
dockerfile_output_path: Dockerfile.generated
```
""" # noqa
namespace, repository = split_repository_path(image_name)
if not namespace:
namespace = PREFECT_DEFAULT_DOCKER_BUILD_NAMESPACE.value()
# join the namespace and repository to create the full image name
# ignore namespace if it is None
image_name = "/".join(filter(None, [namespace, repository]))
auto_build = dockerfile == "auto"
if auto_build:
lines: list[str] = []
base_image = get_prefect_image_name()
lines.append(f"FROM {base_image}")
dir_name = os.path.basename(os.getcwd())
if Path("requirements.txt").exists():
lines.append(
f"COPY requirements.txt /opt/prefect/{dir_name}/requirements.txt"
)
lines.append(
f"RUN uv pip install -r /opt/prefect/{dir_name}/requirements.txt"
)
lines.append(f"COPY . /opt/prefect/{dir_name}/")
lines.append(f"WORKDIR /opt/prefect/{dir_name}/")
temp_dockerfile = Path("Dockerfile")
if Path(temp_dockerfile).exists():
raise ValueError("Dockerfile already exists.")
with Path(temp_dockerfile).open("w") as f:
f.writelines(line + "\n" for line in lines)
if persist_dockerfile:
logger.info(
f"Persisting auto-generated Dockerfile to {dockerfile_output_path or 'Dockerfile.generated'}. Please update your 'dockerfile' value to use this Dockerfile for subsequent runs."
)
output_path = Path(dockerfile_output_path or "Dockerfile.generated")
with output_path.open("w") as out_file:
out_file.writelines(line + "\n" for line in lines)
else:
logger.info(
"Deleting auto-generated Dockerfile after build. Consider using `persist_dockerfile` to save it."
)
dockerfile = str(temp_dockerfile)
build_kwargs["path"] = build_kwargs.get("path", os.getcwd())
build_kwargs["dockerfile"] = dockerfile
build_kwargs["pull"] = build_kwargs.get("pull", True)
build_kwargs["decode"] = True
build_kwargs["labels"] = {**build_kwargs.get("labels", {}), **IMAGE_LABELS}
image_id = None
with docker_client() as client:
try:
events = client.api.build(**build_kwargs)
try:
for event in events:
if "stream" in event:
sys.stdout.write(event["stream"])
sys.stdout.flush()
elif "aux" in event:
image_id = event["aux"]["ID"]
elif "error" in event:
raise BuildError(event["error"])
elif "message" in event:
raise BuildError(event["message"])
except docker.errors.APIError as e:
raise BuildError(e.explanation) from e
finally:
if auto_build:
os.unlink(dockerfile)
if not isinstance(image_id, str):
raise BuildError("Docker did not return an image ID for built image.")
if not tag:
tag = slugify(datetime.now(ZoneInfo("UTC")).isoformat())
image: Image = client.images.get(image_id)
image.tag(repository=image_name, tag=tag)
additional_tags = additional_tags or []
for tag_ in additional_tags:
image.tag(repository=image_name, tag=tag_)
return {
"image_name": image_name,
"tag": tag,
"image": f"{image_name}:{tag}",
"image_id": image_id,
"additional_tags": additional_tags,
}
@cacheable
def push_docker_image(
image_name: str,
tag: str | None = None,
credentials: dict[str, Any] | None = None,
additional_tags: list[str] | None = None,
ignore_cache: bool = False,
) -> PushDockerImageResult:
"""
Push a Docker image to a remote registry.
Args:
image_name: The name of the Docker image to push, including the registry and
repository.
tag: The tag of the Docker image to push.
credentials: A dictionary containing the username, password, and URL for the
registry to push the image to.
additional_tags: Additional tags on the image, in addition to `tag`, to apply to the built image.
Returns:
A dictionary containing the image name and tag of the
pushed image.
Examples:
Build and push a Docker image to a private repository:
```yaml
build:
- prefect_docker.deployments.steps.build_docker_image:
id: build-image
requires: prefect-docker
image_name: repo-name/image-name
tag: dev
dockerfile: auto
push:
- prefect_docker.deployments.steps.push_docker_image:
requires: prefect-docker
image_name: "{{ build-image.image_name }}"
tag: "{{ build-image.tag }}"
credentials: "{{ prefect.blocks.docker-registry-credentials.dev-registry }}"
```
Build and push a Docker image to a private repository with multiple tags
```yaml
build:
- prefect_docker.deployments.steps.build_docker_image:
id: build-image
requires: prefect-docker
image_name: repo-name/image-name
tag: dev
dockerfile: auto
additional_tags: [
v0.1.0,
dac9ccccedaa55a17916eef14f95cc7bdd3c8199
]
push:
- prefect_docker.deployments.steps.push_docker_image:
requires: prefect-docker
image_name: "{{ build-image.image_name }}"
tag: "{{ build-image.tag }}"
credentials: "{{ prefect.blocks.docker-registry-credentials.dev-registry }}"
additional_tags: "{{ build-image.additional_tags }}"
```
""" # noqa
namespace, repository = split_repository_path(image_name)
if not namespace:
namespace = PREFECT_DEFAULT_DOCKER_BUILD_NAMESPACE.value()
# join the namespace and repository to create the full image name
# ignore namespace if it is None
image_name = "/".join(filter(None, [namespace, repository]))
with docker_client() as client:
if credentials is not None:
client.login(
username=credentials.get("username"),
password=credentials.get("password"),
registry=credentials.get("registry_url"),
reauth=credentials.get("reauth", True),
)
events = list(
client.api.push(repository=image_name, tag=tag, stream=True, decode=True)
)
additional_tags = additional_tags or []
for tag_ in additional_tags:
event = list(
client.api.push(
repository=image_name, tag=tag_, stream=True, decode=True
)
)
events = events + event
for event in events:
if "status" in event:
sys.stdout.write(event["status"])
if "progress" in event:
sys.stdout.write(" " + event["progress"])
sys.stdout.write("\n")
sys.stdout.flush()
elif "error" in event:
raise OSError(event["error"])
return {
"image_name": image_name,
"tag": tag,
"image": f"{image_name}:{tag}",
"additional_tags": additional_tags,
}
| PushDockerImageResult |
python | explosion__spaCy | spacy/lang/ru/lemmatizer.py | {
"start": 294,
"end": 7973
} | class ____(Lemmatizer):
def __init__(
self,
vocab: Vocab,
model: Optional[Model],
name: str = "lemmatizer",
*,
mode: str = "pymorphy3",
overwrite: bool = False,
scorer: Optional[Callable] = lemmatizer_score,
) -> None:
if mode in {"pymorphy2", "pymorphy2_lookup"}:
try:
from pymorphy2 import MorphAnalyzer
except ImportError:
raise ImportError(
"The lemmatizer mode 'pymorphy2' requires the "
"pymorphy2 library and dictionaries. Install them with: "
"pip install pymorphy2"
"# for Ukrainian dictionaries:"
"pip install pymorphy2-dicts-uk"
) from None
if getattr(self, "_morph", None) is None:
self._morph = MorphAnalyzer(lang="ru")
elif mode in {"pymorphy3", "pymorphy3_lookup"}:
try:
from pymorphy3 import MorphAnalyzer
except ImportError:
raise ImportError(
"The lemmatizer mode 'pymorphy3' requires the "
"pymorphy3 library and dictionaries. Install them with: "
"pip install pymorphy3"
"# for Ukrainian dictionaries:"
"pip install pymorphy3-dicts-uk"
) from None
if getattr(self, "_morph", None) is None:
self._morph = MorphAnalyzer(lang="ru")
super().__init__(
vocab, model, name, mode=mode, overwrite=overwrite, scorer=scorer
)
def _pymorphy_lemmatize(self, token: Token) -> List[str]:
string = token.text
univ_pos = token.pos_
morphology = token.morph.to_dict()
if univ_pos == "PUNCT":
return [PUNCT_RULES.get(string, string)]
if univ_pos not in ("ADJ", "DET", "NOUN", "NUM", "PRON", "PROPN", "VERB"):
return self._pymorphy_lookup_lemmatize(token)
analyses = self._morph.parse(string)
filtered_analyses = []
for analysis in analyses:
if not analysis.is_known:
# Skip suggested parse variant for unknown word for pymorphy
continue
analysis_pos, _ = oc2ud(str(analysis.tag))
if (
analysis_pos == univ_pos
or (analysis_pos in ("NOUN", "PROPN") and univ_pos in ("NOUN", "PROPN"))
or ((analysis_pos == "PRON") and (univ_pos == "DET"))
):
filtered_analyses.append(analysis)
if not len(filtered_analyses):
return [string.lower()]
if morphology is None or (len(morphology) == 1 and POS in morphology):
return list(
dict.fromkeys([analysis.normal_form for analysis in filtered_analyses])
)
if univ_pos in ("ADJ", "DET", "NOUN", "PROPN"):
features_to_compare = ["Case", "Number", "Gender"]
elif univ_pos == "NUM":
features_to_compare = ["Case", "Gender"]
elif univ_pos == "PRON":
features_to_compare = ["Case", "Number", "Gender", "Person"]
else: # VERB
features_to_compare = [
"Aspect",
"Gender",
"Mood",
"Number",
"Tense",
"VerbForm",
"Voice",
]
analyses, filtered_analyses = filtered_analyses, []
for analysis in analyses:
_, analysis_morph = oc2ud(str(analysis.tag))
for feature in features_to_compare:
if (
feature in morphology
and feature in analysis_morph
and morphology[feature].lower() != analysis_morph[feature].lower()
):
break
else:
filtered_analyses.append(analysis)
if not len(filtered_analyses):
return [string.lower()]
return list(
dict.fromkeys([analysis.normal_form for analysis in filtered_analyses])
)
def _pymorphy_lookup_lemmatize(self, token: Token) -> List[str]:
string = token.text
analyses = self._morph.parse(string)
# often multiple forms would derive from the same normal form
# thus check _unique_ normal forms
normal_forms = set([an.normal_form for an in analyses])
if len(normal_forms) == 1:
return [next(iter(normal_forms))]
return [string]
def pymorphy2_lemmatize(self, token: Token) -> List[str]:
return self._pymorphy_lemmatize(token)
def pymorphy2_lookup_lemmatize(self, token: Token) -> List[str]:
return self._pymorphy_lookup_lemmatize(token)
def pymorphy3_lemmatize(self, token: Token) -> List[str]:
return self._pymorphy_lemmatize(token)
def pymorphy3_lookup_lemmatize(self, token: Token) -> List[str]:
return self._pymorphy_lookup_lemmatize(token)
def oc2ud(oc_tag: str) -> Tuple[str, Dict[str, str]]:
gram_map = {
"_POS": {
"ADJF": "ADJ",
"ADJS": "ADJ",
"ADVB": "ADV",
"Apro": "DET",
"COMP": "ADJ", # Can also be an ADV - unchangeable
"CONJ": "CCONJ", # Can also be a SCONJ - both unchangeable ones
"GRND": "VERB",
"INFN": "VERB",
"INTJ": "INTJ",
"NOUN": "NOUN",
"NPRO": "PRON",
"NUMR": "NUM",
"NUMB": "NUM",
"PNCT": "PUNCT",
"PRCL": "PART",
"PREP": "ADP",
"PRTF": "VERB",
"PRTS": "VERB",
"VERB": "VERB",
},
"Animacy": {"anim": "Anim", "inan": "Inan"},
"Aspect": {"impf": "Imp", "perf": "Perf"},
"Case": {
"ablt": "Ins",
"accs": "Acc",
"datv": "Dat",
"gen1": "Gen",
"gen2": "Gen",
"gent": "Gen",
"loc2": "Loc",
"loct": "Loc",
"nomn": "Nom",
"voct": "Voc",
},
"Degree": {"COMP": "Cmp", "Supr": "Sup"},
"Gender": {"femn": "Fem", "masc": "Masc", "neut": "Neut"},
"Mood": {"impr": "Imp", "indc": "Ind"},
"Number": {"plur": "Plur", "sing": "Sing"},
"NumForm": {"NUMB": "Digit"},
"Person": {"1per": "1", "2per": "2", "3per": "3", "excl": "2", "incl": "1"},
"Tense": {"futr": "Fut", "past": "Past", "pres": "Pres"},
"Variant": {"ADJS": "Brev", "PRTS": "Brev"},
"VerbForm": {
"GRND": "Conv",
"INFN": "Inf",
"PRTF": "Part",
"PRTS": "Part",
"VERB": "Fin",
},
"Voice": {"actv": "Act", "pssv": "Pass"},
"Abbr": {"Abbr": "Yes"},
}
pos = "X"
morphology = dict()
unmatched = set()
grams = oc_tag.replace(" ", ",").split(",")
for gram in grams:
match = False
for categ, gmap in sorted(gram_map.items()):
if gram in gmap:
match = True
if categ == "_POS":
pos = gmap[gram]
else:
morphology[categ] = gmap[gram]
if not match:
unmatched.add(gram)
while len(unmatched) > 0:
gram = unmatched.pop()
if gram in ("Name", "Patr", "Surn", "Geox", "Orgn"):
pos = "PROPN"
elif gram == "Auxt":
pos = "AUX"
elif gram == "Pltm":
morphology["Number"] = "Ptan"
return pos, morphology
| RussianLemmatizer |
python | langchain-ai__langchain | libs/core/langchain_core/messages/modifier.py | {
"start": 144,
"end": 875
} | class ____(BaseMessage):
"""Message responsible for deleting other messages."""
type: Literal["remove"] = "remove"
"""The type of the message (used for serialization)."""
def __init__(
self,
id: str,
**kwargs: Any,
) -> None:
"""Create a RemoveMessage.
Args:
id: The ID of the message to remove.
**kwargs: Additional fields to pass to the message.
Raises:
ValueError: If the 'content' field is passed in kwargs.
"""
if kwargs.pop("content", None):
msg = "RemoveMessage does not support 'content' field."
raise ValueError(msg)
super().__init__("", id=id, **kwargs)
| RemoveMessage |
python | django__django | tests/template_tests/syntax_tests/test_url.py | {
"start": 11932,
"end": 12560
} | class ____(SimpleTestCase):
def test_repr(self):
url_node = URLNode(view_name="named-view", args=[], kwargs={}, asvar=None)
self.assertEqual(
repr(url_node),
"<URLNode view_name='named-view' args=[] kwargs={} as=None>",
)
url_node = URLNode(
view_name="named-view",
args=[1, 2],
kwargs={"action": "update"},
asvar="my_url",
)
self.assertEqual(
repr(url_node),
"<URLNode view_name='named-view' args=[1, 2] "
"kwargs={'action': 'update'} as='my_url'>",
)
| URLNodeTest |
python | google__flatbuffers | tests/monster_test_generated.py | {
"start": 64950,
"end": 97485
} | class ____(object):
# MonsterT
def __init__(
self,
pos = None,
mana = 150,
hp = 100,
name = None,
inventory = None,
color = 8,
testType = 0,
test = None,
test4 = None,
testarrayofstring = None,
testarrayoftables = None,
enemy = None,
testnestedflatbuffer = None,
testempty = None,
testbool = False,
testhashs32Fnv1 = 0,
testhashu32Fnv1 = 0,
testhashs64Fnv1 = 0,
testhashu64Fnv1 = 0,
testhashs32Fnv1a = 0,
testhashu32Fnv1a = 0,
testhashs64Fnv1a = 0,
testhashu64Fnv1a = 0,
testarrayofbools = None,
testf = 3.14159,
testf2 = 3.0,
testf3 = 0.0,
testarrayofstring2 = None,
testarrayofsortedstruct = None,
flex = None,
test5 = None,
vectorOfLongs = None,
vectorOfDoubles = None,
parentNamespaceTest = None,
vectorOfReferrables = None,
singleWeakReference = 0,
vectorOfWeakReferences = None,
vectorOfStrongReferrables = None,
coOwningReference = 0,
vectorOfCoOwningReferences = None,
nonOwningReference = 0,
vectorOfNonOwningReferences = None,
anyUniqueType = 0,
anyUnique = None,
anyAmbiguousType = 0,
anyAmbiguous = None,
vectorOfEnums = None,
signedEnum = -1,
testrequirednestedflatbuffer = None,
scalarKeySortedTables = None,
nativeInline = None,
longEnumNonEnumDefault = 0,
longEnumNormalDefault = 2,
nanDefault = float('nan'),
infDefault = float('inf'),
positiveInfDefault = float('inf'),
infinityDefault = float('inf'),
positiveInfinityDefault = float('inf'),
negativeInfDefault = float('-inf'),
negativeInfinityDefault = float('-inf'),
doubleInfDefault = float('inf'),
):
self.pos = pos # type: Optional[Vec3T]
self.mana = mana # type: int
self.hp = hp # type: int
self.name = name # type: Optional[str]
self.inventory = inventory # type: Optional[List[int]]
self.color = color # type: int
self.testType = testType # type: int
self.test = test # type: Union[None, 'MonsterT', 'TestSimpleTableWithEnumT', 'MonsterT']
self.test4 = test4 # type: Optional[List[TestT]]
self.testarrayofstring = testarrayofstring # type: Optional[List[Optional[str]]]
self.testarrayoftables = testarrayoftables # type: Optional[List[MonsterT]]
self.enemy = enemy # type: Optional[MonsterT]
self.testnestedflatbuffer = testnestedflatbuffer # type: Optional[List[int]]
self.testempty = testempty # type: Optional[StatT]
self.testbool = testbool # type: bool
self.testhashs32Fnv1 = testhashs32Fnv1 # type: int
self.testhashu32Fnv1 = testhashu32Fnv1 # type: int
self.testhashs64Fnv1 = testhashs64Fnv1 # type: int
self.testhashu64Fnv1 = testhashu64Fnv1 # type: int
self.testhashs32Fnv1a = testhashs32Fnv1a # type: int
self.testhashu32Fnv1a = testhashu32Fnv1a # type: int
self.testhashs64Fnv1a = testhashs64Fnv1a # type: int
self.testhashu64Fnv1a = testhashu64Fnv1a # type: int
self.testarrayofbools = testarrayofbools # type: Optional[List[bool]]
self.testf = testf # type: float
self.testf2 = testf2 # type: float
self.testf3 = testf3 # type: float
self.testarrayofstring2 = testarrayofstring2 # type: Optional[List[Optional[str]]]
self.testarrayofsortedstruct = testarrayofsortedstruct # type: Optional[List[AbilityT]]
self.flex = flex # type: Optional[List[int]]
self.test5 = test5 # type: Optional[List[TestT]]
self.vectorOfLongs = vectorOfLongs # type: Optional[List[int]]
self.vectorOfDoubles = vectorOfDoubles # type: Optional[List[float]]
self.parentNamespaceTest = parentNamespaceTest # type: Optional[InParentNamespaceT]
self.vectorOfReferrables = vectorOfReferrables # type: Optional[List[ReferrableT]]
self.singleWeakReference = singleWeakReference # type: int
self.vectorOfWeakReferences = vectorOfWeakReferences # type: Optional[List[int]]
self.vectorOfStrongReferrables = vectorOfStrongReferrables # type: Optional[List[ReferrableT]]
self.coOwningReference = coOwningReference # type: int
self.vectorOfCoOwningReferences = vectorOfCoOwningReferences # type: Optional[List[int]]
self.nonOwningReference = nonOwningReference # type: int
self.vectorOfNonOwningReferences = vectorOfNonOwningReferences # type: Optional[List[int]]
self.anyUniqueType = anyUniqueType # type: int
self.anyUnique = anyUnique # type: Union[None, 'MonsterT', 'TestSimpleTableWithEnumT', 'MonsterT']
self.anyAmbiguousType = anyAmbiguousType # type: int
self.anyAmbiguous = anyAmbiguous # type: Union[None, 'MonsterT', 'MonsterT', 'MonsterT']
self.vectorOfEnums = vectorOfEnums # type: Optional[List[int]]
self.signedEnum = signedEnum # type: int
self.testrequirednestedflatbuffer = testrequirednestedflatbuffer # type: Optional[List[int]]
self.scalarKeySortedTables = scalarKeySortedTables # type: Optional[List[StatT]]
self.nativeInline = nativeInline # type: Optional[TestT]
self.longEnumNonEnumDefault = longEnumNonEnumDefault # type: int
self.longEnumNormalDefault = longEnumNormalDefault # type: int
self.nanDefault = nanDefault # type: float
self.infDefault = infDefault # type: float
self.positiveInfDefault = positiveInfDefault # type: float
self.infinityDefault = infinityDefault # type: float
self.positiveInfinityDefault = positiveInfinityDefault # type: float
self.negativeInfDefault = negativeInfDefault # type: float
self.negativeInfinityDefault = negativeInfinityDefault # type: float
self.doubleInfDefault = doubleInfDefault # type: float
@classmethod
def InitFromBuf(cls, buf, pos):
monster = Monster()
monster.Init(buf, pos)
return cls.InitFromObj(monster)
@classmethod
def InitFromPackedBuf(cls, buf, pos=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos)
return cls.InitFromBuf(buf, pos+n)
@classmethod
def InitFromObj(cls, monster):
x = MonsterT()
x._UnPack(monster)
return x
# MonsterT
def _UnPack(self, monster):
if monster is None:
return
if monster.Pos() is not None:
self.pos = Vec3T.InitFromObj(monster.Pos())
self.mana = monster.Mana()
self.hp = monster.Hp()
self.name = monster.Name()
if not monster.InventoryIsNone():
if np is None:
self.inventory = []
for i in range(monster.InventoryLength()):
self.inventory.append(monster.Inventory(i))
else:
self.inventory = monster.InventoryAsNumpy()
self.color = monster.Color()
self.testType = monster.TestType()
self.test = AnyCreator(self.testType, monster.Test())
if not monster.Test4IsNone():
self.test4 = []
for i in range(monster.Test4Length()):
if monster.Test4(i) is None:
self.test4.append(None)
else:
test_ = TestT.InitFromObj(monster.Test4(i))
self.test4.append(test_)
if not monster.TestarrayofstringIsNone():
self.testarrayofstring = []
for i in range(monster.TestarrayofstringLength()):
self.testarrayofstring.append(monster.Testarrayofstring(i))
if not monster.TestarrayoftablesIsNone():
self.testarrayoftables = []
for i in range(monster.TestarrayoftablesLength()):
if monster.Testarrayoftables(i) is None:
self.testarrayoftables.append(None)
else:
monster_ = MonsterT.InitFromObj(monster.Testarrayoftables(i))
self.testarrayoftables.append(monster_)
if monster.Enemy() is not None:
self.enemy = MonsterT.InitFromObj(monster.Enemy())
if not monster.TestnestedflatbufferIsNone():
if np is None:
self.testnestedflatbuffer = []
for i in range(monster.TestnestedflatbufferLength()):
self.testnestedflatbuffer.append(monster.Testnestedflatbuffer(i))
else:
self.testnestedflatbuffer = monster.TestnestedflatbufferAsNumpy()
if monster.Testempty() is not None:
self.testempty = StatT.InitFromObj(monster.Testempty())
self.testbool = monster.Testbool()
self.testhashs32Fnv1 = monster.Testhashs32Fnv1()
self.testhashu32Fnv1 = monster.Testhashu32Fnv1()
self.testhashs64Fnv1 = monster.Testhashs64Fnv1()
self.testhashu64Fnv1 = monster.Testhashu64Fnv1()
self.testhashs32Fnv1a = monster.Testhashs32Fnv1a()
self.testhashu32Fnv1a = monster.Testhashu32Fnv1a()
self.testhashs64Fnv1a = monster.Testhashs64Fnv1a()
self.testhashu64Fnv1a = monster.Testhashu64Fnv1a()
if not monster.TestarrayofboolsIsNone():
if np is None:
self.testarrayofbools = []
for i in range(monster.TestarrayofboolsLength()):
self.testarrayofbools.append(monster.Testarrayofbools(i))
else:
self.testarrayofbools = monster.TestarrayofboolsAsNumpy()
self.testf = monster.Testf()
self.testf2 = monster.Testf2()
self.testf3 = monster.Testf3()
if not monster.Testarrayofstring2IsNone():
self.testarrayofstring2 = []
for i in range(monster.Testarrayofstring2Length()):
self.testarrayofstring2.append(monster.Testarrayofstring2(i))
if not monster.TestarrayofsortedstructIsNone():
self.testarrayofsortedstruct = []
for i in range(monster.TestarrayofsortedstructLength()):
if monster.Testarrayofsortedstruct(i) is None:
self.testarrayofsortedstruct.append(None)
else:
ability_ = AbilityT.InitFromObj(monster.Testarrayofsortedstruct(i))
self.testarrayofsortedstruct.append(ability_)
if not monster.FlexIsNone():
if np is None:
self.flex = []
for i in range(monster.FlexLength()):
self.flex.append(monster.Flex(i))
else:
self.flex = monster.FlexAsNumpy()
if not monster.Test5IsNone():
self.test5 = []
for i in range(monster.Test5Length()):
if monster.Test5(i) is None:
self.test5.append(None)
else:
test_ = TestT.InitFromObj(monster.Test5(i))
self.test5.append(test_)
if not monster.VectorOfLongsIsNone():
if np is None:
self.vectorOfLongs = []
for i in range(monster.VectorOfLongsLength()):
self.vectorOfLongs.append(monster.VectorOfLongs(i))
else:
self.vectorOfLongs = monster.VectorOfLongsAsNumpy()
if not monster.VectorOfDoublesIsNone():
if np is None:
self.vectorOfDoubles = []
for i in range(monster.VectorOfDoublesLength()):
self.vectorOfDoubles.append(monster.VectorOfDoubles(i))
else:
self.vectorOfDoubles = monster.VectorOfDoublesAsNumpy()
if monster.ParentNamespaceTest() is not None:
self.parentNamespaceTest = InParentNamespaceT.InitFromObj(monster.ParentNamespaceTest())
if not monster.VectorOfReferrablesIsNone():
self.vectorOfReferrables = []
for i in range(monster.VectorOfReferrablesLength()):
if monster.VectorOfReferrables(i) is None:
self.vectorOfReferrables.append(None)
else:
referrable_ = ReferrableT.InitFromObj(monster.VectorOfReferrables(i))
self.vectorOfReferrables.append(referrable_)
self.singleWeakReference = monster.SingleWeakReference()
if not monster.VectorOfWeakReferencesIsNone():
if np is None:
self.vectorOfWeakReferences = []
for i in range(monster.VectorOfWeakReferencesLength()):
self.vectorOfWeakReferences.append(monster.VectorOfWeakReferences(i))
else:
self.vectorOfWeakReferences = monster.VectorOfWeakReferencesAsNumpy()
if not monster.VectorOfStrongReferrablesIsNone():
self.vectorOfStrongReferrables = []
for i in range(monster.VectorOfStrongReferrablesLength()):
if monster.VectorOfStrongReferrables(i) is None:
self.vectorOfStrongReferrables.append(None)
else:
referrable_ = ReferrableT.InitFromObj(monster.VectorOfStrongReferrables(i))
self.vectorOfStrongReferrables.append(referrable_)
self.coOwningReference = monster.CoOwningReference()
if not monster.VectorOfCoOwningReferencesIsNone():
if np is None:
self.vectorOfCoOwningReferences = []
for i in range(monster.VectorOfCoOwningReferencesLength()):
self.vectorOfCoOwningReferences.append(monster.VectorOfCoOwningReferences(i))
else:
self.vectorOfCoOwningReferences = monster.VectorOfCoOwningReferencesAsNumpy()
self.nonOwningReference = monster.NonOwningReference()
if not monster.VectorOfNonOwningReferencesIsNone():
if np is None:
self.vectorOfNonOwningReferences = []
for i in range(monster.VectorOfNonOwningReferencesLength()):
self.vectorOfNonOwningReferences.append(monster.VectorOfNonOwningReferences(i))
else:
self.vectorOfNonOwningReferences = monster.VectorOfNonOwningReferencesAsNumpy()
self.anyUniqueType = monster.AnyUniqueType()
self.anyUnique = AnyUniqueAliasesCreator(self.anyUniqueType, monster.AnyUnique())
self.anyAmbiguousType = monster.AnyAmbiguousType()
self.anyAmbiguous = AnyAmbiguousAliasesCreator(self.anyAmbiguousType, monster.AnyAmbiguous())
if not monster.VectorOfEnumsIsNone():
if np is None:
self.vectorOfEnums = []
for i in range(monster.VectorOfEnumsLength()):
self.vectorOfEnums.append(monster.VectorOfEnums(i))
else:
self.vectorOfEnums = monster.VectorOfEnumsAsNumpy()
self.signedEnum = monster.SignedEnum()
if not monster.TestrequirednestedflatbufferIsNone():
if np is None:
self.testrequirednestedflatbuffer = []
for i in range(monster.TestrequirednestedflatbufferLength()):
self.testrequirednestedflatbuffer.append(monster.Testrequirednestedflatbuffer(i))
else:
self.testrequirednestedflatbuffer = monster.TestrequirednestedflatbufferAsNumpy()
if not monster.ScalarKeySortedTablesIsNone():
self.scalarKeySortedTables = []
for i in range(monster.ScalarKeySortedTablesLength()):
if monster.ScalarKeySortedTables(i) is None:
self.scalarKeySortedTables.append(None)
else:
stat_ = StatT.InitFromObj(monster.ScalarKeySortedTables(i))
self.scalarKeySortedTables.append(stat_)
if monster.NativeInline() is not None:
self.nativeInline = TestT.InitFromObj(monster.NativeInline())
self.longEnumNonEnumDefault = monster.LongEnumNonEnumDefault()
self.longEnumNormalDefault = monster.LongEnumNormalDefault()
self.nanDefault = monster.NanDefault()
self.infDefault = monster.InfDefault()
self.positiveInfDefault = monster.PositiveInfDefault()
self.infinityDefault = monster.InfinityDefault()
self.positiveInfinityDefault = monster.PositiveInfinityDefault()
self.negativeInfDefault = monster.NegativeInfDefault()
self.negativeInfinityDefault = monster.NegativeInfinityDefault()
self.doubleInfDefault = monster.DoubleInfDefault()
# MonsterT
def Pack(self, builder):
if self.name is not None:
name = builder.CreateString(self.name)
if self.inventory is not None:
if np is not None and type(self.inventory) is np.ndarray:
inventory = builder.CreateNumpyVector(self.inventory)
else:
MonsterStartInventoryVector(builder, len(self.inventory))
for i in reversed(range(len(self.inventory))):
builder.PrependUint8(self.inventory[i])
inventory = builder.EndVector()
if self.test is not None:
test = self.test.Pack(builder)
if self.test4 is not None:
MonsterStartTest4Vector(builder, len(self.test4))
for i in reversed(range(len(self.test4))):
self.test4[i].Pack(builder)
test4 = builder.EndVector()
if self.testarrayofstring is not None:
testarrayofstringlist = []
for i in range(len(self.testarrayofstring)):
testarrayofstringlist.append(builder.CreateString(self.testarrayofstring[i]))
MonsterStartTestarrayofstringVector(builder, len(self.testarrayofstring))
for i in reversed(range(len(self.testarrayofstring))):
builder.PrependUOffsetTRelative(testarrayofstringlist[i])
testarrayofstring = builder.EndVector()
if self.testarrayoftables is not None:
testarrayoftableslist = []
for i in range(len(self.testarrayoftables)):
testarrayoftableslist.append(self.testarrayoftables[i].Pack(builder))
MonsterStartTestarrayoftablesVector(builder, len(self.testarrayoftables))
for i in reversed(range(len(self.testarrayoftables))):
builder.PrependUOffsetTRelative(testarrayoftableslist[i])
testarrayoftables = builder.EndVector()
if self.enemy is not None:
enemy = self.enemy.Pack(builder)
if self.testnestedflatbuffer is not None:
if np is not None and type(self.testnestedflatbuffer) is np.ndarray:
testnestedflatbuffer = builder.CreateNumpyVector(self.testnestedflatbuffer)
else:
MonsterStartTestnestedflatbufferVector(builder, len(self.testnestedflatbuffer))
for i in reversed(range(len(self.testnestedflatbuffer))):
builder.PrependUint8(self.testnestedflatbuffer[i])
testnestedflatbuffer = builder.EndVector()
if self.testempty is not None:
testempty = self.testempty.Pack(builder)
if self.testarrayofbools is not None:
if np is not None and type(self.testarrayofbools) is np.ndarray:
testarrayofbools = builder.CreateNumpyVector(self.testarrayofbools)
else:
MonsterStartTestarrayofboolsVector(builder, len(self.testarrayofbools))
for i in reversed(range(len(self.testarrayofbools))):
builder.PrependBool(self.testarrayofbools[i])
testarrayofbools = builder.EndVector()
if self.testarrayofstring2 is not None:
testarrayofstring2list = []
for i in range(len(self.testarrayofstring2)):
testarrayofstring2list.append(builder.CreateString(self.testarrayofstring2[i]))
MonsterStartTestarrayofstring2Vector(builder, len(self.testarrayofstring2))
for i in reversed(range(len(self.testarrayofstring2))):
builder.PrependUOffsetTRelative(testarrayofstring2list[i])
testarrayofstring2 = builder.EndVector()
if self.testarrayofsortedstruct is not None:
MonsterStartTestarrayofsortedstructVector(builder, len(self.testarrayofsortedstruct))
for i in reversed(range(len(self.testarrayofsortedstruct))):
self.testarrayofsortedstruct[i].Pack(builder)
testarrayofsortedstruct = builder.EndVector()
if self.flex is not None:
if np is not None and type(self.flex) is np.ndarray:
flex = builder.CreateNumpyVector(self.flex)
else:
MonsterStartFlexVector(builder, len(self.flex))
for i in reversed(range(len(self.flex))):
builder.PrependUint8(self.flex[i])
flex = builder.EndVector()
if self.test5 is not None:
MonsterStartTest5Vector(builder, len(self.test5))
for i in reversed(range(len(self.test5))):
self.test5[i].Pack(builder)
test5 = builder.EndVector()
if self.vectorOfLongs is not None:
if np is not None and type(self.vectorOfLongs) is np.ndarray:
vectorOfLongs = builder.CreateNumpyVector(self.vectorOfLongs)
else:
MonsterStartVectorOfLongsVector(builder, len(self.vectorOfLongs))
for i in reversed(range(len(self.vectorOfLongs))):
builder.PrependInt64(self.vectorOfLongs[i])
vectorOfLongs = builder.EndVector()
if self.vectorOfDoubles is not None:
if np is not None and type(self.vectorOfDoubles) is np.ndarray:
vectorOfDoubles = builder.CreateNumpyVector(self.vectorOfDoubles)
else:
MonsterStartVectorOfDoublesVector(builder, len(self.vectorOfDoubles))
for i in reversed(range(len(self.vectorOfDoubles))):
builder.PrependFloat64(self.vectorOfDoubles[i])
vectorOfDoubles = builder.EndVector()
if self.parentNamespaceTest is not None:
parentNamespaceTest = self.parentNamespaceTest.Pack(builder)
if self.vectorOfReferrables is not None:
vectorOfReferrableslist = []
for i in range(len(self.vectorOfReferrables)):
vectorOfReferrableslist.append(self.vectorOfReferrables[i].Pack(builder))
MonsterStartVectorOfReferrablesVector(builder, len(self.vectorOfReferrables))
for i in reversed(range(len(self.vectorOfReferrables))):
builder.PrependUOffsetTRelative(vectorOfReferrableslist[i])
vectorOfReferrables = builder.EndVector()
if self.vectorOfWeakReferences is not None:
if np is not None and type(self.vectorOfWeakReferences) is np.ndarray:
vectorOfWeakReferences = builder.CreateNumpyVector(self.vectorOfWeakReferences)
else:
MonsterStartVectorOfWeakReferencesVector(builder, len(self.vectorOfWeakReferences))
for i in reversed(range(len(self.vectorOfWeakReferences))):
builder.PrependUint64(self.vectorOfWeakReferences[i])
vectorOfWeakReferences = builder.EndVector()
if self.vectorOfStrongReferrables is not None:
vectorOfStrongReferrableslist = []
for i in range(len(self.vectorOfStrongReferrables)):
vectorOfStrongReferrableslist.append(self.vectorOfStrongReferrables[i].Pack(builder))
MonsterStartVectorOfStrongReferrablesVector(builder, len(self.vectorOfStrongReferrables))
for i in reversed(range(len(self.vectorOfStrongReferrables))):
builder.PrependUOffsetTRelative(vectorOfStrongReferrableslist[i])
vectorOfStrongReferrables = builder.EndVector()
if self.vectorOfCoOwningReferences is not None:
if np is not None and type(self.vectorOfCoOwningReferences) is np.ndarray:
vectorOfCoOwningReferences = builder.CreateNumpyVector(self.vectorOfCoOwningReferences)
else:
MonsterStartVectorOfCoOwningReferencesVector(builder, len(self.vectorOfCoOwningReferences))
for i in reversed(range(len(self.vectorOfCoOwningReferences))):
builder.PrependUint64(self.vectorOfCoOwningReferences[i])
vectorOfCoOwningReferences = builder.EndVector()
if self.vectorOfNonOwningReferences is not None:
if np is not None and type(self.vectorOfNonOwningReferences) is np.ndarray:
vectorOfNonOwningReferences = builder.CreateNumpyVector(self.vectorOfNonOwningReferences)
else:
MonsterStartVectorOfNonOwningReferencesVector(builder, len(self.vectorOfNonOwningReferences))
for i in reversed(range(len(self.vectorOfNonOwningReferences))):
builder.PrependUint64(self.vectorOfNonOwningReferences[i])
vectorOfNonOwningReferences = builder.EndVector()
if self.anyUnique is not None:
anyUnique = self.anyUnique.Pack(builder)
if self.anyAmbiguous is not None:
anyAmbiguous = self.anyAmbiguous.Pack(builder)
if self.vectorOfEnums is not None:
if np is not None and type(self.vectorOfEnums) is np.ndarray:
vectorOfEnums = builder.CreateNumpyVector(self.vectorOfEnums)
else:
MonsterStartVectorOfEnumsVector(builder, len(self.vectorOfEnums))
for i in reversed(range(len(self.vectorOfEnums))):
builder.PrependUint8(self.vectorOfEnums[i])
vectorOfEnums = builder.EndVector()
if self.testrequirednestedflatbuffer is not None:
if np is not None and type(self.testrequirednestedflatbuffer) is np.ndarray:
testrequirednestedflatbuffer = builder.CreateNumpyVector(self.testrequirednestedflatbuffer)
else:
MonsterStartTestrequirednestedflatbufferVector(builder, len(self.testrequirednestedflatbuffer))
for i in reversed(range(len(self.testrequirednestedflatbuffer))):
builder.PrependUint8(self.testrequirednestedflatbuffer[i])
testrequirednestedflatbuffer = builder.EndVector()
if self.scalarKeySortedTables is not None:
scalarKeySortedTableslist = []
for i in range(len(self.scalarKeySortedTables)):
scalarKeySortedTableslist.append(self.scalarKeySortedTables[i].Pack(builder))
MonsterStartScalarKeySortedTablesVector(builder, len(self.scalarKeySortedTables))
for i in reversed(range(len(self.scalarKeySortedTables))):
builder.PrependUOffsetTRelative(scalarKeySortedTableslist[i])
scalarKeySortedTables = builder.EndVector()
MonsterStart(builder)
if self.pos is not None:
pos = self.pos.Pack(builder)
MonsterAddPos(builder, pos)
MonsterAddMana(builder, self.mana)
MonsterAddHp(builder, self.hp)
if self.name is not None:
MonsterAddName(builder, name)
if self.inventory is not None:
MonsterAddInventory(builder, inventory)
MonsterAddColor(builder, self.color)
MonsterAddTestType(builder, self.testType)
if self.test is not None:
MonsterAddTest(builder, test)
if self.test4 is not None:
MonsterAddTest4(builder, test4)
if self.testarrayofstring is not None:
MonsterAddTestarrayofstring(builder, testarrayofstring)
if self.testarrayoftables is not None:
MonsterAddTestarrayoftables(builder, testarrayoftables)
if self.enemy is not None:
MonsterAddEnemy(builder, enemy)
if self.testnestedflatbuffer is not None:
MonsterAddTestnestedflatbuffer(builder, testnestedflatbuffer)
if self.testempty is not None:
MonsterAddTestempty(builder, testempty)
MonsterAddTestbool(builder, self.testbool)
MonsterAddTesthashs32Fnv1(builder, self.testhashs32Fnv1)
MonsterAddTesthashu32Fnv1(builder, self.testhashu32Fnv1)
MonsterAddTesthashs64Fnv1(builder, self.testhashs64Fnv1)
MonsterAddTesthashu64Fnv1(builder, self.testhashu64Fnv1)
MonsterAddTesthashs32Fnv1a(builder, self.testhashs32Fnv1a)
MonsterAddTesthashu32Fnv1a(builder, self.testhashu32Fnv1a)
MonsterAddTesthashs64Fnv1a(builder, self.testhashs64Fnv1a)
MonsterAddTesthashu64Fnv1a(builder, self.testhashu64Fnv1a)
if self.testarrayofbools is not None:
MonsterAddTestarrayofbools(builder, testarrayofbools)
MonsterAddTestf(builder, self.testf)
MonsterAddTestf2(builder, self.testf2)
MonsterAddTestf3(builder, self.testf3)
if self.testarrayofstring2 is not None:
MonsterAddTestarrayofstring2(builder, testarrayofstring2)
if self.testarrayofsortedstruct is not None:
MonsterAddTestarrayofsortedstruct(builder, testarrayofsortedstruct)
if self.flex is not None:
MonsterAddFlex(builder, flex)
if self.test5 is not None:
MonsterAddTest5(builder, test5)
if self.vectorOfLongs is not None:
MonsterAddVectorOfLongs(builder, vectorOfLongs)
if self.vectorOfDoubles is not None:
MonsterAddVectorOfDoubles(builder, vectorOfDoubles)
if self.parentNamespaceTest is not None:
MonsterAddParentNamespaceTest(builder, parentNamespaceTest)
if self.vectorOfReferrables is not None:
MonsterAddVectorOfReferrables(builder, vectorOfReferrables)
MonsterAddSingleWeakReference(builder, self.singleWeakReference)
if self.vectorOfWeakReferences is not None:
MonsterAddVectorOfWeakReferences(builder, vectorOfWeakReferences)
if self.vectorOfStrongReferrables is not None:
MonsterAddVectorOfStrongReferrables(builder, vectorOfStrongReferrables)
MonsterAddCoOwningReference(builder, self.coOwningReference)
if self.vectorOfCoOwningReferences is not None:
MonsterAddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences)
MonsterAddNonOwningReference(builder, self.nonOwningReference)
if self.vectorOfNonOwningReferences is not None:
MonsterAddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences)
MonsterAddAnyUniqueType(builder, self.anyUniqueType)
if self.anyUnique is not None:
MonsterAddAnyUnique(builder, anyUnique)
MonsterAddAnyAmbiguousType(builder, self.anyAmbiguousType)
if self.anyAmbiguous is not None:
MonsterAddAnyAmbiguous(builder, anyAmbiguous)
if self.vectorOfEnums is not None:
MonsterAddVectorOfEnums(builder, vectorOfEnums)
MonsterAddSignedEnum(builder, self.signedEnum)
if self.testrequirednestedflatbuffer is not None:
MonsterAddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer)
if self.scalarKeySortedTables is not None:
MonsterAddScalarKeySortedTables(builder, scalarKeySortedTables)
if self.nativeInline is not None:
nativeInline = self.nativeInline.Pack(builder)
MonsterAddNativeInline(builder, nativeInline)
MonsterAddLongEnumNonEnumDefault(builder, self.longEnumNonEnumDefault)
MonsterAddLongEnumNormalDefault(builder, self.longEnumNormalDefault)
MonsterAddNanDefault(builder, self.nanDefault)
MonsterAddInfDefault(builder, self.infDefault)
MonsterAddPositiveInfDefault(builder, self.positiveInfDefault)
MonsterAddInfinityDefault(builder, self.infinityDefault)
MonsterAddPositiveInfinityDefault(builder, self.positiveInfinityDefault)
MonsterAddNegativeInfDefault(builder, self.negativeInfDefault)
MonsterAddNegativeInfinityDefault(builder, self.negativeInfinityDefault)
MonsterAddDoubleInfDefault(builder, self.doubleInfDefault)
monster = MonsterEnd(builder)
return monster
| MonsterT |
python | pytorch__pytorch | torch/backends/_nnapi/serializer.py | {
"start": 2987,
"end": 3626
} | class ____(enum.Enum):
QUINT8 = 13
def approx_equal(lhs, rhs, tolerance=1e-6):
return abs(lhs - rhs) <= tolerance * min(lhs, rhs)
def tensor_size(op_type, dims):
ITEM_SIZES = {
NNAPI_OperandCode.TENSOR_FLOAT32: 4,
NNAPI_OperandCode.TENSOR_INT32: 4,
NNAPI_OperandCode.TENSOR_QUANT8_ASYMM: 1,
NNAPI_OperandCode.TENSOR_QUANT16_SYMM: 2,
NNAPI_OperandCode.TENSOR_QUANT16_ASYMM: 2,
}
size = ITEM_SIZES[op_type]
for d in dims:
size *= d
return size
def change_element(tup, index, value):
ls = list(tup)
ls[index] = value
return tuple(ls)
| TorchScalarTypes |
python | bokeh__bokeh | src/bokeh/models/widgets/pickers.py | {
"start": 9868,
"end": 10230
} | class ____(BaseDatetimePicker):
""" Calendar-based date and time picker widget.
"""
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
value = Nullable(Datetime, default=None, help="""
The initial or picked date and time.
""")
| DatetimePicker |
python | huggingface__transformers | tests/models/shieldgemma2/test_processing_shieldgemma2.py | {
"start": 2758,
"end": 9769
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = ShieldGemma2Processor
@classmethod
def _setup_image_processor(cls):
image_processor_class = cls._get_component_class_from_processor("image_processor")
return image_processor_class.from_pretrained("google/siglip-so400m-patch14-384")
@classmethod
def _setup_tokenizer(cls):
tokenizer_class = cls._get_component_class_from_processor("tokenizer")
extra_special_tokens = {
"image_token": "<image_soft_token>",
"boi_token": "<start_of_image>",
"eoi_token": "<end_of_image>",
}
return tokenizer_class(SAMPLE_VOCAB, keep_accents=True, extra_special_tokens=extra_special_tokens)
@classmethod
def prepare_processor_dict(cls):
return {
"chat_template": _CHAT_TEMPLATE,
"policy_definitions": _SHIELDGEMMA2_POLICIES,
}
def test_policy_definitions_saved_in_config(self):
processor_config_path = os.path.join(self.tmpdirname, "processor_config.json")
with open(processor_config_path, "rb") as processor_config_file:
json_dict = json.load(processor_config_file)
self.assertIsInstance(json_dict, dict)
self.assertIn("policy_definitions", json_dict)
self.assertIs(len(json_dict["policy_definitions"]), 3)
@parameterized.expand(
[
("all_policies", None, 3),
("selected_policies", ["dangerous", "violence"], 2),
("single_policy", ["sexual"], 1),
]
)
def test_with_default_policies(self, name, policies, expected_batch_size):
processor = self.get_processor()
if processor.chat_template is None:
self.skipTest("Processor has no chat template")
images = self.prepare_image_inputs()
processed_inputs = processor(images=images, policies=policies)
self.assertEqual(len(processed_inputs[self.text_input_name]), expected_batch_size)
self.assertEqual(len(processed_inputs[self.images_input_name]), expected_batch_size)
@parameterized.expand(
[
("all_policies", None, 6),
("selected_policies_from_both", ["cbrne", "dangerous", "specialized_advice", "violence"], 4),
("selected_policies_from_custom", ["cbrne", "specialized_advice"], 2),
("selected_policies_from_default", ["dangerous", "violence"], 2),
("single_policy_from_custom", ["ip"], 1),
("single_policy_from_default", ["sexual"], 1),
]
)
def test_with_custom_policies(self, name, policies, expected_batch_size):
processor = self.get_processor()
if processor.chat_template is None:
self.skipTest("Processor has no chat template")
# Test policies adapted from https://ailuminate.mlcommons.org/benchmarks/ hazard categories
custom_policies = {
"cbrne": "Test policy related to indiscriminate weapons.",
"ip": "Test policy related to intellectual property.",
"specialized_advice": "Test policy related to specialized advice.",
}
images = self.prepare_image_inputs()
processed_inputs = processor(images=images, custom_policies=custom_policies, policies=policies)
self.assertEqual(len(processed_inputs[self.text_input_name]), expected_batch_size)
self.assertEqual(len(processed_inputs[self.images_input_name]), expected_batch_size)
def test_with_multiple_images(self):
processor = self.get_processor()
if processor.chat_template is None:
self.skipTest("Processor has no chat template")
images = self.prepare_image_inputs(batch_size=2)
processed_inputs = processor(images=images)
self.assertEqual(len(processed_inputs[self.text_input_name]), 6)
self.assertEqual(len(processed_inputs[self.images_input_name]), 6)
# TODO(ryanmullins): Adapt this test for ShieldGemma 2
@parameterized.expand([(1, "np"), (1, "pt"), (2, "np"), (2, "pt")])
@unittest.skip("ShieldGemma 2 chat template requires different message structure from parent.")
def test_apply_chat_template_image(self, batch_size: int, return_tensors: str):
pass
# TODO(ryanmullins): Adapt this test for ShieldGemma 2
@unittest.skip("Parent test needs to be adapted for ShieldGemma 2.")
def test_unstructured_kwargs_batched(self):
pass
# TODO(ryanmullins): Adapt this test for ShieldGemma 2
@unittest.skip("Parent test needs to be adapted for ShieldGemma 2.")
def test_unstructured_kwargs(self):
pass
# TODO(ryanmullins): Adapt this test for ShieldGemma 2
@unittest.skip("Parent test needs to be adapted for ShieldGemma 2.")
def test_tokenizer_defaults_preserved_by_kwargs(self):
pass
# TODO(ryanmullins): Adapt this test for ShieldGemma 2
@unittest.skip("Parent test needs to be adapted for ShieldGemma 2.")
def test_structured_kwargs_nested_from_dict(self):
pass
# TODO(ryanmullins): Adapt this test for ShieldGemma 2
@unittest.skip("Parent test needs to be adapted for ShieldGemma 2.")
def test_structured_kwargs_nested(self):
pass
# TODO(ryanmullins): Adapt this test for ShieldGemma 2
@unittest.skip("Parent test needs to be adapted for ShieldGemma 2.")
def test_kwargs_overrides_default_tokenizer_kwargs(self):
pass
# TODO(ryanmullins): Adapt this test for ShieldGemma 2
@unittest.skip("Parent test needs to be adapted for ShieldGemma 2.")
def test_kwargs_overrides_default_image_processor_kwargs(self):
pass
@unittest.skip("ShieldGemma requires images in input, and fails in text-only processing")
def test_apply_chat_template_assistant_mask(self):
pass
def test_processor_text_has_no_visual(self):
# Overwritten: Shieldgemma has a complicated processing so we don't check id values
processor = self.get_processor()
text = self.prepare_text_inputs(batch_size=3, modalities="image")
image_inputs = self.prepare_image_inputs(batch_size=3)
processing_kwargs = {"return_tensors": "pt", "padding": True, "multi_page": True}
# Call with nested list of vision inputs
image_inputs_nested = [[image] if not isinstance(image, list) else image for image in image_inputs]
inputs_dict_nested = {"text": text, "images": image_inputs_nested}
inputs = processor(**inputs_dict_nested, **processing_kwargs)
self.assertTrue(self.text_input_name in inputs)
# Call with one of the samples with no associated vision input
plain_text = "lower newer"
image_inputs_nested[0] = []
text[0] = plain_text
inputs_dict_no_vision = {"text": text, "images": image_inputs_nested}
inputs_nested = processor(**inputs_dict_no_vision, **processing_kwargs)
self.assertTrue(self.text_input_name in inputs_nested)
| ShieldGemma2ProcessorTest |
python | pytorch__pytorch | torch/_utils.py | {
"start": 33119,
"end": 36805
} | class ____:
def __init__(self, fget, fset=None):
self.fget = fget
def __get__(self, instance, owner=None):
if owner is None:
owner = type(instance)
return self.fget.__get__(instance, owner)()
def classproperty(func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
return _ClassPropertyDescriptor(func)
if TYPE_CHECKING:
# TorchScript does not support `@deprecated`
# This is a workaround to avoid breaking TorchScript
@deprecated(
"`torch._utils.is_compiling` is deprecated. Use `torch.compiler.is_compiling` instead.",
category=FutureWarning,
)
def is_compiling() -> bool:
return torch.compiler.is_compiling()
else:
def is_compiling() -> bool:
"""
Indicates whether we are tracing/compiling with torch.compile() or torch.export().
"""
warnings.warn( # use `warnings.warn` instead of `@deprecated`
"`torch._utils.is_compiling` is deprecated. Use `torch.compiler.is_compiling` instead.",
# FutureWarning, # TorchScript does not support Warning type
stacklevel=2,
)
return torch.compiler.is_compiling()
def _functionalize_sync(t):
# This code lives in python instead of C++ since conditioning on a certain python subclass
# is much more of a pain in C++.
from torch._subclasses.functional_tensor import FunctionalTensor
if isinstance(t, FunctionalTensor):
# If a FunctionalTensorMode is active while syncing, we don't want it to intercept any ops that get called
# when we sync our inner tensor.
# Why?
# (1) If there are input mutations in the graph, then they will be re-applied during
# AOTAutograd when we call _sync() from inside of our functionalization kernels.
# (2) _sync() causes us to regenerate our updated the tensor from the updated base,
# which dispatches to a bunch of view ops
# (3) The input to these view ops is our inner FunctionalTensorWrapper
# (since the sync was called from C++), not the python FunctionalTensor
# (4) if a python FunctionalTensorMode is active, it will complain when it intercepts
# the view op, since it will see an input that is a C++ FunctionalTensorWrapper
# (aka a normal torch.Tensor) instead of a python `FunctionalTensor).
maybe_functional_mode = torch._C._unset_dispatch_mode(
torch._C._TorchDispatchModeKey.FUNCTIONAL
)
try:
torch._functionalize_sync(t.elem) # type: ignore[attr-defined]
finally:
if maybe_functional_mode is not None:
torch._C._set_dispatch_mode(maybe_functional_mode)
else:
torch._functionalize_sync(t) # type: ignore[attr-defined]
@functools.lru_cache(2)
def _get_device_module(device_type: str):
device_module = getattr(torch, device_type, None)
if device_module is None:
raise RuntimeError(
f"Device '{device_type}' does not have a corresponding module registered as 'torch.{device_type}'."
)
return device_module
def _dummy_type(name: str) -> type:
def get_err_fn(is_init: bool):
def err_fn(obj, *args, **kwargs):
if is_init:
class_name = obj.__class__.__name__
else:
class_name = obj.__name__
raise RuntimeError(f"Tried to instantiate dummy base class {class_name}")
return err_fn
return type(
name, (object,), {"__init__": get_err_fn(True), "__new__": get_err_fn(False)}
)
| _ClassPropertyDescriptor |
python | huggingface__transformers | src/transformers/models/patchtsmixer/modeling_patchtsmixer.py | {
"start": 55265,
"end": 56666
} | class ____(ModelOutput):
r"""
loss (*optional*, returned when `y` is provided, `torch.FloatTensor` of shape `()`):
Total loss.
prediction_outputs (`torch.FloatTensor` of shape `(batch_size, prediction_length, num_input_channels)`):
Prediction output from the forecast head.
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_input_channels, num_patches, d_model)`):
Backbone embeddings before passing through the head.
hidden_states (`tuple(torch.FloatTensor)`, *optional*):
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
loc (`torch.FloatTensor`, *optional* of shape `(batch_size, 1, num_input_channels)`):
Input mean
scale (`torch.FloatTensor`, *optional* of shape `(batch_size, 1, num_input_channels)`):
Input std dev
"""
loss: Optional[torch.FloatTensor] = None
prediction_outputs: Optional[torch.FloatTensor] = None
last_hidden_state: Optional[torch.FloatTensor] = None
hidden_states: Optional[tuple[torch.FloatTensor]] = None
loc: Optional[torch.FloatTensor] = None
scale: Optional[torch.FloatTensor] = None
@dataclass
@auto_docstring(
custom_intro="""
Base class for time series model's predictions outputs that contains the sampled values from the chosen
distribution.
"""
)
| PatchTSMixerForPredictionOutput |
python | spack__spack | lib/spack/spack/vendor/macholib/mach_o.py | {
"start": 19411,
"end": 24182
} | class ____(Structure):
_fields_ = (
("sectname", p_str16),
("segname", p_str16),
("addr", p_uint64),
("size", p_uint64),
("offset", p_uint32),
("align", p_uint32),
("reloff", p_uint32),
("nreloc", p_uint32),
("flags", p_uint32),
("reserved1", p_uint32),
("reserved2", p_uint32),
("reserved3", p_uint32),
)
def describe(self):
s = {}
s["sectname"] = self.sectname.rstrip("\x00")
s["segname"] = self.segname.rstrip("\x00")
s["addr"] = int(self.addr)
s["size"] = int(self.size)
s["offset"] = int(self.offset)
s["align"] = int(self.align)
s["reloff"] = int(self.reloff)
s["nreloc"] = int(self.nreloc)
f = {}
f["type"] = FLAG_SECTION_TYPES[int(self.flags) & 0xFF]
f["attributes"] = []
for k in FLAG_SECTION_ATTRIBUTES:
if k & self.flags:
f["attributes"].append(FLAG_SECTION_ATTRIBUTES[k])
if not f["attributes"]:
del f["attributes"]
s["flags"] = f
s["reserved1"] = int(self.reserved1)
s["reserved2"] = int(self.reserved2)
s["reserved3"] = int(self.reserved3)
return s
def add_section_data(self, data):
self.section_data = data
SECTION_TYPE = 0xFF
SECTION_ATTRIBUTES = 0xFFFFFF00
S_REGULAR = 0x0
S_ZEROFILL = 0x1
S_CSTRING_LITERALS = 0x2
S_4BYTE_LITERALS = 0x3
S_8BYTE_LITERALS = 0x4
S_LITERAL_POINTERS = 0x5
S_NON_LAZY_SYMBOL_POINTERS = 0x6
S_LAZY_SYMBOL_POINTERS = 0x7
S_SYMBOL_STUBS = 0x8
S_MOD_INIT_FUNC_POINTERS = 0x9
S_MOD_TERM_FUNC_POINTERS = 0xA
S_COALESCED = 0xB
S_GB_ZEROFILL = 0xC
S_INTERPOSING = 0xD
S_16BYTE_LITERALS = 0xE
S_DTRACE_DOF = 0xF
S_LAZY_DYLIB_SYMBOL_POINTERS = 0x10
S_THREAD_LOCAL_REGULAR = 0x11
S_THREAD_LOCAL_ZEROFILL = 0x12
S_THREAD_LOCAL_VARIABLES = 0x13
S_THREAD_LOCAL_VARIABLE_POINTERS = 0x14
S_THREAD_LOCAL_INIT_FUNCTION_POINTERS = 0x15
FLAG_SECTION_TYPES = {
S_REGULAR: "S_REGULAR",
S_ZEROFILL: "S_ZEROFILL",
S_CSTRING_LITERALS: "S_CSTRING_LITERALS",
S_4BYTE_LITERALS: "S_4BYTE_LITERALS",
S_8BYTE_LITERALS: "S_8BYTE_LITERALS",
S_LITERAL_POINTERS: "S_LITERAL_POINTERS",
S_NON_LAZY_SYMBOL_POINTERS: "S_NON_LAZY_SYMBOL_POINTERS",
S_LAZY_SYMBOL_POINTERS: "S_LAZY_SYMBOL_POINTERS",
S_SYMBOL_STUBS: "S_SYMBOL_STUBS",
S_MOD_INIT_FUNC_POINTERS: "S_MOD_INIT_FUNC_POINTERS",
S_MOD_TERM_FUNC_POINTERS: "S_MOD_TERM_FUNC_POINTERS",
S_COALESCED: "S_COALESCED",
S_GB_ZEROFILL: "S_GB_ZEROFILL",
S_INTERPOSING: "S_INTERPOSING",
S_16BYTE_LITERALS: "S_16BYTE_LITERALS",
S_DTRACE_DOF: "S_DTRACE_DOF",
S_LAZY_DYLIB_SYMBOL_POINTERS: "S_LAZY_DYLIB_SYMBOL_POINTERS",
S_THREAD_LOCAL_REGULAR: "S_THREAD_LOCAL_REGULAR",
S_THREAD_LOCAL_ZEROFILL: "S_THREAD_LOCAL_ZEROFILL",
S_THREAD_LOCAL_VARIABLES: "S_THREAD_LOCAL_VARIABLES",
S_THREAD_LOCAL_VARIABLE_POINTERS: "S_THREAD_LOCAL_VARIABLE_POINTERS",
S_THREAD_LOCAL_INIT_FUNCTION_POINTERS: "S_THREAD_LOCAL_INIT_FUNCTION_POINTERS",
}
SECTION_ATTRIBUTES_USR = 0xFF000000
S_ATTR_PURE_INSTRUCTIONS = 0x80000000
S_ATTR_NO_TOC = 0x40000000
S_ATTR_STRIP_STATIC_SYMS = 0x20000000
S_ATTR_NO_DEAD_STRIP = 0x10000000
S_ATTR_LIVE_SUPPORT = 0x08000000
S_ATTR_SELF_MODIFYING_CODE = 0x04000000
S_ATTR_DEBUG = 0x02000000
SECTION_ATTRIBUTES_SYS = 0x00FFFF00
S_ATTR_SOME_INSTRUCTIONS = 0x00000400
S_ATTR_EXT_RELOC = 0x00000200
S_ATTR_LOC_RELOC = 0x00000100
FLAG_SECTION_ATTRIBUTES = {
S_ATTR_PURE_INSTRUCTIONS: "S_ATTR_PURE_INSTRUCTIONS",
S_ATTR_NO_TOC: "S_ATTR_NO_TOC",
S_ATTR_STRIP_STATIC_SYMS: "S_ATTR_STRIP_STATIC_SYMS",
S_ATTR_NO_DEAD_STRIP: "S_ATTR_NO_DEAD_STRIP",
S_ATTR_LIVE_SUPPORT: "S_ATTR_LIVE_SUPPORT",
S_ATTR_SELF_MODIFYING_CODE: "S_ATTR_SELF_MODIFYING_CODE",
S_ATTR_DEBUG: "S_ATTR_DEBUG",
S_ATTR_SOME_INSTRUCTIONS: "S_ATTR_SOME_INSTRUCTIONS",
S_ATTR_EXT_RELOC: "S_ATTR_EXT_RELOC",
S_ATTR_LOC_RELOC: "S_ATTR_LOC_RELOC",
}
SEG_PAGEZERO = "__PAGEZERO"
SEG_TEXT = "__TEXT"
SECT_TEXT = "__text"
SECT_FVMLIB_INIT0 = "__fvmlib_init0"
SECT_FVMLIB_INIT1 = "__fvmlib_init1"
SEG_DATA = "__DATA"
SECT_DATA = "__data"
SECT_BSS = "__bss"
SECT_COMMON = "__common"
SEG_OBJC = "__OBJC"
SECT_OBJC_SYMBOLS = "__symbol_table"
SECT_OBJC_MODULES = "__module_info"
SECT_OBJC_STRINGS = "__selector_strs"
SECT_OBJC_REFS = "__selector_refs"
SEG_ICON = "__ICON"
SECT_ICON_HEADER = "__header"
SECT_ICON_TIFF = "__tiff"
SEG_LINKEDIT = "__LINKEDIT"
SEG_UNIXSTACK = "__UNIXSTACK"
SEG_IMPORT = "__IMPORT"
#
# I really should remove all these _command classes because they
# are no different. I decided to keep the load commands separate,
# so classes like fvmlib and fvmlib_command are equivalent.
#
| section_64 |
python | kamyu104__LeetCode-Solutions | Python/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits.py | {
"start": 427,
"end": 1122
} | class ____(object):
def minInteger(self, num, k):
"""
:type num: str
:type k: int
:rtype: str
"""
lookup = collections.defaultdict(list)
bit = BIT(len(num)+1)
for i in reversed(xrange(len(num))):
bit.add(i+1, 1)
lookup[int(num[i])].append(i+1)
result = []
for _ in xrange(len(num)):
for d in xrange(10):
if lookup[d] and bit.sum(lookup[d][-1]-1) <= k:
k -= bit.sum(lookup[d][-1]-1)
bit.add(lookup[d].pop(), -1)
result.append(d)
break
return "".join(map(str, result))
| Solution |
python | pallets__click | src/click/_termui_impl.py | {
"start": 18044,
"end": 27093
} | class ____:
def __init__(
self,
editor: str | None = None,
env: cabc.Mapping[str, str] | None = None,
require_save: bool = True,
extension: str = ".txt",
) -> None:
self.editor = editor
self.env = env
self.require_save = require_save
self.extension = extension
def get_editor(self) -> str:
if self.editor is not None:
return self.editor
for key in "VISUAL", "EDITOR":
rv = os.environ.get(key)
if rv:
return rv
if WIN:
return "notepad"
from shutil import which
for editor in "sensible-editor", "vim", "nano":
if which(editor) is not None:
return editor
return "vi"
def edit_files(self, filenames: cabc.Iterable[str]) -> None:
import subprocess
editor = self.get_editor()
environ: dict[str, str] | None = None
if self.env:
environ = os.environ.copy()
environ.update(self.env)
exc_filename = " ".join(f'"{filename}"' for filename in filenames)
try:
c = subprocess.Popen(
args=f"{editor} {exc_filename}", env=environ, shell=True
)
exit_code = c.wait()
if exit_code != 0:
raise ClickException(
_("{editor}: Editing failed").format(editor=editor)
)
except OSError as e:
raise ClickException(
_("{editor}: Editing failed: {e}").format(editor=editor, e=e)
) from e
@t.overload
def edit(self, text: bytes | bytearray) -> bytes | None: ...
# We cannot know whether or not the type expected is str or bytes when None
# is passed, so str is returned as that was what was done before.
@t.overload
def edit(self, text: str | None) -> str | None: ...
def edit(self, text: str | bytes | bytearray | None) -> str | bytes | None:
import tempfile
if text is None:
data: bytes | bytearray = b""
elif isinstance(text, (bytes, bytearray)):
data = text
else:
if text and not text.endswith("\n"):
text += "\n"
if WIN:
data = text.replace("\n", "\r\n").encode("utf-8-sig")
else:
data = text.encode("utf-8")
fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)
f: t.BinaryIO
try:
with os.fdopen(fd, "wb") as f:
f.write(data)
# If the filesystem resolution is 1 second, like Mac OS
# 10.12 Extended, or 2 seconds, like FAT32, and the editor
# closes very fast, require_save can fail. Set the modified
# time to be 2 seconds in the past to work around this.
os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2))
# Depending on the resolution, the exact value might not be
# recorded, so get the new recorded value.
timestamp = os.path.getmtime(name)
self.edit_files((name,))
if self.require_save and os.path.getmtime(name) == timestamp:
return None
with open(name, "rb") as f:
rv = f.read()
if isinstance(text, (bytes, bytearray)):
return rv
return rv.decode("utf-8-sig").replace("\r\n", "\n")
finally:
os.unlink(name)
def open_url(url: str, wait: bool = False, locate: bool = False) -> int:
import subprocess
def _unquote_file(url: str) -> str:
from urllib.parse import unquote
if url.startswith("file://"):
url = unquote(url[7:])
return url
if sys.platform == "darwin":
args = ["open"]
if wait:
args.append("-W")
if locate:
args.append("-R")
args.append(_unquote_file(url))
null = open("/dev/null", "w")
try:
return subprocess.Popen(args, stderr=null).wait()
finally:
null.close()
elif WIN:
if locate:
url = _unquote_file(url)
args = ["explorer", f"/select,{url}"]
else:
args = ["start"]
if wait:
args.append("/WAIT")
args.append("")
args.append(url)
try:
return subprocess.call(args)
except OSError:
# Command not found
return 127
elif CYGWIN:
if locate:
url = _unquote_file(url)
args = ["cygstart", os.path.dirname(url)]
else:
args = ["cygstart"]
if wait:
args.append("-w")
args.append(url)
try:
return subprocess.call(args)
except OSError:
# Command not found
return 127
try:
if locate:
url = os.path.dirname(_unquote_file(url)) or "."
else:
url = _unquote_file(url)
c = subprocess.Popen(["xdg-open", url])
if wait:
return c.wait()
return 0
except OSError:
if url.startswith(("http://", "https://")) and not locate and not wait:
import webbrowser
webbrowser.open(url)
return 0
return 1
def _translate_ch_to_exc(ch: str) -> None:
if ch == "\x03":
raise KeyboardInterrupt()
if ch == "\x04" and not WIN: # Unix-like, Ctrl+D
raise EOFError()
if ch == "\x1a" and WIN: # Windows, Ctrl+Z
raise EOFError()
return None
if sys.platform == "win32":
import msvcrt
@contextlib.contextmanager
def raw_terminal() -> cabc.Iterator[int]:
yield -1
def getchar(echo: bool) -> str:
# The function `getch` will return a bytes object corresponding to
# the pressed character. Since Windows 10 build 1803, it will also
# return \x00 when called a second time after pressing a regular key.
#
# `getwch` does not share this probably-bugged behavior. Moreover, it
# returns a Unicode object by default, which is what we want.
#
# Either of these functions will return \x00 or \xe0 to indicate
# a special key, and you need to call the same function again to get
# the "rest" of the code. The fun part is that \u00e0 is
# "latin small letter a with grave", so if you type that on a French
# keyboard, you _also_ get a \xe0.
# E.g., consider the Up arrow. This returns \xe0 and then \x48. The
# resulting Unicode string reads as "a with grave" + "capital H".
# This is indistinguishable from when the user actually types
# "a with grave" and then "capital H".
#
# When \xe0 is returned, we assume it's part of a special-key sequence
# and call `getwch` again, but that means that when the user types
# the \u00e0 character, `getchar` doesn't return until a second
# character is typed.
# The alternative is returning immediately, but that would mess up
# cross-platform handling of arrow keys and others that start with
# \xe0. Another option is using `getch`, but then we can't reliably
# read non-ASCII characters, because return values of `getch` are
# limited to the current 8-bit codepage.
#
# Anyway, Click doesn't claim to do this Right(tm), and using `getwch`
# is doing the right thing in more situations than with `getch`.
if echo:
func = t.cast(t.Callable[[], str], msvcrt.getwche)
else:
func = t.cast(t.Callable[[], str], msvcrt.getwch)
rv = func()
if rv in ("\x00", "\xe0"):
# \x00 and \xe0 are control characters that indicate special key,
# see above.
rv += func()
_translate_ch_to_exc(rv)
return rv
else:
import termios
import tty
@contextlib.contextmanager
def raw_terminal() -> cabc.Iterator[int]:
f: t.TextIO | None
fd: int
if not isatty(sys.stdin):
f = open("/dev/tty")
fd = f.fileno()
else:
fd = sys.stdin.fileno()
f = None
try:
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
yield fd
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
sys.stdout.flush()
if f is not None:
f.close()
except termios.error:
pass
def getchar(echo: bool) -> str:
with raw_terminal() as fd:
ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace")
if echo and isatty(sys.stdout):
sys.stdout.write(ch)
_translate_ch_to_exc(ch)
return ch
| Editor |
python | kamyu104__LeetCode-Solutions | Python/rotate-array.py | {
"start": 1277,
"end": 1874
} | class ____(object):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
def rotate(self, nums, k):
count = 0
start = 0
while count < len(nums):
curr = start
prev = nums[curr]
while True:
idx = (curr + k) % len(nums)
nums[idx], prev = prev, nums[idx]
curr = idx
count += 1
if start == curr:
break
start += 1
# Time: O(n)
# Space: O(n)
| Solution3 |
python | doocs__leetcode | lcof/面试题54. 二叉搜索树的第k大节点/Solution.py | {
"start": 164,
"end": 532
} | class ____:
def kthLargest(self, root: TreeNode, k: int) -> int:
def dfs(root):
nonlocal k, ans
if root is None or k == 0:
return
dfs(root.right)
k -= 1
if k == 0:
ans = root.val
dfs(root.left)
ans = 0
dfs(root)
return ans
| Solution |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/stackdriver.py | {
"start": 20068,
"end": 25214
} | class ____(GoogleCloudBaseOperator):
"""
Fetches all the Notification Channels identified by the filter passed as filter parameter.
The desired return type can be specified by the format parameter, the
supported formats are "dict", "json" and None which returns python
dictionary, stringified JSON and protobuf respectively.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:StackdriverListNotificationChannelsOperator`
:param format_: (Optional) Desired output format of the result. The
supported formats are "dict", "json" and None which returns
python dictionary, stringified JSON and protobuf respectively.
:param filter_: If provided, this field specifies the criteria that
must be met by notification channels to be included in the response.
For more details, see https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
:param order_by: A comma-separated list of fields by which to sort the result.
Supports the same set of field references as the ``filter`` field. Entries
can be prefixed with a minus sign to sort by the field in descending order.
For more details, see https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
:param page_size: The maximum number of resources contained in the
underlying API response. If page streaming is performed per-
resource, this parameter does not affect the return value. If page
streaming is performed per-page, this determines the maximum number
of resources in a page.
:param retry: A retry object used to retry requests. If ``None`` is
specified, requests will be retried using a default configuration.
:param timeout: The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
:param metadata: Additional metadata that is provided to the method.
:param gcp_conn_id: (Optional) The connection ID used to connect to Google
Cloud Platform.
:param project_id: The project to fetch notification channels from.
: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).
"""
template_fields: Sequence[str] = (
"filter_",
"impersonation_chain",
)
operator_extra_links = (StackdriverNotificationsLink(),)
ui_color = "#e5ffcc"
def __init__(
self,
*,
format_: str | None = None,
filter_: str | None = None,
order_by: str | None = None,
page_size: int | None = None,
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
gcp_conn_id: str = "google_cloud_default",
project_id: str = PROVIDE_PROJECT_ID,
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.format_ = format_
self.filter_ = filter_
self.order_by = order_by
self.page_size = page_size
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
self.project_id = project_id
self.impersonation_chain = impersonation_chain
self.hook: StackdriverHook | None = None
def execute(self, context: Context):
self.log.info(
"List Notification Channels: Project id: %s Format: %s Filter: %s Order By: %s Page Size: %s",
self.project_id,
self.format_,
self.filter_,
self.order_by,
self.page_size,
)
if self.hook is None:
self.hook = StackdriverHook(
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
)
channels = self.hook.list_notification_channels(
format_=self.format_,
project_id=self.project_id,
filter_=self.filter_,
order_by=self.order_by,
page_size=self.page_size,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
StackdriverNotificationsLink.persist(
context=context,
project_id=self.project_id or self.hook.project_id,
)
return [NotificationChannel.to_dict(channel) for channel in channels]
| StackdriverListNotificationChannelsOperator |
python | bottlepy__bottle | bottle.py | {
"start": 150183,
"end": 151940
} | class ____(threading.Thread):
""" Interrupt main-thread as soon as a changed module file is detected,
the lockfile gets deleted or gets too old. """
def __init__(self, lockfile, interval):
threading.Thread.__init__(self)
self.daemon = True
self.lockfile, self.interval = lockfile, interval
#: Is one of 'reload', 'error' or 'exit'
self.status = None
def run(self):
exists = os.path.exists
mtime = lambda p: os.stat(p).st_mtime
files = {}
for module in list(sys.modules.values()):
path = getattr(module, '__file__', '') or ''
if path[-4:] in ('.pyo', '.pyc'): path = path[:-1]
if path and exists(path): files[path] = mtime(path)
while not self.status:
if not exists(self.lockfile)\
or mtime(self.lockfile) < time.time() - self.interval - 5:
self.status = 'error'
thread.interrupt_main()
for path, lmtime in list(files.items()):
if not exists(path) or mtime(path) > lmtime:
self.status = 'reload'
thread.interrupt_main()
break
time.sleep(self.interval)
def __enter__(self):
self.start()
def __exit__(self, exc_type, *_):
if not self.status: self.status = 'exit' # silent exit
self.join()
return exc_type is not None and issubclass(exc_type, KeyboardInterrupt)
###############################################################################
# Template Adapters ############################################################
###############################################################################
| FileCheckerThread |
python | pytorch__pytorch | torch/_dynamo/resume_execution.py | {
"start": 8459,
"end": 9996
} | class ____:
code: types.CodeType
instructions: list[Instruction] = dataclasses.field(default_factory=list)
# Python 3.11+ fields
# NOTE: Python 3.11 removed blocks, but for our purposes, a "block" consists
# of instructions of all exception table entries that have the same target.
# map from PUSH_EXC_INFO's in the prefix to original block target offset
prefix_block_target_offset_remap: list[int] = dataclasses.field(
default_factory=list
)
# per-offset map from new block target offsets to original block target offsets
block_target_offset_remap: dict[tuple[int, int], dict[int, int]] = (
dataclasses.field(default_factory=dict)
)
def _filter_iter(
l1: Iterable[Any],
l2: Iterable[Any],
cond: Callable[[Any, Any], bool],
) -> list[Any]:
"""
Two-pointer conditional filter.
e.g. _filter_iter(insts, sorted_offsets, lambda i, o: i.offset == o)
returns the instructions with offsets in sorted_offsets
"""
it = iter(l2)
res: list[Instruction] = []
try:
cur = next(it)
for val in l1:
if cond(val, cur):
res.append(val)
cur = next(it)
except StopIteration:
pass
return res
def _load_tuple_and_call(tup: tuple[Any, ...]) -> list[Instruction]:
insts: list[Instruction] = []
_initial_push_null(insts)
insts.extend(create_load_const(val) for val in tup)
insts.extend(create_call_function(len(tup), False))
return insts
| ResumeFunctionMetadata |
python | doocs__leetcode | solution/0900-0999/0920.Number of Music Playlists/Solution.py | {
"start": 0,
"end": 447
} | class ____:
def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:
mod = 10**9 + 7
f = [[0] * (n + 1) for _ in range(goal + 1)]
f[0][0] = 1
for i in range(1, goal + 1):
for j in range(1, n + 1):
f[i][j] = f[i - 1][j - 1] * (n - j + 1)
if j > k:
f[i][j] += f[i - 1][j] * (j - k)
f[i][j] %= mod
return f[goal][n]
| Solution |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 17429,
"end": 17717
} | class ____(MetaFeature):
def _calculate(self, X, y, logger, feat_type):
values = helper_functions.get_value("NumSymbols")
if len(values) == 0:
return 0
return max(max(values), 0)
@metafeatures.define("SymbolsMean", dependency="NumSymbols")
| SymbolsMax |
python | rq__rq | rq/exceptions.py | {
"start": 337,
"end": 491
} | class ____(Exception):
def __init__(self, msg, extra_info):
self.extra_info = extra_info
super().__init__(msg)
| ShutDownImminentException |
python | run-llama__llama_index | llama-index-core/llama_index/core/tools/function_tool.py | {
"start": 1806,
"end": 16048
} | class ____(AsyncBaseTool):
"""
Function Tool.
A tool that takes in a function, optionally handles workflow context,
and allows the use of callbacks. The callback can return a new ToolOutput
to override the default one or a string that will be used as the final content.
"""
def __init__(
self,
fn: Optional[Callable[..., Any]] = None,
metadata: Optional[ToolMetadata] = None,
async_fn: Optional[AsyncCallable] = None,
callback: Optional[Callable[..., Any]] = None,
async_callback: Optional[Callable[..., Any]] = None,
partial_params: Optional[Dict[str, Any]] = None,
) -> None:
if fn is None and async_fn is None:
raise ValueError("fn or async_fn must be provided.")
# Handle function (sync and async)
self._real_fn = fn or async_fn
if async_fn is not None:
self._async_fn = async_fn
self._fn = fn or async_to_sync(async_fn)
else:
assert fn is not None
if inspect.iscoroutinefunction(fn):
self._async_fn = fn
self._fn = async_to_sync(fn)
else:
self._fn = fn
self._async_fn = sync_to_async(fn)
# Determine if the function requires context by inspecting its signature
fn_to_inspect = fn or async_fn
assert fn_to_inspect is not None
sig = inspect.signature(fn_to_inspect)
self.requires_context = any(
_is_context_param(param.annotation) for param in sig.parameters.values()
)
self.ctx_param_name = (
next(
param.name
for param in sig.parameters.values()
if _is_context_param(param.annotation)
)
if self.requires_context
else None
)
if metadata is None:
raise ValueError("metadata must be provided")
self._metadata = metadata
# Handle callback (sync and async)
self._callback = None
if callback is not None:
self._callback = callback
elif async_callback is not None:
self._callback = async_to_sync(async_callback)
self._async_callback = None
if async_callback is not None:
self._async_callback = async_callback
elif self._callback is not None:
self._async_callback = sync_to_async(self._callback)
self.partial_params = partial_params or {}
def _run_sync_callback(self, result: Any) -> CallbackReturn:
"""
Runs the sync callback, if provided, and returns either a ToolOutput
to override the default output or a string to override the content.
"""
if self._callback:
ret: CallbackReturn = self._callback(result)
return ret
return None
async def _run_async_callback(self, result: Any) -> CallbackReturn:
"""
Runs the async callback, if provided, and returns either a ToolOutput
to override the default output or a string to override the content.
"""
if self._async_callback:
ret: CallbackReturn = await self._async_callback(result)
return ret
return None
@classmethod
def from_defaults(
cls,
fn: Optional[Callable[..., Any]] = None,
name: Optional[str] = None,
description: Optional[str] = None,
return_direct: bool = False,
fn_schema: Optional[Type[BaseModel]] = None,
async_fn: Optional[AsyncCallable] = None,
tool_metadata: Optional[ToolMetadata] = None,
callback: Optional[Callable[[Any], Any]] = None,
async_callback: Optional[AsyncCallable] = None,
partial_params: Optional[Dict[str, Any]] = None,
) -> "FunctionTool":
partial_params = partial_params or {}
if tool_metadata is None:
fn_to_parse = fn or async_fn
assert fn_to_parse is not None, "fn must be provided"
name = name or fn_to_parse.__name__
docstring = fn_to_parse.__doc__ or ""
# Get function signature
fn_sig = inspect.signature(fn_to_parse)
fn_params = set(fn_sig.parameters.keys())
# 1. Extract docstring param descriptions
param_docs, unknown_params = cls.extract_param_docs(docstring, fn_params)
# 2. Filter context and self in a single pass
ctx_param_name = None
has_self = False
filtered_params = []
for param in fn_sig.parameters.values():
if _is_context_param(param.annotation):
ctx_param_name = param.name
continue
if param.name == "self":
has_self = True
continue
filtered_params.append(param)
# 3. Remove FieldInfo defaults and partial_params
final_params = [
param.replace(default=inspect.Parameter.empty)
if isinstance(param.default, FieldInfo)
else param
for param in filtered_params
if param.name not in (partial_params or {})
]
# 4. Replace signature in one go
fn_sig = fn_sig.replace(parameters=final_params)
# 5. Build description
if description is None:
description = f"{name}{fn_sig}\n"
if docstring:
description += docstring
description = description.strip()
# 6. Build fn_schema only if not already provided
if fn_schema is None:
ignore_fields = []
if ctx_param_name:
ignore_fields.append(ctx_param_name)
if has_self:
ignore_fields.append("self")
ignore_fields.extend(partial_params.keys())
fn_schema = create_schema_from_function(
f"{name}",
fn_to_parse,
additional_fields=None,
ignore_fields=ignore_fields,
)
if fn_schema is not None and param_docs:
for param_name, field in fn_schema.model_fields.items():
if not field.description and param_name in param_docs:
field.description = param_docs[param_name].strip()
tool_metadata = ToolMetadata(
name=name,
description=description,
fn_schema=fn_schema,
return_direct=return_direct,
)
return cls(
fn=fn,
metadata=tool_metadata,
async_fn=async_fn,
callback=callback,
async_callback=async_callback,
partial_params=partial_params,
)
@property
def metadata(self) -> ToolMetadata:
"""Metadata."""
return self._metadata
@property
def fn(self) -> Callable[..., Any]:
"""Function."""
return self._fn
@property
def async_fn(self) -> AsyncCallable:
"""Async function."""
return self._async_fn
@property
def real_fn(self) -> Union[Callable[..., Any], AsyncCallable]:
"""Real function."""
if self._real_fn is None:
raise ValueError("Real function is not set!")
return self._real_fn
def _parse_tool_output(self, raw_output: Any) -> List[ContentBlock]:
"""Parse tool output into content blocks."""
if isinstance(
raw_output, (TextBlock, ImageBlock, AudioBlock, CitableBlock, CitationBlock)
):
return [raw_output]
elif isinstance(raw_output, list) and all(
isinstance(
item, (TextBlock, ImageBlock, AudioBlock, CitableBlock, CitationBlock)
)
for item in raw_output
):
return raw_output
elif isinstance(raw_output, (BaseNode, Document)):
return [TextBlock(text=raw_output.get_content())]
elif isinstance(raw_output, list) and all(
isinstance(item, (BaseNode, Document)) for item in raw_output
):
return [TextBlock(text=item.get_content()) for item in raw_output]
else:
return [TextBlock(text=str(raw_output))]
def __call__(self, *args: Any, **kwargs: Any) -> ToolOutput:
all_kwargs = {**self.partial_params, **kwargs}
return self.call(*args, **all_kwargs)
def call(self, *args: Any, **kwargs: Any) -> ToolOutput:
"""Sync Call."""
all_kwargs = {**self.partial_params, **kwargs}
if self.requires_context and self.ctx_param_name is not None:
if self.ctx_param_name not in all_kwargs:
raise ValueError("Context is required for this tool")
raw_output = self._fn(*args, **all_kwargs)
# Exclude the Context param from the tool output so that the Context can be serialized
tool_output_kwargs = {
k: v for k, v in all_kwargs.items() if k != self.ctx_param_name
}
# Parse tool output into content blocks
output_blocks = self._parse_tool_output(raw_output)
# Default ToolOutput based on the raw output
default_output = ToolOutput(
blocks=output_blocks,
tool_name=self.metadata.get_name(),
raw_input={"args": args, "kwargs": tool_output_kwargs},
raw_output=raw_output,
)
# Check for a sync callback override
callback_result = self._run_sync_callback(raw_output)
if callback_result is not None:
if isinstance(callback_result, ToolOutput):
return callback_result
else:
# Assume callback_result is a string to override the content.
return ToolOutput(
content=str(callback_result),
tool_name=self.metadata.get_name(),
raw_input={"args": args, "kwargs": tool_output_kwargs},
raw_output=raw_output,
)
return default_output
async def acall(self, *args: Any, **kwargs: Any) -> ToolOutput:
"""Async Call."""
all_kwargs = {**self.partial_params, **kwargs}
if self.requires_context and self.ctx_param_name is not None:
if self.ctx_param_name not in all_kwargs:
raise ValueError("Context is required for this tool")
raw_output = await self._async_fn(*args, **all_kwargs)
# Exclude the Context param from the tool output so that the Context can be serialized
tool_output_kwargs = {
k: v for k, v in all_kwargs.items() if k != self.ctx_param_name
}
# Parse tool output into content blocks
output_blocks = self._parse_tool_output(raw_output)
# Default ToolOutput based on the raw output
default_output = ToolOutput(
blocks=output_blocks,
tool_name=self.metadata.get_name(),
raw_input={"args": args, "kwargs": tool_output_kwargs},
raw_output=raw_output,
)
# Check for an async callback override
callback_result = await self._run_async_callback(raw_output)
if callback_result is not None:
if isinstance(callback_result, ToolOutput):
return callback_result
else:
# Assume callback_result is a string to override the content.
return ToolOutput(
content=str(callback_result),
tool_name=self.metadata.get_name(),
raw_input={"args": args, "kwargs": tool_output_kwargs},
raw_output=raw_output,
)
return default_output
def to_langchain_tool(self, **langchain_tool_kwargs: Any) -> "Tool":
"""To langchain tool."""
from llama_index.core.bridge.langchain import Tool
langchain_tool_kwargs = self._process_langchain_tool_kwargs(
langchain_tool_kwargs
)
return Tool.from_function(
func=self.fn,
coroutine=self.async_fn,
**langchain_tool_kwargs,
)
def to_langchain_structured_tool(
self, **langchain_tool_kwargs: Any
) -> "StructuredTool":
"""To langchain structured tool."""
from llama_index.core.bridge.langchain import StructuredTool
langchain_tool_kwargs = self._process_langchain_tool_kwargs(
langchain_tool_kwargs
)
return StructuredTool.from_function(
func=self.fn,
coroutine=self.async_fn,
**langchain_tool_kwargs,
)
@staticmethod
def extract_param_docs(
docstring: str, fn_params: Optional[set] = None
) -> Tuple[dict, set]:
"""
Parses param descriptions from a docstring.
Returns:
- param_docs: Only for params in fn_params with non-conflicting descriptions.
- unknown_params: Params found in docstring but not in fn_params (ignored in final output).
"""
raw_param_docs: dict[str, str] = {}
unknown_params = set()
def try_add_param(name: str, desc: str) -> None:
desc = desc.strip()
if fn_params and name not in fn_params:
unknown_params.add(name)
return
if name in raw_param_docs and raw_param_docs[name] != desc:
return
raw_param_docs[name] = desc
# Sphinx style
for match in re.finditer(r":param (\w+): (.+)", docstring):
try_add_param(match.group(1), match.group(2))
# Google style
for match in re.finditer(
r"^\s*(\w+)\s*\(.*?\):\s*(.+)$", docstring, re.MULTILINE
):
try_add_param(match.group(1), match.group(2))
# Javadoc style
for match in re.finditer(r"@param (\w+)\s+(.+)", docstring):
try_add_param(match.group(1), match.group(2))
return raw_param_docs, unknown_params
| FunctionTool |
python | ApeWorX__ape | src/ape/exceptions.py | {
"start": 4700,
"end": 5007
} | class ____(ContractDataError):
"""
Raises when sending funds to a non-payable method
"""
_TRACE_ARG = Optional[Union["TraceAPI", Callable[[], Optional["TraceAPI"]]]]
_SOURCE_TRACEBACK_ARG = Optional[
Union["SourceTraceback", Callable[[], Optional["SourceTraceback"]]]
]
| MethodNonPayableError |
python | cherrypy__cherrypy | cherrypy/__init__.py | {
"start": 6534,
"end": 8367
} | class ____(object):
__slots__ = ['__attrname__', '__dict__']
def __init__(self, attrname):
self.__attrname__ = attrname
def __getattr__(self, name):
child = getattr(serving, self.__attrname__)
return getattr(child, name)
def __setattr__(self, name, value):
if name in ('__attrname__',):
object.__setattr__(self, name, value)
else:
child = getattr(serving, self.__attrname__)
setattr(child, name, value)
def __delattr__(self, name):
child = getattr(serving, self.__attrname__)
delattr(child, name)
@property
def __dict__(self):
child = getattr(serving, self.__attrname__)
d = child.__class__.__dict__.copy()
d.update(child.__dict__)
return d
def __getitem__(self, key):
child = getattr(serving, self.__attrname__)
return child[key]
def __setitem__(self, key, value):
child = getattr(serving, self.__attrname__)
child[key] = value
def __delitem__(self, key):
child = getattr(serving, self.__attrname__)
del child[key]
def __contains__(self, key):
child = getattr(serving, self.__attrname__)
return key in child
def __len__(self):
child = getattr(serving, self.__attrname__)
return len(child)
def __nonzero__(self):
child = getattr(serving, self.__attrname__)
return bool(child)
# Python 3
__bool__ = __nonzero__
# Create request and response object (the same objects will be used
# throughout the entire life of the webserver, but will redirect
# to the "serving" object)
request = _ThreadLocalProxy('request')
response = _ThreadLocalProxy('response')
# Create thread_data object as a thread-specific all-purpose storage
| _ThreadLocalProxy |
python | pytorch__pytorch | torch/ao/quantization/backend_config/backend_config.py | {
"start": 17346,
"end": 31509
} | class ____:
"""
Config object that specifies quantization behavior for a given operator pattern.
For a detailed example usage, see :class:`~torch.ao.quantization.backend_config.BackendConfig`.
"""
def __init__(self, pattern: Pattern | None = None):
self.pattern: Pattern | None = pattern
self.observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
self.dtype_configs: list[DTypeConfig] = []
self.root_module: type[torch.nn.Module] | None = None
self.qat_module: type[torch.nn.Module] | None = None
self.reference_quantized_module: type[torch.nn.Module] | None = None
self.fused_module: type[torch.nn.Module] | None = None
self.fuser_method: Callable | None = None
# Temporary/internal configs
self._root_node_getter: Callable | None = None
self._extra_inputs_getter: Callable | None = None
self._num_tensor_args_to_observation_type: dict[int, ObservationType] = {}
self._input_type_to_index: dict[str, int] = {}
self._pattern_complex_format: Pattern | None = None
def __repr__(self):
dict_nonempty = {
k: v
for k, v in self.__dict__.items()
if (
(not isinstance(v, (list, dict)) and v is not None)
or (isinstance(v, (list, dict)) and len(v) > 0)
)
}
return f"BackendPatternConfig({dict_nonempty})"
def set_pattern(self, pattern: Pattern) -> BackendPatternConfig:
"""
Set the pattern to configure.
The pattern can be a float module, functional operator, pytorch operator, or a tuple
combination of the above. Tuple patterns are treated as sequential patterns, and
currently only tuples of 2 or 3 elements are supported.
"""
if self._pattern_complex_format is not None:
raise ValueError(
"Only one of 'pattern' or 'pattern_complex_format' can be set"
)
self.pattern = pattern
return self
def set_observation_type(
self, observation_type: ObservationType
) -> BackendPatternConfig:
"""
Set how observers should be inserted in the graph for this pattern.
Observation type here refers to how observers (or quant-dequant ops) will be placed
in the graph. This is used to produce the desired reference patterns understood by
the backend. Weighted ops such as linear and conv require different observers
(or quantization parameters passed to quantize ops in the reference model) for the
input and the output.
There are two observation types:
`OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT` (default): the output observer instance
will be different from the input. This is the most common observation type.
`OUTPUT_SHARE_OBSERVER_WITH_INPUT`: the output observer instance will be the
same as the input. This is useful for operators like `cat`.
Note: This will be renamed in the near future, since we will soon insert QuantDeQuantStubs
with observers (and fake quantizes) attached instead of observers themselves.
"""
self.observation_type = observation_type
return self
def add_dtype_config(self, dtype_config: DTypeConfig) -> BackendPatternConfig:
"""
Add a set of supported data types passed as arguments to quantize ops in the
reference model spec.
"""
self.dtype_configs.append(dtype_config)
return self
def set_dtype_configs(
self, dtype_configs: list[DTypeConfig]
) -> BackendPatternConfig:
"""
Set the supported data types passed as arguments to quantize ops in the
reference model spec, overriding all previously registered data types.
"""
self.dtype_configs = dtype_configs
return self
def set_root_module(
self, root_module: type[torch.nn.Module]
) -> BackendPatternConfig:
"""
Set the module that represents the root for this pattern.
When we construct the reference quantized model during the convert phase,
the root modules (e.g. torch.nn.Linear for torch.ao.nn.intrinsic.LinearReLU)
will be swapped to the corresponding reference quantized modules (e.g.
torch.ao.nn.reference.quantized.Linear). This allows custom backends to
specify custom reference quantized module implementations to match the
numerics of their lowered operators. Since this is a one-to-one mapping,
both the root module and the reference quantized module must be specified
in the same BackendPatternConfig in order for the conversion to take place.
"""
self.root_module = root_module
return self
def set_qat_module(self, qat_module: type[torch.nn.Module]) -> BackendPatternConfig:
"""
Set the module that represents the QAT implementation for this pattern.
"""
self.qat_module = qat_module
return self
def set_reference_quantized_module(
self, reference_quantized_module: type[torch.nn.Module]
) -> BackendPatternConfig:
"""
Set the module that represents the reference quantized implementation for
this pattern's root module.
For more detail, see :func:`~torch.ao.quantization.backend_config.BackendPatternConfig.set_root_module`.
"""
self.reference_quantized_module = reference_quantized_module
return self
def set_fused_module(
self, fused_module: type[torch.nn.Module]
) -> BackendPatternConfig:
"""
Set the module that represents the fused implementation for this pattern.
"""
self.fused_module = fused_module
return self
def set_fuser_method(self, fuser_method: Callable) -> BackendPatternConfig:
"""
Set the function that specifies how to fuse this BackendPatternConfig's pattern.
The first argument of this function should be `is_qat`, and the rest of the arguments
should be the items in the tuple pattern. The return value of this function should be
the resulting fused module.
For example, the fuser method for the pattern `(torch.nn.Linear, torch.nn.ReLU)` can be:
def fuse_linear_relu(is_qat, linear, relu):
return torch.ao.nn.intrinsic.LinearReLU(linear, relu)
For a more complicated example, see https://gist.github.com/jerryzh168/8bea7180a8ba3c279f2c9b050f2a69a6.
"""
self.fuser_method = fuser_method
return self
def _set_root_node_getter(self, root_node_getter: Callable) -> BackendPatternConfig:
self._root_node_getter = root_node_getter
return self
def _set_extra_inputs_getter(
self, extra_inputs_getter: Callable
) -> BackendPatternConfig:
self._extra_inputs_getter = extra_inputs_getter
return self
def _set_num_tensor_args_to_observation_type(
self, num_tensor_args_to_observation_type: dict[int, ObservationType]
) -> BackendPatternConfig:
self._num_tensor_args_to_observation_type = num_tensor_args_to_observation_type
return self
def _set_input_type_to_index(
self, input_type_to_index: dict[str, int]
) -> BackendPatternConfig:
self._input_type_to_index = input_type_to_index
return self
def _set_pattern_complex_format(self, pattern: Pattern) -> BackendPatternConfig:
"""
Set the pattern to configure, using the reversed nested tuple format.
See the BackendConfig README for more detail:
https://github.com/pytorch/pytorch/blob/master/torch/ao/quantization/backend_config/README.md#advanced-pattern-specification
"""
if self.pattern is not None:
raise ValueError(
"Only one of 'pattern' or 'pattern_complex_format' can be set"
)
self._pattern_complex_format = pattern
return self
@classmethod
def from_dict(
cls, backend_pattern_config_dict: dict[str, Any]
) -> BackendPatternConfig:
"""
Create a ``BackendPatternConfig`` from a dictionary with the following items:
"pattern": the pattern being configured
"observation_type": the :class:`~torch.ao.quantization.backend_config.ObservationType` that specifies how
observers should be inserted for this pattern
"dtype_configs": a list of dictionaries that represents :class:`~torch.ao.quantization.backend_config.DTypeConfig` s
"root_module": a :class:`torch.nn.Module` that represents the root for this pattern
"qat_module": a :class:`torch.nn.Module` that represents the QAT implementation for this pattern
"reference_quantized_module": a :class:`torch.nn.Module` that represents the reference quantized
implementation for this pattern's root module.
"fused_module": a :class:`torch.nn.Module` that represents the fused implementation for this pattern
"fuser_method": a function that specifies how to fuse the pattern for this pattern
"pattern_complex_format": the pattern specified in the reversed nested tuple format (deprecated)
"""
def _get_dtype_config(obj: Any) -> DTypeConfig:
"""
Convert the given object into a ``DTypeConfig`` if possible, else throw an exception.
"""
if isinstance(obj, DTypeConfig):
return obj
if isinstance(obj, dict):
return DTypeConfig.from_dict(obj)
raise ValueError(
f"Expected a list of DTypeConfigs in "
f"backend_pattern_config_dict[\"{DTYPE_CONFIGS_DICT_KEY}\"], got '{type(obj)}'"
)
conf = cls()
if PATTERN_DICT_KEY in backend_pattern_config_dict:
conf.set_pattern(backend_pattern_config_dict[PATTERN_DICT_KEY])
if OBSERVATION_TYPE_DICT_KEY in backend_pattern_config_dict:
conf.set_observation_type(
backend_pattern_config_dict[OBSERVATION_TYPE_DICT_KEY]
)
for d in backend_pattern_config_dict.get(DTYPE_CONFIGS_DICT_KEY, []):
conf.add_dtype_config(_get_dtype_config(d))
conf.set_root_module(
backend_pattern_config_dict.get(ROOT_MODULE_DICT_KEY) # type: ignore[arg-type]
)
conf.set_qat_module(backend_pattern_config_dict.get(QAT_MODULE_DICT_KEY)) # type: ignore[arg-type]
conf.set_reference_quantized_module(
backend_pattern_config_dict.get(REFERENCE_QUANTIZED_MODULE_DICT_KEY) # type: ignore[arg-type]
)
conf.set_fused_module(
backend_pattern_config_dict.get(FUSED_MODULE_DICT_KEY) # type: ignore[arg-type]
)
conf.set_fuser_method(
backend_pattern_config_dict.get(FUSER_METHOD_DICT_KEY) # type: ignore[arg-type]
)
conf._set_root_node_getter(
backend_pattern_config_dict.get(ROOT_NODE_GETTER_DICT_KEY) # type: ignore[arg-type]
)
conf._set_extra_inputs_getter(
backend_pattern_config_dict.get(EXTRA_INPUTS_GETTER_DICT_KEY) # type: ignore[arg-type]
)
conf._set_num_tensor_args_to_observation_type(
backend_pattern_config_dict.get(
NUM_TENSOR_ARGS_TO_OBSERVATION_TYPE_DICT_KEY, {}
)
)
conf._set_input_type_to_index(
backend_pattern_config_dict.get(INPUT_TYPE_TO_INDEX_DICT_KEY, {})
)
if PATTERN_COMPLEX_FORMAT_DICT_KEY in backend_pattern_config_dict:
conf._set_pattern_complex_format(
backend_pattern_config_dict[PATTERN_COMPLEX_FORMAT_DICT_KEY]
)
return conf
def to_dict(self) -> dict[str, Any]:
"""
Convert this ``BackendPatternConfig`` to a dictionary with the items described in
:func:`~torch.ao.quantization.backend_config.BackendPatternConfig.from_dict`.
"""
backend_pattern_config_dict: dict[str, Any] = {
OBSERVATION_TYPE_DICT_KEY: self.observation_type,
DTYPE_CONFIGS_DICT_KEY: [c.to_dict() for c in self.dtype_configs],
}
if self.pattern is not None:
backend_pattern_config_dict[PATTERN_DICT_KEY] = self.pattern
if self.root_module is not None:
backend_pattern_config_dict[ROOT_MODULE_DICT_KEY] = self.root_module
if self.qat_module is not None:
backend_pattern_config_dict[QAT_MODULE_DICT_KEY] = self.qat_module
if self.reference_quantized_module is not None:
backend_pattern_config_dict[REFERENCE_QUANTIZED_MODULE_DICT_KEY] = (
self.reference_quantized_module
)
if self.fused_module is not None:
backend_pattern_config_dict[FUSED_MODULE_DICT_KEY] = self.fused_module
if self.fuser_method is not None:
backend_pattern_config_dict[FUSER_METHOD_DICT_KEY] = self.fuser_method
if self._root_node_getter is not None:
backend_pattern_config_dict[ROOT_NODE_GETTER_DICT_KEY] = (
self._root_node_getter
)
if self._extra_inputs_getter is not None:
backend_pattern_config_dict[EXTRA_INPUTS_GETTER_DICT_KEY] = (
self._extra_inputs_getter
)
if len(self._num_tensor_args_to_observation_type) > 0:
backend_pattern_config_dict[
NUM_TENSOR_ARGS_TO_OBSERVATION_TYPE_DICT_KEY
] = self._num_tensor_args_to_observation_type
if len(self._input_type_to_index) > 0:
backend_pattern_config_dict[INPUT_TYPE_TO_INDEX_DICT_KEY] = (
self._input_type_to_index
)
if self._pattern_complex_format is not None:
backend_pattern_config_dict[PATTERN_COMPLEX_FORMAT_DICT_KEY] = (
self._pattern_complex_format
)
return backend_pattern_config_dict
| BackendPatternConfig |
python | walkccc__LeetCode | solutions/1545. Find Kth Bit in Nth Binary String/1545.py | {
"start": 0,
"end": 311
} | class ____:
def findKthBit(self, n: int, k: int) -> str:
if n == 1:
return '0'
midIndex = pow(2, n - 1) # 1-indexed
if k == midIndex:
return '1'
if k < midIndex:
return self.findKthBit(n - 1, k)
return '1' if self.findKthBit(n - 1, midIndex * 2 - k) == '0' else '0'
| Solution |
python | mwaskom__seaborn | tests/test_distributions.py | {
"start": 72921,
"end": 80683
} | class ____:
# TODO probably good to move these utility attributes/methods somewhere else
@pytest.mark.parametrize(
"kwargs", [
dict(),
dict(x="x"),
dict(x="t"),
dict(x="a"),
dict(x="z", log_scale=True),
dict(x="x", binwidth=4),
dict(x="x", weights="f", bins=5),
dict(x="x", color="green", linewidth=2, binwidth=4),
dict(x="x", hue="a", fill=False),
dict(x="y", hue="a", fill=False),
dict(x="x", hue="a", multiple="stack"),
dict(x="x", hue="a", element="step"),
dict(x="x", hue="a", palette="muted"),
dict(x="x", hue="a", kde=True),
dict(x="x", hue="a", stat="density", common_norm=False),
dict(x="x", y="y"),
],
)
def test_versus_single_histplot(self, long_df, kwargs):
ax = histplot(long_df, **kwargs)
g = displot(long_df, **kwargs)
assert_plots_equal(ax, g.ax)
if ax.legend_ is not None:
assert_legends_equal(ax.legend_, g._legend)
if kwargs:
long_df["_"] = "_"
g2 = displot(long_df, col="_", **kwargs)
assert_plots_equal(ax, g2.ax)
@pytest.mark.parametrize(
"kwargs", [
dict(),
dict(x="x"),
dict(x="t"),
dict(x="z", log_scale=True),
dict(x="x", bw_adjust=.5),
dict(x="x", weights="f"),
dict(x="x", color="green", linewidth=2),
dict(x="x", hue="a", multiple="stack"),
dict(x="x", hue="a", fill=True),
dict(x="y", hue="a", fill=False),
dict(x="x", hue="a", palette="muted"),
dict(x="x", y="y"),
],
)
def test_versus_single_kdeplot(self, long_df, kwargs):
ax = kdeplot(data=long_df, **kwargs)
g = displot(long_df, kind="kde", **kwargs)
assert_plots_equal(ax, g.ax)
if ax.legend_ is not None:
assert_legends_equal(ax.legend_, g._legend)
if kwargs:
long_df["_"] = "_"
g2 = displot(long_df, kind="kde", col="_", **kwargs)
assert_plots_equal(ax, g2.ax)
@pytest.mark.parametrize(
"kwargs", [
dict(),
dict(x="x"),
dict(x="t"),
dict(x="z", log_scale=True),
dict(x="x", weights="f"),
dict(y="x"),
dict(x="x", color="green", linewidth=2),
dict(x="x", hue="a", complementary=True),
dict(x="x", hue="a", stat="count"),
dict(x="x", hue="a", palette="muted"),
],
)
def test_versus_single_ecdfplot(self, long_df, kwargs):
ax = ecdfplot(data=long_df, **kwargs)
g = displot(long_df, kind="ecdf", **kwargs)
assert_plots_equal(ax, g.ax)
if ax.legend_ is not None:
assert_legends_equal(ax.legend_, g._legend)
if kwargs:
long_df["_"] = "_"
g2 = displot(long_df, kind="ecdf", col="_", **kwargs)
assert_plots_equal(ax, g2.ax)
@pytest.mark.parametrize(
"kwargs", [
dict(x="x"),
dict(x="x", y="y"),
dict(x="x", hue="a"),
]
)
def test_with_rug(self, long_df, kwargs):
ax = plt.figure().subplots()
histplot(data=long_df, **kwargs, ax=ax)
rugplot(data=long_df, **kwargs, ax=ax)
g = displot(long_df, rug=True, **kwargs)
assert_plots_equal(ax, g.ax, labels=False)
long_df["_"] = "_"
g2 = displot(long_df, col="_", rug=True, **kwargs)
assert_plots_equal(ax, g2.ax, labels=False)
@pytest.mark.parametrize(
"facet_var", ["col", "row"],
)
def test_facets(self, long_df, facet_var):
kwargs = {facet_var: "a"}
ax = kdeplot(data=long_df, x="x", hue="a")
g = displot(long_df, x="x", kind="kde", **kwargs)
legend_texts = ax.legend_.get_texts()
for i, line in enumerate(ax.lines[::-1]):
facet_ax = g.axes.flat[i]
facet_line = facet_ax.lines[0]
assert_array_equal(line.get_xydata(), facet_line.get_xydata())
text = legend_texts[i].get_text()
assert text in facet_ax.get_title()
@pytest.mark.parametrize("multiple", ["dodge", "stack", "fill"])
def test_facet_multiple(self, long_df, multiple):
bins = np.linspace(0, 20, 5)
ax = histplot(
data=long_df[long_df["c"] == 0],
x="x", hue="a", hue_order=["a", "b", "c"],
multiple=multiple, bins=bins,
)
g = displot(
data=long_df, x="x", hue="a", col="c", hue_order=["a", "b", "c"],
multiple=multiple, bins=bins,
)
assert_plots_equal(ax, g.axes_dict[0])
def test_ax_warning(self, long_df):
ax = plt.figure().subplots()
with pytest.warns(UserWarning, match="`displot` is a figure-level"):
displot(long_df, x="x", ax=ax)
@pytest.mark.parametrize("key", ["col", "row"])
def test_array_faceting(self, long_df, key):
a = long_df["a"].to_numpy()
vals = categorical_order(a)
g = displot(long_df, x="x", **{key: a})
assert len(g.axes.flat) == len(vals)
for ax, val in zip(g.axes.flat, vals):
assert val in ax.get_title()
def test_legend(self, long_df):
g = displot(long_df, x="x", hue="a")
assert g._legend is not None
def test_empty(self):
g = displot(x=[], y=[])
assert isinstance(g, FacetGrid)
def test_bivariate_ecdf_error(self, long_df):
with pytest.raises(NotImplementedError):
displot(long_df, x="x", y="y", kind="ecdf")
def test_bivariate_kde_norm(self, rng):
x, y = rng.normal(0, 1, (2, 100))
z = [0] * 80 + [1] * 20
def count_contours(ax):
if _version_predates(mpl, "3.8.0rc1"):
return sum(bool(get_contour_coords(c)) for c in ax.collections)
else:
return sum(bool(p.vertices.size) for p in ax.collections[0].get_paths())
g = displot(x=x, y=y, col=z, kind="kde", levels=10)
l1 = count_contours(g.axes.flat[0])
l2 = count_contours(g.axes.flat[1])
assert l1 > l2
g = displot(x=x, y=y, col=z, kind="kde", levels=10, common_norm=False)
l1 = count_contours(g.axes.flat[0])
l2 = count_contours(g.axes.flat[1])
assert l1 == l2
def test_bivariate_hist_norm(self, rng):
x, y = rng.normal(0, 1, (2, 100))
z = [0] * 80 + [1] * 20
g = displot(x=x, y=y, col=z, kind="hist")
clim1 = g.axes.flat[0].collections[0].get_clim()
clim2 = g.axes.flat[1].collections[0].get_clim()
assert clim1 == clim2
g = displot(x=x, y=y, col=z, kind="hist", common_norm=False)
clim1 = g.axes.flat[0].collections[0].get_clim()
clim2 = g.axes.flat[1].collections[0].get_clim()
assert clim1[1] > clim2[1]
def test_facetgrid_data(self, long_df):
g = displot(
data=long_df.to_dict(orient="list"),
x="z",
hue=long_df["a"].rename("hue_var"),
col=long_df["c"].to_numpy(),
)
expected_cols = set(long_df.columns.to_list() + ["hue_var", "_col_"])
assert set(g.data.columns) == expected_cols
assert_array_equal(g.data["hue_var"], long_df["a"])
assert_array_equal(g.data["_col_"], long_df["c"])
def integrate(y, x):
""""Simple numerical integration for testing KDE code."""
y = np.asarray(y)
x = np.asarray(x)
dx = np.diff(x)
return (dx * y[:-1] + dx * y[1:]).sum() / 2
| TestDisPlot |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_team_all_unresolved_issues.py | {
"start": 570,
"end": 11789
} | class ____(APITestCase):
endpoint = "sentry-api-0-team-all-unresolved-issues"
def test_status_format(self) -> None:
project1 = self.create_project(teams=[self.team])
group1_1 = self.create_group(project=project1, first_seen=before_now(days=40))
group1_2 = self.create_group(project=project1, first_seen=before_now(days=5))
group1_3 = self.create_group(
project=project1,
first_seen=before_now(days=40),
status=GroupStatus.RESOLVED,
resolved_at=before_now(days=35),
)
group1_4 = self.create_group(
project=project1,
first_seen=before_now(days=40),
status=GroupStatus.RESOLVED,
resolved_at=before_now(days=9),
)
group1_5 = self.create_group(project=project1, first_seen=before_now(days=40))
# Should be excluded from counts even though it has no group history row
group1_6 = self.create_group(
project=project1, first_seen=before_now(days=41), status=GroupStatus.IGNORED
)
# Should be excluded from initial counts because it has a regressed status without a
# corresponding resolved status
group1_7 = self.create_group(project=project1, first_seen=before_now(days=40))
group1_8 = self.create_group(
project=project1, first_seen=before_now(days=40), status=GroupStatus.UNRESOLVED
)
GroupAssignee.objects.assign(group1_1, self.user)
GroupAssignee.objects.assign(group1_2, self.user)
GroupAssignee.objects.assign(group1_3, self.user)
GroupAssignee.objects.assign(group1_4, self.user)
GroupAssignee.objects.assign(group1_5, self.user)
GroupAssignee.objects.assign(group1_6, self.user)
GroupAssignee.objects.assign(group1_7, self.user)
GroupAssignee.objects.assign(group1_8, self.user)
GroupHistory.objects.all().delete()
self.create_group_history(
group=group1_1, date_added=before_now(days=5), status=GroupHistoryStatus.RESOLVED
)
# Duplicate statuses shouldn't count multiple times.
self.create_group_history(
group=group1_1,
date_added=before_now(days=4, hours=10),
status=GroupHistoryStatus.RESOLVED,
)
self.create_group_history(
group=group1_1,
date_added=before_now(days=4, hours=8),
status=GroupHistoryStatus.RESOLVED,
)
self.create_group_history(
group=group1_1, date_added=before_now(days=3), status=GroupHistoryStatus.UNRESOLVED
)
self.create_group_history(
group=group1_2, date_added=before_now(days=3), status=GroupHistoryStatus.RESOLVED
)
self.create_group_history(
group=group1_2,
date_added=before_now(days=2, hours=23),
status=GroupHistoryStatus.REGRESSED,
)
self.create_group_history(
group=group1_4, date_added=before_now(days=9), status=GroupHistoryStatus.RESOLVED
)
self.create_group_history(
group=group1_4,
date_added=before_now(days=8, hours=7),
status=GroupHistoryStatus.RESOLVED,
)
self.create_group_history(
group=group1_4,
date_added=before_now(days=8, hours=6),
status=GroupHistoryStatus.RESOLVED,
)
self.create_group_history(
group=group1_7,
date_added=before_now(days=1),
status=GroupHistoryStatus.REGRESSED,
)
self.create_group_history(
group=group1_8,
date_added=before_now(days=8, hours=0),
status=GroupHistoryStatus.RESOLVED,
)
project2 = self.create_project(teams=[self.team])
group2_1 = self.create_group(
project=project2, first_seen=before_now(days=40), status=GroupStatus.RESOLVED
)
GroupAssignee.objects.assign(group2_1, self.user)
self.create_group_history(
group=group2_1, date_added=before_now(days=6), status=GroupHistoryStatus.RESOLVED
)
self.create_group_history(
group=group2_1, date_added=before_now(days=5), status=GroupHistoryStatus.REGRESSED
)
self.create_group_history(
group=group2_1, date_added=before_now(days=4), status=GroupHistoryStatus.IGNORED
)
self.create_group_history(
group=group2_1, date_added=before_now(days=3), status=GroupHistoryStatus.UNIGNORED
)
self.create_group_history(
group=group2_1,
date_added=before_now(days=2),
status=GroupHistoryStatus.SET_RESOLVED_IN_RELEASE,
)
self.create_group_history(
group=group2_1, date_added=before_now(days=1), status=GroupHistoryStatus.REGRESSED
)
self.create_group_history(
group=group2_1, date_added=before_now(days=0), status=GroupHistoryStatus.RESOLVED
)
project3 = self.create_project(teams=[self.team])
group3_1 = self.create_group(
project=project3, first_seen=before_now(days=5), status=GroupStatus.RESOLVED
)
GroupAssignee.objects.assign(group3_1, self.user)
self.create_group_history(
group=group3_1, date_added=before_now(days=4), status=GroupHistoryStatus.RESOLVED
)
self.create_group_history(
group=group3_1, date_added=before_now(days=4), status=GroupHistoryStatus.UNRESOLVED
)
self.create_group_history(
group=group3_1, date_added=before_now(days=4), status=GroupHistoryStatus.RESOLVED
)
self.create_group_history(
group=group3_1, date_added=before_now(days=4), status=GroupHistoryStatus.UNRESOLVED
)
self.create_group_history(
group=group3_1, date_added=before_now(days=4), status=GroupHistoryStatus.RESOLVED
)
self.create_group_history(
group=group3_1, date_added=before_now(days=4), status=GroupHistoryStatus.UNRESOLVED
)
self.create_group_history(
group=group3_1, date_added=before_now(days=4), status=GroupHistoryStatus.RESOLVED
)
# Test that we don't double-count creation if first GroupHistory row is "open"
# If error, should see index 0 incorrectly report 0 open issues
project4 = self.create_project(teams=[self.team])
group4_1 = self.create_group(
project=project4, first_seen=before_now(days=40), status=GroupStatus.UNRESOLVED
)
GroupAssignee.objects.assign(group4_1, self.user)
group4_2 = self.create_group(
project=project4, first_seen=before_now(days=5), status=GroupStatus.RESOLVED
)
GroupAssignee.objects.assign(group4_2, self.user)
self.create_group_history(
group=group4_2, date_added=before_now(days=3), status=GroupHistoryStatus.UNRESOLVED
)
self.create_group_history(
group=group4_2, date_added=before_now(days=1), status=GroupHistoryStatus.RESOLVED
)
self.login_as(user=self.user)
response = self.get_success_response(
self.team.organization.slug, self.team.slug, statsPeriod="7d"
)
def compare_response(
response: Response, project: Project, expected_results: list[int]
) -> None:
start = (now() - timedelta(days=len(expected_results) - 1)).replace(
hour=0, minute=0, second=0, microsecond=0, tzinfo=timezone.utc
)
expected = {
(start + timedelta(days=i)).isoformat(): {"unresolved": value}
for i, value in enumerate(expected_results)
}
assert expected == response.data[project.id]
compare_response(response, project1, [3, 3, 3, 4, 4, 5, 5])
compare_response(response, project2, [0, 1, 0, 1, 0, 1, 0])
compare_response(response, project3, [0, 1, 0, 0, 0, 0, 0])
compare_response(response, project4, [1, 2, 2, 2, 2, 1, 1])
def test_status_format_with_environment(self) -> None:
project1 = self.create_project(teams=[self.team])
env1 = self.create_environment(name="development", project=project1)
env2 = self.create_environment(name="production", project=project1)
group1_1 = self.create_group(project_id=project1.id, first_seen=before_now(days=40))
group1_2 = self.create_group(project_id=project1.id, first_seen=before_now(days=40))
group1_3 = self.create_group(project_id=project1.id, first_seen=before_now(days=40))
GroupEnvironment.objects.create(group_id=group1_1.id, environment_id=env2.id)
GroupEnvironment.objects.create(group_id=group1_2.id, environment_id=env2.id)
GroupEnvironment.objects.create(group_id=group1_3.id, environment_id=env1.id)
GroupAssignee.objects.assign(group1_1, self.user)
GroupAssignee.objects.assign(group1_2, self.user)
GroupAssignee.objects.assign(group1_3, self.user)
GroupHistory.objects.all().delete()
self.create_group_history(
group=group1_1, date_added=before_now(days=40), status=GroupHistoryStatus.UNRESOLVED
)
self.create_group_history(
group=group1_2, date_added=before_now(days=40), status=GroupHistoryStatus.UNRESOLVED
)
self.create_group_history(
group=group1_3, date_added=before_now(days=40), status=GroupHistoryStatus.UNRESOLVED
)
self.login_as(user=self.user)
response = self.get_success_response(
self.team.organization.slug, self.team.slug, statsPeriod="7d", environment="production"
)
def compare_response(
response: Response, project: Project, expected_results: list[int]
) -> None:
start = (now() - timedelta(days=len(expected_results) - 1)).replace(
hour=0, minute=0, second=0, microsecond=0, tzinfo=timezone.utc
)
expected = {
(start + timedelta(days=i)).isoformat(): {"unresolved": value}
for i, value in enumerate(expected_results)
}
assert expected == response.data[project.id]
compare_response(response, project1, [2, 2, 2, 2, 2, 2, 2])
response = self.get_success_response(
self.team.organization.slug, self.team.slug, statsPeriod="7d"
)
compare_response(response, project1, [3, 3, 3, 3, 3, 3, 3])
def test_no_projects(self) -> None:
self.login_as(user=self.user)
self.get_success_response(self.team.organization.slug, self.team.slug, statsPeriod="7d")
def test_no_group_history(self) -> None:
project1 = self.create_project(teams=[self.team])
group1_1 = self.create_group(project=project1, first_seen=before_now(days=40))
GroupAssignee.objects.assign(group1_1, self.user)
GroupHistory.objects.all().delete()
self.login_as(user=self.user)
self.get_success_response(self.team.organization.slug, self.team.slug, statsPeriod="7d")
| TeamIssueBreakdownTest |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vision.py | {
"start": 8671,
"end": 9490
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.vision.CloudVisionHook")
def test_minimal_green_path(self, mock_hook):
mock_hook.return_value.update_product.return_value = {}
op = CloudVisionUpdateProductOperator(location=LOCATION_TEST, product=PRODUCT_TEST, task_id="id")
op.execute(context=None)
mock_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=None,
)
mock_hook.return_value.update_product.assert_called_once_with(
location=LOCATION_TEST,
product=PRODUCT_TEST,
product_id=None,
project_id=None,
retry=DEFAULT,
timeout=None,
metadata=(),
update_mask=None,
)
| TestCloudVisionProductUpdate |
python | astropy__astropy | astropy/time/formats.py | {
"start": 36804,
"end": 37280
} | class ____(TimeFromEpoch):
"""
Stardate: date units from 2318-07-05 12:00:00 UTC.
For example, stardate 41153.7 is 00:52 on April 30, 2363.
See https://trekguide.com/Stardates.htm#TNG for calculations and reference points.
"""
name = "stardate"
unit = 0.397766856 # Stardate units per day
epoch_val = "2318-07-05 11:00:00" # Date and time of stardate 00000.00
epoch_val2 = None
epoch_scale = "tai"
epoch_format = "iso"
| TimeStardate |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/util.py | {
"start": 18714,
"end": 32510
} | class ____(_repr_base):
"""Provide a string view of bound parameters.
Truncates display to a given number of 'multi' parameter sets,
as well as long values to a given number of characters.
"""
__slots__ = "params", "batches", "ismulti", "max_params"
def __init__(
self,
params: Optional[_AnyExecuteParams],
batches: int,
max_params: int = 100,
max_chars: int = 300,
ismulti: Optional[bool] = None,
):
self.params = params
self.ismulti = ismulti
self.batches = batches
self.max_chars = max_chars
self.max_params = max_params
def __repr__(self) -> str:
if self.ismulti is None:
return self.trunc(self.params)
if isinstance(self.params, list):
typ = self._LIST
elif isinstance(self.params, tuple):
typ = self._TUPLE
elif isinstance(self.params, dict):
typ = self._DICT
else:
return self.trunc(self.params)
if self.ismulti:
multi_params = cast(
"_AnyMultiExecuteParams",
self.params,
)
if len(self.params) > self.batches:
msg = (
" ... displaying %i of %i total bound parameter sets ... "
)
return " ".join(
(
self._repr_multi(
multi_params[: self.batches - 2],
typ,
)[0:-1],
msg % (self.batches, len(self.params)),
self._repr_multi(multi_params[-2:], typ)[1:],
)
)
else:
return self._repr_multi(multi_params, typ)
else:
return self._repr_params(
cast(
"_AnySingleExecuteParams",
self.params,
),
typ,
)
def _repr_multi(
self,
multi_params: _AnyMultiExecuteParams,
typ: int,
) -> str:
if multi_params:
if isinstance(multi_params[0], list):
elem_type = self._LIST
elif isinstance(multi_params[0], tuple):
elem_type = self._TUPLE
elif isinstance(multi_params[0], dict):
elem_type = self._DICT
else:
assert False, "Unknown parameter type %s" % (
type(multi_params[0])
)
elements = ", ".join(
self._repr_params(params, elem_type) for params in multi_params
)
else:
elements = ""
if typ == self._LIST:
return "[%s]" % elements
else:
return "(%s)" % elements
def _get_batches(self, params: Iterable[Any]) -> Any:
lparams = list(params)
lenparams = len(lparams)
if lenparams > self.max_params:
lleft = self.max_params // 2
return (
lparams[0:lleft],
lparams[-lleft:],
lenparams - self.max_params,
)
else:
return lparams, None, None
def _repr_params(
self,
params: _AnySingleExecuteParams,
typ: int,
) -> str:
if typ is self._DICT:
return self._repr_param_dict(
cast("_CoreSingleExecuteParams", params)
)
elif typ is self._TUPLE:
return self._repr_param_tuple(cast("Sequence[Any]", params))
else:
return self._repr_param_list(params)
def _repr_param_dict(self, params: _CoreSingleExecuteParams) -> str:
trunc = self.trunc
(
items_first_batch,
items_second_batch,
trunclen,
) = self._get_batches(params.items())
if items_second_batch:
text = "{%s" % (
", ".join(
f"{key!r}: {trunc(value)}"
for key, value in items_first_batch
)
)
text += f" ... {trunclen} parameters truncated ... "
text += "%s}" % (
", ".join(
f"{key!r}: {trunc(value)}"
for key, value in items_second_batch
)
)
else:
text = "{%s}" % (
", ".join(
f"{key!r}: {trunc(value)}"
for key, value in items_first_batch
)
)
return text
def _repr_param_tuple(self, params: Sequence[Any]) -> str:
trunc = self.trunc
(
items_first_batch,
items_second_batch,
trunclen,
) = self._get_batches(params)
if items_second_batch:
text = "(%s" % (
", ".join(trunc(value) for value in items_first_batch)
)
text += f" ... {trunclen} parameters truncated ... "
text += "%s)" % (
", ".join(trunc(value) for value in items_second_batch),
)
else:
text = "(%s%s)" % (
", ".join(trunc(value) for value in items_first_batch),
"," if len(items_first_batch) == 1 else "",
)
return text
def _repr_param_list(self, params: _AnySingleExecuteParams) -> str:
trunc = self.trunc
(
items_first_batch,
items_second_batch,
trunclen,
) = self._get_batches(params)
if items_second_batch:
text = "[%s" % (
", ".join(trunc(value) for value in items_first_batch)
)
text += f" ... {trunclen} parameters truncated ... "
text += "%s]" % (
", ".join(trunc(value) for value in items_second_batch)
)
else:
text = "[%s]" % (
", ".join(trunc(value) for value in items_first_batch)
)
return text
def adapt_criterion_to_null(crit: _CE, nulls: Collection[Any]) -> _CE:
"""given criterion containing bind params, convert selected elements
to IS NULL.
"""
def visit_binary(binary):
if (
isinstance(binary.left, BindParameter)
and binary.left._identifying_key in nulls
):
# reverse order if the NULL is on the left side
binary.left = binary.right
binary.right = Null()
binary.operator = operators.is_
binary.negate = operators.is_not
elif (
isinstance(binary.right, BindParameter)
and binary.right._identifying_key in nulls
):
binary.right = Null()
binary.operator = operators.is_
binary.negate = operators.is_not
return visitors.cloned_traverse(crit, {}, {"binary": visit_binary})
def splice_joins(
left: Optional[FromClause],
right: Optional[FromClause],
stop_on: Optional[FromClause] = None,
) -> Optional[FromClause]:
if left is None:
return right
stack: List[Tuple[Optional[FromClause], Optional[Join]]] = [(right, None)]
adapter = ClauseAdapter(left)
ret = None
while stack:
(right, prevright) = stack.pop()
if isinstance(right, Join) and right is not stop_on:
right = right._clone()
right.onclause = adapter.traverse(right.onclause)
stack.append((right.left, right))
else:
right = adapter.traverse(right)
if prevright is not None:
assert right is not None
prevright.left = right
if ret is None:
ret = right
return ret
@overload
def reduce_columns(
columns: Iterable[ColumnElement[Any]],
*clauses: Optional[ClauseElement],
**kw: bool,
) -> Sequence[ColumnElement[Any]]: ...
@overload
def reduce_columns(
columns: _SelectIterable,
*clauses: Optional[ClauseElement],
**kw: bool,
) -> Sequence[Union[ColumnElement[Any], TextClause]]: ...
def reduce_columns(
columns: _SelectIterable,
*clauses: Optional[ClauseElement],
**kw: bool,
) -> Collection[Union[ColumnElement[Any], TextClause]]:
r"""given a list of columns, return a 'reduced' set based on natural
equivalents.
the set is reduced to the smallest list of columns which have no natural
equivalent present in the list. A "natural equivalent" means that two
columns will ultimately represent the same value because they are related
by a foreign key.
\*clauses is an optional list of join clauses which will be traversed
to further identify columns that are "equivalent".
\**kw may specify 'ignore_nonexistent_tables' to ignore foreign keys
whose tables are not yet configured, or columns that aren't yet present.
This function is primarily used to determine the most minimal "primary
key" from a selectable, by reducing the set of primary key columns present
in the selectable to just those that are not repeated.
"""
ignore_nonexistent_tables = kw.pop("ignore_nonexistent_tables", False)
only_synonyms = kw.pop("only_synonyms", False)
column_set = util.OrderedSet(columns)
cset_no_text: util.OrderedSet[ColumnElement[Any]] = column_set.difference(
c for c in column_set if is_text_clause(c) # type: ignore
)
omit = util.column_set()
for col in cset_no_text:
for fk in chain(*[c.foreign_keys for c in col.proxy_set]):
for c in cset_no_text:
if c is col:
continue
try:
fk_col = fk.column
except exc.NoReferencedColumnError:
# TODO: add specific coverage here
# to test/sql/test_selectable ReduceTest
if ignore_nonexistent_tables:
continue
else:
raise
except exc.NoReferencedTableError:
# TODO: add specific coverage here
# to test/sql/test_selectable ReduceTest
if ignore_nonexistent_tables:
continue
else:
raise
if fk_col.shares_lineage(c) and (
not only_synonyms or c.name == col.name
):
omit.add(col)
break
if clauses:
def visit_binary(binary):
if binary.operator == operators.eq:
cols = util.column_set(
chain(
*[c.proxy_set for c in cset_no_text.difference(omit)]
)
)
if binary.left in cols and binary.right in cols:
for c in reversed(cset_no_text):
if c.shares_lineage(binary.right) and (
not only_synonyms or c.name == binary.left.name
):
omit.add(c)
break
for clause in clauses:
if clause is not None:
visitors.traverse(clause, {}, {"binary": visit_binary})
return column_set.difference(omit)
def criterion_as_pairs(
expression,
consider_as_foreign_keys=None,
consider_as_referenced_keys=None,
any_operator=False,
):
"""traverse an expression and locate binary criterion pairs."""
if consider_as_foreign_keys and consider_as_referenced_keys:
raise exc.ArgumentError(
"Can only specify one of "
"'consider_as_foreign_keys' or "
"'consider_as_referenced_keys'"
)
def col_is(a, b):
# return a is b
return a.compare(b)
def visit_binary(binary):
if not any_operator and binary.operator is not operators.eq:
return
if not isinstance(binary.left, ColumnElement) or not isinstance(
binary.right, ColumnElement
):
return
if consider_as_foreign_keys:
if binary.left in consider_as_foreign_keys and (
col_is(binary.right, binary.left)
or binary.right not in consider_as_foreign_keys
):
pairs.append((binary.right, binary.left))
elif binary.right in consider_as_foreign_keys and (
col_is(binary.left, binary.right)
or binary.left not in consider_as_foreign_keys
):
pairs.append((binary.left, binary.right))
elif consider_as_referenced_keys:
if binary.left in consider_as_referenced_keys and (
col_is(binary.right, binary.left)
or binary.right not in consider_as_referenced_keys
):
pairs.append((binary.left, binary.right))
elif binary.right in consider_as_referenced_keys and (
col_is(binary.left, binary.right)
or binary.left not in consider_as_referenced_keys
):
pairs.append((binary.right, binary.left))
else:
if isinstance(binary.left, Column) and isinstance(
binary.right, Column
):
if binary.left.references(binary.right):
pairs.append((binary.right, binary.left))
elif binary.right.references(binary.left):
pairs.append((binary.left, binary.right))
pairs: List[Tuple[ColumnElement[Any], ColumnElement[Any]]] = []
visitors.traverse(expression, {}, {"binary": visit_binary})
return pairs
| _repr_params |
python | walkccc__LeetCode | solutions/2044. Count Number of Maximum Bitwise-OR Subsets/2044.py | {
"start": 0,
"end": 360
} | class ____:
def countMaxOrSubsets(self, nums: list[int]) -> int:
ors = functools.reduce(operator.or_, nums)
ans = 0
def dfs(i: int, path: int) -> None:
nonlocal ans
if i == len(nums):
if path == ors:
ans += 1
return
dfs(i + 1, path)
dfs(i + 1, path | nums[i])
dfs(0, 0)
return ans
| Solution |
python | kamyu104__LeetCode-Solutions | Python/minesweeper.py | {
"start": 43,
"end": 1222
} | class ____(object):
def updateBoard(self, board, click):
"""
:type board: List[List[str]]
:type click: List[int]
:rtype: List[List[str]]
"""
if board[click[0]][click[1]] == 'M':
board[click[0]][click[1]] = 'X'
return board
stk = [click]
while stk:
r, c = stk.pop()
cnt = 0
adj = []
for dr in xrange(-1, 2):
for dc in xrange(-1, 2):
if dr == dc == 0:
continue
nr, nc = r+dr, c+dc
if not (0 <= nr < len(board) and 0 <= nc < len(board[r])):
continue
if board[nr][nc] == 'M':
cnt += 1
elif board[nr][nc] == 'E':
adj.append((nr, nc))
if cnt:
board[r][c] = chr(cnt + ord('0'))
continue
board[r][c] = 'B'
for nr, nc in adj:
board[nr][nc] = ' '
stk.append((nr, nc))
return board
# Time: O(m * n)
# Space: O(m + n)
# dfs
| Solution |
python | getsentry__sentry | src/sentry/models/dynamicsampling.py | {
"start": 2282,
"end": 2895
} | class ____(Model):
"""
Many-to-many relationship between a custom dynamic sampling rule and a project.
"""
__relocation_scope__ = RelocationScope.Organization
custom_dynamic_sampling_rule = FlexibleForeignKey(
"sentry.CustomDynamicSamplingRule", on_delete=models.CASCADE
)
project = FlexibleForeignKey("sentry.Project", on_delete=models.CASCADE)
class Meta:
app_label = "sentry"
db_table = "sentry_customdynamicsamplingruleproject"
unique_together = (("custom_dynamic_sampling_rule", "project"),)
@region_silo_model
| CustomDynamicSamplingRuleProject |
python | protocolbuffers__protobuf | objectivec/DevTools/pddm.py | {
"start": 4203,
"end": 4365
} | class ____(Exception):
"""Error thrown by pddm."""
def __init__(self, message="Error"):
self.message = message
super().__init__(self.message)
| PDDMError |
python | pytorch__pytorch | torch/_inductor/runtime/triton_heuristics.py | {
"start": 140740,
"end": 140969
} | class ____(GridExpr):
def generate(self, meta: dict[str, int]) -> None:
assert meta.get("XBLOCK", 1) == 1
self.x_grid = self.ceildiv("r0_numel", meta.get("R0_BLOCK"))
self.y_grid = "xnumel"
| SplitScanGrid |
python | django__django | tests/multiple_database/tests.py | {
"start": 77644,
"end": 77957
} | class ____:
# A router that only expresses an opinion on migrate,
# passing pets to the 'other' database
def allow_migrate(self, db, app_label, model_name=None, **hints):
if db == "other":
return model_name == "pet"
else:
return model_name != "pet"
| AntiPetRouter |
python | encode__django-rest-framework | tests/test_one_to_one_with_inheritance.py | {
"start": 433,
"end": 603
} | class ____(serializers.ModelSerializer):
class Meta:
model = ChildModel
fields = ['id', 'name1', 'name2', 'childassociatedmodel']
| DerivedModelSerializer |
python | coleifer__peewee | tests/sqlcipher_ext.py | {
"start": 739,
"end": 803
} | class ____(FTSModel, TestModel):
content = TextField()
| FTSNote |
python | qdrant__qdrant-client | tools/async_client_generator/client_generator.py | {
"start": 465,
"end": 3847
} | class ____(BaseGenerator):
def __init__(
self,
keep_sync: Optional[list[str]] = None,
class_replace_map: Optional[dict[str, str]] = None,
import_replace_map: Optional[dict[str, str]] = None,
exclude_methods: Optional[list[str]] = None,
):
super().__init__()
self._async_methods: Optional[list[str]] = None
self.transformers.append(ImportTransformer(import_replace_map=import_replace_map))
self.transformers.append(ImportFromTransformer(import_replace_map=import_replace_map))
self.transformers.append(
ClientFunctionDefTransformer(
keep_sync=keep_sync,
class_replace_map=class_replace_map,
exclude_methods=exclude_methods,
async_methods=self.async_methods,
)
)
self.transformers.append(ClassDefTransformer(class_replace_map=class_replace_map))
# call_transformer should be after function_def_transformer
self.transformers.append(
CallTransformer(class_replace_map=class_replace_map, async_methods=self.async_methods)
)
# name_transformer should be after function_def, class_def and ann_assign transformers
self.transformers.append(
NameTransformer(
class_replace_map=class_replace_map,
import_replace_map=import_replace_map,
)
)
@property
def async_methods(self) -> list[str]:
if self._async_methods is None:
self._async_methods = self.get_async_methods(AsyncQdrantBase)
return self._async_methods
@staticmethod
def get_async_methods(class_obj: type) -> list[str]:
async_methods = []
for name, method in inspect.getmembers(class_obj):
if inspect.iscoroutinefunction(method):
async_methods.append(name)
return async_methods
if __name__ == "__main__":
from tools.async_client_generator.config import CLIENT_DIR, CODE_DIR
with open(CLIENT_DIR / "qdrant_client.py", "r") as source_file:
code = source_file.read()
generator = ClientGenerator(
class_replace_map={
"QdrantBase": "AsyncQdrantBase",
"QdrantFastembedMixin": "AsyncQdrantFastembedMixin",
"QdrantClient": "AsyncQdrantClient",
"QdrantRemote": "AsyncQdrantRemote",
"QdrantLocal": "AsyncQdrantLocal",
},
import_replace_map={
"qdrant_client.client_base": "qdrant_client.async_client_base",
"QdrantBase": "AsyncQdrantBase",
"QdrantFastembedMixin": "AsyncQdrantFastembedMixin",
"qdrant_client.qdrant_fastembed": "qdrant_client.async_qdrant_fastembed",
"qdrant_client.qdrant_remote": "qdrant_client.async_qdrant_remote",
"QdrantRemote": "AsyncQdrantRemote",
"ApiClient": "AsyncApiClient",
"SyncApis": "AsyncApis",
"qdrant_client.local.qdrant_local": "qdrant_client.local.async_qdrant_local",
"QdrantLocal": "AsyncQdrantLocal",
},
exclude_methods=[
"__del__",
"migrate",
],
)
modified_code = generator.generate(code)
with open(CODE_DIR / "async_qdrant_client.py", "w") as target_file:
target_file.write(modified_code)
| ClientGenerator |
python | protocolbuffers__protobuf | python/google/protobuf/internal/json_format_test.py | {
"start": 1148,
"end": 3175
} | class ____(unittest.TestCase):
def FillAllFields(self, message):
message.int32_value = 20
message.int64_value = -20
message.uint32_value = 3120987654
message.uint64_value = 12345678900
message.float_value = float('-inf')
message.double_value = 3.1415
message.bool_value = True
message.string_value = 'foo'
message.bytes_value = b'bar'
message.message_value.value = 10
message.enum_value = json_format_proto3_pb2.BAR
# Repeated
message.repeated_int32_value.append(0x7FFFFFFF)
message.repeated_int32_value.append(-2147483648)
message.repeated_int64_value.append(9007199254740992)
message.repeated_int64_value.append(-9007199254740992)
message.repeated_uint32_value.append(0xFFFFFFF)
message.repeated_uint32_value.append(0x7FFFFFF)
message.repeated_uint64_value.append(9007199254740992)
message.repeated_uint64_value.append(9007199254740991)
message.repeated_float_value.append(0)
message.repeated_double_value.append(1e-15)
message.repeated_double_value.append(float('inf'))
message.repeated_bool_value.append(True)
message.repeated_bool_value.append(False)
message.repeated_string_value.append('Few symbols!#$,;')
message.repeated_string_value.append('bar')
message.repeated_bytes_value.append(b'foo')
message.repeated_bytes_value.append(b'bar')
message.repeated_message_value.add().value = 10
message.repeated_message_value.add().value = 11
message.repeated_enum_value.append(json_format_proto3_pb2.FOO)
message.repeated_enum_value.append(json_format_proto3_pb2.BAR)
self.message = message
def CheckParseBack(self, message, parsed_message):
json_format.Parse(json_format.MessageToJson(message), parsed_message)
self.assertEqual(message, parsed_message)
def CheckError(self, text, error_message):
message = json_format_proto3_pb2.TestMessage()
self.assertRaisesRegex(
json_format.ParseError, error_message, json_format.Parse, text, message
)
| JsonFormatBase |
python | tiangolo__fastapi | fastapi/security/oauth2.py | {
"start": 17920,
"end": 21248
} | class ____(OAuth2):
"""
OAuth2 flow for authentication using a bearer token obtained with an OAuth2 code
flow. An instance of it would be used as a dependency.
"""
def __init__(
self,
authorizationUrl: str,
tokenUrl: Annotated[
str,
Doc(
"""
The URL to obtain the OAuth2 token.
"""
),
],
refreshUrl: Annotated[
Optional[str],
Doc(
"""
The URL to refresh the token and obtain a new one.
"""
),
] = None,
scheme_name: Annotated[
Optional[str],
Doc(
"""
Security scheme name.
It will be included in the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
scopes: Annotated[
Optional[Dict[str, str]],
Doc(
"""
The OAuth2 scopes that would be required by the *path operations* that
use this dependency.
"""
),
] = None,
description: Annotated[
Optional[str],
Doc(
"""
Security scheme description.
It will be included in the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
auto_error: Annotated[
bool,
Doc(
"""
By default, if no HTTP Authorization header is provided, required for
OAuth2 authentication, it will automatically cancel the request and
send the client an error.
If `auto_error` is set to `False`, when the HTTP Authorization header
is not available, instead of erroring out, the dependency result will
be `None`.
This is useful when you want to have optional authentication.
It is also useful when you want to have authentication that can be
provided in one of multiple optional ways (for example, with OAuth2
or in a cookie).
"""
),
] = True,
):
if not scopes:
scopes = {}
flows = OAuthFlowsModel(
authorizationCode=cast(
Any,
{
"authorizationUrl": authorizationUrl,
"tokenUrl": tokenUrl,
"refreshUrl": refreshUrl,
"scopes": scopes,
},
)
)
super().__init__(
flows=flows,
scheme_name=scheme_name,
description=description,
auto_error=auto_error,
)
async def __call__(self, request: Request) -> Optional[str]:
authorization = request.headers.get("Authorization")
scheme, param = get_authorization_scheme_param(authorization)
if not authorization or scheme.lower() != "bearer":
if self.auto_error:
raise self.make_not_authenticated_error()
else:
return None # pragma: nocover
return param
| OAuth2AuthorizationCodeBearer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.