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
|
jmcnamara__XlsxWriter
|
xlsxwriter/test/comparison/test_chart_line04.py
|
{
"start": 315,
"end": 1375
}
|
class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_line04.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "line"})
chart.axis_ids = [47670016, 47671552]
data = [
[5, 2, 3, 4, 3],
[10, 4, 6, 8, 6],
[15, 6, 9, 12, 9],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series({"values": "=Sheet1!$A$1:$A$5", "smooth": True})
chart.add_series({"values": "=Sheet1!$B$1:$B$5"})
chart.add_series({"values": "=Sheet1!$C$1:$C$5", "smooth": True})
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
|
TestCompareXLSXFiles
|
python
|
apache__airflow
|
helm-tests/tests/helm_tests/other/test_pgbouncer.py
|
{
"start": 15965,
"end": 24677
}
|
class ____:
"""Tests PgBouncer config."""
def test_config_not_created_by_default(self):
docs = render_chart(
show_only=["templates/secrets/pgbouncer-config-secret.yaml"],
)
assert docs == []
def test_should_add_annotations_to_pgbouncer_config_secret(self):
docs = render_chart(
values={
"pgbouncer": {
"enabled": True,
"configSecretAnnotations": {"test_annotation": "test_annotation_value"},
},
},
show_only=["templates/secrets/pgbouncer-config-secret.yaml"],
)[0]
assert "annotations" in jmespath.search("metadata", docs)
assert jmespath.search("metadata.annotations", docs)["test_annotation"] == "test_annotation_value"
def _get_pgbouncer_ini(self, values: dict) -> str:
docs = render_chart(
values=values,
show_only=["templates/secrets/pgbouncer-config-secret.yaml"],
)
encoded_ini = jmespath.search('data."pgbouncer.ini"', docs[0])
return base64.b64decode(encoded_ini).decode()
def test_databases_default(self):
ini = self._get_pgbouncer_ini({"pgbouncer": {"enabled": True}})
assert (
"release-name-metadata = host=release-name-postgresql.default dbname=postgres port=5432"
" pool_size=10" in ini
)
assert (
"release-name-result-backend = host=release-name-postgresql.default dbname=postgres port=5432"
" pool_size=5" in ini
)
def test_databases_override(self):
values = {
"pgbouncer": {
"enabled": True,
"metadataPoolSize": 12,
"resultBackendPoolSize": 7,
"extraIniMetadata": "reserve_pool = 5",
"extraIniResultBackend": "reserve_pool = 3",
},
"data": {
"metadataConnection": {"host": "meta_host", "db": "meta_db", "port": 1111},
"resultBackendConnection": {
"protocol": "postgresql",
"host": "rb_host",
"user": "someuser",
"pass": "someuser",
"db": "rb_db",
"port": 2222,
"sslmode": "disabled",
},
},
}
ini = self._get_pgbouncer_ini(values)
assert (
"release-name-metadata = host=meta_host dbname=meta_db port=1111 pool_size=12 reserve_pool = 5"
in ini
)
assert (
"release-name-result-backend = host=rb_host dbname=rb_db port=2222 pool_size=7 reserve_pool = 3"
in ini
)
def test_config_defaults(self):
ini = self._get_pgbouncer_ini({"pgbouncer": {"enabled": True}})
assert "listen_port = 6543" in ini
assert "stats_users = postgres" in ini
assert "max_client_conn = 100" in ini
assert "verbose = 0" in ini
assert "log_disconnections = 0" in ini
assert "log_connections = 0" in ini
assert "server_tls_sslmode = prefer" in ini
assert "server_tls_ciphers = normal" in ini
assert "server_tls_ca_file = " not in ini
assert "server_tls_cert_file = " not in ini
assert "server_tls_key_file = " not in ini
def test_config_overrides(self):
values = {
"pgbouncer": {
"enabled": True,
"maxClientConn": 111,
"verbose": 2,
"logDisconnections": 1,
"logConnections": 1,
"sslmode": "verify-full",
"ciphers": "secure",
},
"ports": {"pgbouncer": 7777},
"data": {"metadataConnection": {"user": "someuser"}},
}
ini = self._get_pgbouncer_ini(values)
assert "listen_port = 7777" in ini
assert "stats_users = someuser" in ini
assert "max_client_conn = 111" in ini
assert "verbose = 2" in ini
assert "log_disconnections = 1" in ini
assert "log_connections = 1" in ini
assert "server_tls_sslmode = verify-full" in ini
assert "server_tls_ciphers = secure" in ini
def test_auth_type_file_defaults(self):
values = {
"pgbouncer": {"enabled": True},
"ports": {"pgbouncer": 7777},
"data": {"metadataConnection": {"user": "someuser"}},
}
ini = self._get_pgbouncer_ini(values)
assert "auth_type = scram-sha-256" in ini
assert "auth_file = /etc/pgbouncer/users.txt" in ini
def test_auth_type_file_overrides(self):
values = {
"pgbouncer": {"enabled": True, "auth_type": "any", "auth_file": "/home/auth.txt"},
"ports": {"pgbouncer": 7777},
"data": {"metadataConnection": {"user": "someuser"}},
}
ini = self._get_pgbouncer_ini(values)
assert "auth_type = any" in ini
assert "auth_file = /home/auth.txt" in ini
def test_ssl_defaults_dont_create_cert_secret(self):
docs = render_chart(
values={"pgbouncer": {"enabled": True}},
show_only=["templates/secrets/pgbouncer-certificates-secret.yaml"],
)
assert docs == []
def test_ssl_config(self):
values = {
"pgbouncer": {"enabled": True, "ssl": {"ca": "someca", "cert": "somecert", "key": "somekey"}}
}
ini = self._get_pgbouncer_ini(values)
assert "server_tls_ca_file = /etc/pgbouncer/root.crt" in ini
assert "server_tls_cert_file = /etc/pgbouncer/server.crt" in ini
assert "server_tls_key_file = /etc/pgbouncer/server.key" in ini
docs = render_chart(
values=values,
show_only=["templates/secrets/pgbouncer-certificates-secret.yaml"],
)
for key, expected in [("root.crt", "someca"), ("server.crt", "somecert"), ("server.key", "somekey")]:
encoded = jmespath.search(f'data."{key}"', docs[0])
value = base64.b64decode(encoded).decode()
assert expected == value
def test_should_add_annotations_to_pgbouncer_certificates_secret(self):
docs = render_chart(
values={
"pgbouncer": {
"enabled": True,
"ssl": {"ca": "someca", "cert": "somecert", "key": "somekey"},
"certificatesSecretAnnotations": {"test_annotation": "test_annotation_value"},
},
},
show_only=["templates/secrets/pgbouncer-certificates-secret.yaml"],
)[0]
assert "annotations" in jmespath.search("metadata", docs)
assert jmespath.search("metadata.annotations", docs)["test_annotation"] == "test_annotation_value"
def test_extra_ini_configs(self):
values = {"pgbouncer": {"enabled": True, "extraIni": "server_round_robin = 1\nstats_period = 30"}}
ini = self._get_pgbouncer_ini(values)
assert "server_round_robin = 1" in ini
assert "stats_period = 30" in ini
def test_should_add_custom_env_variables(self):
env1 = {"name": "TEST_ENV_1", "value": "test_env_1"}
docs = render_chart(
values={
"pgbouncer": {
"enabled": True,
"env": [env1],
},
},
show_only=["templates/pgbouncer/pgbouncer-deployment.yaml"],
)[0]
assert jmespath.search("spec.template.spec.containers[0].env", docs) == [env1]
def test_should_add_extra_containers(self):
docs = render_chart(
values={
"pgbouncer": {
"enabled": True,
"extraContainers": [
{"name": "{{ .Chart.Name }}", "image": "test-registry/test-repo:test-tag"}
],
},
},
show_only=["templates/pgbouncer/pgbouncer-deployment.yaml"],
)
assert jmespath.search("spec.template.spec.containers[-1]", docs[0]) == {
"name": "airflow",
"image": "test-registry/test-repo:test-tag",
}
def test_no_config_secret_mount(self):
docs = render_chart(
values={
"pgbouncer": {
"enabled": True,
"mountConfigSecret": False,
},
},
show_only=["templates/pgbouncer/pgbouncer-deployment.yaml"],
)
spec = jmespath.search("spec.template.spec", docs[0])
assert spec is not None
assert "volumes" not in spec
|
TestPgbouncerConfig
|
python
|
getsentry__sentry
|
src/sentry/db/models/fields/array.py
|
{
"start": 400,
"end": 2715
}
|
class ____(models.Field):
def __init__(self, of=models.TextField, **kwargs):
# Arrays in PostgreSQL are arrays of a particular type.
# Save the subtype in our field class.
if isinstance(of, type):
of = of()
self.of = of
# Set "null" to True. Arrays don't have nulls, but null=True
# in the ORM amounts to nothing in SQL (whereas null=False
# corresponds to `NOT NULL`)
kwargs["null"] = True
super().__init__(**kwargs)
def contribute_to_class(self, cls: type[models.Model], name: str, private_only: bool = False):
"""
Add a descriptor for backwards compatibility
with previous Django behavior.
"""
super().contribute_to_class(cls, name, private_only=private_only)
setattr(cls, name, Creator(self))
def db_type(self, connection) -> str:
return f"{self.of.db_type(connection)}[]"
def get_internal_type(self) -> str:
return "TextField"
def get_prep_value(self, value):
"""Iterate over each item in the array, and run it
through the `get_prep_value` of this array's type.
"""
# If no valid value was given, return an empty list.
if not value:
return []
# Appropriately coerce each individual value within
# our array.
return [self.of.get_prep_value(item) for item in value]
def to_python(self, value):
if not value:
value = []
if isinstance(value, str):
try:
value = json.loads(value)
except json.JSONDecodeError:
# This is to accommodate the erroneous exports pre 21.4.0
# See getsentry/sentry#23843 for more details
try:
value = ast.literal_eval(value)
except ValueError:
# this handles old database values using postgresql array format
# see https://sentry.sentry.io/issues/4524783782/
assert value[0] == "{" and value[-1] == "}", "Unexpected ArrayField format"
assert "\\" not in value, "Unexpected ArrayField format"
value = value[1:-1].split(",")
return [self.of.to_python(x) for x in value]
|
ArrayField
|
python
|
pydata__xarray
|
xarray/core/indexing.py
|
{
"start": 14716,
"end": 15331
}
|
class ____:
"""Provide getitem and setitem syntax for callable objects."""
__slots__ = ("getter", "setter")
def __init__(
self, getter: Callable[..., Any], setter: Callable[..., Any] | None = None
):
self.getter = getter
self.setter = setter
def __getitem__(self, key: Any) -> Any:
return self.getter(key)
def __setitem__(self, key: Any, value: Any) -> None:
if self.setter is None:
raise NotImplementedError(
"Setting values is not supported for this indexer."
)
self.setter(key, value)
|
IndexCallable
|
python
|
kamyu104__LeetCode-Solutions
|
Python/minimum-time-difference.py
|
{
"start": 33,
"end": 394
}
|
class ____(object):
def findMinDifference(self, timePoints):
"""
:type timePoints: List[str]
:rtype: int
"""
minutes = map(lambda x: int(x[:2]) * 60 + int(x[3:]), timePoints)
minutes.sort()
return min((y - x) % (24 * 60) \
for x, y in zip(minutes, minutes[1:] + minutes[:1]))
|
Solution
|
python
|
facebook__pyre-check
|
client/configuration/tests/search_path_test.py
|
{
"start": 581,
"end": 9258
}
|
class ____(testslide.TestCase):
def test_create_raw_element(self) -> None:
self.assertEqual(create_raw_element("foo"), SimpleRawElement("foo"))
self.assertEqual(
create_raw_element({"root": "foo", "subdirectory": "bar"}),
SubdirectoryRawElement("foo", "bar"),
)
self.assertEqual(
create_raw_element({"import_root": "foo", "source": "bar"}),
SubdirectoryRawElement("foo", "bar"),
)
self.assertEqual(
create_raw_element({"site-package": "foo"}),
SitePackageRawElement("foo"),
)
self.assertEqual(
create_raw_element({"site-package": "foo"}),
SitePackageRawElement("foo"),
)
self.assertEqual(
create_raw_element(
{"site-package": "foo", "is_toplevel_module": True},
),
SitePackageRawElement("foo", True),
)
with self.assertRaises(InvalidConfiguration):
create_raw_element({})
with self.assertRaises(InvalidConfiguration):
create_raw_element({"foo": "bar"})
with self.assertRaises(InvalidConfiguration):
create_raw_element({"root": "foo"})
with self.assertRaises(InvalidConfiguration):
create_raw_element({"root": 42, "subdirectory": "bar"})
with self.assertRaises(InvalidConfiguration):
create_raw_element({"root": "foo", "subdirectory": []})
with self.assertRaises(InvalidConfiguration):
create_raw_element({"import_root": 4.2, "source": "bar"})
with self.assertRaises(InvalidConfiguration):
create_raw_element({"import_root": "foo", "source": False})
with self.assertRaises(InvalidConfiguration):
create_raw_element({"site-package": {}})
with self.assertRaises(InvalidConfiguration):
create_raw_element(
{"site-package": "foo", "is_toplevel_module": "derp"},
)
def test_path(self) -> None:
self.assertEqual(SimpleElement("foo").path(), "foo")
self.assertEqual(SubdirectoryElement("foo", "bar").path(), "foo/bar")
self.assertEqual(SitePackageElement("foo", "bar").path(), "foo/bar")
def test_command_line_argument(self) -> None:
self.assertEqual(SimpleElement("foo").command_line_argument(), "foo")
self.assertEqual(
SubdirectoryElement("foo", "bar").command_line_argument(),
"foo$bar",
)
self.assertEqual(
SitePackageElement("foo", "bar").command_line_argument(),
"foo$bar",
)
self.assertEqual(
SitePackageElement("foo", "bar", True).command_line_argument(),
"foo$bar.py",
)
def test_expand_global_root(self) -> None:
self.assertEqual(
SimpleRawElement("//simple/path").expand_global_root("root"),
SimpleRawElement("root/simple/path"),
)
self.assertEqual(
SubdirectoryRawElement("//path", "sub").expand_global_root("root"),
SubdirectoryRawElement("root/path", "sub"),
)
self.assertEqual(
SitePackageRawElement("package").expand_global_root("root"),
SitePackageRawElement("package"),
)
def test_expand_relative_root(self) -> None:
self.assertEqual(
SimpleRawElement("simple/path").expand_relative_root("root/local_project"),
SimpleRawElement("root/local_project/simple/path"),
)
self.assertEqual(
SubdirectoryRawElement("path", "sub").expand_relative_root(
"root/local_project"
),
SubdirectoryRawElement("root/local_project/path", "sub"),
)
self.assertEqual(
SitePackageRawElement("package").expand_relative_root("root/local_project"),
SitePackageRawElement("package"),
)
def test_expand_glob(self) -> None:
with tempfile.TemporaryDirectory() as root:
root_path = Path(root)
ensure_directories_exists(root_path, ["a1", "a2", "b"])
search_path = SimpleRawElement(str(root_path / "a*"))
self.assertListEqual(
search_path.expand_glob(),
[
SimpleRawElement(str(root_path / "a1")),
SimpleRawElement(str(root_path / "a2")),
],
)
def test_process_raw_elements_glob(self) -> None:
with tempfile.TemporaryDirectory() as root:
root_path = Path(root).resolve()
ensure_directories_exists(root_path, ["a1", "a2", "b"])
self.assertListEqual(
process_raw_elements(
[SimpleRawElement(str(root_path / "a?"))], site_roots=[]
),
[
SimpleElement(str(root_path / "a1")),
SimpleElement(str(root_path / "a2")),
],
)
def test_process_raw_elements_existence(self) -> None:
with tempfile.TemporaryDirectory() as root:
root_path = Path(root).resolve()
ensure_directories_exists(
root_path, ["a", "b/c", "d/e/f", "venv/lib/pythonX/site-packages"]
)
self.assertListEqual(
process_raw_elements(
[
SimpleRawElement(str(root_path / "a")),
SimpleRawElement(str(root_path / "x")),
SubdirectoryRawElement(
root=str(root_path / "b"), subdirectory="c"
),
SubdirectoryRawElement(
root=str(root_path / "y"), subdirectory="z"
),
SitePackageRawElement(package_name="f"),
SitePackageRawElement(package_name="w"),
],
site_roots=[str(root_path / "d/e"), str(root_path / "u/v")],
required=False,
),
[
SimpleElement(str(root_path / "a")),
SubdirectoryElement(root=str(root_path / "b"), subdirectory="c"),
SitePackageElement(
site_root=str(root_path / "d/e"), package_name="f"
),
],
)
def test_process_raw_elements_site_root_priority(self) -> None:
with tempfile.TemporaryDirectory() as root:
root_path = Path(root).resolve()
ensure_directories_exists(root_path, ["system/foo", "user/foo", "derp"])
self.assertListEqual(
process_raw_elements(
[
SitePackageRawElement(package_name="foo"),
],
site_roots=[
str(root_path / "derp"),
str(root_path / "user"),
str(root_path / "system"),
],
),
[
SitePackageElement(
site_root=str(root_path / "user"), package_name="foo"
),
],
)
def test_process_required_raw_elements_nonexistence(self) -> None:
with self.assertRaises(InvalidConfiguration):
process_raw_elements(
[
SimpleRawElement("/tmp/does-not-exist"),
],
site_roots=[],
required=True,
)
def test_process_required_raw_elements_glob_nonexistence(self) -> None:
with self.assertRaises(InvalidConfiguration):
process_raw_elements(
[
SimpleRawElement("/tmp/does-not-exist/*"),
],
site_roots=[],
required=True,
)
def test_process_required_raw_elements_subdirectory_nonexistence(self) -> None:
with self.assertRaises(InvalidConfiguration):
process_raw_elements(
[
SubdirectoryRawElement(root="/tmp", subdirectory="does-not-exist"),
],
site_roots=[],
required=True,
)
def test_process_required_raw_elements_site_package_nonexistence(self) -> None:
with self.assertRaises(InvalidConfiguration):
process_raw_elements(
[SitePackageRawElement(package_name="f")],
site_roots=[],
required=True,
)
|
SearchPathTest
|
python
|
pytorch__pytorch
|
test/test_cpp_extensions_aot.py
|
{
"start": 10719,
"end": 14464
}
|
class ____(common.TestCase):
def test_unregistered(self):
torch.arange(0, 10, device="cpu")
with self.assertRaisesRegex(RuntimeError, "Could not run"):
torch.arange(0, 10, device="maia")
@skipIfTorchDynamo("dynamo cannot model maia device")
def test_zeros(self):
a = torch.empty(5, 5, device="cpu")
self.assertEqual(a.device, torch.device("cpu"))
b = torch.empty(5, 5, device="maia")
self.assertEqual(b.device, torch.device("maia", 0))
self.assertEqual(maia_extension.get_test_int(), 0)
self.assertEqual(torch.get_default_dtype(), b.dtype)
c = torch.empty((5, 5), dtype=torch.int64, device="maia")
self.assertEqual(maia_extension.get_test_int(), 0)
self.assertEqual(torch.int64, c.dtype)
def test_add(self):
a = torch.empty(5, 5, device="maia", requires_grad=True)
self.assertEqual(maia_extension.get_test_int(), 0)
b = torch.empty(5, 5, device="maia")
self.assertEqual(maia_extension.get_test_int(), 0)
a + b
self.assertEqual(maia_extension.get_test_int(), 1)
def test_conv_backend_override(self):
# To simplify tests, we use 4d input here to avoid doing view4d( which
# needs more overrides) in _convolution.
input = torch.empty(2, 4, 10, 2, device="maia", requires_grad=True)
weight = torch.empty(6, 4, 2, 2, device="maia", requires_grad=True)
bias = torch.empty(6, device="maia")
# Make sure forward is overridden
out = torch.nn.functional.conv2d(input, weight, bias, 2, 0, 1, 1)
self.assertEqual(maia_extension.get_test_int(), 2)
self.assertEqual(out.shape[0], input.shape[0])
self.assertEqual(out.shape[1], weight.shape[0])
# Make sure backward is overridden
# Double backward is dispatched to _convolution_double_backward.
# It is not tested here as it involves more computation/overrides.
grad = torch.autograd.grad(out, input, out, create_graph=True)
self.assertEqual(maia_extension.get_test_int(), 3)
self.assertEqual(grad[0].shape, input.shape)
def test_autocast_apis_for_maia_device(self):
# Default low-precision type in MAIA's autocast.
fast_dtype = torch.get_autocast_dtype("maia")
self.assertEqual(fast_dtype, torch.bfloat16)
self.assertTrue(torch._C._is_autocast_available("maia"))
@skipIfTorchDynamo(
"dynamo cannot handle maia device. Output tensor may have wrong dtype."
)
def test_matmul_autocast_float16_precision(self):
# Ensure we can change low precision dtype.
x = torch.empty((2, 4), dtype=torch.float, device="maia")
w = torch.empty((4, 2), dtype=torch.float, device="maia")
with torch.autocast(device_type="maia", dtype=torch.float16):
self.assertTrue(torch.is_autocast_enabled("maia"))
y = torch.ops.aten.matmul(x, w)
self.assertEqual(y.dtype, torch.float16)
self.assertEqual(y.shape, (2, 2))
@skipIfTorchDynamo(
"dynamo cannot handle maia device. Output tensor may have wrong dtype."
)
def test_matmul_autocast_default_precision(self):
# Use default lower precision dtype, bfloat16.
x = torch.empty((2, 4), dtype=torch.float, device="maia")
w = torch.empty((4, 2), dtype=torch.float, device="maia")
with torch.autocast(device_type="maia"):
self.assertTrue(torch.is_autocast_enabled("maia"))
y = torch.ops.aten.matmul(x, w)
self.assertEqual(y.dtype, torch.bfloat16)
self.assertEqual(y.shape, (2, 2))
@torch.testing._internal.common_utils.markDynamoStrictTest
|
TestMAIATensor
|
python
|
fastai__fastai
|
fastai/data/transforms.py
|
{
"start": 9967,
"end": 11122
}
|
class ____(CollBase):
"Collection of categories with the reverse mapping in `o2i`"
def __init__(self, col, sort=True, add_na=False, strict=False):
if hasattr(col, 'dtype') and isinstance(col.dtype, CategoricalDtype):
items = L(col.cat.categories, use_list=True)
#Remove non-used categories while keeping order
if strict: items = L(o for o in items if o in col.unique())
else:
if not hasattr(col,'unique'): col = L(col, use_list=True)
# `o==o` is the generalized definition of non-NaN used by Pandas
items = L(o for o in col.unique() if o==o)
if sort: items = items.sorted()
self.items = '#na#' + items if add_na else items
self.o2i = defaultdict(int, self.items.val2idx()) if add_na else dict(self.items.val2idx())
def map_objs(self,objs):
"Map `objs` to IDs"
return L(self.o2i[o] for o in objs)
def map_ids(self,ids):
"Map `ids` to objects in vocab"
return L(self.items[o] for o in ids)
def __eq__(self,b): return all_equal(b,self)
# %% ../../nbs/05_data.transforms.ipynb 78
|
CategoryMap
|
python
|
doocs__leetcode
|
solution/0000-0099/0069.Sqrt(x)/Solution.py
|
{
"start": 0,
"end": 247
}
|
class ____:
def mySqrt(self, x: int) -> int:
l, r = 0, x
while l < r:
mid = (l + r + 1) >> 1
if mid > x // mid:
r = mid - 1
else:
l = mid
return l
|
Solution
|
python
|
apache__airflow
|
providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_synapse.py
|
{
"start": 5612,
"end": 15359
}
|
class ____:
@pytest.fixture(autouse=True)
def setup_test_cases(self, create_mock_connection):
self.mock_ti = MagicMock()
self.mock_context = {"ti": self.mock_ti}
self.config = {
"task_id": AZURE_SYNAPSE_PIPELINE_TASK_ID,
"azure_synapse_conn_id": AZURE_SYNAPSE_CONN_ID,
"pipeline_name": PIPELINE_NAME,
"azure_synapse_workspace_dev_endpoint": AZURE_SYNAPSE_WORKSPACE_DEV_ENDPOINT,
"check_interval": 1,
"timeout": 3,
}
create_mock_connection(
Connection(
conn_id=AZURE_SYNAPSE_CONN_ID,
conn_type="azure_synapse_pipeline",
host=AZURE_SYNAPSE_WORKSPACE_URL,
login="client_id",
password="client_secret",
extra=SYNAPSE_PIPELINE_CONN_EXTRAS,
)
)
@staticmethod
def create_pipeline_run(status: str):
"""Helper function to create a mock pipeline run with a given execution status."""
run = MagicMock()
run.status = status
return run
@patch.object(AzureSynapsePipelineHook, "run_pipeline", return_value=MagicMock(**PIPELINE_RUN_RESPONSE))
@pytest.mark.parametrize(
("pipeline_run_status", "expected_output"),
[
(AzureSynapsePipelineRunStatus.SUCCEEDED, None),
(AzureSynapsePipelineRunStatus.FAILED, "exception"),
(AzureSynapsePipelineRunStatus.CANCELLED, "exception"),
(AzureSynapsePipelineRunStatus.IN_PROGRESS, "timeout"),
(AzureSynapsePipelineRunStatus.QUEUED, "timeout"),
(AzureSynapsePipelineRunStatus.CANCELING, "timeout"),
],
)
def test_execute_wait_for_termination(self, mock_run_pipeline, pipeline_run_status, expected_output):
# Initialize the operator with mock config, (**) unpacks the config dict.
operator = AzureSynapseRunPipelineOperator(**self.config)
assert operator.azure_synapse_conn_id == self.config["azure_synapse_conn_id"]
assert operator.pipeline_name == self.config["pipeline_name"]
assert (
operator.azure_synapse_workspace_dev_endpoint
== self.config["azure_synapse_workspace_dev_endpoint"]
)
assert operator.check_interval == self.config["check_interval"]
assert operator.timeout == self.config["timeout"]
assert operator.wait_for_termination
with patch.object(AzureSynapsePipelineHook, "get_pipeline_run") as mock_get_pipeline_run:
mock_get_pipeline_run.return_value = TestAzureSynapseRunPipelineOperator.create_pipeline_run(
pipeline_run_status
)
if not expected_output:
# A successful operator execution should not return any values.
assert not operator.execute(context=self.mock_context)
elif expected_output == "exception":
# The operator should fail if the pipeline run fails or is canceled.
with pytest.raises(
AzureSynapsePipelineRunException,
match=f"Pipeline run {PIPELINE_RUN_RESPONSE['run_id']} has failed or has been cancelled.",
):
operator.execute(context=self.mock_context)
else:
# Demonstrating the operator timing out after surpassing the configured timeout value.
with pytest.raises(
AzureSynapsePipelineRunException,
match=(
f"Pipeline run {PIPELINE_RUN_RESPONSE['run_id']} has not reached a terminal status "
f"after {self.config['timeout']} seconds."
),
):
operator.execute(context=self.mock_context)
# Check the ``run_id`` attr is assigned after executing the pipeline.
assert operator.run_id == PIPELINE_RUN_RESPONSE["run_id"]
# Check to ensure an `XCom` is pushed regardless of pipeline run result.
self.mock_ti.xcom_push.assert_called_once_with(
key="run_id", value=PIPELINE_RUN_RESPONSE["run_id"]
)
# Check if mock_run_pipeline called with particular set of arguments.
mock_run_pipeline.assert_called_once_with(
pipeline_name=self.config["pipeline_name"],
reference_pipeline_run_id=None,
is_recovery=None,
start_activity_name=None,
parameters=None,
)
if pipeline_run_status in AzureSynapsePipelineRunStatus.TERMINAL_STATUSES:
mock_get_pipeline_run.assert_called_once_with(run_id=mock_run_pipeline.return_value.run_id)
else:
# When the pipeline run status is not in a terminal status or "Succeeded", the operator will
# continue to call ``get_pipeline_run()`` until a ``timeout`` number of seconds has passed
# (3 seconds for this test). Therefore, there should be 4 calls of this function: one
# initially and 3 for each check done at a 1 second interval.
assert mock_get_pipeline_run.call_count == 4
mock_get_pipeline_run.assert_called_with(run_id=mock_run_pipeline.return_value.run_id)
@patch.object(AzureSynapsePipelineHook, "run_pipeline", return_value=MagicMock(**PIPELINE_RUN_RESPONSE))
def test_execute_no_wait_for_termination(self, mock_run_pipeline):
operator = AzureSynapseRunPipelineOperator(wait_for_termination=False, **self.config)
assert operator.azure_synapse_conn_id == self.config["azure_synapse_conn_id"]
assert operator.pipeline_name == self.config["pipeline_name"]
assert (
operator.azure_synapse_workspace_dev_endpoint
== self.config["azure_synapse_workspace_dev_endpoint"]
)
assert operator.check_interval == self.config["check_interval"]
assert operator.timeout == self.config["timeout"]
assert not operator.wait_for_termination
with patch.object(
AzureSynapsePipelineHook, "get_pipeline_run", autospec=True
) as mock_get_pipeline_run:
operator.execute(context=self.mock_context)
# Check the ``run_id`` attr is assigned after executing the pipeline.
assert operator.run_id == PIPELINE_RUN_RESPONSE["run_id"]
# Check to ensure an `XCom` is pushed regardless of pipeline run result.
self.mock_ti.xcom_push.assert_called_once_with(
key="run_id", value=PIPELINE_RUN_RESPONSE["run_id"]
)
mock_run_pipeline.assert_called_once_with(
pipeline_name=self.config["pipeline_name"],
reference_pipeline_run_id=None,
is_recovery=None,
start_activity_name=None,
parameters=None,
)
# Checking the pipeline run status should _not_ be called when ``wait_for_termination`` is False.
mock_get_pipeline_run.assert_not_called()
@pytest.mark.db_test
def test_run_pipeline_operator_link(self, create_task_instance_of_operator, mock_supervisor_comms):
ti = create_task_instance_of_operator(
AzureSynapseRunPipelineOperator,
dag_id="test_synapse_run_pipeline_op_link",
task_id=AZURE_SYNAPSE_PIPELINE_TASK_ID,
azure_synapse_conn_id=AZURE_SYNAPSE_CONN_ID,
pipeline_name=PIPELINE_NAME,
azure_synapse_workspace_dev_endpoint=AZURE_SYNAPSE_WORKSPACE_DEV_ENDPOINT,
)
ti.xcom_push(key="run_id", value=PIPELINE_RUN_RESPONSE["run_id"])
if AIRFLOW_V_3_0_PLUS and mock_supervisor_comms:
mock_supervisor_comms.send.return_value = XComResult(
key="run_id",
value=PIPELINE_RUN_RESPONSE["run_id"],
)
url = ti.task.operator_extra_links[0].get_link(operator=ti.task, ti_key=ti.key)
EXPECTED_PIPELINE_RUN_OP_EXTRA_LINK = (
"https://ms.web.azuresynapse.net/en/monitoring/pipelineruns/{run_id}"
"?workspace=%2Fsubscriptions%2F{subscription_id}%2F"
"resourceGroups%2F{resource_group}%2Fproviders%2FMicrosoft.Synapse"
"%2Fworkspaces%2F{workspace_name}"
)
conn = AzureSynapsePipelineHook.get_connection(AZURE_SYNAPSE_CONN_ID)
conn_synapse_workspace_url = conn.host
# Extract the workspace_name, subscription_id and resource_group from the Synapse workspace url.
pipeline_run_object = AzureSynapsePipelineRunLink()
fields = pipeline_run_object.get_fields_from_url(workspace_url=conn_synapse_workspace_url)
assert url == (
EXPECTED_PIPELINE_RUN_OP_EXTRA_LINK.format(
run_id=PIPELINE_RUN_RESPONSE["run_id"],
subscription_id=fields["subscription_id"],
resource_group=fields["resource_group"],
workspace_name=fields["workspace_name"],
)
)
def test_pipeline_operator_link_invalid_uri_pattern(self):
with pytest.raises(ValueError, match="Invalid workspace URL format"):
AzureSynapsePipelineRunLink().get_fields_from_url(workspace_url="https://example.org/")
def test_pipeline_operator_link_invalid_uri_workspace_segments(self):
workspace_url = "https://web.azuresynapse.net?workspace=%2Fsubscriptions%2Fspam-egg"
with pytest.raises(ValueError, match="Workspace expected at least 5 segments"):
AzureSynapsePipelineRunLink().get_fields_from_url(workspace_url=workspace_url)
|
TestAzureSynapseRunPipelineOperator
|
python
|
getsentry__sentry
|
tests/sentry/integrations/api/endpoints/test_organization_integration_details.py
|
{
"start": 3728,
"end": 4942
}
|
class ____(OrganizationIntegrationDetailsTest):
method = "delete"
def test_removal(self) -> None:
self.get_success_response(self.organization.slug, self.integration.id)
assert Integration.objects.filter(id=self.integration.id).exists()
org_integration = OrganizationIntegration.objects.get(
integration=self.integration, organization_id=self.organization.id
)
assert ScheduledDeletion.objects.filter(
model_name="OrganizationIntegration", object_id=org_integration.id
)
def test_delete_disabled_integration(self) -> None:
org_integration = OrganizationIntegration.objects.get(
integration=self.integration, organization_id=self.organization.id
)
org_integration.update(status=ObjectStatus.DISABLED)
self.get_success_response(self.organization.slug, self.integration.id)
assert Integration.objects.filter(id=self.integration.id).exists()
org_integration.refresh_from_db()
assert ScheduledDeletion.objects.filter(
model_name="OrganizationIntegration", object_id=org_integration.id
)
@control_silo_test
|
OrganizationIntegrationDetailsDeleteTest
|
python
|
huggingface__transformers
|
src/transformers/models/mask2former/modeling_mask2former.py
|
{
"start": 94754,
"end": 96647
}
|
class ____(nn.Module):
def __init__(self, hidden_size: int, num_heads: int, mask_feature_size: torch.Tensor):
"""
This class is used to get the predicted mask for a given Mask2FormerMaskedAttentionDecoder layer. It also
generates the binarized attention mask associated with the given predicted mask. The attention mask obtained
using predicted mask of the (l-1)th decoder layer is fed to the cross(masked)-attention block of the next
decoder layer as input.
Args:
hidden_size (`int`):
The feature dimension of the Mask2FormerMaskedAttentionDecoder
num_heads (`int`):
The number of heads used in the Mask2FormerMaskedAttentionDecoder
mask_feature_size (`torch.Tensor`):
one of the output dimensions of the predicted masks for each query
"""
super().__init__()
self.hidden_size = hidden_size
self.num_heads = num_heads
self.mask_embedder = Mask2FormerMLPPredictionHead(self.hidden_size, self.hidden_size, mask_feature_size)
def forward(
self, outputs: torch.Tensor, pixel_embeddings: torch.Tensor, attention_mask_target_size: Optional[int] = None
):
mask_embeddings = self.mask_embedder(outputs.transpose(0, 1))
# Sum up over the channels
outputs_mask = torch.einsum("bqc, bchw -> bqhw", mask_embeddings, pixel_embeddings)
attention_mask = nn.functional.interpolate(
outputs_mask, size=attention_mask_target_size, mode="bilinear", align_corners=False
)
attention_mask = attention_mask.sigmoid().flatten(2).unsqueeze(1).repeat(1, self.num_heads, 1, 1)
attention_mask = (attention_mask.flatten(0, 1) < 0.5).bool()
attention_mask = attention_mask.detach()
return outputs_mask, attention_mask
|
Mask2FormerMaskPredictor
|
python
|
Lightning-AI__lightning
|
src/lightning/fabric/_graveyard/tpu.py
|
{
"start": 3243,
"end": 4355
}
|
class ____(XLABf16Precision):
"""Legacy class.
Use :class:`~lightning.fabric.plugins.precision.xla.XLAPrecision` instead.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
rank_zero_deprecation(
"The `TPUBf16Precision` class is deprecated. Use `lightning.fabric.plugins.precision.XLAPrecision` instead."
)
super().__init__(*args, **kwargs)
def _patch_classes() -> None:
setattr(fabric.strategies, "SingleTPUStrategy", SingleTPUStrategy)
setattr(fabric.accelerators, "TPUAccelerator", TPUAccelerator)
setattr(fabric.plugins, "TPUPrecision", TPUPrecision)
setattr(fabric.plugins.precision, "TPUPrecision", TPUPrecision)
setattr(fabric.plugins, "TPUBf16Precision", TPUBf16Precision)
setattr(fabric.plugins.precision, "TPUBf16Precision", TPUBf16Precision)
setattr(fabric.plugins, "XLABf16Precision", XLABf16Precision)
setattr(fabric.plugins.precision, "XLABf16Precision", XLABf16Precision)
_patch_sys_modules()
_patch_classes()
SingleTPUStrategy.register_strategies(fabric.strategies.STRATEGY_REGISTRY)
|
TPUBf16Precision
|
python
|
python__mypy
|
mypyc/test/test_optimizations.py
|
{
"start": 750,
"end": 1870
}
|
class ____(MypycDataSuite):
"""Base class for IR optimization test suites.
To use this, add a base class and define "files" and "do_optimizations".
"""
base_path = test_temp_dir
def run_case(self, testcase: DataDrivenTestCase) -> None:
with use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase):
expected_output = remove_comment_lines(testcase.output)
try:
ir = build_ir_for_single_file(testcase.input)
except CompileError as e:
actual = e.messages
else:
actual = []
for fn in ir:
if fn.name == TOP_LEVEL_NAME and not testcase.name.endswith("_toplevel"):
continue
insert_uninit_checks(fn)
self.do_optimizations(fn)
actual.extend(format_func(fn))
assert_test_output(testcase, actual, "Invalid source code output", expected_output)
def do_optimizations(self, fn: FuncIR) -> None:
raise NotImplementedError
|
OptimizationSuite
|
python
|
doocs__leetcode
|
solution/3000-3099/3004.Maximum Subtree of the Same Color/Solution.py
|
{
"start": 0,
"end": 684
}
|
class ____:
def maximumSubtreeSize(self, edges: List[List[int]], colors: List[int]) -> int:
def dfs(a: int, fa: int) -> bool:
ok = True
for b in g[a]:
if b != fa:
t = dfs(b, a)
ok = ok and colors[a] == colors[b] and t
size[a] += size[b]
if ok:
nonlocal ans
ans = max(ans, size[a])
return ok
n = len(edges) + 1
g = [[] for _ in range(n)]
size = [1] * n
for a, b in edges:
g[a].append(b)
g[b].append(a)
ans = 0
dfs(0, -1)
return ans
|
Solution
|
python
|
keras-team__keras
|
keras/src/utils/file_utils_test.py
|
{
"start": 28691,
"end": 29106
}
|
class ____(test_case.TestCase):
def test_raise_if_no_gfile_raises_correct_message(self):
path = "gs://bucket/some/file.txt"
expected_error_msg = (
"Handling remote paths requires installing TensorFlow "
f".*Received path: {path}"
)
with self.assertRaisesRegex(ValueError, expected_error_msg):
file_utils._raise_if_no_gfile(path)
|
TestRaiseIfNoGFile
|
python
|
altair-viz__altair
|
altair/vegalite/v6/schema/core.py
|
{
"start": 991244,
"end": 991445
}
|
class ____(VegaLiteSchema):
"""ProjectionType schema wrapper."""
_schema = {"$ref": "#/definitions/ProjectionType"}
def __init__(self, *args):
super().__init__(*args)
|
ProjectionType
|
python
|
getsentry__sentry
|
tests/sentry/db/models/fields/test_picklefield.py
|
{
"start": 106,
"end": 1327
}
|
class ____(models.Model):
id = models.AutoField(primary_key=True)
data = picklefield.PickledObjectField()
class Meta:
app_label = "fixtures"
@pytest.mark.django_db
def test_json_by_default() -> None:
obj = JsonWritingPickleModel.objects.create(
data={"foo": "bar2"},
)
obj = JsonWritingPickleModel.objects.get(id=obj.id)
assert obj.data == {"foo": "bar2"}
with connection.cursor() as cur:
cur.execute("select * from fixtures_jsonwritingpicklemodel where id = %s", [obj.id])
row = cur.fetchone()
# should be JSON
assert row[1] == '{"foo":"bar2"}'
# put some pickle there
cur.execute(
"update fixtures_jsonwritingpicklemodel set data = %s where id = %s",
["gAJ9cQBYAwAAAGZvb3EBWAMAAABiYXJxAnMu", obj.id],
)
# we observe the update as pickle
obj = JsonWritingPickleModel.objects.get(id=obj.id)
assert obj.data == {"foo": "bar"}
def test_to_python_int() -> None:
obj = picklefield.PickledObjectField()
assert obj.to_python(9) == 9
def test_to_python_bool() -> None:
obj = picklefield.PickledObjectField()
assert obj.to_python(True) is True
|
JsonWritingPickleModel
|
python
|
python-openxml__python-docx
|
src/docx/oxml/xmlchemy.py
|
{
"start": 23582,
"end": 25458
}
|
class ____(etree.ElementBase, metaclass=MetaOxmlElement):
"""Effective base class for all custom element classes.
Adds standardized behavior to all classes in one place.
"""
def __repr__(self):
return "<%s '<%s>' at 0x%0x>" % (
self.__class__.__name__,
self._nsptag,
id(self),
)
def first_child_found_in(self, *tagnames: str) -> _Element | None:
"""First child with tag in `tagnames`, or None if not found."""
for tagname in tagnames:
child = self.find(qn(tagname))
if child is not None:
return child
return None
def insert_element_before(self, elm: ElementBase, *tagnames: str):
successor = self.first_child_found_in(*tagnames)
if successor is not None:
successor.addprevious(elm)
else:
self.append(elm)
return elm
def remove_all(self, *tagnames: str) -> None:
"""Remove child elements with tagname (e.g. "a:p") in `tagnames`."""
for tagname in tagnames:
matching = self.findall(qn(tagname))
for child in matching:
self.remove(child)
@property
def xml(self) -> str:
"""XML string for this element, suitable for testing purposes.
Pretty printed for readability and without an XML declaration at the top.
"""
return serialize_for_reading(self)
def xpath(self, xpath_str: str) -> Any: # pyright: ignore[reportIncompatibleMethodOverride]
"""Override of `lxml` _Element.xpath() method.
Provides standard Open XML namespace mapping (`nsmap`) in centralized location.
"""
return super().xpath(xpath_str, namespaces=nsmap)
@property
def _nsptag(self) -> str:
return NamespacePrefixedTag.from_clark_name(self.tag)
|
BaseOxmlElement
|
python
|
ipython__ipython
|
IPython/testing/plugin/pytest_ipdoctest.py
|
{
"start": 16667,
"end": 19883
}
|
class ____(pytest.Module):
obj = None
def collect(self) -> Iterable[IPDoctestItem]:
import doctest
from .ipdoctest import IPDocTestParser
# Inspired by doctest.testfile; ideally we would use it directly,
# but it doesn't support passing a custom checker.
encoding = self.config.getini("ipdoctest_encoding")
text = self.path.read_text(encoding)
filename = str(self.path)
name = self.path.name
globs = {"__name__": "__main__"}
optionflags = get_optionflags(self)
runner = _get_runner(
verbose=False,
optionflags=optionflags,
checker=_get_checker(),
continue_on_failure=_get_continue_on_failure(self.config),
)
parser = IPDocTestParser()
test = parser.get_doctest(text, globs, name, filename, 0)
if test.examples:
yield IPDoctestItem.from_parent(
self, name=test.name, runner=runner, dtest=test
)
if pytest_version[0] < 7:
@property
def path(self) -> Path:
return Path(self.fspath)
@classmethod
def from_parent(
cls,
parent,
*,
fspath=None,
path: Optional[Path] = None,
**kw,
):
if path is not None:
import py.path
fspath = py.path.local(path)
return super().from_parent(parent=parent, fspath=fspath, **kw)
def _check_all_skipped(test: "doctest.DocTest") -> None:
"""Raise pytest.skip() if all examples in the given DocTest have the SKIP
option set."""
import doctest
all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples)
if all_skipped:
pytest.skip("all docstests skipped by +SKIP option")
def _is_mocked(obj: object) -> bool:
"""Return if an object is possibly a mock object by checking the
existence of a highly improbable attribute."""
return (
safe_getattr(obj, "pytest_mock_example_attribute_that_shouldnt_exist", None)
is not None
)
@contextmanager
def _patch_unwrap_mock_aware() -> Generator[None, None, None]:
"""Context manager which replaces ``inspect.unwrap`` with a version
that's aware of mock objects and doesn't recurse into them."""
real_unwrap = inspect.unwrap
def _mock_aware_unwrap(
func: Callable[..., Any], *, stop: Optional[Callable[[Any], Any]] = None
) -> Any:
try:
if stop is None or stop is _is_mocked:
return real_unwrap(func, stop=_is_mocked)
_stop = stop
return real_unwrap(func, stop=lambda obj: _is_mocked(obj) or _stop(func))
except Exception as e:
warnings.warn(
"Got %r when unwrapping %r. This is usually caused "
"by a violation of Python's object protocol; see e.g. "
"https://github.com/pytest-dev/pytest/issues/5080" % (e, func),
PytestWarning,
)
raise
inspect.unwrap = _mock_aware_unwrap
try:
yield
finally:
inspect.unwrap = real_unwrap
|
IPDoctestTextfile
|
python
|
numba__numba
|
numba/core/types/npytypes.py
|
{
"start": 8955,
"end": 9442
}
|
class ____(SimpleIteratorType):
"""
Type class for `np.ndenumerate()` objects.
"""
def __init__(self, arrty):
from . import Tuple, UniTuple, intp
self.array_type = arrty
yield_type = Tuple((UniTuple(intp, arrty.ndim), arrty.dtype))
name = "ndenumerate({arrayty})".format(arrayty=arrty)
super(NumpyNdEnumerateType, self).__init__(name, yield_type)
@property
def key(self):
return self.array_type
|
NumpyNdEnumerateType
|
python
|
airbytehq__airbyte
|
airbyte-integrations/connectors/source-s3/source_s3/source_files_abstract/source.py
|
{
"start": 1083,
"end": 5112
}
|
class ____(AbstractSource, ABC):
@property
@abstractmethod
def stream_class(self) -> type:
"""
:return: reference to the relevant FileStream class e.g. IncrementalFileStreamS3
"""
@property
@abstractmethod
def spec_class(self) -> type:
"""
:return: reference to the relevant pydantic spec class e.g. SourceS3Spec
"""
@property
@abstractmethod
def documentation_url(self) -> str:
"""
:return: link to docs page for this source e.g. "https://docs.airbyte.com/integrations/sources/s3"
"""
def check_connection(self, logger: logging.Logger, config: Mapping[str, Any]) -> Tuple[bool, Optional[Any]]:
"""
This method checks two things:
- That the credentials provided in config are valid for access.
- That the path pattern(s) provided in config are valid to be matched against.
:param logger: an instance of logging.Logger to use
:param config: The user-provided configuration as specified by the source's spec.
This usually contains information required to check connection e.g. tokens, secrets and keys etc.
:return: A tuple of (boolean, error). If boolean is true, then the connection check is successful, and we can connect to the underlying data
source using the provided configuration.
Otherwise, the input config cannot be used to connect to the underlying data source, and the "error" object should describe what went wrong.
The error object will be cast to string to display the problem to the user.
"""
try:
stream = self.stream_class.with_minimal_block_size(config)
stream.fileformatparser_class(stream._format)._validate_config(config)
for file_info in stream.filepath_iterator():
# TODO: will need to split config.get("path_pattern") up by stream once supporting multiple streams
# test that matching on the pattern doesn't error
globmatch(file_info.key, config.get("path_pattern"), flags=GLOBSTAR | SPLIT)
# just need first file here to test connection and valid patterns
break
slice_ = next(stream.stream_slices(sync_mode=SyncMode.full_refresh), None)
if slice_:
next(stream.read_records(sync_mode=SyncMode.full_refresh, stream_slice=slice_), None)
except Exception as e:
logger.error(format_exc())
return False, e
return True, None
def streams(self, config: Mapping[str, Any]) -> List[Stream]:
"""
We just have a single stream per source so construct that here
:param config: The user-provided configuration as specified by the source's spec.
:return: A list of the streams in this source connector.
"""
return [self.stream_class(**config)]
def spec(self, *args: Any, **kwargs: Any) -> ConnectorSpecification:
"""
Returns the spec for this integration. The spec is a JSON-Schema object describing the required configurations (e.g: username and password)
required to run this integration.
"""
# make dummy instance of stream_class in order to get 'supports_incremental' property
incremental = self.stream_class(dataset="", provider={}, format="", path_pattern="").supports_incremental
supported_dest_sync_modes = [DestinationSyncMode.overwrite]
if incremental:
supported_dest_sync_modes.extend([DestinationSyncMode.append, DestinationSyncMode.append_dedup])
return ConnectorSpecification(
documentationUrl=self.documentation_url,
changelogUrl=self.documentation_url,
supportsIncremental=incremental,
supported_destination_sync_modes=supported_dest_sync_modes,
connectionSpecification=self.spec_class.schema(), # type: ignore[attr-defined]
)
|
SourceFilesAbstract
|
python
|
altair-viz__altair
|
altair/vegalite/v6/schema/channels.py
|
{
"start": 1100259,
"end": 1109910
}
|
class ____(FieldChannelMixin, core.SecondaryFieldDef):
r"""
Y2 schema wrapper.
A field definition of a secondary channel that shares a scale with another primary channel.
For example, ``x2``, ``xError`` and ``xError2`` share the same scale with ``x``.
Parameters
----------
shorthand : str, dict, Sequence[str], :class:`RepeatRef`
shorthand for field, aggregate, and type
aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :class:`NonArgAggregateOp`, Literal['average', 'count', 'distinct', 'max', 'mean', 'median', 'min', 'missing', 'product', 'q1', 'q3', 'ci0', 'ci1', 'stderr', 'stdev', 'stdevp', 'sum', 'valid', 'values', 'variance', 'variancep', 'exponential', 'exponentialb']
Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``,
``"min"``, ``"max"``, ``"count"``).
**Default value:** ``undefined`` (None)
**See also:** `aggregate <https://vega.github.io/vega-lite/docs/aggregate.html>`__
documentation.
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned at the beginning of the band if set to ``0``,
and at the middle of the band if set to ``0.5``.
bin : None
A flag for binning a ``quantitative`` field, `an object defining binning parameters
<https://vega.github.io/vega-lite/docs/bin.html#bin-parameters>`__, or indicating
that the data for ``x`` or ``y`` channel are binned before they are imported into
Vega-Lite (``"binned"``).
* If ``true``, default `binning parameters
<https://vega.github.io/vega-lite/docs/bin.html#bin-parameters>`__ will be
applied.
* If ``"binned"``, this indicates that the data for the ``x`` (or ``y``) channel are
already binned. You can map the bin-start field to ``x`` (or ``y``) and the
bin-end field to ``x2`` (or ``y2``). The scale and axis will be formatted similar
to binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can
also set the axis's `tickMinStep
<https://vega.github.io/vega-lite/docs/axis.html#ticks>`__ property.
**Default value:** ``false``
**See also:** `bin <https://vega.github.io/vega-lite/docs/bin.html>`__
documentation.
field : str, dict, :class:`Field`, :class:`FieldName`, :class:`RepeatRef`
**Required.** A string defining the name of the field from which to pull a data
value or an object defining iterated values from the `repeat
<https://vega.github.io/vega-lite/docs/repeat.html>`__ operator.
**See also:** `field <https://vega.github.io/vega-lite/docs/field.html>`__
documentation.
**Notes:** 1) Dots (``.``) and brackets (``[`` and ``]``) can be used to access
nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"``). If
field names contain dots or brackets but are not nested, you can use ``\\`` to
escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"``). See more details
about escaping in the `field documentation
<https://vega.github.io/vega-lite/docs/field.html>`__. 2) ``field`` is not required
if ``aggregate`` is ``count``.
timeUnit : dict, :class:`TimeUnit`, :class:`MultiTimeUnit`, :class:`BinnedTimeUnit`, :class:`SingleTimeUnit`, :class:`TimeUnitParams`, :class:`UtcMultiTimeUnit`, :class:`UtcSingleTimeUnit`, :class:`LocalMultiTimeUnit`, :class:`LocalSingleTimeUnit`, Literal['binnedyear', 'binnedyearquarter', 'binnedyearquartermonth', 'binnedyearmonth', 'binnedyearmonthdate', 'binnedyearmonthdatehours', 'binnedyearmonthdatehoursminutes', 'binnedyearmonthdatehoursminutesseconds', 'binnedyearweek', 'binnedyearweekday', 'binnedyearweekdayhours', 'binnedyearweekdayhoursminutes', 'binnedyearweekdayhoursminutesseconds', 'binnedyeardayofyear', 'binnedutcyear', 'binnedutcyearquarter', 'binnedutcyearquartermonth', 'binnedutcyearmonth', 'binnedutcyearmonthdate', 'binnedutcyearmonthdatehours', 'binnedutcyearmonthdatehoursminutes', 'binnedutcyearmonthdatehoursminutesseconds', 'binnedutcyearweek', 'binnedutcyearweekday', 'binnedutcyearweekdayhours', 'binnedutcyearweekdayhoursminutes', 'binnedutcyearweekdayhoursminutesseconds', 'binnedutcyeardayofyear', 'utcyear', 'utcquarter', 'utcmonth', 'utcweek', 'utcday', 'utcdayofyear', 'utcdate', 'utchours', 'utcminutes', 'utcseconds', 'utcmilliseconds', 'year', 'quarter', 'month', 'week', 'day', 'dayofyear', 'date', 'hours', 'minutes', 'seconds', 'milliseconds', 'utcyearquarter', 'utcyearquartermonth', 'utcyearmonth', 'utcyearmonthdate', 'utcyearmonthdatehours', 'utcyearmonthdatehoursminutes', 'utcyearmonthdatehoursminutesseconds', 'utcyearweek', 'utcyearweekday', 'utcyearweekdayhours', 'utcyearweekdayhoursminutes', 'utcyearweekdayhoursminutesseconds', 'utcyeardayofyear', 'utcquartermonth', 'utcmonthdate', 'utcmonthdatehours', 'utcmonthdatehoursminutes', 'utcmonthdatehoursminutesseconds', 'utcweekday', 'utcweekdayhours', 'utcweekdayhoursminutes', 'utcweekdayhoursminutesseconds', 'utcdayhours', 'utcdayhoursminutes', 'utcdayhoursminutesseconds', 'utchoursminutes', 'utchoursminutesseconds', 'utcminutesseconds', 'utcsecondsmilliseconds', 'yearquarter', 'yearquartermonth', 'yearmonth', 'yearmonthdate', 'yearmonthdatehours', 'yearmonthdatehoursminutes', 'yearmonthdatehoursminutesseconds', 'yearweek', 'yearweekday', 'yearweekdayhours', 'yearweekdayhoursminutes', 'yearweekdayhoursminutesseconds', 'yeardayofyear', 'quartermonth', 'monthdate', 'monthdatehours', 'monthdatehoursminutes', 'monthdatehoursminutesseconds', 'weekday', 'weekdayhours', 'weekdayhoursminutes', 'weekdayhoursminutesseconds', 'dayhours', 'dayhoursminutes', 'dayhoursminutesseconds', 'hoursminutes', 'hoursminutesseconds', 'minutesseconds', 'secondsmilliseconds']
Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours``) for a temporal
field. or `a temporal field that gets casted as ordinal
<https://vega.github.io/vega-lite/docs/type.html#cast>`__.
**Default value:** ``undefined`` (None)
**See also:** `timeUnit <https://vega.github.io/vega-lite/docs/timeunit.html>`__
documentation.
title : str, :class:`Text`, Sequence[str], None
A title for the field. If ``null``, the title will be removed.
**Default value:** derived from the field's name and transformation function
(``aggregate``, ``bin`` and ``timeUnit``). If the field has an aggregate function,
the function is displayed as part of the title (e.g., ``"Sum of Profit"``). If the
field is binned or has a time unit applied, the applied function is shown in
parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"``).
Otherwise, the title is simply the field name.
**Notes**:
1) You can customize the default field title format by providing the `fieldTitle
<https://vega.github.io/vega-lite/docs/config.html#top-level-config>`__ property in
the `config <https://vega.github.io/vega-lite/docs/config.html>`__ or `fieldTitle
function via the compile function's options
<https://vega.github.io/vega-lite/usage/compile.html#field-title>`__.
2) If both field definition's ``title`` and axis, header, or legend ``title`` are
defined, axis/header/legend title will be used.
"""
_class_is_valid_at_instantiation = False
_encoding_name = "y2"
@overload
def aggregate(self, _: NonArgAggregateOp_T, /) -> Y2: ...
@overload
def aggregate(self, *, argmax: Optional[str | SchemaBase] = Undefined) -> Y2: ...
@overload
def aggregate(self, *, argmin: Optional[str | SchemaBase] = Undefined) -> Y2: ...
@overload
def bandPosition(self, _: float, /) -> Y2: ...
@overload
def bin(self, _: None, /) -> Y2: ...
@overload
def field(self, _: str | RepeatRef, /) -> Y2: ...
@overload
def field(
self,
*,
repeat: Optional[Literal["row", "column", "repeat", "layer"]] = Undefined,
) -> Y2: ...
@overload
def timeUnit(
self,
_: TimeUnitParams | MultiTimeUnit_T | BinnedTimeUnit_T | SingleTimeUnit_T,
/,
) -> Y2: ...
@overload
def timeUnit(
self,
*,
binned: Optional[bool] = Undefined,
maxbins: Optional[float] = Undefined,
step: Optional[float] = Undefined,
unit: Optional[SchemaBase | MultiTimeUnit_T | SingleTimeUnit_T] = Undefined,
utc: Optional[bool] = Undefined,
) -> Y2: ...
@overload
def title(self, _: str | Sequence[str] | None, /) -> Y2: ...
def __init__(
self,
shorthand: Optional[str | SchemaBase | Sequence[str] | Map] = Undefined,
aggregate: Optional[SchemaBase | Map | NonArgAggregateOp_T] = Undefined,
bandPosition: Optional[float] = Undefined,
bin: Optional[None] = Undefined,
field: Optional[str | SchemaBase | Map] = Undefined,
timeUnit: Optional[
SchemaBase | Map | MultiTimeUnit_T | BinnedTimeUnit_T | SingleTimeUnit_T
] = Undefined,
title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined,
**kwds,
):
super().__init__(
shorthand=shorthand,
aggregate=aggregate,
bandPosition=bandPosition,
bin=bin,
field=field,
timeUnit=timeUnit,
title=title,
**kwds,
)
@with_property_setters
|
Y2
|
python
|
mlflow__mlflow
|
mlflow/lightgbm/__init__.py
|
{
"start": 16565,
"end": 36743
}
|
class ____:
def __init__(self, lgb_model):
self.lgb_model = lgb_model
def get_raw_model(self):
"""
Returns the underlying model.
"""
return self.lgb_model
def predict(self, dataframe, params: dict[str, Any] | None = None):
"""
Args:
dataframe: Model input data.
params: Additional parameters to pass to the model for inference.
Returns:
Model predictions.
"""
return self.lgb_model.predict(dataframe)
def _patch_metric_names(metric_dict):
# lightgbm provides some metrics with "@", e.g. "ndcg@3" that are not valid MLflow metric names
patched_metrics = {
metric_name.replace("@", "_at_"): value for metric_name, value in metric_dict.items()
}
if changed_keys := set(patched_metrics.keys()) - set(metric_dict.keys()):
_logger.info(
"Identified one or more metrics with names containing the invalid character `@`."
" These metric names have been sanitized by replacing `@` with `_at_`, as follows: %s",
", ".join(changed_keys),
)
return patched_metrics
def _autolog_callback(env, metrics_logger, eval_results):
res = {}
for data_name, eval_name, value, _ in env.evaluation_result_list:
key = data_name + "-" + eval_name
res[key] = value
res = _patch_metric_names(res)
metrics_logger.record_metrics(res, env.iteration)
eval_results.append(res)
@autologging_integration(FLAVOR_NAME)
def autolog(
log_input_examples=False,
log_model_signatures=True,
log_models=True,
log_datasets=True,
disable=False,
exclusive=False,
disable_for_unsupported_versions=False,
silent=False,
registered_model_name=None,
extra_tags=None,
):
"""
Enables (or disables) and configures autologging from LightGBM to MLflow. Logs the following:
- parameters specified in `lightgbm.train`_.
- metrics on each iteration (if ``valid_sets`` specified).
- metrics at the best iteration (if ``early_stopping_rounds`` specified or
``early_stopping`` callback is set).
- feature importance (both "split" and "gain") as JSON files and plots.
- trained model, including:
- an example of valid input.
- inferred signature of the inputs and outputs of the model.
Note that the `scikit-learn API`_ is now supported.
Args:
log_input_examples: If ``True``, input examples from training datasets are collected and
logged along with LightGBM model artifacts during training. If
``False``, input examples are not logged.
Note: Input examples are MLflow model attributes
and are only collected if ``log_models`` is also ``True``.
log_model_signatures: If ``True``,
:py:class:`ModelSignatures <mlflow.models.ModelSignature>`
describing model inputs and outputs are collected and logged along
with LightGBM model artifacts during training. If ``False``,
signatures are not logged.
Note: Model signatures are MLflow model attributes
and are only collected if ``log_models`` is also ``True``.
log_models: If ``True``, trained models are logged as MLflow model artifacts.
If ``False``, trained models are not logged.
Input examples and model signatures, which are attributes of MLflow models,
are also omitted when ``log_models`` is ``False``.
log_datasets: If ``True``, train and validation dataset information is logged to MLflow
Tracking if applicable. If ``False``, dataset information is not logged.
disable: If ``True``, disables the LightGBM autologging integration. If ``False``,
enables the LightGBM autologging integration.
exclusive: If ``True``, autologged content is not logged to user-created fluent runs.
If ``False``, autologged content is logged to the active fluent run,
which may be user-created.
disable_for_unsupported_versions: If ``True``, disable autologging for versions of
lightgbm that have not been tested against this version of the MLflow client
or are incompatible.
silent: If ``True``, suppress all event logs and warnings from MLflow during LightGBM
autologging. If ``False``, show all events and warnings during LightGBM
autologging.
registered_model_name: If given, each time a model is trained, it is registered as a
new model version of the registered model with this name.
The registered model is created if it does not already exist.
extra_tags: A dictionary of extra tags to set on each managed run created by autologging.
.. code-block:: python
:caption: Example
import mlflow
from lightgbm import LGBMClassifier
from sklearn import datasets
def print_auto_logged_info(run):
tags = {k: v for k, v in run.data.tags.items() if not k.startswith("mlflow.")}
artifacts = [
f.path for f in mlflow.MlflowClient().list_artifacts(run.info.run_id, "model")
]
feature_importances = [
f.path
for f in mlflow.MlflowClient().list_artifacts(run.info.run_id)
if f.path != "model"
]
print(f"run_id: {run.info.run_id}")
print(f"artifacts: {artifacts}")
print(f"feature_importances: {feature_importances}")
print(f"params: {run.data.params}")
print(f"metrics: {run.data.metrics}")
print(f"tags: {tags}")
# Load iris dataset
X, y = datasets.load_iris(return_X_y=True, as_frame=True)
# Initialize our model
model = LGBMClassifier(objective="multiclass", random_state=42)
# Auto log all MLflow entities
mlflow.lightgbm.autolog()
# Train the model
with mlflow.start_run() as run:
model.fit(X, y)
# fetch the auto logged parameters and metrics
print_auto_logged_info(mlflow.get_run(run_id=run.info.run_id))
.. code-block:: text
:caption: Output
run_id: e08dd59d57a74971b68cf78a724dfaf6
artifacts: ['model/MLmodel',
'model/conda.yaml',
'model/model.pkl',
'model/python_env.yaml',
'model/requirements.txt']
feature_importances: ['feature_importance_gain.json',
'feature_importance_gain.png',
'feature_importance_split.json',
'feature_importance_split.png']
params: {'boosting_type': 'gbdt',
'categorical_feature': 'auto',
'colsample_bytree': '1.0',
...
'verbose_eval': 'warn'}
metrics: {}
tags: {}
"""
import lightgbm
import numpy as np
# Patching this function so we can get a copy of the data given to Dataset.__init__
# to use as an input example and for inferring the model signature.
# (there is no way to get the data back from a Dataset object once it is consumed by train)
# We store it on the Dataset object so the train function is able to read it.
def __init__(original, self, *args, **kwargs):
data = args[0] if len(args) > 0 else kwargs.get("data")
if data is not None:
try:
if isinstance(data, str):
raise Exception(
"cannot gather example input when dataset is loaded from a file."
)
input_example_info = InputExampleInfo(
input_example=deepcopy(data[:INPUT_EXAMPLE_SAMPLE_ROWS])
)
except Exception as e:
input_example_info = InputExampleInfo(error_msg=str(e))
self.input_example_info = input_example_info
original(self, *args, **kwargs)
def train_impl(_log_models, _log_datasets, original, *args, **kwargs):
def record_eval_results(eval_results, metrics_logger):
"""
Create a callback function that records evaluation results.
"""
return picklable_exception_safe_function(
functools.partial(
_autolog_callback, metrics_logger=metrics_logger, eval_results=eval_results
)
)
def log_feature_importance_plot(features, importance, importance_type):
"""
Log feature importance plot.
"""
import matplotlib.pyplot as plt
indices = np.argsort(importance)
features = np.array(features)[indices]
importance = importance[indices]
num_features = len(features)
# If num_features > 10, increase the figure height to prevent the plot
# from being too dense.
w, h = [6.4, 4.8] # matplotlib's default figure size
h = h + 0.1 * num_features if num_features > 10 else h
fig, ax = plt.subplots(figsize=(w, h))
yloc = np.arange(num_features)
ax.barh(yloc, importance, align="center", height=0.5)
ax.set_yticks(yloc)
ax.set_yticklabels(features)
ax.set_xlabel("Importance")
ax.set_title(f"Feature Importance ({importance_type})")
fig.tight_layout()
with tempfile.TemporaryDirectory() as tmpdir:
try:
filepath = os.path.join(tmpdir, f"feature_importance_{imp_type}.png")
fig.savefig(filepath)
mlflow.log_artifact(filepath)
finally:
plt.close(fig)
autologging_client = MlflowAutologgingQueueingClient()
# logging booster params separately via mlflow.log_params to extract key/value pairs
# and make it easier to compare them across runs.
booster_params = args[0] if len(args) > 0 else kwargs["params"]
autologging_client.log_params(run_id=mlflow.active_run().info.run_id, params=booster_params)
unlogged_params = [
"params",
"train_set",
"valid_sets",
"valid_names",
"fobj",
"feval",
"init_model",
"learning_rates",
"callbacks",
]
if Version(lightgbm.__version__) <= Version("3.3.1"):
# The parameter `evals_result` in `lightgbm.train` is removed in this PR:
# https://github.com/microsoft/LightGBM/pull/4882
unlogged_params.append("evals_result")
params_to_log_for_fn = get_mlflow_run_params_for_fn_args(
original, args, kwargs, unlogged_params
)
autologging_client.log_params(
run_id=mlflow.active_run().info.run_id, params=params_to_log_for_fn
)
param_logging_operations = autologging_client.flush(synchronous=False)
all_arg_names = _get_arg_names(original)
num_pos_args = len(args)
# adding a callback that records evaluation results.
eval_results = []
callbacks_index = all_arg_names.index("callbacks")
run_id = mlflow.active_run().info.run_id
train_set = args[1] if len(args) > 1 else kwargs.get("train_set")
# Whether to automatically log the training dataset as a dataset artifact.
if _log_datasets and train_set:
try:
context_tags = context_registry.resolve_tags()
source = CodeDatasetSource(tags=context_tags)
_log_lightgbm_dataset(train_set, source, "train", autologging_client)
valid_sets = kwargs.get("valid_sets")
if valid_sets is not None:
valid_names = kwargs.get("valid_names")
if valid_names is None:
for valid_set in valid_sets:
_log_lightgbm_dataset(valid_set, source, "eval", autologging_client)
else:
for valid_set, valid_name in zip(valid_sets, valid_names):
_log_lightgbm_dataset(
valid_set, source, "eval", autologging_client, name=valid_name
)
dataset_logging_operations = autologging_client.flush(synchronous=False)
dataset_logging_operations.await_completion()
except Exception as e:
_logger.warning(
"Failed to log dataset information to MLflow Tracking. Reason: %s", e
)
model_id = None
if _log_models:
model_id = _initialize_logged_model("model", flavor=FLAVOR_NAME).model_id
with batch_metrics_logger(run_id, model_id=model_id) as metrics_logger:
callback = record_eval_results(eval_results, metrics_logger)
if num_pos_args >= callbacks_index + 1:
tmp_list = list(args)
tmp_list[callbacks_index] += [callback]
args = tuple(tmp_list)
elif "callbacks" in kwargs and kwargs["callbacks"] is not None:
kwargs["callbacks"] += [callback]
else:
kwargs["callbacks"] = [callback]
# training model
model = original(*args, **kwargs)
# If early stopping is activated, logging metrics at the best iteration
# as extra metrics with the max step + 1.
early_stopping = model.best_iteration > 0
if early_stopping:
extra_step = len(eval_results)
autologging_client.log_metrics(
run_id=mlflow.active_run().info.run_id,
metrics={
"stopped_iteration": extra_step,
# best_iteration is set even if training does not stop early.
"best_iteration": model.best_iteration,
},
model_id=model_id,
)
# iteration starts from 1 in LightGBM.
last_iter_results = eval_results[model.best_iteration - 1]
autologging_client.log_metrics(
run_id=mlflow.active_run().info.run_id,
metrics=last_iter_results,
step=extra_step,
model_id=model_id,
)
early_stopping_logging_operations = autologging_client.flush(synchronous=False)
# logging feature importance as artifacts.
for imp_type in ["split", "gain"]:
features = model.feature_name()
importance = model.feature_importance(importance_type=imp_type)
try:
log_feature_importance_plot(features, importance, imp_type)
except Exception:
_logger.exception(
"Failed to log feature importance plot. LightGBM autologging "
"will ignore the failure and continue. Exception: "
)
imp = dict(zip(features, importance.tolist()))
with tempfile.TemporaryDirectory() as tmpdir:
filepath = os.path.join(tmpdir, f"feature_importance_{imp_type}.json")
with open(filepath, "w") as f:
json.dump(imp, f, indent=2)
mlflow.log_artifact(filepath)
# train_set must exist as the original train function already ran successfully
# it is possible that the dataset was constructed before the patched
# constructor was applied, so we cannot assume the input_example_info exists
input_example_info = getattr(train_set, "input_example_info", None)
def get_input_example():
if input_example_info is None:
raise Exception(ENSURE_AUTOLOGGING_ENABLED_TEXT)
if input_example_info.error_msg is not None:
raise Exception(input_example_info.error_msg)
return input_example_info.input_example
def infer_model_signature(input_example):
model_output = model.predict(input_example)
return infer_signature(input_example, model_output)
# Whether to automatically log the trained model based on boolean flag.
if _log_models:
# Will only resolve `input_example` and `signature` if `log_models` is `True`.
input_example, signature = resolve_input_example_and_signature(
get_input_example,
infer_model_signature,
log_input_examples,
log_model_signatures,
_logger,
)
log_model(
model,
"model",
signature=signature,
input_example=input_example,
registered_model_name=registered_model_name,
model_id=model_id,
)
param_logging_operations.await_completion()
if early_stopping:
early_stopping_logging_operations.await_completion()
return model
def train(_log_models, _log_datasets, original, *args, **kwargs):
with _SklearnTrainingSession(estimator=lightgbm.train, allow_children=False) as t:
if t.should_log():
return train_impl(_log_models, _log_datasets, original, *args, **kwargs)
else:
return original(*args, **kwargs)
safe_patch(FLAVOR_NAME, lightgbm.Dataset, "__init__", __init__)
safe_patch(
FLAVOR_NAME,
lightgbm,
"train",
functools.partial(train, log_models, log_datasets),
manage_run=True,
extra_tags=extra_tags,
)
# The `train()` method logs LightGBM models as Booster objects. When using LightGBM
# scikit-learn models, we want to save / log models as their model classes. So we turn
# off the log_models functionality in the `train()` method patched to `lightgbm.sklearn`.
# Instead the model logging is handled in `fit_mlflow_xgboost_and_lightgbm()`
# in `mlflow.sklearn._autolog()`, where models are logged as LightGBM scikit-learn models
# after the `fit()` method returns.
safe_patch(
FLAVOR_NAME,
lightgbm.sklearn,
"train",
functools.partial(train, False, log_datasets),
manage_run=True,
extra_tags=extra_tags,
)
# enable LightGBM scikit-learn estimators autologging
import mlflow.sklearn
mlflow.sklearn._autolog(
flavor_name=FLAVOR_NAME,
log_input_examples=log_input_examples,
log_model_signatures=log_model_signatures,
log_models=log_models,
log_datasets=log_datasets,
disable=disable,
exclusive=exclusive,
disable_for_unsupported_versions=disable_for_unsupported_versions,
silent=silent,
max_tuning_runs=None,
log_post_training_metrics=True,
extra_tags=extra_tags,
)
def _log_lightgbm_dataset(lgb_dataset, source, context, autologging_client, name=None):
import numpy as np
import pandas as pd
from scipy.sparse import issparse
data = lgb_dataset.data
label = lgb_dataset.label
if isinstance(data, pd.DataFrame):
dataset = from_pandas(df=data, source=source, name=name)
elif issparse(data):
arr_data = data.toarray() if issparse(data) else data
dataset = from_numpy(features=arr_data, targets=label, source=source, name=name)
elif isinstance(data, np.ndarray):
dataset = from_numpy(features=data, targets=label, source=source, name=name)
else:
_logger.warning("Unrecognized dataset type %s. Dataset logging skipped.", type(data))
return
tags = [InputTag(key=MLFLOW_DATASET_CONTEXT, value=context)]
dataset_input = DatasetInput(dataset=dataset._to_mlflow_entity(), tags=tags)
# log the dataset
autologging_client.log_inputs(run_id=mlflow.active_run().info.run_id, datasets=[dataset_input])
|
_LGBModelWrapper
|
python
|
pydantic__pydantic
|
pydantic/v1/errors.py
|
{
"start": 14996,
"end": 15129
}
|
class ____(PydanticTypeError):
code = 'int_enum_instance'
msg_template = '{value} is not a valid IntEnum instance'
|
IntEnumError
|
python
|
pytest-dev__pytest
|
src/_pytest/capture.py
|
{
"start": 12927,
"end": 13413
}
|
class ____(SysCaptureBase[str]):
EMPTY_BUFFER = ""
def snap(self) -> str:
self._assert_state("snap", ("started", "suspended"))
assert isinstance(self.tmpfile, CaptureIO)
res = self.tmpfile.getvalue()
self.tmpfile.seek(0)
self.tmpfile.truncate()
return res
def writeorg(self, data: str) -> None:
self._assert_state("writeorg", ("started", "suspended"))
self._old.write(data)
self._old.flush()
|
SysCapture
|
python
|
scipy__scipy
|
scipy/stats/_distribution_infrastructure.py
|
{
"start": 24414,
"end": 32129
}
|
class ____(ABC):
r""" Representation of a distribution parameter or variable.
A `_Parameter` object is responsible for storing information about a
parameter or variable, providing input validation/standardization of
values passed for that parameter, providing a text/mathematical
representation of the parameter for the documentation (`__str__`), and
drawing random values of itself for testing and benchmarking. It does
not provide a complete implementation of this functionality and is meant
for subclassing.
Attributes
----------
name : str
The keyword used to pass numerical values of the parameter into the
initializer of the distribution
symbol : str
The text representation of the variable in the documentation. May
include LaTeX.
domain : _Domain
The domain of the parameter for which the distribution is valid.
typical : 2-tuple of floats or strings (consider making a _Domain)
Defines the endpoints of a typical range of values of the parameter.
Used for sampling.
Methods
-------
__str__():
Returns a string description of the variable for use in documentation,
including the keyword used to represent it in code, the symbol used to
represent it mathemtatically, and a description of the valid domain.
draw(size, *, rng, domain, proportions)
Draws random values of the parameter. Proportions of values within
the valid domain, on the endpoints of the domain, outside the domain,
and having value NaN are specified by `proportions`.
validate(x):
Validates and standardizes the argument for use as numerical values
of the parameter.
"""
# generic type compatibility with scipy-stubs
__class_getitem__ = classmethod(GenericAlias)
def __init__(self, name, *, domain, symbol=None, typical=None):
self.name = name
self.symbol = symbol or name
self.domain = domain
if typical is not None and not isinstance(typical, _Domain):
typical = domain.__class__(typical)
self.typical = typical or domain
def __str__(self):
r""" String representation of the parameter for use in documentation."""
return f"`{self.name}` for :math:`{self.symbol} \\in {str(self.domain)}`"
def draw(self, size=None, *, rng=None, region='domain', proportions=None,
parameter_values=None):
r""" Draw random values of the parameter for use in testing.
Parameters
----------
size : tuple of ints
The shape of the array of valid values to be drawn.
rng : np.Generator
The Generator used for drawing random values.
region : str
The region of the `_Parameter` from which to draw. Default is
"domain" (the *full* domain); alternative is "typical". An
enhancement would give a way to interpolate between the two.
proportions : tuple of numbers
A tuple of four non-negative numbers that indicate the expected
relative proportion of elements that:
- are strictly within the domain,
- are at one of the two endpoints,
- are strictly outside the domain, and
- are NaN,
respectively. Default is (1, 0, 0, 0). The number of elements in
each category is drawn from the multinomial distribution with
`np.prod(size)` as the number of trials and `proportions` as the
event probabilities. The values in `proportions` are automatically
normalized to sum to 1.
parameter_values : dict
Map between the names of parameters (that define the endpoints of
`typical`) and numerical values (arrays).
"""
parameter_values = parameter_values or {}
domain = self.domain
proportions = (1, 0, 0, 0) if proportions is None else proportions
pvals = proportions / np.sum(proportions)
a, b = domain.get_numerical_endpoints(parameter_values)
a, b = np.broadcast_arrays(a, b)
base_shape = a.shape
extended_shape = np.broadcast_shapes(size, base_shape)
n_extended = np.prod(extended_shape)
n_base = np.prod(base_shape)
n = int(n_extended / n_base) if n_extended else 0
rng = np.random.default_rng(rng)
n_in, n_on, n_out, n_nan = rng.multinomial(n, pvals)
# `min` and `max` can have singleton dimensions that correspond with
# non-singleton dimensions in `size`. We need to be careful to avoid
# shuffling results (e.g. a value that was generated for the domain
# [min[i], max[i]] ends up at index j). To avoid this:
# - Squeeze the singleton dimensions out of `min`/`max`. Squeezing is
# often not the right thing to do, but here is equivalent to moving
# all the dimensions that are singleton in `min`/`max` (which may be
# non-singleton in the result) to the left. This is what we want.
# - Now all the non-singleton dimensions of the result are on the left.
# Ravel them to a single dimension of length `n`, which is now along
# the 0th axis.
# - Reshape the 0th axis back to the required dimensions, and move
# these axes back to their original places.
base_shape_padded = ((1,)*(len(extended_shape) - len(base_shape))
+ base_shape)
base_singletons = np.where(np.asarray(base_shape_padded)==1)[0]
new_base_singletons = tuple(range(len(base_singletons)))
# Base singleton dimensions are going to get expanded to these lengths
shape_expansion = np.asarray(extended_shape)[base_singletons]
# assert(np.prod(shape_expansion) == n) # check understanding
# min = np.reshape(min, base_shape_padded)
# max = np.reshape(max, base_shape_padded)
# min = np.moveaxis(min, base_singletons, new_base_singletons)
# max = np.moveaxis(max, base_singletons, new_base_singletons)
# squeezed_base_shape = max.shape[len(base_singletons):]
# assert np.all(min.reshape(squeezed_base_shape) == min.squeeze())
# assert np.all(max.reshape(squeezed_base_shape) == max.squeeze())
# min = np.maximum(a, _fiinfo(a).min/10) if np.any(np.isinf(a)) else a
# max = np.minimum(b, _fiinfo(b).max/10) if np.any(np.isinf(b)) else b
min = np.asarray(a.squeeze())
max = np.asarray(b.squeeze())
squeezed_base_shape = max.shape
if region == 'typical':
typical = self.typical
a, b = typical.get_numerical_endpoints(parameter_values)
a, b = np.broadcast_arrays(a, b)
min_here = np.asarray(a.squeeze())
max_here = np.asarray(b.squeeze())
z_in = typical.draw(n_in, 'in', min_here, max_here, squeezed_base_shape,
rng=rng)
else:
z_in = domain.draw(n_in, 'in', min, max, squeezed_base_shape, rng=rng)
z_on = domain.draw(n_on, 'on', min, max, squeezed_base_shape, rng=rng)
z_out = domain.draw(n_out, 'out', min, max, squeezed_base_shape, rng=rng)
z_nan= domain.draw(n_nan, 'nan', min, max, squeezed_base_shape, rng=rng)
z = np.concatenate((z_in, z_on, z_out, z_nan), axis=0)
z = rng.permuted(z, axis=0)
z = np.reshape(z, tuple(shape_expansion) + squeezed_base_shape)
z = np.moveaxis(z, new_base_singletons, base_singletons)
return z
@abstractmethod
def validate(self, arr):
raise NotImplementedError()
|
_Parameter
|
python
|
chroma-core__chroma
|
chromadb/db/mixins/embeddings_queue.py
|
{
"start": 1365,
"end": 19325
}
|
class ____(SqlDB, Producer, Consumer):
"""A SQL database that stores embeddings, allowing a traditional RDBMS to be used as
the primary ingest queue and satisfying the top level Producer/Consumer interfaces.
Note that this class is only suitable for use cases where the producer and consumer
are in the same process.
This is because notification of new embeddings happens solely in-process: this
implementation does not actively listen to the the database for new records added by
other processes.
"""
class Subscription:
id: UUID
topic_name: str
start: int
end: int
callback: ConsumerCallbackFn
def __init__(
self,
id: UUID,
topic_name: str,
start: int,
end: int,
callback: ConsumerCallbackFn,
):
self.id = id
self.topic_name = topic_name
self.start = start
self.end = end
self.callback = callback
_subscriptions: Dict[str, Set[Subscription]]
_max_batch_size: Optional[int]
_tenant: str
_topic_namespace: str
# How many variables are in the insert statement for a single record
VARIABLES_PER_RECORD = 6
def __init__(self, system: System):
self._subscriptions = defaultdict(set)
self._max_batch_size = None
self._opentelemetry_client = system.require(OpenTelemetryClient)
self._tenant = system.settings.require("tenant_id")
self._topic_namespace = system.settings.require("topic_namespace")
super().__init__(system)
@trace_method("SqlEmbeddingsQueue.reset_state", OpenTelemetryGranularity.ALL)
@override
def reset_state(self) -> None:
super().reset_state()
self._subscriptions = defaultdict(set)
# Invalidate the cached property
try:
del self.config
except AttributeError:
# Cached property hasn't been accessed yet
pass
@trace_method("SqlEmbeddingsQueue.delete_topic", OpenTelemetryGranularity.ALL)
@override
def delete_log(self, collection_id: UUID) -> None:
topic_name = create_topic_name(
self._tenant, self._topic_namespace, collection_id
)
t = Table("embeddings_queue")
q = (
self.querybuilder()
.from_(t)
.where(t.topic == ParameterValue(topic_name))
.delete()
)
with self.tx() as cur:
sql, params = get_sql(q, self.parameter_format())
cur.execute(sql, params)
@trace_method("SqlEmbeddingsQueue.purge_log", OpenTelemetryGranularity.ALL)
@override
def purge_log(self, collection_id: UUID) -> None:
# (We need to purge on a per topic/collection basis, because the maximum sequence ID is tracked on a per topic/collection basis.)
segments_t = Table("segments")
segment_ids_q = (
self.querybuilder()
.from_(segments_t)
# This coalesce prevents a correctness bug when > 1 segments exist and:
# - > 1 has written to the max_seq_id table
# - > 1 has not never written to the max_seq_id table
# In that case, we should not delete any WAL entries as we can't be sure that the all segments are caught up.
.select(functions.Coalesce(Table("max_seq_id").seq_id, -1))
.where(
segments_t.collection == ParameterValue(self.uuid_to_db(collection_id))
)
.left_join(Table("max_seq_id"))
.on(segments_t.id == Table("max_seq_id").segment_id)
)
topic_name = create_topic_name(
self._tenant, self._topic_namespace, collection_id
)
with self.tx() as cur:
sql, params = get_sql(segment_ids_q, self.parameter_format())
cur.execute(sql, params)
results = cur.fetchall()
if results:
min_seq_id = min(row[0] for row in results)
else:
return
t = Table("embeddings_queue")
q = (
self.querybuilder()
.from_(t)
.where(t.seq_id < ParameterValue(min_seq_id))
.where(t.topic == ParameterValue(topic_name))
.delete()
)
sql, params = get_sql(q, self.parameter_format())
cur.execute(sql, params)
@trace_method("SqlEmbeddingsQueue.submit_embedding", OpenTelemetryGranularity.ALL)
@override
def submit_embedding(
self, collection_id: UUID, embedding: OperationRecord
) -> SeqId:
if not self._running:
raise RuntimeError("Component not running")
return self.submit_embeddings(collection_id, [embedding])[0]
@trace_method("SqlEmbeddingsQueue.submit_embeddings", OpenTelemetryGranularity.ALL)
@override
def submit_embeddings(
self, collection_id: UUID, embeddings: Sequence[OperationRecord]
) -> Sequence[SeqId]:
if not self._running:
raise RuntimeError("Component not running")
if len(embeddings) == 0:
return []
if len(embeddings) > self.max_batch_size:
raise BatchSizeExceededError(
f"""
Cannot submit more than {self.max_batch_size:,} embeddings at once.
Please submit your embeddings in batches of size
{self.max_batch_size:,} or less.
"""
)
# This creates the persisted configuration if it doesn't exist.
# It should be run as soon as possible (before any WAL mutations) since the default configuration depends on the WAL size.
# (We can't run this in __init__()/start() because the migrations have not been run at that point and the table may not be available.)
_ = self.config
topic_name = create_topic_name(
self._tenant, self._topic_namespace, collection_id
)
t = Table("embeddings_queue")
insert = (
self.querybuilder()
.into(t)
.columns(t.operation, t.topic, t.id, t.vector, t.encoding, t.metadata)
)
id_to_idx: Dict[str, int] = {}
for embedding in embeddings:
(
embedding_bytes,
encoding,
metadata,
) = self._prepare_vector_encoding_metadata(embedding)
insert = insert.insert(
ParameterValue(_operation_codes[embedding["operation"]]),
ParameterValue(topic_name),
ParameterValue(embedding["id"]),
ParameterValue(embedding_bytes),
ParameterValue(encoding),
ParameterValue(metadata),
)
id_to_idx[embedding["id"]] = len(id_to_idx)
with self.tx() as cur:
sql, params = get_sql(insert, self.parameter_format())
# The returning clause does not guarantee order, so we need to do reorder
# the results. https://www.sqlite.org/lang_returning.html
sql = f"{sql} RETURNING seq_id, id" # Pypika doesn't support RETURNING
results = cur.execute(sql, params).fetchall()
# Reorder the results
seq_ids = [cast(SeqId, None)] * len(
results
) # Lie to mypy: https://stackoverflow.com/questions/76694215/python-type-casting-when-preallocating-list
embedding_records = []
for seq_id, id in results:
seq_ids[id_to_idx[id]] = seq_id
submit_embedding_record = embeddings[id_to_idx[id]]
# We allow notifying consumers out of order relative to one call to
# submit_embeddings so we do not reorder the records before submitting them
embedding_record = LogRecord(
log_offset=seq_id,
record=OperationRecord(
id=id,
embedding=submit_embedding_record["embedding"],
encoding=submit_embedding_record["encoding"],
metadata=submit_embedding_record["metadata"],
operation=submit_embedding_record["operation"],
),
)
embedding_records.append(embedding_record)
self._notify_all(topic_name, embedding_records)
if self.config.get_parameter("automatically_purge").value:
self.purge_log(collection_id)
return seq_ids
@trace_method("SqlEmbeddingsQueue.subscribe", OpenTelemetryGranularity.ALL)
@override
def subscribe(
self,
collection_id: UUID,
consume_fn: ConsumerCallbackFn,
start: Optional[SeqId] = None,
end: Optional[SeqId] = None,
id: Optional[UUID] = None,
) -> UUID:
if not self._running:
raise RuntimeError("Component not running")
topic_name = create_topic_name(
self._tenant, self._topic_namespace, collection_id
)
subscription_id = id or uuid.uuid4()
start, end = self._validate_range(start, end)
subscription = self.Subscription(
subscription_id, topic_name, start, end, consume_fn
)
# Backfill first, so if it errors we do not add the subscription
self._backfill(subscription)
self._subscriptions[topic_name].add(subscription)
return subscription_id
@trace_method("SqlEmbeddingsQueue.unsubscribe", OpenTelemetryGranularity.ALL)
@override
def unsubscribe(self, subscription_id: UUID) -> None:
for topic_name, subscriptions in self._subscriptions.items():
for subscription in subscriptions:
if subscription.id == subscription_id:
subscriptions.remove(subscription)
if len(subscriptions) == 0:
del self._subscriptions[topic_name]
return
@override
def min_seqid(self) -> SeqId:
return -1
@override
def max_seqid(self) -> SeqId:
return 2**63 - 1
@property
@trace_method("SqlEmbeddingsQueue.max_batch_size", OpenTelemetryGranularity.ALL)
@override
def max_batch_size(self) -> int:
if self._max_batch_size is None:
with self.tx() as cur:
cur.execute("PRAGMA compile_options;")
compile_options = cur.fetchall()
for option in compile_options:
if "MAX_VARIABLE_NUMBER" in option[0]:
# The pragma returns a string like 'MAX_VARIABLE_NUMBER=999'
self._max_batch_size = int(option[0].split("=")[1]) // (
self.VARIABLES_PER_RECORD
)
if self._max_batch_size is None:
# This value is the default for sqlite3 versions < 3.32.0
# It is the safest value to use if we can't find the pragma for some
# reason
self._max_batch_size = 999 // self.VARIABLES_PER_RECORD
return self._max_batch_size
@trace_method(
"SqlEmbeddingsQueue._prepare_vector_encoding_metadata",
OpenTelemetryGranularity.ALL,
)
def _prepare_vector_encoding_metadata(
self, embedding: OperationRecord
) -> Tuple[Optional[bytes], Optional[str], Optional[str]]:
if embedding["embedding"] is not None:
encoding_type = cast(ScalarEncoding, embedding["encoding"])
encoding = encoding_type.value
embedding_bytes = encode_vector(embedding["embedding"], encoding_type)
else:
embedding_bytes = None
encoding = None
metadata = json.dumps(embedding["metadata"]) if embedding["metadata"] else None
return embedding_bytes, encoding, metadata
@trace_method("SqlEmbeddingsQueue._backfill", OpenTelemetryGranularity.ALL)
def _backfill(self, subscription: Subscription) -> None:
"""Backfill the given subscription with any currently matching records in the
DB"""
t = Table("embeddings_queue")
q = (
self.querybuilder()
.from_(t)
.where(t.topic == ParameterValue(subscription.topic_name))
.where(t.seq_id > ParameterValue(subscription.start))
.where(t.seq_id <= ParameterValue(subscription.end))
.select(t.seq_id, t.operation, t.id, t.vector, t.encoding, t.metadata)
.orderby(t.seq_id)
)
with self.tx() as cur:
sql, params = get_sql(q, self.parameter_format())
cur.execute(sql, params)
rows = cur.fetchall()
for row in rows:
if row[3]:
encoding = ScalarEncoding(row[4])
vector = decode_vector(row[3], encoding)
else:
encoding = None
vector = None
self._notify_one(
subscription,
[
LogRecord(
log_offset=row[0],
record=OperationRecord(
operation=_operation_codes_inv[row[1]],
id=row[2],
embedding=vector,
encoding=encoding,
metadata=json.loads(row[5]) if row[5] else None,
),
)
],
)
@trace_method("SqlEmbeddingsQueue._validate_range", OpenTelemetryGranularity.ALL)
def _validate_range(
self, start: Optional[SeqId], end: Optional[SeqId]
) -> Tuple[int, int]:
"""Validate and normalize the start and end SeqIDs for a subscription using this
impl."""
start = start or self._next_seq_id()
end = end or self.max_seqid()
if not isinstance(start, int) or not isinstance(end, int):
raise TypeError("SeqIDs must be integers for sql-based EmbeddingsDB")
if start >= end:
raise ValueError(f"Invalid SeqID range: {start} to {end}")
return start, end
@trace_method("SqlEmbeddingsQueue._next_seq_id", OpenTelemetryGranularity.ALL)
def _next_seq_id(self) -> int:
"""Get the next SeqID for this database."""
t = Table("embeddings_queue")
q = self.querybuilder().from_(t).select(functions.Max(t.seq_id))
with self.tx() as cur:
cur.execute(q.get_sql())
return int(cur.fetchone()[0]) + 1
@trace_method("SqlEmbeddingsQueue._notify_all", OpenTelemetryGranularity.ALL)
def _notify_all(self, topic: str, embeddings: Sequence[LogRecord]) -> None:
"""Send a notification to each subscriber of the given topic."""
if self._running:
for sub in self._subscriptions[topic]:
self._notify_one(sub, embeddings)
@trace_method("SqlEmbeddingsQueue._notify_one", OpenTelemetryGranularity.ALL)
def _notify_one(self, sub: Subscription, embeddings: Sequence[LogRecord]) -> None:
"""Send a notification to a single subscriber."""
# Filter out any embeddings that are not in the subscription range
should_unsubscribe = False
filtered_embeddings = []
for embedding in embeddings:
if embedding["log_offset"] <= sub.start:
continue
if embedding["log_offset"] > sub.end:
should_unsubscribe = True
break
filtered_embeddings.append(embedding)
# Log errors instead of throwing them to preserve async semantics
# for consistency between local and distributed configurations
try:
if len(filtered_embeddings) > 0:
sub.callback(filtered_embeddings)
if should_unsubscribe:
self.unsubscribe(sub.id)
except BaseException as e:
logger.error(
f"Exception occurred invoking consumer for subscription {sub.id.hex}"
+ f"to topic {sub.topic_name} %s",
str(e),
)
if _called_from_test:
raise e
@cached_property
def config(self) -> EmbeddingsQueueConfigurationInternal:
t = Table("embeddings_queue_config")
q = self.querybuilder().from_(t).select(t.config_json_str).limit(1)
with self.tx() as cur:
cur.execute(q.get_sql())
result = cur.fetchone()
if result is None:
is_fresh_system = self._get_wal_size() == 0
config = EmbeddingsQueueConfigurationInternal(
[ConfigurationParameter("automatically_purge", is_fresh_system)]
)
self.set_config(config)
return config
return EmbeddingsQueueConfigurationInternal.from_json_str(result[0])
def set_config(self, config: EmbeddingsQueueConfigurationInternal) -> None:
with self.tx() as cur:
cur.execute(
"""
INSERT OR REPLACE INTO embeddings_queue_config (id, config_json_str)
VALUES (?, ?)
""",
(
1,
config.to_json_str(),
),
)
# Invalidate the cached property
try:
del self.config
except AttributeError:
# Cached property hasn't been accessed yet
pass
def _get_wal_size(self) -> int:
t = Table("embeddings_queue")
q = self.querybuilder().from_(t).select(functions.Count("*"))
with self.tx() as cur:
cur.execute(q.get_sql())
return int(cur.fetchone()[0])
|
SqlEmbeddingsQueue
|
python
|
pypa__warehouse
|
tests/unit/accounts/test_views.py
|
{
"start": 109933,
"end": 116242
}
|
class ____:
@pytest.mark.parametrize(
("is_primary", "confirm_message"),
[
(True, "This is your primary address."),
(False, "You can now set this email as your primary address."),
],
)
def test_verify_email(
self, mocker, db_request, ratelimit_service, is_primary, confirm_message
):
user = UserFactory(is_active=False, totp_secret=None)
email = EmailFactory(user=user, verified=False, primary=is_primary)
db_request.user = user
db_request.GET.update({"token": "RANDOM_KEY"})
db_request.route_path = mocker.Mock(return_value="/")
mock_token_service_loads = mocker.patch(
"warehouse.accounts.services.TokenService.loads",
return_value={"action": "email-verify", "email.id": str(email.id)},
)
spy_find_service = mocker.spy(db_request, "find_service")
spy_session_flash = mocker.spy(db_request.session, "flash")
result = views.verify_email(db_request)
db_request.db.flush()
assert email.verified
assert email.domain_last_status == ["active"]
assert user.is_active
assert isinstance(result, HTTPSeeOther)
assert result.headers["Location"] == "/"
db_request.route_path.assert_called_once_with("manage.account.two-factor")
mock_token_service_loads.assert_called_once_with("RANDOM_KEY")
ratelimit_service.clear.assert_has_calls(
[
mocker.call(db_request.remote_addr),
mocker.call(user.id),
]
)
spy_session_flash.assert_called_once_with(
f"Email address {email.email} verified. " + confirm_message, queue="success"
)
spy_find_service.assert_has_calls(
[
mocker.call(ITokenService, name="email"),
mocker.call(IRateLimiter, name="email.add"),
mocker.call(IRateLimiter, name="email.verify"),
mocker.call(IDomainStatusService),
]
)
@pytest.mark.parametrize(
("exception", "message"),
[
(TokenInvalid, "Invalid token: request a new email verification link"),
(TokenExpired, "Expired token: request a new email verification link"),
(TokenMissing, "Invalid token: no token supplied"),
],
)
def test_verify_email_loads_failure(self, pyramid_request, exception, message):
def loads(token):
raise exception
pyramid_request.find_service = lambda *a, **kw: pretend.stub(loads=loads)
pyramid_request.params = {"token": "RANDOM_KEY"}
pyramid_request.route_path = pretend.call_recorder(lambda name: "/")
pyramid_request.session.flash = pretend.call_recorder(lambda *a, **kw: None)
views.verify_email(pyramid_request)
assert pyramid_request.route_path.calls == [pretend.call("manage.account")]
assert pyramid_request.session.flash.calls == [
pretend.call(message, queue="error")
]
def test_verify_email_invalid_action(self, pyramid_request):
data = {"action": "invalid-action"}
pyramid_request.find_service = lambda *a, **kw: pretend.stub(
loads=lambda a: data
)
pyramid_request.params = {"token": "RANDOM_KEY"}
pyramid_request.route_path = pretend.call_recorder(lambda name: "/")
pyramid_request.session.flash = pretend.call_recorder(lambda *a, **kw: None)
views.verify_email(pyramid_request)
assert pyramid_request.route_path.calls == [pretend.call("manage.account")]
assert pyramid_request.session.flash.calls == [
pretend.call(
"Invalid token: not an email verification token", queue="error"
)
]
def test_verify_email_not_found(self, pyramid_request):
data = {"action": "email-verify", "email.id": "invalid"}
pyramid_request.find_service = lambda *a, **kw: pretend.stub(
loads=lambda a: data
)
pyramid_request.params = {"token": "RANDOM_KEY"}
pyramid_request.route_path = pretend.call_recorder(lambda name: "/")
pyramid_request.session.flash = pretend.call_recorder(lambda *a, **kw: None)
def raise_no_result(*a):
raise NoResultFound
pyramid_request.db = pretend.stub(query=raise_no_result)
views.verify_email(pyramid_request)
assert pyramid_request.route_path.calls == [pretend.call("manage.account")]
assert pyramid_request.session.flash.calls == [
pretend.call("Email not found", queue="error")
]
def test_verify_email_already_verified(self, db_request):
user = UserFactory()
email = EmailFactory(user=user, verified=True)
data = {"action": "email-verify", "email.id": email.id}
db_request.user = user
db_request.find_service = lambda *a, **kw: pretend.stub(loads=lambda a: data)
db_request.params = {"token": "RANDOM_KEY"}
db_request.route_path = pretend.call_recorder(lambda name: "/")
db_request.session.flash = pretend.call_recorder(lambda *a, **kw: None)
views.verify_email(db_request)
assert db_request.route_path.calls == [pretend.call("manage.account")]
assert db_request.session.flash.calls == [
pretend.call("Email already verified", queue="error")
]
def test_verify_email_with_existing_2fa(self, mocker, db_request):
user = UserFactory(is_active=False, totp_secret=b"secret")
email = EmailFactory(user=user, verified=False, primary=False)
db_request.user = user
db_request.GET.update({"token": "RANDOM_KEY"})
db_request.route_path = mocker.Mock(return_value="/")
mocker.patch(
"warehouse.accounts.services.TokenService.loads",
return_value={"action": "email-verify", "email.id": str(email.id)},
)
assert db_request.user.has_two_factor
result = views.verify_email(db_request)
assert isinstance(result, HTTPSeeOther)
assert result.headers["Location"] == "/"
db_request.route_path.assert_called_once_with("manage.account")
assert db_request.user.is_active
|
TestVerifyEmail
|
python
|
microsoft__pyright
|
packages/pyright-internal/src/tests/samples/slice1.py
|
{
"start": 53,
"end": 381
}
|
class ____:
def __getitem__[T](self, item: T) -> T:
return item
a1 = ClassA()
reveal_type(a1[::], expected_text="slice[None, None, None]")
reveal_type(
a1[1:"a":False], expected_text="slice[Literal[1], Literal['a'], Literal[False]]"
)
reveal_type(a1[:3:5.0], expected_text="slice[None, Literal[3], float]")
|
ClassA
|
python
|
ray-project__ray
|
python/ray/tune/tests/test_convergence.py
|
{
"start": 318,
"end": 4412
}
|
class ____(unittest.TestCase):
"""Test convergence in gaussian process."""
@classmethod
def setUpClass(cls) -> None:
ray.init(local_mode=False, num_cpus=1, num_gpus=0)
@classmethod
def tearDownClass(cls) -> None:
ray.shutdown()
def _testConvergence(self, searcher, top=3, patience=20):
# This is the space of parameters to explore
space = {"x": tune.uniform(0, 20)}
resources_per_trial = {"cpu": 1, "gpu": 0}
analysis = tune.run(
loss,
metric="loss",
mode="min",
stop=ExperimentPlateauStopper(metric="loss", top=top, patience=patience),
search_alg=searcher,
config=space,
num_samples=max(100, patience), # Number of iterations
resources_per_trial=resources_per_trial,
raise_on_failed_trial=False,
fail_fast=True,
reuse_actors=True,
verbose=1,
)
print(
f"Num trials: {len(analysis.trials)}. "
f"Best result: {analysis.best_config['x']}"
)
return analysis
@unittest.skip("ax warm start tests currently failing (need to upgrade ax)")
def testConvergenceAx(self):
from ray.tune.search.ax import AxSearch
np.random.seed(0)
searcher = AxSearch()
analysis = self._testConvergence(searcher, patience=10)
assert math.isclose(analysis.best_config["x"], 0, abs_tol=1e-5)
def testConvergenceBayesOpt(self):
from ray.tune.search.bayesopt import BayesOptSearch
np.random.seed(0)
# Following bayesian optimization
searcher = BayesOptSearch(random_search_steps=10)
searcher.repeat_float_precision = 5
searcher = ConcurrencyLimiter(searcher, 1)
analysis = self._testConvergence(searcher, patience=100)
assert len(analysis.trials) < 50
assert math.isclose(analysis.best_config["x"], 0, abs_tol=1e-5)
@pytest.mark.skipif(
sys.version_info >= (3, 12), reason="HEBO doesn't support py312"
)
def testConvergenceHEBO(self):
from ray.tune.search.hebo import HEBOSearch
np.random.seed(0)
searcher = HEBOSearch()
analysis = self._testConvergence(searcher)
assert len(analysis.trials) < 100
assert math.isclose(analysis.best_config["x"], 0, abs_tol=1e-2)
def testConvergenceHyperopt(self):
from ray.tune.search.hyperopt import HyperOptSearch
np.random.seed(0)
searcher = HyperOptSearch(random_state_seed=1234)
analysis = self._testConvergence(searcher, patience=50, top=5)
assert math.isclose(analysis.best_config["x"], 0, abs_tol=1e-2)
def testConvergenceNevergrad(self):
import nevergrad as ng
from ray.tune.search.nevergrad import NevergradSearch
np.random.seed(0)
searcher = NevergradSearch(optimizer=ng.optimizers.PSO)
analysis = self._testConvergence(searcher, patience=50, top=5)
assert math.isclose(analysis.best_config["x"], 0, abs_tol=1e-3)
def testConvergenceOptuna(self):
from ray.tune.search.optuna import OptunaSearch
np.random.seed(1)
searcher = OptunaSearch(seed=1)
analysis = self._testConvergence(
searcher,
top=5,
)
# This assertion is much weaker than in the BO case, but TPE
# don't converge too close. It is still unlikely to get to this
# tolerance with random search (5 * 0.1 = 0.5% chance)
assert len(analysis.trials) < 100
assert math.isclose(analysis.best_config["x"], 0, abs_tol=1e-1)
def testConvergenceZoopt(self):
from ray.tune.search.zoopt import ZOOptSearch
np.random.seed(0)
searcher = ZOOptSearch(budget=100)
analysis = self._testConvergence(searcher)
assert len(analysis.trials) < 100
assert math.isclose(analysis.best_config["x"], 0, abs_tol=1e-3)
if __name__ == "__main__":
sys.exit(pytest.main(["-v", __file__]))
|
ConvergenceTest
|
python
|
mlflow__mlflow
|
mlflow/utils/import_hooks/__init__.py
|
{
"start": 8631,
"end": 13050
}
|
class ____:
def __init__(self):
self.in_progress = {}
@synchronized(_post_import_hooks_lock)
@synchronized(_import_error_hooks_lock)
def find_module(self, fullname, path=None):
# If the module being imported is not one we have registered
# import hooks for, we can return immediately. We will
# take no further part in the importing of this module.
if fullname not in _post_import_hooks and fullname not in _import_error_hooks:
return None
# When we are interested in a specific module, we will call back
# into the import system a second time to defer to the import
# finder that is supposed to handle the importing of the module.
# We set an in progress flag for the target module so that on
# the second time through we don't trigger another call back
# into the import system and cause a infinite loop.
if fullname in self.in_progress:
return None
self.in_progress[fullname] = True
# Now call back into the import system again.
try:
# For Python 3 we need to use find_spec().loader
# from the importlib.util module. It doesn't actually
# import the target module and only finds the
# loader. If a loader is found, we need to return
# our own loader which will then in turn call the
# real loader to import the module and invoke the
# post import hooks.
try:
import importlib.util # clint: disable=lazy-builtin-import
loader = importlib.util.find_spec(fullname).loader
# If an ImportError (or AttributeError) is encountered while finding the module,
# notify the hooks for import errors
except (ImportError, AttributeError):
notify_module_import_error(fullname)
loader = importlib.find_loader(fullname, path)
if loader:
return _ImportHookChainedLoader(loader)
finally:
del self.in_progress[fullname]
@synchronized(_post_import_hooks_lock)
@synchronized(_import_error_hooks_lock)
def find_spec(self, fullname, path, target=None):
# If the module being imported is not one we have registered
# import hooks for, we can return immediately. We will
# take no further part in the importing of this module.
if fullname not in _post_import_hooks and fullname not in _import_error_hooks:
return None
# When we are interested in a specific module, we will call back
# into the import system a second time to defer to the import
# finder that is supposed to handle the importing of the module.
# We set an in progress flag for the target module so that on
# the second time through we don't trigger another call back
# into the import system and cause a infinite loop.
if fullname in self.in_progress:
return None
self.in_progress[fullname] = True
# Now call back into the import system again.
try:
import importlib.util # clint: disable=lazy-builtin-import
spec = importlib.util.find_spec(fullname)
# Replace the module spec's loader with a wrapped version that executes import
# hooks when the module is loaded
spec.loader = _ImportHookChainedLoader(spec.loader)
return spec
except (ImportError, AttributeError):
notify_module_import_error(fullname)
finally:
del self.in_progress[fullname]
# Decorator for marking that a function should be called as a post
# import hook when the target module is imported.
# If error_handler is True, then apply the marked function as an import hook
# for import errors (instead of successful imports).
# It is assumed that all error hooks are added during driver start-up,
# and thus added prior to any import calls. If an error hook is added
# after a module has already failed the import, there's no guarantee
# that the hook will fire.
def when_imported(name, error_handler=False):
def register(hook):
if error_handler:
register_import_error_hook(hook, name)
else:
register_post_import_hook(hook, name)
return hook
return register
|
ImportHookFinder
|
python
|
pytorch__pytorch
|
torch/_export/serde/schema.py
|
{
"start": 9479,
"end": 9602
}
|
class ____:
arg: Annotated[TensorArgument, 10]
user_input_name: Annotated[str, 20]
@dataclass
|
GradientToUserInputSpec
|
python
|
doocs__leetcode
|
solution/1000-1099/1002.Find Common Characters/Solution.py
|
{
"start": 0,
"end": 262
}
|
class ____:
def commonChars(self, words: List[str]) -> List[str]:
cnt = Counter(words[0])
for w in words:
t = Counter(w)
for c in cnt:
cnt[c] = min(cnt[c], t[c])
return list(cnt.elements())
|
Solution
|
python
|
jazzband__django-pipeline
|
pipeline/compressors/__init__.py
|
{
"start": 15171,
"end": 15311
}
|
class ____(CompressorBase):
def compress_js(self, js):
return js
def compress_css(self, css):
return css
|
NoopCompressor
|
python
|
plotly__plotly.py
|
plotly/graph_objs/volume/_spaceframe.py
|
{
"start": 233,
"end": 3741
}
|
class ____(_BaseTraceHierarchyType):
_parent_path_str = "volume"
_path_str = "volume.spaceframe"
_valid_props = {"fill", "show"}
@property
def fill(self):
"""
Sets the fill ratio of the `spaceframe` elements. The default
fill value is 1 meaning that they are entirely shaded. Applying
a `fill` ratio less than one would allow the creation of
openings parallel to the edges.
The 'fill' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
"""
return self["fill"]
@fill.setter
def fill(self, val):
self["fill"] = val
@property
def show(self):
"""
Displays/hides tetrahedron shapes between minimum and maximum
iso-values. Often useful when either caps or surfaces are
disabled or filled with values less than 1.
The 'show' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["show"]
@show.setter
def show(self, val):
self["show"] = val
@property
def _prop_descriptions(self):
return """\
fill
Sets the fill ratio of the `spaceframe` elements. The
default fill value is 1 meaning that they are entirely
shaded. Applying a `fill` ratio less than one would
allow the creation of openings parallel to the edges.
show
Displays/hides tetrahedron shapes between minimum and
maximum iso-values. Often useful when either caps or
surfaces are disabled or filled with values less than
1.
"""
def __init__(self, arg=None, fill=None, show=None, **kwargs):
"""
Construct a new Spaceframe object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.volume.Spaceframe`
fill
Sets the fill ratio of the `spaceframe` elements. The
default fill value is 1 meaning that they are entirely
shaded. Applying a `fill` ratio less than one would
allow the creation of openings parallel to the edges.
show
Displays/hides tetrahedron shapes between minimum and
maximum iso-values. Often useful when either caps or
surfaces are disabled or filled with values less than
1.
Returns
-------
Spaceframe
"""
super().__init__("spaceframe")
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.volume.Spaceframe
constructor must be a dict or
an instance of :class:`plotly.graph_objs.volume.Spaceframe`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("fill", arg, fill)
self._set_property("show", arg, show)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
|
Spaceframe
|
python
|
getsentry__sentry
|
src/sentry/grouping/variants.py
|
{
"start": 2855,
"end": 2990
}
|
class ____(BaseVariant):
type = "fallback"
def get_hash(self) -> str | None:
return hash_from_values([])
|
FallbackVariant
|
python
|
xlwings__xlwings
|
xlwings/constants.py
|
{
"start": 12033,
"end": 12168
}
|
class ____:
xlColumnThenRow = 2 # from enum XlApplyNamesOrder
xlRowThenColumn = 1 # from enum XlApplyNamesOrder
|
ApplyNamesOrder
|
python
|
scipy__scipy
|
scipy/odr/_odrpack.py
|
{
"start": 2068,
"end": 2243
}
|
class ____(Exception):
"""
Exception indicating an error in fitting.
This is raised by `~scipy.odr.odr` if an error occurs during fitting.
"""
pass
|
OdrError
|
python
|
Pylons__pyramid
|
docs/quick_tutorial/databases/tutorial/views.py
|
{
"start": 363,
"end": 3001
}
|
class ____:
def __init__(self, request):
self.request = request
@property
def wiki_form(self):
schema = WikiPage()
return deform.Form(schema, buttons=('submit',))
@property
def reqts(self):
return self.wiki_form.get_widget_resources()
@view_config(route_name='wiki_view', renderer='wiki_view.pt')
def wiki_view(self):
pages = DBSession.query(Page).order_by(Page.title)
return dict(title='Wiki View', pages=pages)
@view_config(route_name='wikipage_add',
renderer='wikipage_addedit.pt')
def wikipage_add(self):
form = self.wiki_form.render()
if 'submit' in self.request.params:
controls = self.request.POST.items()
try:
appstruct = self.wiki_form.validate(controls)
except deform.ValidationFailure as e:
# Form is NOT valid
return dict(form=e.render())
# Add a new page to the database
new_title = appstruct['title']
new_body = appstruct['body']
DBSession.add(Page(title=new_title, body=new_body))
# Get the new ID and redirect
page = DBSession.query(Page).filter_by(title=new_title).one()
new_uid = page.uid
url = self.request.route_url('wikipage_view', uid=new_uid)
return HTTPFound(url)
return dict(form=form)
@view_config(route_name='wikipage_view', renderer='wikipage_view.pt')
def wikipage_view(self):
uid = int(self.request.matchdict['uid'])
page = DBSession.query(Page).filter_by(uid=uid).one()
return dict(page=page)
@view_config(route_name='wikipage_edit',
renderer='wikipage_addedit.pt')
def wikipage_edit(self):
uid = int(self.request.matchdict['uid'])
page = DBSession.query(Page).filter_by(uid=uid).one()
wiki_form = self.wiki_form
if 'submit' in self.request.params:
controls = self.request.POST.items()
try:
appstruct = wiki_form.validate(controls)
except deform.ValidationFailure as e:
return dict(page=page, form=e.render())
# Change the content and redirect to the view
page.title = appstruct['title']
page.body = appstruct['body']
url = self.request.route_url('wikipage_view', uid=uid)
return HTTPFound(url)
form = self.wiki_form.render(dict(
uid=page.uid, title=page.title, body=page.body)
)
return dict(page=page, form=form)
|
WikiViews
|
python
|
sqlalchemy__sqlalchemy
|
examples/asyncio/async_orm_writeonly.py
|
{
"start": 716,
"end": 1099
}
|
class ____(Base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
data: Mapped[Optional[str]]
create_date: Mapped[datetime.datetime] = mapped_column(
server_default=func.now()
)
# collection relationships are declared with WriteOnlyMapped. There
# is no separate collection type
bs: WriteOnlyMapped[B] = relationship()
|
A
|
python
|
pytorch__pytorch
|
torch/nn/modules/instancenorm.py
|
{
"start": 7754,
"end": 9528
}
|
class ____(_LazyNormBase, _InstanceNorm):
r"""A :class:`torch.nn.InstanceNorm1d` module with lazy initialization of the ``num_features`` argument.
The ``num_features`` argument of the :class:`InstanceNorm1d` is inferred from the ``input.size(1)``.
The attributes that will be lazily initialized are `weight`, `bias`, `running_mean` and `running_var`.
Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
on lazy modules and their limitations.
Args:
num_features: :math:`C` from an expected input of size
:math:`(N, C, L)` or :math:`(C, L)`
eps: a value added to the denominator for numerical stability. Default: 1e-5
momentum: the value used for the running_mean and running_var computation. Default: 0.1
affine: a boolean value that when set to ``True``, this module has
learnable affine parameters, initialized the same way as done for batch normalization.
Default: ``False``.
track_running_stats: a boolean value that when set to ``True``, this
module tracks the running mean and variance, and when set to ``False``,
this module does not track such statistics and always uses batch
statistics in both training and eval modes. Default: ``False``
Shape:
- Input: :math:`(N, C, L)` or :math:`(C, L)`
- Output: :math:`(N, C, L)` or :math:`(C, L)` (same shape as input)
"""
cls_to_become = InstanceNorm1d # type: ignore[assignment]
def _get_no_batch_dim(self) -> int:
return 2
def _check_input_dim(self, input) -> None:
if input.dim() not in (2, 3):
raise ValueError(f"expected 2D or 3D input (got {input.dim()}D input)")
|
LazyInstanceNorm1d
|
python
|
run-llama__llama_index
|
llama-index-integrations/vector_stores/llama-index-vector-stores-vectorx/tests/test_vector_stores_vectorx.py
|
{
"start": 10059,
"end": 12462
}
|
class ____(unittest.TestCase):
def setUp(self):
self.mock_index = MagicMock()
self.mock_index.dimension = 2
self.mock_index.query.return_value = [
{
"id": "1",
"similarity": 0.9,
"meta": {"text": "mock text"},
"vector": [0.1, 0.2],
}
]
self.mock_index.delete_with_filter = MagicMock()
self.store = VectorXVectorStore(
vectorx_index=self.mock_index, dimension=2, index_name="mock_index"
)
def test_initialize_vectorx_index_import_error(self):
import builtins
original_import = builtins.__import__
def mock_import(name, *args, **kwargs):
if name == "vecx.vectorx":
raise ImportError("No module named vecx.vectorx")
return original_import(name, *args, **kwargs)
builtins.__import__ = mock_import
with pytest.raises(ImportError):
VectorXVectorStore._initialize_vectorx_index(
api_token="token", encryption_key="key", index_name="idx", dimension=2
)
builtins.__import__ = original_import
def test_query_hybrid_with_alpha(self):
query = VectorStoreQuery(
query_embedding=[0.1, 0.2], similarity_top_k=1, mode="HYBRID", alpha=2.0
)
result = self.store.query(query)
self.assertEqual(result.similarities[0], 0.9)
def test_delete_with_error_logging(self):
self.store._vectorx_index.delete_with_filter.side_effect = Exception(
"Delete failed"
)
self.store.delete("ref_doc")
def test_query_missing_dimension_and_no_embedding(self):
self.store._vectorx_index = MagicMock()
del self.store._vectorx_index.dimension
self.store._vectorx_index.describe.side_effect = Exception("No dimension")
with pytest.raises(ValueError):
self.store.query(VectorStoreQuery(query_embedding=None, similarity_top_k=1))
def test_mocked_vectorx_index_usage(self):
query = VectorStoreQuery(query_embedding=[0.1, 0.2], similarity_top_k=1)
result = self.store.query(query)
self.assertEqual(result.similarities[0], 0.9)
self.assertEqual(len(result.nodes), 1)
# ------------------ Run Tests ------------------
if __name__ == "__main__":
unittest.main()
|
TestVectorXAdvanced
|
python
|
getsentry__sentry
|
tests/sentry/backup/test_imports.py
|
{
"start": 111485,
"end": 118279
}
|
class ____(TestCase):
"""
Ensure large lists of a single model type are batched properly, and that this batching does not disrupt pk mapping. These tests do not inherit from `ImportTestCase` because they do not require a completely clean database.
"""
def import_n_users_with_options(self, import_uuid: str, n: int) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = Path(tmp_dir).joinpath(f"{self._testMethodName}.json")
with open(tmp_path, "wb") as tmp_file:
users = []
user_options = []
for i in range(1, n + 1):
users.append(
{
"model": "sentry.user",
"pk": i + 100,
"fields": {
"password": "fake",
"username": f"user-{i}",
"name": f"user-{i}",
"email": f"{i}@example.com",
"is_staff": False,
"is_active": True,
"is_superuser": False,
"is_managed": False,
"is_password_expired": False,
"is_unclaimed": False,
"last_password_change": "2023-06-22T22:59:57.023Z",
"flags": "0",
"date_joined": "2023-06-22T22:59:55.488Z",
"last_active": "2023-06-22T22:59:55.489Z",
"avatar_type": 0,
},
}
)
user_options.append(
{
"model": "sentry.useroption",
"pk": i + 1000,
"fields": {
"user": i + 100,
"key": f"key-{i}",
"value": f"user-{i}",
},
}
)
tmp_file.write(orjson.dumps(users + user_options))
with open(tmp_path, "rb") as tmp_file:
import_in_user_scope(
tmp_file, flags=ImportFlags(import_uuid=import_uuid), printer=NOOP_PRINTER
)
def test_exact_multiple_of_batch_size(self) -> None:
import_uuid = uuid4().hex
want_chunks = 2
n = MAX_BATCH_SIZE * want_chunks
self.import_n_users_with_options(import_uuid, n)
with assume_test_silo_mode(SiloMode.CONTROL):
user_chunks = list(
ControlImportChunk.objects.filter(import_uuid=import_uuid, model="sentry.user")
)
user_option_chunks = list(
ControlImportChunk.objects.filter(
import_uuid=import_uuid, model="sentry.useroption"
)
)
assert len(user_chunks) == want_chunks
assert len(user_option_chunks) == want_chunks
assert user_chunks[0].min_ordinal == 1
assert user_chunks[0].max_ordinal == MAX_BATCH_SIZE
assert user_chunks[0].min_source_pk == 101
assert user_chunks[0].max_source_pk == MAX_BATCH_SIZE + 100
assert user_chunks[1].min_ordinal == MAX_BATCH_SIZE + 1
assert user_chunks[1].max_ordinal == MAX_BATCH_SIZE * 2
assert user_chunks[1].min_source_pk == MAX_BATCH_SIZE + 101
assert user_chunks[1].max_source_pk == (MAX_BATCH_SIZE * 2) + 100
assert user_option_chunks[0].min_ordinal == 1
assert user_option_chunks[0].max_ordinal == MAX_BATCH_SIZE
assert user_option_chunks[0].min_source_pk == 1001
assert user_option_chunks[0].max_source_pk == MAX_BATCH_SIZE + 1000
assert user_option_chunks[1].min_ordinal == MAX_BATCH_SIZE + 1
assert user_option_chunks[1].max_ordinal == MAX_BATCH_SIZE * 2
assert user_option_chunks[1].min_source_pk == MAX_BATCH_SIZE + 1001
assert user_option_chunks[1].max_source_pk == (MAX_BATCH_SIZE * 2) + 1000
# Ensure pk mapping from a later batch is still consistent.
target = MAX_BATCH_SIZE + (MAX_BATCH_SIZE // 2)
user_option = UserOption.objects.get(key=f"key-{target}")
user = User.objects.get(id=user_option.user_id)
assert user.name == f"user-{target}"
def test_one_more_than_batch_size(self) -> None:
import_uuid = uuid4().hex
want_chunks = 2
n = MAX_BATCH_SIZE + 1
self.import_n_users_with_options(import_uuid, n)
with assume_test_silo_mode(SiloMode.CONTROL):
user_chunks = list(
ControlImportChunk.objects.filter(import_uuid=import_uuid, model="sentry.user")
)
user_option_chunks = list(
ControlImportChunk.objects.filter(
import_uuid=import_uuid, model="sentry.useroption"
)
)
assert len(user_chunks) == want_chunks
assert len(user_option_chunks) == want_chunks
assert user_chunks[0].min_ordinal == 1
assert user_chunks[0].max_ordinal == MAX_BATCH_SIZE
assert user_chunks[0].min_source_pk == 101
assert user_chunks[0].max_source_pk == MAX_BATCH_SIZE + 100
assert user_chunks[1].min_ordinal == MAX_BATCH_SIZE + 1
assert user_chunks[1].max_ordinal == MAX_BATCH_SIZE + 1
assert user_chunks[1].min_source_pk == MAX_BATCH_SIZE + 101
assert user_chunks[1].max_source_pk == MAX_BATCH_SIZE + 101
assert user_option_chunks[0].min_ordinal == 1
assert user_option_chunks[0].max_ordinal == MAX_BATCH_SIZE
assert user_option_chunks[0].min_source_pk == 1001
assert user_option_chunks[0].max_source_pk == MAX_BATCH_SIZE + 1000
assert user_option_chunks[1].min_ordinal == MAX_BATCH_SIZE + 1
assert user_option_chunks[1].max_ordinal == MAX_BATCH_SIZE + 1
assert user_option_chunks[1].min_source_pk == MAX_BATCH_SIZE + 1001
assert user_option_chunks[1].max_source_pk == MAX_BATCH_SIZE + 1001
# Ensure pk mapping from a later batch is still consistent.
target = MAX_BATCH_SIZE + 1
user_option = UserOption.objects.get(key=f"key-{target}")
user = User.objects.get(id=user_option.user_id)
assert user.name == f"user-{target}"
@pytest.mark.skipif(reason="not legacy")
|
BatchingTests
|
python
|
facebook__pyre-check
|
client/commands/tests/start_test.py
|
{
"start": 1288,
"end": 6054
}
|
class ____(testslide.TestCase):
def test_serialize_critical_file(self) -> None:
self.assertDictEqual(
start.CriticalFile(
policy=start.MatchPolicy.BASE_NAME, path="foo"
).serialize(),
{"base_name": "foo"},
)
self.assertDictEqual(
start.CriticalFile(
policy=start.MatchPolicy.EXTENSION, path="foo"
).serialize(),
{"extension": "foo"},
)
self.assertDictEqual(
start.CriticalFile(
policy=start.MatchPolicy.FULL_PATH, path="/foo/bar"
).serialize(),
{"full_path": "/foo/bar"},
)
def test_serialize_saved_state_action(self) -> None:
self.assertTupleEqual(
start.LoadSavedStateFromFile(shared_memory_path="/foo/bar").serialize(),
("load_from_file", {"shared_memory_path": "/foo/bar"}),
)
self.assertTupleEqual(
start.LoadSavedStateFromFile(
shared_memory_path="/foo/bar", changed_files_path="derp.txt"
).serialize(),
(
"load_from_file",
{"shared_memory_path": "/foo/bar", "changed_files_path": "derp.txt"},
),
)
self.assertTupleEqual(
start.LoadSavedStateFromProject(project_name="my_project").serialize(),
("load_from_project", {"project_name": "my_project"}),
)
self.assertTupleEqual(
start.LoadSavedStateFromProject(
project_name="my_project", project_metadata="my_metadata"
).serialize(),
(
"load_from_project",
{"project_name": "my_project", "project_metadata": "my_metadata"},
),
)
self.assertTupleEqual(
start.StoreSavedStateToFile(shared_memory_path="/foo/bar").serialize(),
("save_to_file", {"shared_memory_path": "/foo/bar"}),
)
def test_serialize_arguments(self) -> None:
def assert_serialized(
arguments: start.Arguments, items: Iterable[Tuple[str, object]]
) -> None:
serialized = arguments.serialize()
for key, value in items:
if key not in serialized:
self.fail(f"Cannot find key `{key}` in serialized arguments")
else:
self.assertEqual(value, serialized[key])
assert_serialized(
start.Arguments(
base_arguments=backend_arguments.BaseArguments(
log_path="foo",
global_root="bar",
source_paths=backend_arguments.SimpleSourcePath(
[search_path.SimpleElement("source")]
),
),
taint_models_path=["/taint/model"],
strict=True,
show_error_traces=True,
store_type_check_resolution=True,
critical_files=[
start.CriticalFile(
policy=start.MatchPolicy.BASE_NAME, path="foo.py"
),
start.CriticalFile(policy=start.MatchPolicy.EXTENSION, path="txt"),
start.CriticalFile(
policy=start.MatchPolicy.FULL_PATH, path="/home/bar.txt"
),
],
watchman_root=Path("/project"),
saved_state_action=start.LoadSavedStateFromProject(
project_name="my_project", project_metadata="my_metadata"
),
socket_path=Path("not_relevant_for_this_test.sock"),
),
[
("log_path", "foo"),
("global_root", "bar"),
("source_paths", {"kind": "simple", "paths": ["source"]}),
("taint_model_paths", ["/taint/model"]),
("strict", True),
("show_error_traces", True),
("store_type_check_resolution", True),
(
"critical_files",
[
{"base_name": "foo.py"},
{"extension": "txt"},
{"full_path": "/home/bar.txt"},
],
),
("watchman_root", "/project"),
(
"saved_state_action",
(
"load_from_project",
{
"project_name": "my_project",
"project_metadata": "my_metadata",
},
),
),
],
)
|
ArgumentTest
|
python
|
PrefectHQ__prefect
|
tests/server/schemas/test_schedules.py
|
{
"start": 11224,
"end": 12622
}
|
class ____:
def test_create_cron_schedule(self):
clock = CronSchedule(cron="5 4 * * *")
assert clock.cron == "5 4 * * *"
@pytest.mark.parametrize(
"cron_string",
[
"@yearly",
"@weekly",
"@daily",
"@hourly",
"* * * * MON",
"30 8 * * sat-sun",
"* * * * mon,wed,fri",
],
)
def test_create_cron_schedule_with_keywords(self, cron_string):
clock = CronSchedule(cron=cron_string)
assert clock.cron == cron_string
def test_create_cron_schedule_with_timezone(self):
clock = CronSchedule(cron="5 4 * * *", timezone="America/New_York")
assert clock.timezone == "America/New_York"
def test_invalid_timezone(self):
with pytest.raises(ValidationError):
CronSchedule(cron="5 4 * * *", timezone="fake")
@pytest.mark.parametrize("cron_string", ["invalid cron"])
def test_invalid_cron_string(self, cron_string):
with pytest.raises(ValidationError):
CronSchedule(cron=cron_string)
@pytest.mark.parametrize("cron_string", ["5 4 R * *"])
def test_unsupported_cron_string(self, cron_string):
with pytest.raises(
ValidationError, match="(Random and Hashed expressions are unsupported)"
):
CronSchedule(cron=cron_string)
|
TestCreateCronSchedule
|
python
|
sqlalchemy__sqlalchemy
|
lib/sqlalchemy/dialects/mssql/base.py
|
{
"start": 38711,
"end": 39602
}
|
class ____(sqltypes.Date):
def bind_processor(self, dialect):
def process(value):
if type(value) == datetime.date:
return datetime.datetime(value.year, value.month, value.day)
else:
return value
return process
_reg = re.compile(r"(\d+)-(\d+)-(\d+)")
def result_processor(self, dialect, coltype):
def process(value):
if isinstance(value, datetime.datetime):
return value.date()
elif isinstance(value, str):
m = self._reg.match(value)
if not m:
raise ValueError(
"could not parse %r as a date value" % (value,)
)
return datetime.date(*[int(x or 0) for x in m.groups()])
else:
return value
return process
|
_MSDate
|
python
|
kamyu104__LeetCode-Solutions
|
Python/minimum-moves-to-spread-stones-over-grid.py
|
{
"start": 2650,
"end": 3444
}
|
class ____(object):
def minimumMoves(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def dist(a, b):
return abs(a[0]-b[0])+abs(a[1]-b[1])
src, dst = [], []
for i in xrange(len(grid)):
for j in xrange(len(grid[0])):
if grid[i][j]-1 >= 0:
src.extend([(i, j)]*(grid[i][j]-1))
else:
dst.append((i, j))
adj = [[dist(src[i], dst[j]) for j in xrange(len(dst))] for i in xrange(len(src))]
return sum(adj[i][j] for i, j in itertools.izip(*hungarian(adj)))
# Time: O(max(x^y)) = O((n/2)^(n/2))) = O(5^5), n = len(grid)*len(grid[0]), y = len(zero), x = n-y
# Space: O(y) = O(n) = O(9) = O(1)
# backtracking
|
Solution2
|
python
|
numpy__numpy
|
numpy/f2py/tests/test_f2cmap.py
|
{
"start": 41,
"end": 387
}
|
class ____(util.F2PyTest):
sources = [
util.getpath("tests", "src", "f2cmap", "isoFortranEnvMap.f90"),
util.getpath("tests", "src", "f2cmap", ".f2py_f2cmap")
]
# gh-15095
def test_gh15095(self):
inp = np.ones(3)
out = self.module.func1(inp)
exp_out = 3
assert out == exp_out
|
TestF2Cmap
|
python
|
apache__airflow
|
airflow-core/src/airflow/api_fastapi/common/parameters.py
|
{
"start": 6732,
"end": 10592
}
|
class ____(BaseParam[list[str]]):
"""Order result by the attribute."""
MAX_SORT_PARAMS = 10
def __init__(
self, allowed_attrs: list[str], model: Base, to_replace: dict[str, str | Column] | None = None
) -> None:
super().__init__()
self.allowed_attrs = allowed_attrs
self.model = model
self.to_replace = to_replace
def to_orm(self, select: Select) -> Select:
if self.skip_none is False:
raise ValueError(f"Cannot set 'skip_none' to False on a {type(self)}")
if self.value is None:
self.value = [self.get_primary_key_string()]
order_by_values = self.value
if len(order_by_values) > self.MAX_SORT_PARAMS:
raise HTTPException(
400,
f"Ordering with more than {self.MAX_SORT_PARAMS} parameters is not allowed. Provided: {order_by_values}",
)
columns: list[ColumnElement] = []
for order_by_value in order_by_values:
lstriped_orderby = order_by_value.lstrip("-")
column: Column | None = None
if self.to_replace:
replacement = self.to_replace.get(lstriped_orderby, lstriped_orderby)
if isinstance(replacement, str):
lstriped_orderby = replacement
else:
column = replacement
if (self.allowed_attrs and lstriped_orderby not in self.allowed_attrs) and column is None:
raise HTTPException(
400,
f"Ordering with '{lstriped_orderby}' is disallowed or "
f"the attribute does not exist on the model",
)
if column is None:
column = getattr(self.model, lstriped_orderby)
# MySQL does not support `nullslast`, and True/False ordering depends on the
# database implementation.
nullscheck = case((column.isnot(None), 0), else_=1)
columns.append(nullscheck)
if order_by_value.startswith("-"):
columns.append(column.desc())
else:
columns.append(column.asc())
# Reset default sorting
select = select.order_by(None)
primary_key_column = self.get_primary_key_column()
# Always add a final discriminator to enforce deterministic ordering.
if order_by_values and order_by_values[0].startswith("-"):
columns.append(primary_key_column.desc())
else:
columns.append(primary_key_column.asc())
return select.order_by(*columns)
def get_primary_key_column(self) -> Column:
"""Get the primary key column of the model of SortParam object."""
return inspect(self.model).primary_key[0]
def get_primary_key_string(self) -> str:
"""Get the primary key string of the model of SortParam object."""
return self.get_primary_key_column().name
@classmethod
def depends(cls, *args: Any, **kwargs: Any) -> Self:
raise NotImplementedError("Use dynamic_depends, depends not implemented.")
def dynamic_depends(self, default: str | None = None) -> Callable:
to_replace_attrs = list(self.to_replace.keys()) if self.to_replace else []
all_attrs = self.allowed_attrs + to_replace_attrs
def inner(
order_by: list[str] = Query(
default=[default] if default is not None else [self.get_primary_key_string()],
description=f"Attributes to order by, multi criteria sort is supported. Prefix with `-` for descending order. "
f"Supported attributes: `{', '.join(all_attrs) if all_attrs else self.get_primary_key_string()}`",
),
) -> SortParam:
return self.set_value(order_by)
return inner
|
SortParam
|
python
|
kamyu104__LeetCode-Solutions
|
Python/sort-array-by-moving-items-to-empty-space.py
|
{
"start": 44,
"end": 873
}
|
class ____(object):
def sortArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def min_moves(d):
def index(x):
return d*(len(nums)-1) if x == 0 else x-d
lookup = [False]*len(nums)
result = len(nums)
for i in xrange(len(nums)):
if lookup[nums[i]]:
continue
l = 0
while not lookup[nums[i]]:
lookup[nums[i]] = True
l += 1
i = index(nums[i])
result -= 1
if l >= 2:
result += 2
return result-2*int(nums[d*(len(nums)-1)] != 0)
return min(min_moves(0), min_moves(1))
# Time: O(n)
# Space: O(n)
# greedy, sort
|
Solution
|
python
|
ray-project__ray
|
rllib/models/torch/recurrent_net.py
|
{
"start": 5223,
"end": 12224
}
|
class ____(RecurrentNetwork, nn.Module):
"""An LSTM wrapper serving as an interface for ModelV2s that set use_lstm."""
def __init__(
self,
obs_space: gym.spaces.Space,
action_space: gym.spaces.Space,
num_outputs: int,
model_config: ModelConfigDict,
name: str,
):
nn.Module.__init__(self)
super(LSTMWrapper, self).__init__(
obs_space, action_space, None, model_config, name
)
# At this point, self.num_outputs is the number of nodes coming
# from the wrapped (underlying) model. In other words, self.num_outputs
# is the input size for the LSTM layer.
# If None, set it to the observation space.
if self.num_outputs is None:
self.num_outputs = int(np.prod(self.obs_space.shape))
self.cell_size = model_config["lstm_cell_size"]
self.time_major = model_config.get("_time_major", False)
self.use_prev_action = model_config["lstm_use_prev_action"]
self.use_prev_reward = model_config["lstm_use_prev_reward"]
self.action_space_struct = get_base_struct_from_space(self.action_space)
self.action_dim = 0
for space in tree.flatten(self.action_space_struct):
if isinstance(space, Discrete):
self.action_dim += space.n
elif isinstance(space, MultiDiscrete):
self.action_dim += np.sum(space.nvec)
elif space.shape is not None:
self.action_dim += int(np.prod(space.shape))
else:
self.action_dim += int(len(space))
# Add prev-action/reward nodes to input to LSTM.
if self.use_prev_action:
self.num_outputs += self.action_dim
if self.use_prev_reward:
self.num_outputs += 1
# Define actual LSTM layer (with num_outputs being the nodes coming
# from the wrapped (underlying) layer).
self.lstm = nn.LSTM(
self.num_outputs, self.cell_size, batch_first=not self.time_major
)
# Set self.num_outputs to the number of output nodes desired by the
# caller of this constructor.
self.num_outputs = num_outputs
# Postprocess LSTM output with another hidden layer and compute values.
self._logits_branch = SlimFC(
in_size=self.cell_size,
out_size=self.num_outputs,
activation_fn=None,
initializer=torch.nn.init.xavier_uniform_,
)
self._value_branch = SlimFC(
in_size=self.cell_size,
out_size=1,
activation_fn=None,
initializer=torch.nn.init.xavier_uniform_,
)
# __sphinx_doc_begin__
# Add prev-a/r to this model's view, if required.
if model_config["lstm_use_prev_action"]:
self.view_requirements[SampleBatch.PREV_ACTIONS] = ViewRequirement(
SampleBatch.ACTIONS, space=self.action_space, shift=-1
)
if model_config["lstm_use_prev_reward"]:
self.view_requirements[SampleBatch.PREV_REWARDS] = ViewRequirement(
SampleBatch.REWARDS, shift=-1
)
# __sphinx_doc_end__
@override(RecurrentNetwork)
def forward(
self,
input_dict: Dict[str, TensorType],
state: List[TensorType],
seq_lens: TensorType,
) -> Tuple[TensorType, List[TensorType]]:
assert seq_lens is not None
# Push obs through "unwrapped" net's `forward()` first.
wrapped_out, _ = self._wrapped_forward(input_dict, [], None)
# Concat. prev-action/reward if required.
prev_a_r = []
# Prev actions.
if self.model_config["lstm_use_prev_action"]:
prev_a = input_dict[SampleBatch.PREV_ACTIONS]
# If actions are not processed yet (in their original form as
# have been sent to environment):
# Flatten/one-hot into 1D array.
if self.model_config["_disable_action_flattening"]:
prev_a_r.append(
flatten_inputs_to_1d_tensor(
prev_a, spaces_struct=self.action_space_struct, time_axis=False
)
)
# If actions are already flattened (but not one-hot'd yet!),
# one-hot discrete/multi-discrete actions here.
else:
if isinstance(self.action_space, (Discrete, MultiDiscrete)):
prev_a = one_hot(prev_a.float(), self.action_space)
else:
prev_a = prev_a.float()
prev_a_r.append(torch.reshape(prev_a, [-1, self.action_dim]))
# Prev rewards.
if self.model_config["lstm_use_prev_reward"]:
prev_a_r.append(
torch.reshape(input_dict[SampleBatch.PREV_REWARDS].float(), [-1, 1])
)
# Concat prev. actions + rewards to the "main" input.
if prev_a_r:
wrapped_out = torch.cat([wrapped_out] + prev_a_r, dim=1)
# Push everything through our LSTM.
input_dict["obs_flat"] = wrapped_out
return super().forward(input_dict, state, seq_lens)
@override(RecurrentNetwork)
def forward_rnn(
self, inputs: TensorType, state: List[TensorType], seq_lens: TensorType
) -> Tuple[TensorType, List[TensorType]]:
# Don't show paddings to RNN(?)
# TODO: (sven) For now, only allow, iff time_major=True to not break
# anything retrospectively (time_major not supported previously).
# max_seq_len = inputs.shape[0]
# time_major = self.model_config["_time_major"]
# if time_major and max_seq_len > 1:
# inputs = torch.nn.utils.rnn.pack_padded_sequence(
# inputs, seq_lens,
# batch_first=not time_major, enforce_sorted=False)
self._features, [h, c] = self.lstm(
inputs, [torch.unsqueeze(state[0], 0), torch.unsqueeze(state[1], 0)]
)
# Re-apply paddings.
# if time_major and max_seq_len > 1:
# self._features, _ = torch.nn.utils.rnn.pad_packed_sequence(
# self._features,
# batch_first=not time_major)
model_out = self._logits_branch(self._features)
return model_out, [torch.squeeze(h, 0), torch.squeeze(c, 0)]
@override(ModelV2)
def get_initial_state(self) -> Union[List[np.ndarray], List[TensorType]]:
# Place hidden states on same device as model.
linear = next(self._logits_branch._model.children())
h = [
linear.weight.new(1, self.cell_size).zero_().squeeze(0),
linear.weight.new(1, self.cell_size).zero_().squeeze(0),
]
return h
@override(ModelV2)
def value_function(self) -> TensorType:
assert self._features is not None, "must call forward() first"
return torch.reshape(self._value_branch(self._features), [-1])
|
LSTMWrapper
|
python
|
scikit-learn__scikit-learn
|
sklearn/gaussian_process/tests/_mini_sequence_kernel.py
|
{
"start": 185,
"end": 1571
}
|
class ____(GenericKernelMixin, StationaryKernelMixin, Kernel):
"""
A minimal (but valid) convolutional kernel for sequences of variable
length.
"""
def __init__(self, baseline_similarity=0.5, baseline_similarity_bounds=(1e-5, 1)):
self.baseline_similarity = baseline_similarity
self.baseline_similarity_bounds = baseline_similarity_bounds
@property
def hyperparameter_baseline_similarity(self):
return Hyperparameter(
"baseline_similarity", "numeric", self.baseline_similarity_bounds
)
def _f(self, s1, s2):
return sum(
[1.0 if c1 == c2 else self.baseline_similarity for c1 in s1 for c2 in s2]
)
def _g(self, s1, s2):
return sum([0.0 if c1 == c2 else 1.0 for c1 in s1 for c2 in s2])
def __call__(self, X, Y=None, eval_gradient=False):
if Y is None:
Y = X
if eval_gradient:
return (
np.array([[self._f(x, y) for y in Y] for x in X]),
np.array([[[self._g(x, y)] for y in Y] for x in X]),
)
else:
return np.array([[self._f(x, y) for y in Y] for x in X])
def diag(self, X):
return np.array([self._f(x, x) for x in X])
def clone_with_theta(self, theta):
cloned = clone(self)
cloned.theta = theta
return cloned
|
MiniSeqKernel
|
python
|
PrefectHQ__prefect
|
src/integrations/prefect-aws/tests/observers/test_ecs_observer.py
|
{
"start": 29544,
"end": 33759
}
|
class ____:
@pytest.fixture
def sample_event(self):
return {
"id": str(uuid.uuid4()),
"time": "2024-01-01T12:00:00Z",
"detail": {
"taskArn": "arn:aws:ecs:us-east-1:123456789:task/cluster/task-id",
"clusterArn": "arn:aws:ecs:us-east-1:123456789:cluster/cluster",
"taskDefinitionArn": "arn:aws:ecs:us-east-1:123456789:task-definition/task-def:1",
"lastStatus": "RUNNING",
},
}
@pytest.fixture
def sample_tags(self):
return {
"prefect.io/flow-run-id": "flow-run-123",
"prefect.io/flow-run-name": "my-flow-run",
}
@patch("prefect_aws.observers.ecs.get_events_client")
async def test_replicate_ecs_event(
self, mock_get_events_client, sample_event, sample_tags
):
mock_events_client = AsyncMock()
mock_context = AsyncMock()
mock_context.__aenter__.return_value = mock_events_client
mock_get_events_client.return_value = mock_context
await replicate_ecs_event(sample_event, sample_tags)
mock_events_client.emit.assert_called_once()
emitted_event = mock_events_client.emit.call_args[1]["event"]
assert emitted_event.event == "prefect.ecs.task.running"
assert emitted_event.id == uuid.UUID(sample_event["id"])
assert "prefect.ecs.task.task-id" in str(
emitted_event.resource.model_dump()["prefect.resource.id"]
)
assert len(emitted_event.related) > 0
@patch("prefect_aws.observers.ecs.get_events_client")
async def test_replicate_ecs_event_missing_id(
self, mock_get_events_client, sample_tags
):
event = {"detail": {"taskArn": "arn", "lastStatus": "RUNNING"}}
await replicate_ecs_event(event, sample_tags)
mock_get_events_client.assert_not_called()
@patch("prefect_aws.observers.ecs.get_events_client")
async def test_replicate_ecs_event_missing_task_arn(
self, mock_get_events_client, sample_tags
):
event = {"id": str(uuid.uuid4()), "detail": {"lastStatus": "RUNNING"}}
await replicate_ecs_event(event, sample_tags)
mock_get_events_client.assert_not_called()
@patch("prefect_aws.observers.ecs.get_events_client")
async def test_replicate_ecs_event_missing_last_status(
self, mock_get_events_client, sample_tags
):
event = {
"id": str(uuid.uuid4()),
"detail": {
"taskArn": "arn:aws:ecs:us-east-1:123456789:task/cluster/task-id"
},
}
await replicate_ecs_event(event, sample_tags)
mock_get_events_client.assert_not_called()
@patch("prefect_aws.observers.ecs.get_events_client")
@patch("prefect_aws.observers.ecs._last_event_cache")
async def test_replicate_ecs_event_with_follows(
self, mock_cache, mock_get_events_client, sample_event, sample_tags
):
mock_events_client = AsyncMock()
mock_context = AsyncMock()
mock_context.__aenter__.return_value = mock_events_client
mock_get_events_client.return_value = mock_context
previous_event = Event(
event="prefect.ecs.task.pending",
resource=Resource.model_validate({"prefect.resource.id": "test"}),
occurred=datetime.fromisoformat("2024-01-01T11:59:00+00:00"),
)
mock_cache.get.return_value = previous_event
await replicate_ecs_event(sample_event, sample_tags)
emitted_event = mock_events_client.emit.call_args[1]["event"]
assert emitted_event.follows == previous_event.id
@patch("prefect_aws.observers.ecs.get_events_client")
async def test_replicate_ecs_event_handles_exception(
self, mock_get_events_client, sample_event, sample_tags
):
mock_events_client = AsyncMock()
mock_context = AsyncMock()
mock_context.__aenter__.return_value = mock_events_client
mock_get_events_client.return_value = mock_context
mock_events_client.emit.side_effect = Exception("Emit failed")
await replicate_ecs_event(sample_event, sample_tags)
|
TestReplicateEcsEvent
|
python
|
pandas-dev__pandas
|
asv_bench/benchmarks/strings.py
|
{
"start": 6482,
"end": 6820
}
|
class ____(Dtypes):
params = (Dtypes.params, [True, False])
param_names = ["dtype", "expand"]
def setup(self, dtype, expand):
super().setup(dtype)
def time_extract_single_group(self, dtype, expand):
with warnings.catch_warnings(record=True):
self.s.str.extract("(\\w*)A", expand=expand)
|
Extract
|
python
|
doocs__leetcode
|
solution/2700-2799/2717.Semi-Ordered Permutation/Solution.py
|
{
"start": 0,
"end": 211
}
|
class ____:
def semiOrderedPermutation(self, nums: List[int]) -> int:
n = len(nums)
i = nums.index(1)
j = nums.index(n)
k = 1 if i < j else 2
return i + n - j - k
|
Solution
|
python
|
pytorch__pytorch
|
torch/_inductor/dtype_propagation.py
|
{
"start": 464,
"end": 2236
}
|
class ____(Protocol):
@property
def dtype(self) -> torch.dtype: ...
DTypeArg = Union[DTypeVar, torch.types.Number, str, OpsValue]
# Inputs need to be cacheable (e.g., not a CSEVar) in order for the cache to be effective
# So first decompose CSEVars -> tuple before calling this
@functools.cache
def get_promoted_dtype(
*args: Sequence[tuple[torch.dtype, bool]],
type_promotion_kind: Optional[ELEMENTWISE_TYPE_PROMOTION_KIND] = None,
):
def construct_input(inp):
if inp[1]:
return torch.empty([], dtype=inp[0])
else:
return torch.empty([1], dtype=inp[0])
inps = [construct_input(arg) for arg in args]
_, dtype = torch._prims_common.elementwise_dtypes(
*inps,
type_promotion_kind=(
type_promotion_kind
if type_promotion_kind
else ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
),
)
return dtype
def promote_types(
args: Sequence[DTypeArg],
type_promotion_kind: Optional[ELEMENTWISE_TYPE_PROMOTION_KIND] = None,
):
dtype_prop_candidates = []
# pyrefly: ignore [bad-assignment]
for arg in args:
assert not isinstance(arg, str)
if isinstance(arg, OpsValue):
arg = arg.value
assert isinstance(arg, torch._prims_common.Number) or hasattr(arg, "dtype")
if isinstance(arg, torch._prims_common.Number):
dtype_prop_candidates.append((type_to_dtype(type(arg)), True))
continue
# pyrefly: ignore [missing-attribute]
dtype_prop_candidates.append((arg.dtype, getattr(arg, "is_scalar", False)))
dtype = get_promoted_dtype(
*dtype_prop_candidates,
type_promotion_kind=type_promotion_kind,
)
return dtype
|
DTypeVar
|
python
|
networkx__networkx
|
networkx/algorithms/isomorphism/tests/test_vf2pp_helpers.py
|
{
"start": 46638,
"end": 66703
}
|
class ____:
def test_const_covered_neighbors(self):
G1 = nx.MultiGraph(
[(0, 1), (0, 1), (1, 2), (3, 0), (3, 0), (3, 0), (3, 2), (3, 2)]
)
G2 = nx.MultiGraph(
[
("a", "b"),
("a", "b"),
("b", "c"),
("k", "a"),
("k", "a"),
("k", "a"),
("k", "c"),
("k", "c"),
]
)
gparams = _GraphParameters(G1, G2, None, None, None, None, None)
sparams = _StateParameters(
{0: "a", 1: "b", 2: "c"},
{"a": 0, "b": 1, "c": 2},
None,
None,
None,
None,
None,
None,
None,
None,
)
u, v = 3, "k"
assert _consistent_PT(u, v, gparams, sparams)
def test_const_no_covered_neighbors(self):
G1 = nx.MultiGraph([(0, 1), (0, 1), (1, 2), (3, 4), (3, 4), (3, 5)])
G2 = nx.MultiGraph([("a", "b"), ("b", "c"), ("k", "w"), ("k", "w"), ("k", "z")])
gparams = _GraphParameters(G1, G2, None, None, None, None, None)
sparams = _StateParameters(
{0: "a", 1: "b", 2: "c"},
{"a": 0, "b": 1, "c": 2},
None,
None,
None,
None,
None,
None,
None,
None,
)
u, v = 3, "k"
assert _consistent_PT(u, v, gparams, sparams)
def test_const_mixed_covered_uncovered_neighbors(self):
G1 = nx.MultiGraph(
[(0, 1), (1, 2), (3, 0), (3, 0), (3, 0), (3, 2), (3, 2), (3, 4), (3, 5)]
)
G2 = nx.MultiGraph(
[
("a", "b"),
("b", "c"),
("k", "a"),
("k", "a"),
("k", "a"),
("k", "c"),
("k", "c"),
("k", "w"),
("k", "z"),
]
)
gparams = _GraphParameters(G1, G2, None, None, None, None, None)
sparams = _StateParameters(
{0: "a", 1: "b", 2: "c"},
{"a": 0, "b": 1, "c": 2},
None,
None,
None,
None,
None,
None,
None,
None,
)
u, v = 3, "k"
assert _consistent_PT(u, v, gparams, sparams)
def test_const_fail_cases(self):
G1 = nx.MultiGraph(
[
(0, 1),
(1, 2),
(10, 0),
(10, 0),
(10, 0),
(10, 3),
(10, 3),
(10, 4),
(10, 5),
(10, 6),
(10, 6),
(4, 1),
(5, 3),
]
)
mapped = {0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f", 6: "g", 10: "k"}
G2 = nx.relabel_nodes(G1, mapped)
gparams = _GraphParameters(G1, G2, None, None, None, None, None)
sparams = _StateParameters(
{0: "a", 1: "b", 2: "c", 3: "d"},
{"a": 0, "b": 1, "c": 2, "d": 3},
None,
None,
None,
None,
None,
None,
None,
None,
)
u, v = 10, "k"
assert _consistent_PT(u, v, gparams, sparams)
# Delete one uncovered neighbor of u. Notice how it still passes the test.
# Two reasons for this:
# 1. If u, v had different degrees from the beginning, they wouldn't be
# selected as candidates in the first place.
# 2. Even if they are selected, consistency is basically 1-look-ahead,
# meaning that we take into consideration the relation of the candidates
# with their mapped neighbors. The node we deleted is not a covered
# neighbor. Such nodes will be checked by the cut_PT function, which
# is basically the 2-look-ahead, checking the relation of the candidates
# with T1, T2 (in which belongs the node we just deleted).
G1.remove_node(6)
assert _consistent_PT(u, v, gparams, sparams)
# Add one more covered neighbor of u in G1
G1.add_edge(u, 2)
assert not _consistent_PT(u, v, gparams, sparams)
# Compensate in G2
G2.add_edge(v, "c")
assert _consistent_PT(u, v, gparams, sparams)
# Add one more covered neighbor of v in G2
G2.add_edge(v, "x")
G1.add_node(7)
sparams.mapping.update({7: "x"})
sparams.reverse_mapping.update({"x": 7})
assert not _consistent_PT(u, v, gparams, sparams)
# Compendate in G1
G1.add_edge(u, 7)
assert _consistent_PT(u, v, gparams, sparams)
# Delete an edge between u and a covered neighbor
G1.remove_edges_from([(u, 0), (u, 0)])
assert not _consistent_PT(u, v, gparams, sparams)
# Compensate in G2
G2.remove_edges_from([(v, mapped[0]), (v, mapped[0])])
assert _consistent_PT(u, v, gparams, sparams)
# Remove an edge between v and a covered neighbor
G2.remove_edge(v, mapped[3])
assert not _consistent_PT(u, v, gparams, sparams)
# Compensate in G1
G1.remove_edge(u, 3)
assert _consistent_PT(u, v, gparams, sparams)
def test_cut_same_labels(self):
G1 = nx.MultiGraph(
[
(0, 1),
(1, 2),
(10, 0),
(10, 0),
(10, 0),
(10, 3),
(10, 3),
(10, 4),
(10, 4),
(10, 5),
(10, 5),
(10, 5),
(10, 5),
(10, 6),
(10, 6),
(4, 1),
(5, 3),
]
)
mapped = {0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f", 6: "g", 10: "k"}
G2 = nx.relabel_nodes(G1, mapped)
l1 = {n: "blue" for n in G1.nodes()}
l2 = {n: "blue" for n in G2.nodes()}
gparams = _GraphParameters(
G1, G2, l1, l2, nx.utils.groups(l1), nx.utils.groups(l2), None
)
sparams = _StateParameters(
{0: "a", 1: "b", 2: "c", 3: "d"},
{"a": 0, "b": 1, "c": 2, "d": 3},
{4, 5},
None,
{6},
None,
{"e", "f"},
None,
{"g"},
None,
)
u, v = 10, "k"
assert not _cut_PT(u, v, gparams, sparams)
# Remove one of the multiple edges between u and a neighbor
G1.remove_edge(u, 4)
assert _cut_PT(u, v, gparams, sparams)
# Compensate in G2
G1.remove_edge(u, 4)
G2.remove_edges_from([(v, mapped[4]), (v, mapped[4])])
assert not _cut_PT(u, v, gparams, sparams)
# Change intersection between G2[v] and T2_tilde, so it's not the same
# as the one between G1[u] and T1_tilde
G2.remove_edge(v, mapped[6])
assert _cut_PT(u, v, gparams, sparams)
# Compensate in G1
G1.remove_edge(u, 6)
assert not _cut_PT(u, v, gparams, sparams)
# Add more edges between u and neighbor which belongs in T1_tilde
G1.add_edges_from([(u, 5), (u, 5), (u, 5)])
assert _cut_PT(u, v, gparams, sparams)
# Compensate in G2
G2.add_edges_from([(v, mapped[5]), (v, mapped[5]), (v, mapped[5])])
assert not _cut_PT(u, v, gparams, sparams)
# Add disconnected nodes, which will form the new Ti_out
G1.add_nodes_from([6, 7, 8])
G2.add_nodes_from(["g", "y", "z"])
G1.add_edges_from([(u, 6), (u, 6), (u, 6), (u, 8)])
G2.add_edges_from([(v, "g"), (v, "g"), (v, "g"), (v, "z")])
sparams.T1_tilde.update({6, 7, 8})
sparams.T2_tilde.update({"g", "y", "z"})
l1 = {n: "blue" for n in G1.nodes()}
l2 = {n: "blue" for n in G2.nodes()}
gparams = _GraphParameters(
G1, G2, l1, l2, nx.utils.groups(l1), nx.utils.groups(l2), None
)
assert not _cut_PT(u, v, gparams, sparams)
# Add some new nodes to the mapping
sparams.mapping.update({6: "g", 7: "y"})
sparams.reverse_mapping.update({"g": 6, "y": 7})
# Add more nodes to T1, T2.
G1.add_edges_from([(6, 20), (7, 20), (6, 21)])
G2.add_edges_from([("g", "i"), ("g", "j"), ("y", "j")])
sparams.T1.update({20, 21})
sparams.T2.update({"i", "j"})
sparams.T1_tilde.difference_update({6, 7})
sparams.T2_tilde.difference_update({"g", "y"})
assert not _cut_PT(u, v, gparams, sparams)
# Remove some edges
G2.remove_edge(v, "g")
assert _cut_PT(u, v, gparams, sparams)
G1.remove_edge(u, 6)
G1.add_edge(u, 8)
G2.add_edge(v, "z")
assert not _cut_PT(u, v, gparams, sparams)
# Add nodes from the new T1 and T2, as neighbors of u and v respectively
G1.add_edges_from([(u, 20), (u, 20), (u, 20), (u, 21)])
G2.add_edges_from([(v, "i"), (v, "i"), (v, "i"), (v, "j")])
l1 = {n: "blue" for n in G1.nodes()}
l2 = {n: "blue" for n in G2.nodes()}
gparams = _GraphParameters(
G1, G2, l1, l2, nx.utils.groups(l1), nx.utils.groups(l2), None
)
assert not _cut_PT(u, v, gparams, sparams)
# Change the edges
G1.remove_edge(u, 20)
G1.add_edge(u, 4)
assert _cut_PT(u, v, gparams, sparams)
G2.remove_edge(v, "i")
G2.add_edge(v, mapped[4])
assert not _cut_PT(u, v, gparams, sparams)
def test_cut_different_labels(self):
G1 = nx.MultiGraph(
[
(0, 1),
(0, 1),
(1, 2),
(1, 2),
(1, 14),
(0, 4),
(1, 5),
(2, 6),
(3, 7),
(3, 6),
(4, 10),
(4, 9),
(6, 10),
(20, 9),
(20, 9),
(20, 9),
(20, 15),
(20, 15),
(20, 12),
(20, 11),
(20, 11),
(20, 11),
(12, 13),
(11, 13),
(20, 8),
(20, 8),
(20, 3),
(20, 3),
(20, 5),
(20, 5),
(20, 5),
(20, 0),
(20, 0),
(20, 0),
]
)
mapped = {
0: "a",
1: "b",
2: "c",
3: "d",
4: "e",
5: "f",
6: "g",
7: "h",
8: "i",
9: "j",
10: "k",
11: "l",
12: "m",
13: "n",
14: "o",
15: "p",
20: "x",
}
G2 = nx.relabel_nodes(G1, mapped)
l1 = {n: "none" for n in G1.nodes()}
l2 = {}
l1.update(
{
9: "blue",
15: "blue",
12: "blue",
11: "green",
3: "green",
8: "red",
0: "red",
5: "yellow",
}
)
l2.update({mapped[n]: l for n, l in l1.items()})
gparams = _GraphParameters(
G1, G2, l1, l2, nx.utils.groups(l1), nx.utils.groups(l2), None
)
sparams = _StateParameters(
{0: "a", 1: "b", 2: "c", 3: "d"},
{"a": 0, "b": 1, "c": 2, "d": 3},
{4, 5, 6, 7, 14},
None,
{9, 10, 15, 12, 11, 13, 8},
None,
{"e", "f", "g", "h", "o"},
None,
{"j", "k", "l", "m", "n", "i", "p"},
None,
)
u, v = 20, "x"
assert not _cut_PT(u, v, gparams, sparams)
# Change the orientation of the labels on neighbors of u compared to
# neighbors of v. Leave the structure intact
l1.update({9: "red"})
assert _cut_PT(u, v, gparams, sparams)
# compensate in G2
l2.update({mapped[9]: "red"})
assert not _cut_PT(u, v, gparams, sparams)
# Change the intersection of G1[u] and T1
G1.add_edge(u, 4)
assert _cut_PT(u, v, gparams, sparams)
# Same for G2[v] and T2
G2.add_edge(v, mapped[4])
assert not _cut_PT(u, v, gparams, sparams)
# Delete one from the multiple edges
G2.remove_edge(v, mapped[8])
assert _cut_PT(u, v, gparams, sparams)
# Same for G1[u] and T1_tilde
G1.remove_edge(u, 8)
assert not _cut_PT(u, v, gparams, sparams)
# Place 8 and mapped[8] in T1 and T2 respectively, by connecting it to covered nodes
G1.add_edges_from([(8, 3), (8, 3), (8, u)])
G2.add_edges_from([(mapped[8], mapped[3]), (mapped[8], mapped[3])])
sparams.T1.add(8)
sparams.T2.add(mapped[8])
sparams.T1_tilde.remove(8)
sparams.T2_tilde.remove(mapped[8])
assert _cut_PT(u, v, gparams, sparams)
# Fix uneven edges
G1.remove_edge(8, u)
assert not _cut_PT(u, v, gparams, sparams)
# Remove neighbor of u from T1
G1.remove_node(5)
l1.pop(5)
sparams.T1.remove(5)
assert _cut_PT(u, v, gparams, sparams)
# Same in G2
G2.remove_node(mapped[5])
l2.pop(mapped[5])
sparams.T2.remove(mapped[5])
assert not _cut_PT(u, v, gparams, sparams)
def test_feasibility_same_labels(self):
G1 = nx.MultiGraph(
[
(0, 1),
(0, 1),
(1, 2),
(1, 2),
(1, 14),
(0, 4),
(1, 5),
(2, 6),
(3, 7),
(3, 6),
(4, 10),
(4, 9),
(6, 10),
(20, 9),
(20, 9),
(20, 9),
(20, 15),
(20, 15),
(20, 12),
(20, 11),
(20, 11),
(20, 11),
(12, 13),
(11, 13),
(20, 8),
(20, 8),
(20, 3),
(20, 3),
(20, 5),
(20, 5),
(20, 5),
(20, 0),
(20, 0),
(20, 0),
]
)
mapped = {
0: "a",
1: "b",
2: "c",
3: "d",
4: "e",
5: "f",
6: "g",
7: "h",
8: "i",
9: "j",
10: "k",
11: "l",
12: "m",
13: "n",
14: "o",
15: "p",
20: "x",
}
G2 = nx.relabel_nodes(G1, mapped)
l1 = {n: "blue" for n in G1.nodes()}
l2 = {mapped[n]: "blue" for n in G1.nodes()}
gparams = _GraphParameters(
G1, G2, l1, l2, nx.utils.groups(l1), nx.utils.groups(l2), None
)
sparams = _StateParameters(
{0: "a", 1: "b", 2: "c", 3: "d"},
{"a": 0, "b": 1, "c": 2, "d": 3},
{4, 5, 6, 7, 14},
None,
{9, 10, 15, 12, 11, 13, 8},
None,
{"e", "f", "g", "h", "o"},
None,
{"j", "k", "l", "m", "n", "i", "p"},
None,
)
u, v = 20, "x"
assert not _cut_PT(u, v, gparams, sparams)
# Change structure in G2 such that, ONLY consistency is harmed
G2.remove_edges_from([(mapped[20], mapped[3]), (mapped[20], mapped[3])])
G2.add_edges_from([(mapped[20], mapped[2]), (mapped[20], mapped[2])])
# Consistency check fails, while the cutting rules are satisfied!
assert not _cut_PT(u, v, gparams, sparams)
assert not _consistent_PT(u, v, gparams, sparams)
# Compensate in G1 and make it consistent
G1.remove_edges_from([(20, 3), (20, 3)])
G1.add_edges_from([(20, 2), (20, 2)])
assert not _cut_PT(u, v, gparams, sparams)
assert _consistent_PT(u, v, gparams, sparams)
# ONLY fail the cutting check
G2.add_edges_from([(v, mapped[10])] * 5)
assert _cut_PT(u, v, gparams, sparams)
assert _consistent_PT(u, v, gparams, sparams)
# Pass all tests
G1.add_edges_from([(u, 10)] * 5)
assert not _cut_PT(u, v, gparams, sparams)
assert _consistent_PT(u, v, gparams, sparams)
def test_feasibility_different_labels(self):
G1 = nx.MultiGraph(
[
(0, 1),
(0, 1),
(1, 2),
(1, 2),
(1, 14),
(0, 4),
(1, 5),
(2, 6),
(3, 7),
(3, 6),
(4, 10),
(4, 9),
(6, 10),
(20, 9),
(20, 9),
(20, 9),
(20, 15),
(20, 15),
(20, 12),
(20, 11),
(20, 11),
(20, 11),
(12, 13),
(11, 13),
(20, 8),
(20, 8),
(20, 2),
(20, 2),
(20, 5),
(20, 5),
(20, 5),
(20, 0),
(20, 0),
(20, 0),
]
)
mapped = {
0: "a",
1: "b",
2: "c",
3: "d",
4: "e",
5: "f",
6: "g",
7: "h",
8: "i",
9: "j",
10: "k",
11: "l",
12: "m",
13: "n",
14: "o",
15: "p",
20: "x",
}
G2 = nx.relabel_nodes(G1, mapped)
l1 = {n: "none" for n in G1.nodes()}
l2 = {}
l1.update(
{
9: "blue",
15: "blue",
12: "blue",
11: "green",
2: "green",
8: "red",
0: "red",
5: "yellow",
}
)
l2.update({mapped[n]: l for n, l in l1.items()})
gparams = _GraphParameters(
G1, G2, l1, l2, nx.utils.groups(l1), nx.utils.groups(l2), None
)
sparams = _StateParameters(
{0: "a", 1: "b", 2: "c", 3: "d"},
{"a": 0, "b": 1, "c": 2, "d": 3},
{4, 5, 6, 7, 14},
None,
{9, 10, 15, 12, 11, 13, 8},
None,
{"e", "f", "g", "h", "o"},
None,
{"j", "k", "l", "m", "n", "i", "p"},
None,
)
u, v = 20, "x"
assert not _cut_PT(u, v, gparams, sparams)
# Change structure in G2 such that, ONLY consistency is harmed
G2.remove_edges_from([(mapped[20], mapped[2]), (mapped[20], mapped[2])])
G2.add_edges_from([(mapped[20], mapped[3]), (mapped[20], mapped[3])])
l2.update({mapped[3]: "green"})
# Consistency check fails, while the cutting rules are satisfied!
assert not _cut_PT(u, v, gparams, sparams)
assert not _consistent_PT(u, v, gparams, sparams)
# Compensate in G1 and make it consistent
G1.remove_edges_from([(20, 2), (20, 2)])
G1.add_edges_from([(20, 3), (20, 3)])
l1.update({3: "green"})
assert not _cut_PT(u, v, gparams, sparams)
assert _consistent_PT(u, v, gparams, sparams)
# ONLY fail the cutting check
l1.update({5: "red"})
assert _cut_PT(u, v, gparams, sparams)
assert _consistent_PT(u, v, gparams, sparams)
|
TestMultiGraphISOFeasibility
|
python
|
getsentry__sentry
|
src/sentry/types/grouphash_metadata.py
|
{
"start": 3121,
"end": 3769
}
|
class ____(TypedDict):
"""
Data gathered when grouping browser-based security (Content Security Policy, Certifcate
Transparency, Online Certificate Status Protocol Stapling, or HTTP Public Key Pinning) reports
"""
# Either "csp", "expect_ct", "expect_staple", or "hpkp"
security_report_type: str
# Domain name of the blocked address
blocked_host: str
# The CSP directive which was violated
csp_directive: NotRequired[str]
# In the case of a local `script-src` violation, whether it's an `unsafe-inline` or an
# `unsafe-eval` violation
csp_script_violation: NotRequired[str]
|
SecurityHashingMetadata
|
python
|
astropy__astropy
|
astropy/time/formats.py
|
{
"start": 78513,
"end": 78732
}
|
class ____(TimeEpochDateString):
"""Besselian Epoch year as string value(s) like 'B1950.0'."""
name = "byear_str"
epoch_to_jd = "epb2jd"
jd_to_epoch = "epb"
epoch_prefix = "B"
|
TimeBesselianEpochString
|
python
|
eventlet__eventlet
|
tests/queue_test.py
|
{
"start": 237,
"end": 7988
}
|
class ____(tests.LimitedTestCase):
def test_send_first(self):
q = eventlet.Queue()
q.put('hi')
self.assertEqual(q.get(), 'hi')
def test_send_last(self):
q = eventlet.Queue()
def waiter(q):
self.assertEqual(q.get(), 'hi2')
gt = eventlet.spawn(eventlet.with_timeout, 0.1, waiter, q)
eventlet.sleep(0)
eventlet.sleep(0)
q.put('hi2')
gt.wait()
def test_max_size(self):
q = eventlet.Queue(2)
results = []
def putter(q):
q.put('a')
results.append('a')
q.put('b')
results.append('b')
q.put('c')
results.append('c')
gt = eventlet.spawn(putter, q)
eventlet.sleep(0)
self.assertEqual(results, ['a', 'b'])
self.assertEqual(q.get(), 'a')
eventlet.sleep(0)
self.assertEqual(results, ['a', 'b', 'c'])
self.assertEqual(q.get(), 'b')
self.assertEqual(q.get(), 'c')
gt.wait()
def test_zero_max_size(self):
q = eventlet.Queue(0)
def sender(evt, q):
q.put('hi')
evt.send('done')
def receiver(q):
x = q.get()
return x
evt = event.Event()
gt = eventlet.spawn(sender, evt, q)
eventlet.sleep(0)
assert not evt.ready()
gt2 = eventlet.spawn(receiver, q)
self.assertEqual(gt2.wait(), 'hi')
self.assertEqual(evt.wait(), 'done')
gt.wait()
def test_resize_up(self):
q = eventlet.Queue(0)
def sender(evt, q):
q.put('hi')
evt.send('done')
evt = event.Event()
gt = eventlet.spawn(sender, evt, q)
eventlet.sleep(0)
assert not evt.ready()
q.resize(1)
eventlet.sleep(0)
assert evt.ready()
gt.wait()
def test_resize_down(self):
q = eventlet.Queue(5)
for i in range(5):
q.put(i)
self.assertEqual(list(q.queue), list(range(5)))
q.resize(1)
eventlet.sleep(0)
self.assertEqual(list(q.queue), list(range(5)))
def test_resize_to_Unlimited(self):
q = eventlet.Queue(0)
def sender(evt, q):
q.put('hi')
evt.send('done')
evt = event.Event()
gt = eventlet.spawn(sender, evt, q)
eventlet.sleep()
self.assertFalse(evt.ready())
q.resize(None)
eventlet.sleep()
self.assertTrue(evt.ready())
gt.wait()
def test_multiple_waiters(self):
# tests that multiple waiters get their results back
q = eventlet.Queue()
sendings = ['1', '2', '3', '4']
gts = [eventlet.spawn(q.get) for x in sendings]
eventlet.sleep(0.01) # get 'em all waiting
q.put(sendings[0])
q.put(sendings[1])
q.put(sendings[2])
q.put(sendings[3])
results = set()
for i, gt in enumerate(gts):
results.add(gt.wait())
self.assertEqual(results, set(sendings))
def test_waiters_that_cancel(self):
q = eventlet.Queue()
gt = eventlet.spawn(do_bail, q)
self.assertEqual(gt.wait(), 'timed out')
q.put('hi')
self.assertEqual(q.get(), 'hi')
def test_getting_before_sending(self):
q = eventlet.Queue()
gt = eventlet.spawn(q.put, 'sent')
self.assertEqual(q.get(), 'sent')
gt.wait()
def test_two_waiters_one_dies(self):
def waiter(q):
return q.get()
q = eventlet.Queue()
dying = eventlet.spawn(do_bail, q)
waiting = eventlet.spawn(waiter, q)
eventlet.sleep(0)
q.put('hi')
self.assertEqual(dying.wait(), 'timed out')
self.assertEqual(waiting.wait(), 'hi')
def test_two_bogus_waiters(self):
q = eventlet.Queue()
gt1 = eventlet.spawn(do_bail, q)
gt2 = eventlet.spawn(do_bail, q)
eventlet.sleep(0)
q.put('sent')
self.assertEqual(gt1.wait(), 'timed out')
self.assertEqual(gt2.wait(), 'timed out')
self.assertEqual(q.get(), 'sent')
def test_waiting(self):
q = eventlet.Queue()
gt1 = eventlet.spawn(q.get)
eventlet.sleep(0)
self.assertEqual(1, q.getting())
q.put('hi')
eventlet.sleep(0)
self.assertEqual(0, q.getting())
self.assertEqual('hi', gt1.wait())
self.assertEqual(0, q.getting())
def test_channel_send(self):
channel = eventlet.Queue(0)
events = []
def another_greenlet():
events.append(channel.get())
events.append(channel.get())
eventlet.spawn(another_greenlet)
events.append('sending')
channel.put('hello')
events.append('sent hello')
channel.put('world')
events.append('sent world')
self.assertEqual(['sending', 'hello', 'sent hello', 'world', 'sent world'], events)
def test_channel_wait(self):
channel = eventlet.Queue(0)
events = []
def another_greenlet():
events.append('sending hello')
channel.put('hello')
events.append('sending world')
channel.put('world')
events.append('sent world')
eventlet.spawn(another_greenlet)
events.append('waiting')
events.append(channel.get())
events.append(channel.get())
self.assertEqual(['waiting', 'sending hello', 'hello', 'sending world', 'world'], events)
eventlet.sleep(0)
self.assertEqual(
['waiting', 'sending hello', 'hello', 'sending world', 'world', 'sent world'], events)
def test_channel_waiters(self):
c = eventlet.Queue(0)
w1 = eventlet.spawn(c.get)
w2 = eventlet.spawn(c.get)
w3 = eventlet.spawn(c.get)
eventlet.sleep(0)
self.assertEqual(c.getting(), 3)
s1 = eventlet.spawn(c.put, 1)
s2 = eventlet.spawn(c.put, 2)
s3 = eventlet.spawn(c.put, 3)
s1.wait()
s2.wait()
s3.wait()
self.assertEqual(c.getting(), 0)
# NOTE: we don't guarantee that waiters are served in order
results = sorted([w1.wait(), w2.wait(), w3.wait()])
self.assertEqual(results, [1, 2, 3])
def test_channel_sender_timing_out(self):
c = eventlet.Queue(0)
self.assertRaises(queue.Full, c.put, "hi", timeout=0.001)
self.assertRaises(queue.Empty, c.get_nowait)
def test_task_done(self):
channel = eventlet.Queue(0)
X = object()
gt = eventlet.spawn(channel.put, X)
result = channel.get()
assert result is X, (result, X)
assert channel.unfinished_tasks == 1, channel.unfinished_tasks
channel.task_done()
assert channel.unfinished_tasks == 0, channel.unfinished_tasks
gt.wait()
def test_join_doesnt_block_when_queue_is_already_empty(self):
queue = eventlet.Queue()
queue.join()
def test_zero_length_queue_nonblocking_put(self):
hub = hubs.get_hub()
queue = eventlet.Queue(0)
got = []
def fetch_item():
got.append(queue.get())
for _ in range(10):
good_getter = eventlet.spawn(fetch_item)
bad_getter = eventlet.spawn(fetch_item)
hub.schedule_call_global(0, bad_getter.throw, Exception("kaboom"))
eventlet.sleep(0)
for i in range(10):
queue.put(i)
self.assertEqual(got, list(range(10)))
def store_result(result, func, *args):
try:
result.append(func(*args))
except Exception as exc:
result.append(exc)
|
TestQueue
|
python
|
plotly__plotly.py
|
plotly/graph_objs/_deprecations.py
|
{
"start": 13715,
"end": 14409
}
|
class ____(dict):
"""
plotly.graph_objs.Scene is deprecated.
Please replace it with one of the following more specific types
- plotly.graph_objs.layout.Scene
"""
def __init__(self, *args, **kwargs):
"""
plotly.graph_objs.Scene is deprecated.
Please replace it with one of the following more specific types
- plotly.graph_objs.layout.Scene
"""
warnings.warn(
"""plotly.graph_objs.Scene is deprecated.
Please replace it with one of the following more specific types
- plotly.graph_objs.layout.Scene
""",
DeprecationWarning,
)
super().__init__(*args, **kwargs)
|
Scene
|
python
|
python__mypy
|
mypy/checker_state.py
|
{
"start": 286,
"end": 858
}
|
class ____:
# Wrap this in a class since it's faster that using a module-level attribute.
def __init__(self, type_checker: TypeCheckerSharedApi | None) -> None:
# Value varies by file being processed
self.type_checker = type_checker
@contextmanager
def set(self, value: TypeCheckerSharedApi) -> Iterator[None]:
saved = self.type_checker
self.type_checker = value
try:
yield
finally:
self.type_checker = saved
checker_state: Final = TypeCheckerState(type_checker=None)
|
TypeCheckerState
|
python
|
spack__spack
|
lib/spack/spack/util/spack_yaml.py
|
{
"start": 10111,
"end": 11384
}
|
class ____(emitter.Emitter):
saved = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
del _ANNOTATIONS[:]
self.colors = "KgrbmcyGRBMCY"
self.filename_colors = {}
def process_scalar(self):
super().process_scalar()
if marked(self.event.value):
self.saved = self.event.value
def write_line_break(self, data=None):
super().write_line_break(data)
if self.saved is None:
_ANNOTATIONS.append(colorize("@K{---}"))
return
# append annotations at the end of each line
if self.saved:
mark = self.saved._start_mark
color = self.filename_colors.get(mark.name)
if not color:
ncolors = len(self.colors)
color = self.colors[len(self.filename_colors) % ncolors]
self.filename_colors[mark.name] = color
fmt = "@%s{%%s}" % color
ann = fmt % mark.name
if mark.line is not None:
ann += ":@c{%s}" % (mark.line + 1)
_ANNOTATIONS.append(colorize(ann))
else:
_ANNOTATIONS.append("")
def write_comment(self, comment, pre=False):
pass
|
LineAnnotationEmitter
|
python
|
apache__airflow
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/ecs.py
|
{
"start": 1776,
"end": 1996
}
|
class ____(_StringCompareEnum):
"""Contains the possible State values of an ECS Task Definition."""
ACTIVE = "ACTIVE"
INACTIVE = "INACTIVE"
DELETE_IN_PROGRESS = "DELETE_IN_PROGRESS"
|
EcsTaskDefinitionStates
|
python
|
doocs__leetcode
|
solution/1500-1599/1530.Number of Good Leaf Nodes Pairs/Solution.py
|
{
"start": 192,
"end": 1005
}
|
class ____:
def countPairs(self, root: TreeNode, distance: int) -> int:
def dfs(root, cnt, i):
if root is None or i >= distance:
return
if root.left is None and root.right is None:
cnt[i] += 1
return
dfs(root.left, cnt, i + 1)
dfs(root.right, cnt, i + 1)
if root is None:
return 0
ans = self.countPairs(root.left, distance) + self.countPairs(
root.right, distance
)
cnt1 = Counter()
cnt2 = Counter()
dfs(root.left, cnt1, 1)
dfs(root.right, cnt2, 1)
for k1, v1 in cnt1.items():
for k2, v2 in cnt2.items():
if k1 + k2 <= distance:
ans += v1 * v2
return ans
|
Solution
|
python
|
pytorch__pytorch
|
torch/autograd/graph.py
|
{
"start": 994,
"end": 6154
}
|
class ____(abc.ABC):
@abc.abstractmethod
def name(self) -> str:
r"""Return the name.
Example::
>>> import torch
>>> a = torch.tensor([0., 0., 0.], requires_grad=True)
>>> b = a.clone()
>>> assert isinstance(b.grad_fn, torch.autograd.graph.Node)
>>> print(b.grad_fn.name())
CloneBackward0
"""
raise NotImplementedError
@property
@abc.abstractmethod
def next_functions(self) -> tuple[tuple[Optional["Node"], int], ...]:
raise NotImplementedError
@abc.abstractmethod
def metadata(self) -> dict:
r"""Return the metadata."""
raise NotImplementedError
@property
@abc.abstractmethod
def _input_metadata(self) -> list[Any]:
raise NotImplementedError
@abc.abstractmethod
def _register_hook_dict(self, tensor: torch.Tensor) -> None:
raise NotImplementedError
@abc.abstractmethod
def register_hook(self, fn: Callable[..., Any]) -> RemovableHandle:
r"""Register a backward hook.
The hook will be called every time a gradient with respect to the
Node is computed. The hook should have the following signature::
hook(grad_inputs: Tuple[Tensor], grad_outputs: Tuple[Tensor]) -> Tuple[Tensor] or None
The hook should not modify its argument, but it can optionally return
a new gradient which will be used in place of :attr:`grad_inputs`.
This function returns a handle with a method ``handle.remove()``
that removes the hook from the module.
.. note::
See :ref:`backward-hooks-execution` for more information on how when this hook
is executed, and how its execution is ordered relative to other hooks.
.. note::
In the rare case where the hook is registered while the Node has already
begun execution, there is no longer any guarantee on :attr:`grad_outputs`
content (it might be as usual or empty depending on other factors). The
hook can still optionally return a new gradient to be used in place of
:attr:`grad_inputs` independent of :attr:`grad_outputs`.
Example::
>>> import torch
>>> a = torch.tensor([0., 0., 0.], requires_grad=True)
>>> b = a.clone()
>>> assert isinstance(b.grad_fn, torch.autograd.graph.Node)
>>> handle = b.grad_fn.register_hook(lambda gI, gO: (gO[0] * 2,))
>>> b.sum().backward(retain_graph=True)
>>> print(a.grad)
tensor([2., 2., 2.])
>>> handle.remove() # Removes the hook
>>> a.grad = None
>>> b.sum().backward(retain_graph=True)
>>> print(a.grad)
tensor([1., 1., 1.])
"""
raise NotImplementedError
@abc.abstractmethod
def register_prehook(self, fn: Callable[..., Any]) -> RemovableHandle:
r"""Register a backward pre-hook.
The hook will be called every time a gradient with respect to the
Node is computed. The hook should have the following signature::
hook(grad_outputs: Tuple[Tensor]) -> Tuple[Tensor] or None
The hook should not modify its argument, but it can optionally return
a new gradient which will be used in place of :attr:`grad_outputs`.
This function returns a handle with a method ``handle.remove()``
that removes the hook from the module.
.. note::
See :ref:`backward-hooks-execution` for more information on how when this hook
is executed, and how its execution is ordered relative to other hooks.
Example::
>>> a = torch.tensor([0., 0., 0.], requires_grad=True)
>>> b = a.clone()
>>> assert isinstance(b.grad_fn, torch.autograd.graph.Node)
>>> handle = b.grad_fn.register_prehook(lambda gI: (gI[0] * 2,))
>>> b.sum().backward(retain_graph=True)
>>> print(a.grad)
tensor([2., 2., 2.])
>>> handle.remove()
>>> a.grad = None
>>> b.sum().backward(retain_graph=True)
>>> print(a.grad)
tensor([1., 1., 1.])
"""
raise NotImplementedError
@classmethod
def __subclasshook__(cls, subclass: type) -> bool:
if cls is Node and (
(
subclass is not None
and subclass is getattr(torch._C._functions, subclass.__name__, None)
)
or issubclass(subclass, torch.autograd.function.BackwardCFunction)
):
return True
return NotImplemented
def _get_grad_fn_or_grad_acc(t: Union[torch.Tensor, "GradientEdge"]) -> Node:
if isinstance(t, GradientEdge):
return t.node
if t.requires_grad and t.grad_fn is None:
with torch.enable_grad():
node = t.view_as(t).grad_fn.next_functions[0][0] # type: ignore[union-attr]
else:
node = t.grad_fn
if node is None:
raise AssertionError("Expected gradient function to be set")
return node
|
Node
|
python
|
getsentry__sentry
|
tests/sentry/tasks/test_post_process.py
|
{
"start": 74467,
"end": 78243
}
|
class ____(BasePostProgressGroupMixin):
@with_feature("organizations:sdk-crash-detection")
@override_options(
{
"issues.sdk_crash_detection.cocoa.project_id": 1234,
"issues.sdk_crash_detection.cocoa.sample_rate": 1.0,
"issues.sdk_crash_detection.react-native.project_id": 12345,
"issues.sdk_crash_detection.react-native.sample_rate": 1.0,
"issues.sdk_crash_detection.react-native.organization_allowlist": [1],
}
)
def test_sdk_crash_monitoring_is_called(self, mock_sdk_crash_detection: MagicMock) -> None:
event = self.create_event(
data={"message": "testing"},
project_id=self.project.id,
)
self.call_post_process_group(
is_new=True,
is_regression=False,
is_new_group_environment=True,
event=event,
)
mock_sdk_crash_detection.detect_sdk_crash.assert_called_once()
args = mock_sdk_crash_detection.detect_sdk_crash.call_args[-1]
assert args["event"].project.id == event.project.id
assert len(args["configs"]) == 2
cocoa_config = args["configs"][0]
assert cocoa_config.sdk_name == SdkName.Cocoa
assert cocoa_config.project_id == 1234
assert cocoa_config.sample_rate == 1.0
assert cocoa_config.organization_allowlist == []
react_native_config = args["configs"][1]
assert react_native_config.sdk_name == SdkName.ReactNative
assert react_native_config.project_id == 12345
assert react_native_config.sample_rate == 1.0
assert react_native_config.organization_allowlist == [1]
@with_feature("organizations:sdk-crash-detection")
@override_options(
{
"issues.sdk_crash_detection.cocoa.project_id": 1234,
"issues.sdk_crash_detection.cocoa.sample_rate": 0.0,
}
)
def test_sdk_crash_monitoring_not_called_without_sample_rate(
self, mock_sdk_crash_detection: MagicMock
) -> None:
event = self.create_event(
data={"message": "testing"},
project_id=self.project.id,
)
self.call_post_process_group(
is_new=True,
is_regression=False,
is_new_group_environment=True,
event=event,
)
mock_sdk_crash_detection.detect_sdk_crash.assert_not_called()
def test_sdk_crash_monitoring_is_not_called_with_disabled_feature(
self, mock_sdk_crash_detection
):
event = self.create_event(
data={"message": "testing"},
project_id=self.project.id,
)
self.call_post_process_group(
is_new=True,
is_regression=False,
is_new_group_environment=True,
event=event,
)
mock_sdk_crash_detection.detect_sdk_crash.assert_not_called()
@override_options(
{
"issues.sdk_crash_detection.cocoa.project_id": None,
}
)
@with_feature("organizations:sdk-crash-detection")
def test_sdk_crash_monitoring_is_not_called_without_project_id(
self, mock_sdk_crash_detection: MagicMock
) -> None:
event = self.create_event(
data={"message": "testing"},
project_id=self.project.id,
)
self.call_post_process_group(
is_new=True,
is_regression=False,
is_new_group_environment=True,
event=event,
)
mock_sdk_crash_detection.detect_sdk_crash.assert_not_called()
@mock.patch.object(replays_kafka, "get_kafka_producer_cluster_options")
@mock.patch.object(replays_kafka, "KafkaPublisher")
@mock.patch("sentry.utils.metrics.incr")
|
SDKCrashMonitoringTestMixin
|
python
|
getsentry__sentry
|
tests/sentry/sentry_apps/tasks/test_sentry_apps.py
|
{
"start": 2873,
"end": 4242
}
|
class ____:
def __init__(self):
self.body = "blah blah"
headers = {"Sentry-Hook-Error": "d5111da2c28645c5889d072017e3445d", "Sentry-Hook-Project": "1"}
html_content = "a bunch of garbage HTML"
json_content = '{"error": "bad request"}'
MockResponse = namedtuple(
"MockResponse",
["headers", "content", "text", "ok", "status_code", "raise_for_status", "request"],
)
MockFailureHTMLContentResponseInstance = MockResponse(
headers, html_content, "", True, 400, raiseStatusFalse, RequestMock()
)
MockFailureJSONContentResponseInstance = MockResponse(
headers, json_content, "", True, 400, raiseStatusFalse, RequestMock()
)
MockFailureResponseInstance = MockResponse(
headers, html_content, "", True, 400, raiseStatusFalse, RequestMock()
)
MockResponseWithHeadersInstance = MockResponse(
headers, html_content, "", True, 400, raiseStatusFalse, RequestMock()
)
MockResponseInstance = MockResponse({}, b"{}", "", True, 200, raiseStatusFalse, None)
MockResponse404 = MockResponse({}, b'{"bruh": "bruhhhhhhh"}', "", False, 404, raiseException, None)
MockResponse504 = MockResponse(headers, json_content, "", False, 504, raiseStatusFalse, None)
MockResponse503 = MockResponse(headers, json_content, "", False, 503, raiseStatusFalse, None)
MockResponse502 = MockResponse(headers, json_content, "", False, 502, raiseHTTPError, None)
|
RequestMock
|
python
|
huggingface__transformers
|
src/transformers/models/regnet/modeling_regnet.py
|
{
"start": 5654,
"end": 6945
}
|
class ____(nn.Module):
"""
RegNet's Y layer: an X layer with Squeeze and Excitation.
"""
def __init__(self, config: RegNetConfig, in_channels: int, out_channels: int, stride: int = 1):
super().__init__()
should_apply_shortcut = in_channels != out_channels or stride != 1
groups = max(1, out_channels // config.groups_width)
self.shortcut = (
RegNetShortCut(in_channels, out_channels, stride=stride) if should_apply_shortcut else nn.Identity()
)
self.layer = nn.Sequential(
RegNetConvLayer(in_channels, out_channels, kernel_size=1, activation=config.hidden_act),
RegNetConvLayer(out_channels, out_channels, stride=stride, groups=groups, activation=config.hidden_act),
RegNetSELayer(out_channels, reduced_channels=int(round(in_channels / 4))),
RegNetConvLayer(out_channels, out_channels, kernel_size=1, activation=None),
)
self.activation = ACT2FN[config.hidden_act]
def forward(self, hidden_state):
residual = hidden_state
hidden_state = self.layer(hidden_state)
residual = self.shortcut(residual)
hidden_state += residual
hidden_state = self.activation(hidden_state)
return hidden_state
|
RegNetYLayer
|
python
|
doocs__leetcode
|
solution/1300-1399/1316.Distinct Echo Substrings/Solution.py
|
{
"start": 0,
"end": 724
}
|
class ____:
def distinctEchoSubstrings(self, text: str) -> int:
def get(l, r):
return (h[r] - h[l - 1] * p[r - l + 1]) % mod
n = len(text)
base = 131
mod = int(1e9) + 7
h = [0] * (n + 10)
p = [1] * (n + 10)
for i, c in enumerate(text):
t = ord(c) - ord('a') + 1
h[i + 1] = (h[i] * base) % mod + t
p[i + 1] = (p[i] * base) % mod
vis = set()
for i in range(n - 1):
for j in range(i + 1, n, 2):
k = (i + j) >> 1
a = get(i + 1, k + 1)
b = get(k + 2, j + 1)
if a == b:
vis.add(a)
return len(vis)
|
Solution
|
python
|
google__jax
|
docs/the-training-cookbook.py
|
{
"start": 2476,
"end": 7264
}
|
class ____(dict):
__setattr__ = dict.__setitem__
__getattr__ = dict.__getitem__
def tree_flatten_with_keys(self):
keys = tuple(sorted(self))
return tuple((jax.tree_util.DictKey(k), self[k]) for k in keys), keys
@classmethod
def tree_unflatten(cls, keys, values):
return cls(zip(keys, values))
# tag: get-param-state
def init_param_state(config: Config) -> dot_dict:
root_key = jax.random.key(config.param_seed)
key = map(ft.partial(jax.random.fold_in, root_key), it.count())
zero_init = jax.nn.initializers.constant(0.0)
he_init = jax.nn.initializers.he_normal(1, 1)
dtype = config.dtype
params = dot_dict(
pos_embed=zero_init(next(key), (config.seq_length, config.embed_dim), dtype, config.pos_embed),
layers=dot_dict(),
)
params.embedding = he_init(next(key), (config.vocab_size, config.embed_dim), dtype, config.embed)
params.linear_in = dot_dict(
kernel=he_init(next(key), (1, config.embed_dim), dtype, config.in_kernel),
bias=zero_init(next(key), (config.embed_dim,), dtype, config.in_bias),
)
params.linear_out = dot_dict(
kernel=he_init(next(key), (config.embed_dim, config.vocab_size), dtype, config.out_kernel),
)
for layer in range(config.num_layers):
qkv_shape = (3, config.embed_dim, config.num_heads, config.head_dim)
out_shape = (config.num_heads, config.head_dim, config.embed_dim)
params.layers[layer] = dot_dict(
attention=dot_dict(
qkv=he_init(next(key), qkv_shape, dtype, config.att_qkv),
out=he_init(next(key), out_shape, dtype, config.att_out),
),
mlp=dot_dict(
in_kernel=he_init(next(key), (config.embed_dim, config.mlp_dim), dtype, config.mlp_in),
out_kernel=he_init(next(key), (config.mlp_dim, config.embed_dim), dtype, config.mlp_out),
),
)
return params # tag: get-param-state
# tag: model-apply
def model_apply(config: Config, params: dot_dict, tokens: jax.Array) -> jax.Array:
out = params.embedding.at[tokens].get(out_sharding=config.act_seq)
out += params.pos_embed
del tokens
for layer in range(config.num_layers):
block = params.layers[layer]
att_skip = out # 1 billion dollars in venture capital funding please
qkv = jnp.einsum("bsd,3dkh->bs3kh", out, block.attention.qkv, out_sharding=config.act_att)
out = jax.nn.dot_product_attention(qkv[:, :, 0, :], qkv[:, :, 1, :], qkv[:, :, 2, :], is_causal=True)
out = jnp.einsum("bskh,khd->bsd", out, block.attention.out, out_sharding=config.act_seq)
out += att_skip
out *= jax.lax.rsqrt(jnp.linalg.norm(out, axis=-1, keepdims=True) + 1e-6)
mlp_skip = out # machine learning circa 1986
out = jnp.einsum("bsd,dh->bsh", out, block.mlp.in_kernel, out_sharding=config.act_hidden)
out = jax.nn.gelu(out)
out = jnp.einsum("bsh,hd->bsd", out, block.mlp.out_kernel, out_sharding=config.act_seq)
out += mlp_skip
out *= jax.lax.rsqrt(jnp.linalg.norm(out, axis=-1, keepdims=True) + 1e-6)
logits = jnp.einsum("bsd,dl->bsl", out, params.linear_out.kernel, out_sharding=config.act_seq)
return logits # tag: model-apply
# tag: get-adam-state
def init_adam_state(param: jax.Array) -> dot_dict:
adam_state = dot_dict(mu=jnp.zeros_like(param), nu=jnp.zeros_like(param), count=jnp.array(0))
return adam_state # tag: get-adam-state
# tag: adam-apply
def adam_update(config: Config, param: jax.Ref, grad: jax.Array, adam_state: dot_dict):
adam_state.mu[...] = (1 - config.beta_1) * adam_state.mu[...] + config.beta_1 * grad
adam_state.nu[...] = (1 - config.beta_2) * adam_state.nu[...] + config.beta_2 * grad**2
adam_state.count[...] += 1
mu_hat = adam_state.mu[...] / (1 - config.beta_1 ** adam_state.count[...])
nu_hat = adam_state.nu[...] / (1 - config.beta_2 ** adam_state.count[...])
param[...] -= config.learning_rate * mu_hat / (jnp.sqrt(nu_hat + config.eps_root) + config.eps)
# tag: adam-apply
# tag: get-train-state
@jax.jit
def init_train_state(config: Config) -> dot_dict:
train_state = dot_dict()
train_state.params = init_param_state(config)
train_state.opt = jax.tree.map(init_adam_state, train_state.params)
return train_state # tag: get-train-state
# tag: train-step
@jax.jit
def train_step(config: Config, train_state: dot_dict, batch: dict) -> dict:
def loss_fn(params):
logits = model_apply(config, params, batch["observed_ids"])
labels = jax.nn.one_hot(batch["target_ids"], config.vocab_size)
return -(labels * jax.nn.log_softmax(logits)).mean()
params = jax.tree.map(jax.ref.get, train_state.params)
loss, grad = jax.value_and_grad(loss_fn)(params)
jax.tree.map(ft.partial(adam_update, config), train_state.params, grad, train_state.opt)
metrics = {"train_loss": loss}
return metrics # tag: train-step
# tag: record-writer
|
dot_dict
|
python
|
ansible__ansible
|
lib/ansible/_internal/_encryption/_crypt.py
|
{
"start": 1060,
"end": 5994
}
|
class ____:
"""
Provide an interface for various crypt libraries that might be available.
"""
def __init__(self) -> None:
self._crypt_impl: t.Callable | None = None
self._crypt_gensalt_impl: t.Callable | None = None
self._use_crypt_r = False
self._use_crypt_gensalt_rn = False
self._crypt_name = ""
self._setup()
class _CryptData(ctypes.Structure):
_fields_ = [('_opaque', ctypes.c_char * 131072)]
@property
def has_crypt_gensalt(self) -> bool:
return self._crypt_gensalt_impl is not None
def _setup(self) -> None:
"""Setup crypt implementation"""
for lib_config in _CRYPT_LIBS:
if sys.platform in lib_config.exclude_platforms:
continue
if lib_config.include_platforms and sys.platform not in lib_config.include_platforms:
continue
if lib_config.name is None:
lib_so = None
elif lib_config.is_path:
if os.path.exists(lib_config.name):
lib_so = lib_config.name
else:
continue
else:
lib_so = ctypes.util.find_library(lib_config.name)
if not lib_so:
continue
loaded_lib = ctypes.cdll.LoadLibrary(lib_so)
try:
self._crypt_impl = loaded_lib.crypt_r
self._use_crypt_r = True
except AttributeError:
try:
self._crypt_impl = loaded_lib.crypt
except AttributeError:
continue
if self._use_crypt_r:
self._crypt_impl.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.POINTER(self._CryptData)]
self._crypt_impl.restype = ctypes.c_char_p
else:
self._crypt_impl.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
self._crypt_impl.restype = ctypes.c_char_p
# Try to load crypt_gensalt (available in libxcrypt)
try:
self._crypt_gensalt_impl = loaded_lib.crypt_gensalt_rn
self._crypt_gensalt_impl.argtypes = [ctypes.c_char_p, ctypes.c_ulong, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_int]
self._crypt_gensalt_impl.restype = ctypes.c_char_p
self._use_crypt_gensalt_rn = True
except AttributeError:
try:
self._crypt_gensalt_impl = loaded_lib.crypt_gensalt
self._crypt_gensalt_impl.argtypes = [ctypes.c_char_p, ctypes.c_ulong, ctypes.c_char_p, ctypes.c_int]
self._crypt_gensalt_impl.restype = ctypes.c_char_p
except AttributeError:
self._crypt_gensalt_impl = None
self._crypt_name = lib_config.name
break
else:
raise ImportError('Cannot find crypt implementation')
def crypt(self, word: bytes, salt: bytes) -> bytes:
"""Hash a password using the system's crypt function."""
ctypes.set_errno(0)
if self._use_crypt_r:
data = self._CryptData()
ctypes.memset(ctypes.byref(data), 0, ctypes.sizeof(data))
result = self._crypt_impl(word, salt, ctypes.byref(data))
else:
result = self._crypt_impl(word, salt)
errno = ctypes.get_errno()
if errno:
error_msg = os.strerror(errno)
raise OSError(errno, f'crypt failed: {error_msg}')
if result is None:
raise ValueError('crypt failed: invalid salt or unsupported algorithm')
if result in _FAILURE_TOKENS:
raise ValueError('crypt failed: invalid salt or unsupported algorithm')
return result
def crypt_gensalt(self, prefix: bytes, count: int, rbytes: bytes) -> bytes:
"""Generate a salt string for use with crypt."""
if not self.has_crypt_gensalt:
raise NotImplementedError('crypt_gensalt not available (requires libxcrypt)')
ctypes.set_errno(0)
if self._use_crypt_gensalt_rn:
output = ctypes.create_string_buffer(256)
result = self._crypt_gensalt_impl(prefix, count, rbytes, len(rbytes), output, len(output))
if result is not None:
result = output.value
else:
result = self._crypt_gensalt_impl(prefix, count, rbytes, len(rbytes))
errno = ctypes.get_errno()
if errno:
error_msg = os.strerror(errno)
raise OSError(errno, f'crypt_gensalt failed: {error_msg}')
if result is None:
raise ValueError('crypt_gensalt failed: unable to generate salt')
if result in _FAILURE_TOKENS:
raise ValueError('crypt_gensalt failed: invalid prefix or unsupported algorithm')
return result
|
CryptFacade
|
python
|
charliermarsh__ruff
|
crates/ruff_linter/resources/test/fixtures/flake8_commas/COM81.py
|
{
"start": 6850,
"end": 6907
}
|
class ____[
T
]: pass
type X[T,] = T
def f[T,](): pass
|
C
|
python
|
huggingface__transformers
|
src/transformers/models/jetmoe/modeling_jetmoe.py
|
{
"start": 25710,
"end": 32488
}
|
class ____(JetMoePreTrainedModel):
def __init__(self, config: JetMoeConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.layers = nn.ModuleList(
[JetMoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = JetMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = JetMoeRotaryEmbedding(config=config)
self.gradient_checkpointing = False
self._attn_implementation = config._attn_implementation
# Initialize weights and apply final processing
self.post_init()
@check_model_inputs()
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> MoeModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if use_cache and past_key_values is None:
past_key_values = DynamicCache(config=self.config)
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if cache_position is None:
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
cache_position = torch.arange(
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
)
if position_ids is None:
position_ids = cache_position.unsqueeze(0)
causal_mask = create_causal_mask(
config=self.config,
input_embeds=inputs_embeds,
attention_mask=attention_mask,
cache_position=cache_position,
past_key_values=past_key_values,
position_ids=position_ids,
)
hidden_states = inputs_embeds
# create position embeddings to be shared across the decoder layers
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
attention_mask=causal_mask,
past_key_values=past_key_values,
use_cache=use_cache,
cache_position=cache_position,
position_ids=position_ids,
**kwargs,
)
hidden_states = self.norm(hidden_states)
return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
last_hidden_state=hidden_states,
past_key_values=past_key_values,
)
def load_balancing_loss_func(
gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
num_experts: Optional[int] = None,
top_k=2,
attention_mask: Optional[torch.Tensor] = None,
) -> Union[torch.Tensor, int]:
r"""
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
experts is too unbalanced.
Args:
gate_logits:
Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
shape [batch_size X sequence_length, num_experts].
num_experts:
Number of experts
top_k:
The number of experts to route per-token, can be also interpreted as the `top-k` routing
parameter.
attention_mask (`torch.Tensor`, *optional*):
The attention_mask used in forward function
shape [batch_size X sequence_length] if not None.
Returns:
The auxiliary loss.
"""
if gate_logits is None or not isinstance(gate_logits, tuple):
return 0
if isinstance(gate_logits, tuple):
compute_device = gate_logits[0].device
concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
_, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
if attention_mask is None:
# Compute the percentage of tokens routed to each experts
tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
# Compute the average probability of routing to these experts
router_prob_per_expert = torch.mean(routing_weights, dim=0)
else:
batch_size, sequence_length = attention_mask.shape
num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
# Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
expert_attention_mask = (
attention_mask[None, :, :, None, None]
.expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
.reshape(-1, top_k, num_experts)
.to(compute_device)
)
# Compute the percentage of tokens routed to each experts
tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
expert_attention_mask, dim=0
)
# Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
router_per_expert_attention_mask = (
attention_mask[None, :, :, None]
.expand((num_hidden_layers, batch_size, sequence_length, num_experts))
.reshape(-1, num_experts)
.to(compute_device)
)
# Compute the average probability of routing to these experts
router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
router_per_expert_attention_mask, dim=0
)
overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
return overall_loss * num_experts
|
JetMoeModel
|
python
|
sympy__sympy
|
sympy/stats/frv.py
|
{
"start": 15927,
"end": 16874
}
|
class ____(IndependentProductPSpace, FinitePSpace):
"""
A collection of several independent finite probability spaces
"""
@property
def domain(self):
return ProductFiniteDomain(*[space.domain for space in self.spaces])
@property # type: ignore
@cacheit
def _density(self):
proditer = product(*[iter(space._density.items())
for space in self.spaces])
d = {}
for items in proditer:
elems, probs = list(zip(*items))
elem = sumsets(elems)
prob = Mul(*probs)
d[elem] = d.get(elem, S.Zero) + prob
return Dict(d)
@property # type: ignore
@cacheit
def density(self):
return Dict(self._density)
def probability(self, condition):
return FinitePSpace.probability(self, condition)
def compute_density(self, expr):
return FinitePSpace.compute_density(self, expr)
|
ProductFinitePSpace
|
python
|
ApeWorX__ape
|
src/ape/types/coverage.py
|
{
"start": 12440,
"end": 15160
}
|
class ____(BaseModel):
"""
A project with coverage collected.
"""
name: str
"""
The name of the project being covered.
"""
sources: list[ContractSourceCoverage] = []
"""
Coverage for each source in the project.
"""
@property
def statements(self) -> list[CoverageStatement]:
"""
All valid coverage lines from every function in every contract in every source
in this project.
"""
return list(itertools.chain.from_iterable(s.statements for s in self.sources))
@property
def lines_covered(self) -> NonNegativeInt:
"""
The number of lines with a hit count greater than zero from every function
in every contract in every source in this this project.
"""
return sum(s.lines_covered for s in self.sources)
@property
def lines_valid(self) -> NonNegativeInt:
"""
The number of lines valid for coverage.
"""
return len(self.statements)
@property
def miss_count(self) -> NonNegativeInt:
"""
The number of lines missed.
"""
return self.lines_valid - self.lines_covered
@property
def line_rate(self) -> float:
"""
The number of lines hit divided by number of lines.
"""
return self.lines_covered / self.lines_valid if self.lines_valid > 0 else 0
@property
def total_functions(self) -> NonNegativeInt:
"""
The total number of functions in this source.
"""
return sum(x.total_functions for x in self.sources)
@property
def function_hits(self) -> NonNegativeInt:
"""
The number of functions with a hit counter greater than zero.
"""
return sum(x.function_hits for x in self.sources)
@property
def function_rate(self) -> float:
"""
The rate of functions hit versus total functions.
"""
return self.function_hits / self.total_functions if self.total_functions > 0 else 0
def model_dump(self, *args, **kwargs) -> dict:
attribs = super().model_dump(*args, **kwargs)
# Add coverage stats.
attribs["lines_covered"] = self.lines_covered
attribs["lines_valid"] = self.lines_valid
attribs["line_rate"] = self.line_rate
return attribs
def include(self, contract_source: "ContractSource") -> ContractSourceCoverage:
for src in self.sources:
if src.source_id == contract_source.source_id:
return src
source_cov = ContractSourceCoverage(source_id=contract_source.source_id)
self.sources.append(source_cov)
return source_cov
|
CoverageProject
|
python
|
realpython__materials
|
python-bitwise-operators/src/stegano/encoder.py
|
{
"start": 153,
"end": 1605
}
|
class ____:
"""Convenience class for serializing secret data."""
def __init__(self, path: pathlib.Path):
self.path = path
self.filename = path.name.encode("utf-8") + b"\x00"
self.size_bytes = path.stat().st_size
@property
def num_secret_bytes(self) -> int:
"""Total number of bytes including the null-terminated string."""
return len(self.filename) + self.size_bytes
@property
def secret_bytes(self) -> Iterator[int]:
"""Null-terminated name followed by the file content."""
yield from self.filename
with self.path.open(mode="rb") as file:
yield from file.read()
def encode(bitmap: Bitmap, path: pathlib.Path) -> None:
"""Embed a secret file in the bitmap."""
file = SecretFile(path)
if file.num_secret_bytes > bitmap.max_bytes:
raise EncodingError("Not enough pixels to embed a secret file")
bitmap.reserved_field = file.size_bytes
for secret_byte, eight_bytes in zip(
file.secret_bytes, bitmap.byte_slices, strict=False
):
secret_bits = [(secret_byte >> i) & 1 for i in reversed(range(8))]
bitmap[eight_bytes] = bytes(
[
byte | 1 if bit else byte & ~1
for byte, bit in zip(
bitmap[eight_bytes], secret_bits, strict=False
)
]
)
print("Secret file was embedded in the bitmap")
|
SecretFile
|
python
|
miyuchina__mistletoe
|
mistletoe/span_token.py
|
{
"start": 3068,
"end": 3884
}
|
class ____(SpanToken):
"""
Inline code token. ("`some code`")
This is an inline token with a single child of type RawText.
"""
pattern = re.compile(r"(?<!\\|`)(?:\\\\)*(`+)(?!`)(.+?)(?<!`)\1(?!`)", re.DOTALL)
parse_inner = False
parse_group = 2
def __init__(self, match):
content = match.group(self.parse_group)
self.delimiter = match.group(1)
content = content.replace('\n', ' ')
self.padding = " " if not content.isspace() and content.startswith(" ") and content.endswith(" ") else ""
if self.padding:
content = content[1:-1]
self.children = (RawText(content),)
@classmethod
def find(cls, string):
matches = core_tokens._code_matches
core_tokens._code_matches = []
return matches
|
InlineCode
|
python
|
run-llama__llama_index
|
llama-index-integrations/observability/llama-index-observability-otel/llama_index/observability/otel/base.py
|
{
"start": 1408,
"end": 5367
}
|
class ____(SimpleSpanHandler):
"""OpenTelemetry-compatible span handler."""
_tracer: trace.Tracer = PrivateAttr()
_events_by_span: Dict[str, List[OTelEventAttributes]] = PrivateAttr(
default_factory=dict,
)
all_spans: Dict[str, Union[trace.Span, _Span]] = Field(
default_factory=dict, description="All the registered OpenTelemetry spans."
)
debug: bool = Field(
default=False,
description="Debug the start and end of span and the recording of events",
)
def __init__(
self,
tracer: trace.Tracer,
debug: bool = False,
open_spans: Optional[Dict[str, SimpleSpan]] = None,
completed_spans: Optional[List[SimpleSpan]] = None,
dropped_spans: Optional[List[SimpleSpan]] = None,
current_span_ids: Optional[Dict[Any, str]] = None,
):
super().__init__(
open_spans=open_spans or {},
completed_spans=completed_spans or [],
dropped_spans=dropped_spans or [],
current_span_ids=current_span_ids or {},
)
self._tracer = tracer
self._events_by_span = {}
self.debug = debug
@classmethod
def class_name(cls) -> str:
"""Class name."""
return "OTelCompatibleSpanHandler"
def new_span(
self,
id_: str,
bound_args: inspect.BoundArguments,
instance: Optional[Any] = None,
parent_span_id: Optional[str] = None,
tags: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> SimpleSpan:
span = super().new_span(
id_, bound_args, instance, parent_span_id, tags, **kwargs
)
if parent_span_id is not None:
ctx = set_span_in_context(span=self.all_spans[parent_span_id])
else:
ctx = context.Context(bound_args.arguments)
otel_span = self._tracer.start_span(name=id_, context=ctx)
self.all_spans.update({id_: otel_span})
if self.debug:
cprint(
f"Emitting span {id_} at time: {datetime.now()}",
color="yellow",
attrs=["bold"],
)
return span
def prepare_to_exit_span(
self,
id_: str,
bound_args: inspect.BoundArguments,
instance: Optional[Any] = None,
result: Optional[Any] = None,
**kwargs: Any,
) -> SimpleSpan:
if self.debug:
cprint(
f"Preparing to end span {id_} at time: {datetime.now()}",
color="blue",
attrs=["bold"],
)
sp = super().prepare_to_exit_span(id_, bound_args, instance, result, **kwargs)
span = self.all_spans.pop(id_)
# Get and process events specific to this span
events = self._events_by_span.pop(id_, [])
for event in events:
span.add_event(name=event.name, attributes=event.attributes)
span.set_status(status=trace.StatusCode.OK)
span.end()
return sp
def prepare_to_drop_span(
self,
id_: str,
bound_args: inspect.BoundArguments,
instance: Optional[Any] = None,
err: Optional[BaseException] = None,
**kwargs: Any,
) -> Optional[SimpleSpan]:
if self.debug:
cprint(
f"Preparing to exit span {id_} with an error at time: {datetime.now()}",
color="red",
attrs=["bold"],
)
sp = super().prepare_to_drop_span(id_, bound_args, instance, err, **kwargs)
span = self.all_spans.pop(id_)
# Get and process events specific to this span
events = self._events_by_span.pop(id_, [])
for event in events:
span.add_event(name=event.name, attributes=event.attributes)
span.set_status(status=trace.StatusCode.ERROR, description=err.__str__())
span.end()
return sp
|
OTelCompatibleSpanHandler
|
python
|
gevent__gevent
|
src/gevent/tests/test__greenlet.py
|
{
"start": 2278,
"end": 3839
}
|
class ____(greentest.TestCase):
def test_link_to_asyncresult(self):
p = gevent.spawn(lambda: 100)
event = AsyncResult()
p.link(event)
self.assertEqual(event.get(), 100)
for _ in range(3):
event2 = AsyncResult()
p.link(event2)
self.assertEqual(event2.get(), 100)
def test_link_to_asyncresult_exception(self):
err = ExpectedError('test_link_to_asyncresult_exception')
p = gevent.spawn(lambda: getcurrent().throw(err))
event = AsyncResult()
p.link(event)
with self.assertRaises(ExpectedError) as exc:
event.get()
self.assertIs(exc.exception, err)
for _ in range(3):
event2 = AsyncResult()
p.link(event2)
with self.assertRaises(ExpectedError) as exc:
event2.get()
self.assertIs(exc.exception, err)
def test_link_to_queue(self):
p = gevent.spawn(lambda: 100)
q = Queue()
p.link(q.put)
self.assertEqual(q.get().get(), 100)
for _ in range(3):
p.link(q.put)
self.assertEqual(q.get().get(), 100)
def test_link_to_channel(self):
p1 = gevent.spawn(lambda: 101)
p2 = gevent.spawn(lambda: 102)
p3 = gevent.spawn(lambda: 103)
q = Channel()
p1.link(q.put)
p2.link(q.put)
p3.link(q.put)
results = [q.get().get(), q.get().get(), q.get().get()]
self.assertEqual(sorted(results), [101, 102, 103], results)
|
TestLink
|
python
|
django__django
|
tests/httpwrappers/tests.py
|
{
"start": 21105,
"end": 25284
}
|
class ____(SimpleTestCase):
def test_redirect(self):
response = HttpResponseRedirect("/redirected/")
self.assertEqual(response.status_code, 302)
# Standard HttpResponse init args can be used
response = HttpResponseRedirect(
"/redirected/",
content="The resource has temporarily moved",
)
self.assertContains(
response, "The resource has temporarily moved", status_code=302
)
self.assertEqual(response.url, response.headers["Location"])
def test_redirect_lazy(self):
"""Make sure HttpResponseRedirect works with lazy strings."""
r = HttpResponseRedirect(lazystr("/redirected/"))
self.assertEqual(r.url, "/redirected/")
def test_redirect_modifiers(self):
cases = [
(HttpResponseRedirect, "Moved temporarily", False, 302),
(HttpResponseRedirect, "Moved temporarily preserve method", True, 307),
(HttpResponsePermanentRedirect, "Moved permanently", False, 301),
(
HttpResponsePermanentRedirect,
"Moved permanently preserve method",
True,
308,
),
]
for response_class, content, preserve_request, expected_status_code in cases:
with self.subTest(status_code=expected_status_code):
response = response_class(
"/redirected/", content=content, preserve_request=preserve_request
)
self.assertEqual(response.status_code, expected_status_code)
self.assertEqual(response.content.decode(), content)
self.assertEqual(response.url, response.headers["Location"])
def test_redirect_repr(self):
response = HttpResponseRedirect("/redirected/")
expected = (
'<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", '
'url="/redirected/">'
)
self.assertEqual(repr(response), expected)
def test_invalid_redirect_repr(self):
"""
If HttpResponseRedirect raises DisallowedRedirect, its __repr__()
should work (in the debug view, for example).
"""
response = HttpResponseRedirect.__new__(HttpResponseRedirect)
with self.assertRaisesMessage(
DisallowedRedirect, "Unsafe redirect to URL with protocol 'ssh'"
):
HttpResponseRedirect.__init__(response, "ssh://foo")
expected = (
'<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", '
'url="ssh://foo">'
)
self.assertEqual(repr(response), expected)
def test_not_modified(self):
response = HttpResponseNotModified()
self.assertEqual(response.status_code, 304)
# 304 responses should not have content/content-type
with self.assertRaises(AttributeError):
response.content = "Hello dear"
self.assertNotIn("content-type", response)
def test_not_modified_repr(self):
response = HttpResponseNotModified()
self.assertEqual(repr(response), "<HttpResponseNotModified status_code=304>")
def test_not_allowed(self):
response = HttpResponseNotAllowed(["GET"])
self.assertEqual(response.status_code, 405)
# Standard HttpResponse init args can be used
response = HttpResponseNotAllowed(
["GET"], content="Only the GET method is allowed"
)
self.assertContains(response, "Only the GET method is allowed", status_code=405)
def test_not_allowed_repr(self):
response = HttpResponseNotAllowed(["GET", "OPTIONS"], content_type="text/plain")
expected = (
'<HttpResponseNotAllowed [GET, OPTIONS] status_code=405, "text/plain">'
)
self.assertEqual(repr(response), expected)
def test_not_allowed_repr_no_content_type(self):
response = HttpResponseNotAllowed(("GET", "POST"))
del response.headers["Content-Type"]
self.assertEqual(
repr(response), "<HttpResponseNotAllowed [GET, POST] status_code=405>"
)
|
HttpResponseSubclassesTests
|
python
|
getsentry__sentry
|
tests/sentry/issues/endpoints/test_organization_group_search_view_details.py
|
{
"start": 11164,
"end": 14993
}
|
class ____(APITestCase):
endpoint = "sentry-api-0-organization-group-search-view-details"
def setUp(self) -> None:
super().setUp()
self.user_1 = self.user
self.user_2 = self.create_user()
self.create_member(organization=self.organization, user=self.user_2)
self.user_1_view = GroupSearchView.objects.create(
organization=self.organization,
user_id=self.user_1.id,
name="User 1's View",
query="is:unresolved",
visibility=GroupSearchViewVisibility.ORGANIZATION,
)
GroupSearchViewStarred.objects.create(
organization=self.organization,
user_id=self.user_1.id,
group_search_view=self.user_1_view,
position=0,
)
GroupSearchViewLastVisited.objects.create(
organization=self.organization,
user_id=self.user_1.id,
group_search_view=self.user_1_view,
last_visited=timezone.now(),
)
self.user_2_view = GroupSearchView.objects.create(
organization=self.organization,
user_id=self.user_2.id,
name="User 2's View",
query="is:unresolved",
visibility=GroupSearchViewVisibility.ORGANIZATION,
)
GroupSearchViewStarred.objects.create(
organization=self.organization,
user_id=self.user_2.id,
group_search_view=self.user_1_view,
position=0,
)
GroupSearchViewStarred.objects.create(
organization=self.organization,
user_id=self.user_2.id,
group_search_view=self.user_2_view,
position=1,
)
GroupSearchViewLastVisited.objects.create(
organization=self.organization,
user_id=self.user_2.id,
group_search_view=self.user_1_view,
last_visited=timezone.now(),
)
@with_feature({"organizations:issue-views": True})
def test_cannot_delete_other_users_view(self) -> None:
self.login_as(user=self.user_2)
response = self.client.delete(
reverse(
self.endpoint,
kwargs={
"organization_id_or_slug": self.organization.slug,
"view_id": self.user_1_view.id,
},
)
)
assert response.status_code == 403
@with_feature({"organizations:issue-views": True})
def test_deleting_my_view_deletes_from_others_starred_views(self) -> None:
self.login_as(user=self.user_1)
response = self.client.delete(
reverse(
self.endpoint,
kwargs={
"organization_id_or_slug": self.organization.slug,
"view_id": self.user_1_view.id,
},
)
)
assert response.status_code == 204
# User 2 starred User 1's view. After User 1 deletes the view, it should not be starred for anyone anymore
assert not GroupSearchViewStarred.objects.filter(
organization_id=self.organization.id, group_search_view=self.user_1_view
).exists()
# User 2's other starred view should be moved up to position 0
assert (
GroupSearchViewStarred.objects.get(
organization_id=self.organization.id,
user_id=self.user_2.id,
group_search_view=self.user_2_view,
).position
== 0
)
# All last visited entries should be deleted as well
assert not GroupSearchViewLastVisited.objects.filter(
organization_id=self.organization.id, group_search_view=self.user_1_view
).exists()
|
OrganizationGroupSearchViewsDeleteStarredAndLastVisitedTest
|
python
|
pytorch__pytorch
|
torch/_inductor/custom_graph_pass.py
|
{
"start": 1995,
"end": 3820
}
|
class ____(ABC):
"""
Implement this interface for custom Graph passes:
1) The __call__() method contains the implementation of the custom pass.
2) The uuid() method enables inductor to cache compiled graphs when your custom
passes are applied. This method can return any identifier as long as it uniquely
identifies your implementation (and can be pickled). The caching logic includes this
identifier in its key calculation, i.e., any new value will effectively invalidate
existing entries. We expect custom passes would typically depend purely on the
textual representation of the implementation. In that case, we recommend using the
'get_hash_for_files' helper below to compute a unique hash from the contents of a
static list of source files, i.e., the source(s) containing the custom pass
implementation. That approach ensures that any change to the implementation will
mean a new uuid.
"""
@abstractmethod
def __call__(self, gm: torch.fx.GraphModule) -> None:
"""
Implementation of the custom pass.
"""
@abstractmethod
def uuid(self) -> Optional[Any]:
"""
Return an ID to uniquely identify your custom pass implementation. Return None
to skip inductor code caching entirely.
"""
CustomGraphPassType: TypeAlias = Optional[
Union[CustomGraphPass, Callable[[torch.fx.graph.Graph], None]]
]
@lru_cache(1)
def get_hash_for_files(paths: tuple[str], extra: str = "") -> bytes:
"""
Helper to compute a unique string by hashing the contents of a list of files.
"""
hasher = hashlib.sha256()
hasher.update(extra.encode("utf-8"))
for path in paths:
with open(path, "rb") as f:
hasher.update(f.read())
return hasher.digest()
|
CustomGraphModulePass
|
python
|
mwaskom__seaborn
|
seaborn/_core/plot.py
|
{
"start": 2072,
"end": 4222
}
|
class ____(TypedDict, total=False):
variables: dict[str, VariableSpec]
structure: dict[str, list[str]]
cross: bool
wrap: int | None
# --- Local helpers ---------------------------------------------------------------- #
@contextmanager
def theme_context(params: dict[str, Any]) -> Generator:
"""Temporarily modify specifc matplotlib rcParams."""
orig_params = {k: mpl.rcParams[k] for k in params}
color_codes = "bgrmyck"
nice_colors = [*color_palette("deep6"), (.15, .15, .15)]
orig_colors = [mpl.colors.colorConverter.colors[x] for x in color_codes]
# TODO how to allow this to reflect the color cycle when relevant?
try:
mpl.rcParams.update(params)
for (code, color) in zip(color_codes, nice_colors):
mpl.colors.colorConverter.colors[code] = color
yield
finally:
mpl.rcParams.update(orig_params)
for (code, color) in zip(color_codes, orig_colors):
mpl.colors.colorConverter.colors[code] = color
def build_plot_signature(cls):
"""
Decorator function for giving Plot a useful signature.
Currently this mostly saves us some duplicated typing, but we would
like eventually to have a way of registering new semantic properties,
at which point dynamic signature generation would become more important.
"""
sig = inspect.signature(cls)
params = [
inspect.Parameter("args", inspect.Parameter.VAR_POSITIONAL),
inspect.Parameter("data", inspect.Parameter.KEYWORD_ONLY, default=None)
]
params.extend([
inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, default=None)
for name in PROPERTIES
])
new_sig = sig.replace(parameters=params)
cls.__signature__ = new_sig
known_properties = textwrap.fill(
", ".join([f"|{p}|" for p in PROPERTIES]),
width=78, subsequent_indent=" " * 8,
)
if cls.__doc__ is not None: # support python -OO mode
cls.__doc__ = cls.__doc__.format(known_properties=known_properties)
return cls
# ---- Plot configuration ---------------------------------------------------------- #
|
PairSpec
|
python
|
qdrant__qdrant-client
|
qdrant_client/http/models/models.py
|
{
"start": 83118,
"end": 83439
}
|
class ____(str, Enum):
"""
All possible names of payload types
"""
def __str__(self) -> str:
return str(self.value)
KEYWORD = "keyword"
INTEGER = "integer"
FLOAT = "float"
GEO = "geo"
TEXT = "text"
BOOL = "bool"
DATETIME = "datetime"
UUID = "uuid"
|
PayloadSchemaType
|
python
|
getsentry__sentry
|
src/sentry/api/serializers/models/project.py
|
{
"start": 46931,
"end": 47266
}
|
class ____(Serializer):
def serialize(self, obj, attrs, user, **kwargs):
return {
"slug": obj.slug,
"name": obj.name,
"color": obj.color,
"features": [],
"organization": {"slug": obj.organization.slug, "name": obj.organization.name},
}
|
SharedProjectSerializer
|
python
|
facelessuser__pymdown-extensions
|
tests/test_extensions/test_snippets.py
|
{
"start": 18909,
"end": 20698
}
|
class ____(util.MdCase):
"""Test snippet file case."""
extension = [
'pymdownx.snippets',
]
extension_configs = {
'pymdownx.snippets': {
'base_path': [os.path.join(BASE, '_snippets')],
'check_paths': True
}
}
def test_good(self):
"""Test found file."""
self.check_markdown(
'''
--8<--- "d.txt"
''',
'''
<p>Snippet</p>
''',
True
)
def test_top_level(self):
"""Test top level."""
with self.assertRaises(SnippetMissingError):
self.check_markdown(
R'''
--8<-- "not-here.txt"
''',
'''
''',
True
)
def test_nested(self):
"""Test nested."""
with self.assertRaises(SnippetMissingError):
self.check_markdown(
R'''
--8<-- "missing.txt"
''',
'''
''',
True
)
def test_missing_file_lines(self):
"""Test missing file with line numbers."""
with self.assertRaises(SnippetMissingError):
self.check_markdown(
R'''
--8<-- ":3:4"
''',
'''
''',
True
)
def test_missing_section(self):
"""Test missing section."""
with self.assertRaises(SnippetMissingError):
self.check_markdown(
R'''
--8<-- "section.txt:missing-section"
''',
'''
''',
True
)
|
TestSnippetsMissing
|
python
|
dagster-io__dagster
|
python_modules/dagster/dagster_tests/freshness_tests/test_internal_freshness.py
|
{
"start": 9872,
"end": 15725
}
|
class ____:
def test_cron_freshness_policy_validation_basic(self) -> None:
"""Can we define a cron freshness policy with valid parameters?"""
# Valid cron string and lower bound delta
policy = FreshnessPolicy.cron(
deadline_cron="0 10 * * *",
lower_bound_delta=timedelta(hours=1),
)
assert isinstance(policy, CronFreshnessPolicy)
assert policy.deadline_cron == "0 10 * * *"
assert policy.lower_bound_delta == timedelta(hours=1)
assert policy.timezone == "UTC"
def test_cron_freshness_policy_validation_with_timezone(self) -> None:
policy = FreshnessPolicy.cron(
deadline_cron="0 10 * * *",
lower_bound_delta=timedelta(hours=1),
timezone="America/New_York",
)
assert isinstance(policy, CronFreshnessPolicy)
assert policy.deadline_cron == "0 10 * * *"
assert policy.lower_bound_delta == timedelta(hours=1)
assert policy.timezone == "America/New_York"
def test_cron_freshness_policy_validation_invalid_cron(self) -> None:
with pytest.raises(CheckError, match="Invalid cron string"):
FreshnessPolicy.cron(
deadline_cron="0 10 * * * *", # we don't support seconds resolution in the cron
lower_bound_delta=timedelta(hours=1),
)
def test_cron_freshness_policy_validation_invalid_timezone(self) -> None:
with pytest.raises(CheckError, match="Invalid IANA timezone"):
FreshnessPolicy.cron(
deadline_cron="0 10 * * *",
lower_bound_delta=timedelta(hours=1),
timezone="Invalid/Timezone",
)
def test_cron_freshness_policy_validation_lower_bound_minimum(self) -> None:
with pytest.raises(
CheckError, match="lower_bound_delta must be greater than or equal to 1 minute"
):
FreshnessPolicy.cron(
deadline_cron="0 10 * * *",
lower_bound_delta=timedelta(seconds=59),
)
def test_cron_freshness_policy_validation_zero_lower_bound(self) -> None:
with pytest.raises(
CheckError, match="lower_bound_delta must be greater than or equal to 1 minute"
):
FreshnessPolicy.cron(
deadline_cron="0 10 * * *",
lower_bound_delta=timedelta(seconds=0),
)
def test_cron_freshness_policy_validation_lower_bound_too_large(self) -> None:
with pytest.raises(
CheckError,
match="lower_bound_delta must be less than or equal to the smallest cron interval",
):
FreshnessPolicy.cron(
deadline_cron="0 10 * * *",
lower_bound_delta=timedelta(hours=25),
)
def test_cron_freshness_policy_validation_lower_bound_exceeds_smallest_interval(self) -> None:
"""Does the policy reject lower bound deltas that exceed the smallest cron interval?"""
# 0 10 * * 1-5 means 10am on Monday through Friday
# 30 hours lower bound delta will work over the weekend, but not during the week
with pytest.raises(
CheckError,
match="lower_bound_delta must be less than or equal to the smallest cron interval",
):
FreshnessPolicy.cron(
deadline_cron="0 10 * * 1-5",
lower_bound_delta=timedelta(hours=30),
)
def test_cron_freshness_policy_serdes(self) -> None:
"""Can we serialize and deserialize a cron freshness policy?"""
policy = FreshnessPolicy.cron(
deadline_cron="0 10 * * *",
lower_bound_delta=timedelta(hours=1),
timezone="America/New_York",
)
serialized = dg.serialize_value(policy)
deserialized = dg.deserialize_value(serialized)
assert isinstance(deserialized, CronFreshnessPolicy)
assert deserialized.deadline_cron == "0 10 * * *"
assert deserialized.lower_bound_delta == timedelta(hours=1)
assert deserialized.timezone == "America/New_York"
def test_cron_freshness_policy_apply_to_asset(self) -> None:
@asset(
freshness_policy=FreshnessPolicy.cron(
deadline_cron="0 10 * * *",
lower_bound_delta=timedelta(hours=1),
timezone="UTC",
)
)
def asset_with_internal_freshness_policy():
pass
asset_spec = asset_with_internal_freshness_policy.get_asset_spec()
policy = asset_spec.freshness_policy
assert policy is not None
assert isinstance(policy, CronFreshnessPolicy)
assert policy.deadline_cron == "0 10 * * *"
assert policy.lower_bound_delta == timedelta(hours=1)
assert policy.timezone == "UTC"
def test_cron_freshness_policy_apply_to_asset_spec(self) -> None:
"""Can we apply a cron freshness policy to an asset spec?"""
asset_spec = dg.AssetSpec(
key="foo",
freshness_policy=FreshnessPolicy.cron(
deadline_cron="0 10 * * *",
lower_bound_delta=timedelta(hours=1),
),
)
asset_spec = apply_freshness_policy(
asset_spec,
FreshnessPolicy.cron(
deadline_cron="0 10 * * *",
lower_bound_delta=timedelta(hours=1),
timezone="UTC",
),
)
assert asset_spec.freshness_policy is not None
assert isinstance(asset_spec.freshness_policy, CronFreshnessPolicy)
assert asset_spec.freshness_policy.deadline_cron == "0 10 * * *"
assert asset_spec.freshness_policy.lower_bound_delta == timedelta(hours=1)
assert asset_spec.freshness_policy.timezone == "UTC"
|
TestCronFreshnessPolicy
|
python
|
kamyu104__LeetCode-Solutions
|
Python/filter-characters-by-frequency.py
|
{
"start": 48,
"end": 340
}
|
class ____(object):
def filterCharacters(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
cnt = [0]*26
for x in s:
cnt[ord(x)-ord('a')] += 1
return "".join(x for x in s if cnt[ord(x)-ord('a')] < k)
|
Solution
|
python
|
ray-project__ray
|
rllib/policy/view_requirement.py
|
{
"start": 381,
"end": 6294
}
|
class ____:
"""Single view requirement (for one column in an SampleBatch/input_dict).
Policies and ModelV2s return a Dict[str, ViewRequirement] upon calling
their `[train|inference]_view_requirements()` methods, where the str key
represents the column name (C) under which the view is available in the
input_dict/SampleBatch and ViewRequirement specifies the actual underlying
column names (in the original data buffer), timestep shifts, and other
options to build the view.
.. testcode::
:skipif: True
from ray.rllib.models.modelv2 import ModelV2
# The default ViewRequirement for a Model is:
req = ModelV2(...).view_requirements
print(req)
.. testoutput::
{"obs": ViewRequirement(shift=0)}
Args:
data_col: The data column name from the SampleBatch
(str key). If None, use the dict key under which this
ViewRequirement resides.
space: The gym Space used in case we need to pad data
in inaccessible areas of the trajectory (t<0 or t>H).
Default: Simple box space, e.g. rewards.
shift: Single shift value or
list of relative positions to use (relative to the underlying
`data_col`).
Example: For a view column "prev_actions", you can set
`data_col="actions"` and `shift=-1`.
Example: For a view column "obs" in an Atari framestacking
fashion, you can set `data_col="obs"` and
`shift=[-3, -2, -1, 0]`.
Example: For the obs input to an attention net, you can specify
a range via a str: `shift="-100:0"`, which will pass in
the past 100 observations plus the current one.
index: An optional absolute position arg,
used e.g. for the location of a requested inference dict within
the trajectory. Negative values refer to counting from the end
of a trajectory. (#TODO: Is this still used?)
batch_repeat_value: determines how many time steps we should skip
before we repeat the view indexing for the next timestep. For RNNs this
number is usually the sequence length that we will rollout over.
Example:
view_col = "state_in_0", data_col = "state_out_0"
batch_repeat_value = 5, shift = -1
buffer["state_out_0"] = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
output["state_in_0"] = [-1, 4, 9]
Explanation: For t=0, we output buffer["state_out_0"][-1]. We then skip 5
time steps and repeat the view. for t=5, we output buffer["state_out_0"][4]
. Continuing on this pattern, for t=10, we output buffer["state_out_0"][9].
used_for_compute_actions: Whether the data will be used for
creating input_dicts for `Policy.compute_actions()` calls (or
`Policy.compute_actions_from_input_dict()`).
used_for_training: Whether the data will be used for
training. If False, the column will not be copied into the
final train batch.
"""
data_col: Optional[str] = None
space: gym.Space = None
shift: Union[int, str, List[int]] = 0
index: Optional[int] = None
batch_repeat_value: int = 1
used_for_compute_actions: bool = True
used_for_training: bool = True
shift_arr: Optional[np.ndarray] = dataclasses.field(init=False)
def __post_init__(self):
"""Initializes a ViewRequirement object.
shift_arr is infered from the shift value.
For example:
- if shift is -1, then shift_arr is np.array([-1]).
- if shift is [-1, -2], then shift_arr is np.array([-2, -1]).
- if shift is "-2:2", then shift_arr is np.array([-2, -1, 0, 1, 2]).
"""
if self.space is None:
self.space = gym.spaces.Box(float("-inf"), float("inf"), shape=())
# TODO: ideally we won't need shift_from and shift_to, and shift_step.
# all of them should be captured within shift_arr.
# Special case: Providing a (probably larger) range of indices, e.g.
# "-100:0" (past 100 timesteps plus current one).
self.shift_from = self.shift_to = self.shift_step = None
if isinstance(self.shift, str):
split = self.shift.split(":")
assert len(split) in [2, 3], f"Invalid shift str format: {self.shift}"
if len(split) == 2:
f, t = split
self.shift_step = 1
else:
f, t, s = split
self.shift_step = int(s)
self.shift_from = int(f)
self.shift_to = int(t)
shift = self.shift
self.shfit_arr = None
if self.shift_from:
self.shift_arr = np.arange(
self.shift_from, self.shift_to + 1, self.shift_step
)
else:
if isinstance(shift, int):
self.shift_arr = np.array([shift])
elif isinstance(shift, list):
self.shift_arr = np.array(shift)
else:
ValueError(f'unrecognized shift type: "{shift}"')
def to_dict(self) -> Dict:
"""Return a dict for this ViewRequirement that can be JSON serialized."""
return {
"data_col": self.data_col,
"space": gym_space_to_dict(self.space),
"shift": self.shift,
"index": self.index,
"batch_repeat_value": self.batch_repeat_value,
"used_for_training": self.used_for_training,
"used_for_compute_actions": self.used_for_compute_actions,
}
@classmethod
def from_dict(cls, d: Dict):
"""Construct a ViewRequirement instance from JSON deserialized dict."""
d["space"] = gym_space_from_dict(d["space"])
return cls(**d)
|
ViewRequirement
|
python
|
keras-team__keras
|
keras/src/ops/nn.py
|
{
"start": 611,
"end": 1305
}
|
class ____(Operation):
def call(self, x):
return backend.nn.relu(x)
def compute_output_spec(self, x):
return KerasTensor(x.shape, dtype=x.dtype)
@keras_export(["keras.ops.relu", "keras.ops.nn.relu"])
def relu(x):
"""Rectified linear unit activation function.
It is defined as `f(x) = max(0, x)`.
Args:
x: Input tensor.
Returns:
A tensor with the same shape as `x`.
Example:
>>> x1 = keras.ops.convert_to_tensor([-1.0, 0.0, 1.0, 0.2])
>>> keras.ops.relu(x1)
array([0.0, 0.0, 1.0, 0.2], dtype=float32)
"""
if any_symbolic_tensors((x,)):
return Relu().symbolic_call(x)
return backend.nn.relu(x)
|
Relu
|
python
|
doocs__leetcode
|
solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/Solution.py
|
{
"start": 0,
"end": 392
}
|
class ____:
def areSimilar(self, mat: List[List[int]], k: int) -> bool:
n = len(mat[0])
for i, row in enumerate(mat):
for j, x in enumerate(row):
if i % 2 == 1 and x != mat[i][(j + k) % n]:
return False
if i % 2 == 0 and x != mat[i][(j - k + n) % n]:
return False
return True
|
Solution
|
python
|
joke2k__faker
|
faker/providers/address/ne_NP/__init__.py
|
{
"start": 45,
"end": 13318
}
|
class ____(AddressProvider):
building_number_formats = ("#", "##", "###")
street_name_formats = ("{{last_name}} {{street_suffix}}",)
street_address_formats = ("{{street_name}}",)
city_formats = ("{{city}}",)
# http://www.nepalpost.gov.np/index.php/postal-codes-of-nepal
postcode_formats = ("#####",)
address_formats = ("{{street_name}} {{building_prefix}} {{building_number}} \n{{city}}\n{{district}} {{postcode}}",)
street_suffixes = (
"मार्ग",
"आश्रम",
"बाटो",
"पथ",
"गल्ली",
"गेट",
"हाईट",
"टार",
"रोड",
"कुना",
"चौर",
"निवास",
)
building_prefixes = ("वडा", "घर")
# https://en.wikipedia.org/wiki/List_of_sovereign_states
countries = (
"अंगोला",
"अक्रोटिरी र धेकेलिया",
"अजरबैजान",
"अफगानिस्तान",
"अमेरिकी सामोआ",
"अरुबा",
"अर्जेन्टिना",
"अर्मेनिया",
"अलडेर्नी",
"अल्जेरिया",
"अल्बानिया",
"अस्ट्रिया",
"अस्ट्रेलिया",
"आइजल अफ म्यान",
"आइभोरी कोस्ट",
"आइसल्याण्ड",
"आजाद कश्मीर",
"आयरल्याण्ड",
"इक्वेटोरियल गिनी",
"इक्वेडर",
"इजरायल",
"इटाली",
"इण्डोनेशिया",
"इथियोपिया",
"इराक",
"इरान",
"इस्टोनिया",
"उज्बेकिस्तान",
"उत्तर कोरिया",
"उत्तरी मारिआना टापु",
"उत्तरी साइप्रस",
"उरुग्वे",
"एङगुइला",
"एण्डोरा",
"एन्टिगुआ र बर्बुडा",
"एरिट्रिया",
"एल साल्भादोर",
"एशमोर र कर्टियर टापु",
"ओमान",
"कजाख्स्तान",
"कतार",
"कम्बोडिया",
"किरिबाटी",
"किर्गिजस्तान",
"कुक द्वीप",
"कुराकाओ",
"कुवैत",
"केन्या",
"केप भर्ड",
"केम्यान टापु",
"कोकोस टापु",
"कोटे डी आइभोरी",
"कोमोरोस",
"कोरल सी टापु क्षेत्र",
"कोलम्बिया",
"कोसोभो",
"कोस्टारिका",
"क्यानडा",
"क्यामेरून",
"क्युबा",
"क्रिसमस टापु",
"क्रोएसिया",
"क्लिप्परटन द्वीप",
"क्वीन माउड ल्याण्ड",
"गणतन्त्र कङ्गो",
"गणतन्त्र कोरिया",
"गणतन्त्र स्पर्स्का",
"गाबोन",
"गिनी",
"गिब्राल्टार",
"गिलगीत",
"गुयना",
"गुर्न्जी",
"ग्रिनाडा",
"ग्रीनल्याण्ड",
"ग्रीस",
"ग्वाटेमाला",
"ग्वाम",
"घाना",
"चाड",
"चिली",
"चीन",
"चेक गणतन्त्र",
"जमैका",
"जर्मनी",
"जर्सी",
"जापान",
"जाम्बिया",
"जिबुटी",
"जोर्डन",
"टर्की",
"टिमोर",
"टुभालु",
"टुर्क्स तथा काइकोस टापु",
"टोंगा",
"टोकेलाउ",
"टोगो",
"ट्युनिसिया",
"ट्रान्सनिसट्रिया",
"ट्रिनिडाड र टोबागो",
"डेनमार्क",
"डोमिनिकन गणतन्त्र",
"डोमिनिका",
"तन्जानिया",
"ताइवान",
"ताजिकिस्तान",
"तुर्कमेनिस्तान",
"थाइल्याण्ड",
"दक्षिण अफ्रिका",
"दक्षिण ओसेटिया",
"दक्षिण कोरिया",
"दक्षिण जर्जिया तथा दक्षिण स्याण्डवीच टापु",
"दक्षिणी सुडान",
"नर्वे",
"नर्वेको",
"नाइजर",
"नाइजेरिया",
"नाउरु",
"नागोर्नो",
"नामिबिया",
"निकाराग्वा",
"नियु",
"नेदरल्याण्ड",
"नेपाल",
"नोर्फोक टापु",
"न्यु क्यालोडेनिया",
"न्युजिल्यान्ड",
"पपुवा न्युगिनी",
"पलाउ",
"पाकिस्तान",
"पानामा",
"पाराग्वे",
"पिटकेर्न टापु",
"पिटर द्वीप",
"पूर्वी टिमोर",
"पेरु",
"पोर्चुगल",
"पोल्याण्ड",
"प्यालेस्टाइन",
"प्युर्तो रिको",
"प्रजातान्त्रिक गणतन्त्र कंगो",
"प्रजातान्त्रिक गणतन्त्र कोरिया",
"प्रिडेनेस्ट्रोभी",
"फकल्याण्ड टापु",
"फरोइ टापु",
"फिजी",
"फिनल्याण्ड",
"फिलिपिन्स",
"फ्रान्स",
"फ्रेन्च दक्षिणी र अन्टार्कटिक द्वीप",
"फ्रेन्च पोलिनेसिया",
"बंगलादेश",
"बर्मा",
"बर्मुडा",
"बहराइन",
"बहामस",
"बार्बाडोस",
"बुरुन्डी",
"बुर्किना फासो",
"बुल्गेरिया",
"बेनिन",
"बेलारूस",
"बेलिज",
"बेल्जियम",
"बोत्स्वाना",
"बोलिभिया",
"बोस्निया र हर्जगोभिना",
"बोस्निया र हर्जगोभिना संघ",
"बौभेट द्वीप",
"ब्राजिल",
"ब्रिटिस भर्जिन टापु",
"ब्रुनेई",
"भानुअटु",
"भारत",
"भियतनाम",
"भुटान",
"भेनेजुएला",
"भ्याटिकन",
"भ्याटिकन सिटी",
"मकाउ",
"मङ्गोलिया",
"मध्य अफ्रिकी गणतन्त्र",
"मलावी",
"मलेशिया",
"माइक्रोनेसियाको संघीय राज्य",
"माडागास्कर",
"मार्शल द्वीप",
"माली",
"माल्टा",
"माल्दिभ्स",
"मिश्र",
"मेक्सिको",
"मोजाम्बिक",
"मोनाको",
"मोन्टसेराट",
"मोन्टेनेग्रो",
"मोरक्को",
"मोल्डोभा",
"मौरिसनिया",
"मौरिसस",
"म्यानमार",
"उत्तरी म्यासेडोनिया",
"यमन",
"युक्रेन",
"युगान्डा",
"रसिया",
"रुवाण्डा",
"रोमानिया",
"रोस डिपेन्डेन्सी",
"लक्जेम्बर्ग",
"लाईबेरिया",
"लाओस",
"लात्भिया",
"लिचटेन्स्टाइन",
"लिथुआनिया",
"लिबिया",
"लेबनान",
"लेसोथो",
"वाल्लिस र फुटुना",
"श्रीलंका",
"संघीय राज्य माइक्रोनेसिया",
"संयुक्त अधिराज्य",
"संयुक्त अरब इमिरेट्स",
"संयुक्त राज्य अमेरिका",
"संयुक्त राज्य भर्जिन टापु",
"सर्बिया",
"साइप्रस",
"साउदी अरब",
"साओ टोमे र प्रिन्सिपे",
"सान मारिनो",
"साबा",
"सामोआ",
"साहरवी अरब लोकतान्त्रिक गणतन्त्र",
"सिंगापुर",
"सिन्ट मार्टिन",
"सीरियन कुर्दिस्तान",
"सीरिया",
"सुडान",
"सुरिनेम",
"सेनेगल",
"सेन्ट किट्स र नेभिस",
"सेन्ट पियेर्रे र मिकुएलन",
"सेन्ट बार्थेलेमी",
"सेन्ट भिन्सेन्ट र ग्रेनाडाइन्स",
"सेन्ट मार्टिन",
"सेन्ट लुसिया",
"सेन्ट हेलेना",
"सेरा लियोन",
"सेसेल्स",
"सोमालिया",
"सोमालील्याण्ड",
"सोलोमन द्वीप",
"स्पेन",
"स्लोभाकिया",
"स्लोभेनिया",
"स्वाजिल्याण्ड",
"स्विजरल्याण्ड",
"स्वीडेन",
"हंगेरी",
"हङकङ",
"हर्म",
"हाइटी",
"हेयर्ड द्वीप र म्याकडोनाल्ड टापु",
"होन्डुरस",
"अबखाजिया",
"जर्जिया",
)
# cities are taken from
# https://en.wikipedia.org/wiki/List_of_cities_in_Nepal
cities = (
"मिर्चैया",
"प्युठान",
"कञ्चनपुर",
"लुम्बिनी सांस्कृतिक",
"बागलुङ",
"इलाम",
"भक्तपुर",
"भद्रपुर",
"घोराही",
"स्याङ्जा",
"खैरहानी नगरपालिका",
"म्याग्दी",
"रंगेली",
"काठमाडौं",
"शनि-अर्जुन",
"पर्वत",
"सप्तरी",
"पनौती",
"जयपृथ्वी",
"लहान",
"वालिङ",
"बर्दघाट",
"डोटी",
"धरान",
"पथरी शनिश्चरे",
"चन्दननाथ",
"नवलपरासी",
"किर्तिपुर",
"दैलेख",
"सुनसरी",
"बेलौरी",
"कुस्मा",
"मकवानपुर",
"कञ्चनरूप",
"गुलरिया",
"टीकापुर",
"राजापुर",
"फिदिम",
"खोटाङ",
"धनुषाधाम",
"झापा",
"पुनर्वास",
"भक्तपुर",
"बर्दिया",
"बागलुङ",
"दमक",
"तेह्रथुम",
"नारायण",
"ताप्लेजुङ",
"तानसेन",
"पाँचखाल",
"बनेपा",
"म्याङ्लुङ",
"ललितपुर",
"दिपायल",
"अपी",
"दाङ",
"सन्धिखर्क",
"धनकुटा",
"बिरेन्द्रनगर",
"गौर",
"मोरङ",
"सङ्खुवासभा",
"लम्की-चुहा",
"बारा",
"हरिवन नगरपालिका",
"मलङ्वा",
"सिराहा",
"जनकपुर",
"सल्यान",
"सिन्धुपाल्चोक",
"दुल्लु",
"ओखलढुङ्गा",
"पाल्पा",
"इटहरी",
"रेसुङगा",
"कृष्णनगर",
"शुक्लगण्डकी",
"नुवाकोट",
"साँफेबगर",
"राजविराज",
"नेपालगंज",
"भिमेश्वर",
"ताप्लेजुङ",
"धुलिखेल",
"व्यास",
"भोजपुर",
"धादिङ",
"बेनी",
"अर्घाखाँची",
"भीमदत्त",
"रौतहट",
"जलेश्वर",
"देवदह",
"बेलवारी",
"बुटवल",
"सुर्खेत",
"मङ्गलसेन",
"कैलाली",
"धनकुटा",
"रुपन्देही",
"सल्यान",
"रामपुर",
"बिराटनगर",
"चौतारा",
"देवचुली",
"कपिलवस्तु",
"सुनवल",
"शिवराज",
"चम्पापुर (चापागाउँ)",
"भरतपुर",
"गढिमाई",
"उर्लावारी",
"लेखनाथ",
"सिद्धिचरण",
"मेचीनगर",
"चित्रवन",
"कास्की",
"गौशाला",
"पुतलीबजार",
"बिदुर",
"शम्भुनाथ",
"पर्सा",
"प्युठान",
"निजगढ",
"डडेलधुरा",
"कन्काई",
"गैंडाकोट",
"पाल्पा",
"कार्यविनायक*",
"तिलोत्तमा",
"तुलसीपुर",
"वीरगञ्ज",
"शंखरपुर*",
"अत्तरिया",
"बझाङ",
"मन्थली*",
"कपिलवस्तु",
"कटारी",
"हेटौडा",
"कलैया",
"सुन्दर दुलारी",
"सिन्धुली",
"थाहा",
"बाँके",
"ललितपुर",
"दार्चुला",
"पोखरा",
"बन्दीपुर",
"सर्लाही",
"कोहलपुर",
"सैनामैना",
"अमरागढी",
"उदयपुर",
"काठमाडौं",
"सुर्योदय",
"सिराहा",
"महोत्तरी",
"धनगढी",
"शारदा",
"काभ्रेपलाञ्चोक",
"त्रियुगा",
"रामेछाप",
"पाँचथर",
"इलाम",
"भोजपुर",
"मध्यपुर ठिमी",
"दुहवी-भलुवा",
"दशरथचन्द",
"बैतडी",
"कोशी हरैंचा",
"चापाकोट",
"दिक्तेल",
"चन्द्रपुर",
"लालबन्दी",
"चितवन",
"रत्ननगर",
"पृथ्वीनारायण",
"धनुषा",
"गुल्मी",
"बेंसीशहर",
"लमजुङ",
"अछाम",
"तनहुँ",
"खाँदबारी",
"बिर्तामोड",
"कमलामाई",
"छिरेश्वरनाथ",
"सिद्धार्थनगर",
"निलकण्ठ",
"गोर्खा",
"दोलखा",
"रामग्राम",
"इनरूवा",
"कावासोती",
"बेल्टार बसाहा",
"जुम्ला",
"ईश्वरपुर",
)
# district taken from
# https://www.election.gov.np/election/np/district-wise-constituency-map.html
districts = (
"अछाम",
"अर्घाखाँची",
"इलाम",
"उदयपुर",
"ओखलढुङ्गा",
"कञ्चनपुर",
"कपिलवस्तु",
"काठमाडौं",
"काभ्रेपलाञ्चोक",
"कालीकोट",
"कास्की",
"कैलाली",
"खोटाङ",
"गुल्मी",
"गोर्खा",
"चितवन",
"जाजरकोट",
"जुम्ला",
"झापा",
"डडेल्धुरा",
"डोटी",
"डोल्पा",
"तनहुँ",
"ताप्लेजुङ",
"तेह्रथुम",
"दाङ",
"दार्चुला",
"दैलेख",
"दोलखा",
"धनकुटा",
"धनुषा",
"धादिङ",
"नवलपरासी (बर्दघाट सुस्ता पूर्व)",
"नवलपरासी (बर्दघाट सुस्ता पश्चिम)",
"नुवाकोट",
"पर्वत",
"पर्सा",
"पाँचथर",
"पाल्पा",
"प्युठान",
"बझाङ",
"बर्दिया",
"बाँके",
"बाग्लुङ",
"बाजुरा",
"बारा",
"भक्तपुर",
"भोजपुर",
"मकवानपुर",
"मनाङ",
"महोत्तरी",
"मुगु",
"मुस्ताङ",
"मोरङ",
"म्याग्दी",
"रसुवा",
"रामेछाप",
"रुकुम पूर्व",
"रुकुम पश्चिम",
"रूपन्देही",
"रोल्पा",
"रौतहट",
"लमजुङ्",
"ललितपुर",
"वैतडी",
"संखुवासभा",
"सप्तरी",
"सर्लाही",
"सल्यान",
"सिन्धुपलाञ्चोक",
"सिन्धुली",
"सिराहा",
"सुनसरी",
"सुर्खेत",
"सोलुखुम्बु",
"स्याङ्जा",
"हुम्ला",
)
# province taken from
# https://ne.wikipedia.org/wiki/%E0%A4%A8%E0%A5%87%E0%A4%AA%E0%A4%BE%E0%A4%B2%E0%A4%95%E0%A4%BE_%E0%A4%AA%E0%A5%8D%E0%A4%B0%E0%A4%A6%E0%A5%87%E0%A4%B6%E0%A4%B9%E0%A4%B0%E0%A5%82 # noqa: E501
provinces = (
"प्रदेश नं १",
"प्रदेश नं २",
"बाग्मती प्रदेश",
"गण्डकी प्रदेश",
"प्रदेश नं ५",
"कर्णाली प्रदेश",
"सुदूरपश्चिम प्रदेश",
)
def administrative_unit(self) -> str:
"""
:example: सुदूरपश्चिम प्रदेश
"""
return self.random_element(self.provinces)
province = administrative_unit
def district(self) -> str:
"""
:example: अछाम
"""
return self.random_element(self.districts)
def city(self) -> str:
"""
:example: कावासोती
"""
return self.random_element(self.cities)
def building_prefix(self) -> str:
"""
:example: वडा
"""
return self.random_element(self.building_prefixes)
|
Provider
|
python
|
ansible__ansible
|
test/integration/targets/ansible-test-sanity-pylint/ansible_collections/ns/col/plugins/lookup/deprecated.py
|
{
"start": 4366,
"end": 4484
}
|
class ____:
def __init__(self, thing) -> None:
self.module = thing # type: AnsibleModule
|
MyTypeCommentWrapper
|
python
|
airbytehq__airbyte
|
airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_responses/ticket_forms_response_builder.py
|
{
"start": 228,
"end": 488
}
|
class ____(HttpResponseBuilder):
@classmethod
def ticket_forms_response(cls) -> "TicketFormsResponseBuilder":
return cls(find_template("ticket_forms", __file__), FieldPath("ticket_forms"), CursorBasedPaginationStrategy())
|
TicketFormsResponseBuilder
|
python
|
dask__distributed
|
distributed/comm/ws.py
|
{
"start": 9070,
"end": 9589
}
|
class ____(WS):
prefix = "wss://"
def _read_extra(self):
WS._read_extra(self)
sock = self.sock.stream.socket
if sock is not None:
self._extra.update(peercert=sock.getpeercert(), cipher=sock.cipher())
cipher, proto, bits = self._extra["cipher"]
logger.debug(
"TLS connection with %r: protocol=%s, cipher=%s, bits=%d",
self._peer_addr,
proto,
cipher,
bits,
)
|
WSS
|
python
|
ray-project__ray
|
rllib/models/torch/torch_action_dist.py
|
{
"start": 16818,
"end": 17725
}
|
class ____(TorchDistributionWrapper):
"""Action distribution that returns the input values directly.
This is similar to DiagGaussian with standard deviation zero (thus only
requiring the "mean" values as NN output).
"""
@override(ActionDistribution)
def deterministic_sample(self) -> TensorType:
return self.inputs
@override(TorchDistributionWrapper)
def sampled_action_logp(self) -> TensorType:
return torch.zeros((self.inputs.size()[0],), dtype=torch.float32)
@override(TorchDistributionWrapper)
def sample(self) -> TensorType:
return self.deterministic_sample()
@staticmethod
@override(ActionDistribution)
def required_model_output_shape(
action_space: gym.Space, model_config: ModelConfigDict
) -> Union[int, np.ndarray]:
return np.prod(action_space.shape, dtype=np.int32)
@OldAPIStack
|
TorchDeterministic
|
python
|
pytorch__pytorch
|
test/test_proxy_tensor.py
|
{
"start": 81292,
"end": 83521
}
|
class ____(TestCase):
@ops(op_db + filtered_hop_db + custom_op_db, allowed_dtypes=(torch.float,))
@skipOps('TestProxyTensorOpInfo', 'test_make_fx_exhaustive', make_fx_failures.union(only_real_tensor_failures))
def test_make_fx_exhaustive(self, device, dtype, op):
_test_make_fx_helper(self, device, dtype, op, "real")
@ops(op_db + filtered_hop_db + custom_op_db, allowed_dtypes=(torch.float,))
@skipOps('TestProxyTensorOpInfo', 'test_make_fx_fake_exhaustive',
make_fx_failures.union(fake_tensor_failures, only_fake_tensor_failures))
def test_make_fx_fake_exhaustive(self, device, dtype, op):
_test_make_fx_helper(self, device, dtype, op, "fake")
@ops(op_db + filtered_hop_db + custom_op_db, allowed_dtypes=(torch.float,))
@skipOps('TestProxyTensorOpInfo', 'test_make_fx_symbolic_exhaustive',
make_fx_failures | fake_tensor_failures | symbolic_tensor_failures)
def test_make_fx_symbolic_exhaustive(self, device, dtype, op):
_test_make_fx_helper(self, device, dtype, op, "symbolic")
@ops(op_db + custom_op_db, allowed_dtypes=(torch.float,))
@skipOps('TestProxyTensorOpInfo', 'test_make_fx_symbolic_exhaustive_inplace',
make_fx_failures | fake_tensor_failures | symbolic_tensor_failures | inplace_symbolic_tensor_failures)
def test_make_fx_symbolic_exhaustive_inplace(self, device, dtype, op):
if not op.get_inplace():
self.skipTest("No inplace variable for this op")
_test_make_fx_helper(self, device, dtype, op, "symbolic", inplace=True)
@ops(op_db + custom_op_db, allowed_dtypes=(torch.float,))
@skipOps('TestProxyTensorOpInfo', 'test_make_fx_symbolic_exhaustive_out',
make_fx_failures | fake_tensor_failures | symbolic_tensor_failures | out_symbolic_tensor_failures)
def test_make_fx_symbolic_exhaustive_out(self, device, dtype, op):
if not op.supports_out:
self.skipTest("Op doesn't support out")
_test_make_fx_helper(self, device, dtype, op, "symbolic", out=True)
only_for = ("cpu")
instantiate_device_type_tests(TestProxyTensorOpInfo, globals(), only_for=only_for)
if __name__ == '__main__':
run_tests()
|
TestProxyTensorOpInfo
|
python
|
sqlalchemy__sqlalchemy
|
test/sql/test_update.py
|
{
"start": 53997,
"end": 59167
}
|
class ____(_UpdateFromTestBase, fixtures.TablesTest):
__sparse_driver_backend__ = True
@testing.requires.update_from
def test_exec_two_table(self, connection):
users, addresses = self.tables.users, self.tables.addresses
connection.execute(
addresses.update()
.values(email_address=users.c.name)
.where(users.c.id == addresses.c.user_id)
.where(users.c.name == "ed")
)
expected = [
(1, 7, "x", "jack@bean.com"),
(2, 8, "x", "ed"),
(3, 8, "x", "ed"),
(4, 8, "x", "ed"),
(5, 9, "x", "fred@fred.com"),
]
self._assert_addresses(connection, addresses, expected)
@testing.requires.update_from
def test_exec_two_table_plus_alias(self, connection):
users, addresses = self.tables.users, self.tables.addresses
a1 = addresses.alias()
connection.execute(
addresses.update()
.values(email_address=users.c.name)
.where(users.c.id == a1.c.user_id)
.where(users.c.name == "ed")
.where(a1.c.id == addresses.c.id)
)
expected = [
(1, 7, "x", "jack@bean.com"),
(2, 8, "x", "ed"),
(3, 8, "x", "ed"),
(4, 8, "x", "ed"),
(5, 9, "x", "fred@fred.com"),
]
self._assert_addresses(connection, addresses, expected)
@testing.requires.update_from
def test_exec_three_table(self, connection):
users = self.tables.users
addresses = self.tables.addresses
dingalings = self.tables.dingalings
connection.execute(
addresses.update()
.values(email_address=users.c.name)
.where(users.c.id == addresses.c.user_id)
.where(users.c.name == "ed")
.where(addresses.c.id == dingalings.c.address_id)
.where(dingalings.c.id == 1)
)
expected = [
(1, 7, "x", "jack@bean.com"),
(2, 8, "x", "ed"),
(3, 8, "x", "ed@bettyboop.com"),
(4, 8, "x", "ed@lala.com"),
(5, 9, "x", "fred@fred.com"),
]
self._assert_addresses(connection, addresses, expected)
@testing.requires.multi_table_update
def test_exec_multitable(self, connection):
users, addresses = self.tables.users, self.tables.addresses
values = {addresses.c.email_address: "updated", users.c.name: "ed2"}
connection.execute(
addresses.update()
.values(values)
.where(users.c.id == addresses.c.user_id)
.where(users.c.name == "ed")
)
expected = [
(1, 7, "x", "jack@bean.com"),
(2, 8, "x", "updated"),
(3, 8, "x", "updated"),
(4, 8, "x", "updated"),
(5, 9, "x", "fred@fred.com"),
]
self._assert_addresses(connection, addresses, expected)
expected = [(7, "jack"), (8, "ed2"), (9, "fred"), (10, "chuck")]
self._assert_users(connection, users, expected)
@testing.requires.multi_table_update
def test_exec_join_multitable(self, connection):
users, addresses = self.tables.users, self.tables.addresses
values = {addresses.c.email_address: "updated", users.c.name: "ed2"}
connection.execute(
update(users.join(addresses))
.values(values)
.where(users.c.name == "ed")
)
expected = [
(1, 7, "x", "jack@bean.com"),
(2, 8, "x", "updated"),
(3, 8, "x", "updated"),
(4, 8, "x", "updated"),
(5, 9, "x", "fred@fred.com"),
]
self._assert_addresses(connection, addresses, expected)
expected = [(7, "jack"), (8, "ed2"), (9, "fred"), (10, "chuck")]
self._assert_users(connection, users, expected)
@testing.requires.multi_table_update
def test_exec_multitable_same_name(self, connection):
users, addresses = self.tables.users, self.tables.addresses
values = {addresses.c.name: "ad_ed2", users.c.name: "ed2"}
connection.execute(
addresses.update()
.values(values)
.where(users.c.id == addresses.c.user_id)
.where(users.c.name == "ed")
)
expected = [
(1, 7, "x", "jack@bean.com"),
(2, 8, "ad_ed2", "ed@wood.com"),
(3, 8, "ad_ed2", "ed@bettyboop.com"),
(4, 8, "ad_ed2", "ed@lala.com"),
(5, 9, "x", "fred@fred.com"),
]
self._assert_addresses(connection, addresses, expected)
expected = [(7, "jack"), (8, "ed2"), (9, "fred"), (10, "chuck")]
self._assert_users(connection, users, expected)
def _assert_addresses(self, connection, addresses, expected):
stmt = addresses.select().order_by(addresses.c.id)
eq_(connection.execute(stmt).fetchall(), expected)
def _assert_users(self, connection, users, expected):
stmt = users.select().order_by(users.c.id)
eq_(connection.execute(stmt).fetchall(), expected)
|
UpdateFromRoundTripTest
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.