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 | pydantic__pydantic | tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail.py | {
"start": 1912,
"end": 2183
} | class ____(BaseModel):
model_config = ConfigDict(from_attributes={}) # type: ignore[typeddict-item]
# MYPY: error: Invalid value for "Config.from_attributes" [pydantic-config]
# MYPY: note: Error code "pydantic-config" not covered by "type: ignore" comment
| BadConfig1 |
python | weaviate__weaviate-python-client | weaviate/proto/v1/v4216/v1/weaviate_pb2_grpc.py | {
"start": 549,
"end": 2863
} | class ____(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.Search = channel.unary_unary(
'/weaviate.v1.Weaviate/Search',
request_serializer=v1_dot_search__get__pb2.SearchRequest.SerializeToString,
response_deserializer=v1_dot_search__get__pb2.SearchReply.FromString,
)
self.BatchObjects = channel.unary_unary(
'/weaviate.v1.Weaviate/BatchObjects',
request_serializer=v1_dot_batch__pb2.BatchObjectsRequest.SerializeToString,
response_deserializer=v1_dot_batch__pb2.BatchObjectsReply.FromString,
)
self.BatchReferences = channel.unary_unary(
'/weaviate.v1.Weaviate/BatchReferences',
request_serializer=v1_dot_batch__pb2.BatchReferencesRequest.SerializeToString,
response_deserializer=v1_dot_batch__pb2.BatchReferencesReply.FromString,
)
self.BatchDelete = channel.unary_unary(
'/weaviate.v1.Weaviate/BatchDelete',
request_serializer=v1_dot_batch__delete__pb2.BatchDeleteRequest.SerializeToString,
response_deserializer=v1_dot_batch__delete__pb2.BatchDeleteReply.FromString,
)
self.TenantsGet = channel.unary_unary(
'/weaviate.v1.Weaviate/TenantsGet',
request_serializer=v1_dot_tenants__pb2.TenantsGetRequest.SerializeToString,
response_deserializer=v1_dot_tenants__pb2.TenantsGetReply.FromString,
)
self.Aggregate = channel.unary_unary(
'/weaviate.v1.Weaviate/Aggregate',
request_serializer=v1_dot_aggregate__pb2.AggregateRequest.SerializeToString,
response_deserializer=v1_dot_aggregate__pb2.AggregateReply.FromString,
)
self.BatchStream = channel.stream_stream(
'/weaviate.v1.Weaviate/BatchStream',
request_serializer=v1_dot_batch__pb2.BatchStreamRequest.SerializeToString,
response_deserializer=v1_dot_batch__pb2.BatchStreamReply.FromString,
)
| WeaviateStub |
python | doocs__leetcode | lcci/10.11.Peaks and Valleys/Solution.py | {
"start": 0,
"end": 180
} | class ____:
def wiggleSort(self, nums: List[int]) -> None:
nums.sort()
for i in range(0, len(nums), 2):
nums[i : i + 2] = nums[i : i + 2][::-1]
| Solution |
python | doocs__leetcode | solution/3000-3099/3020.Find the Maximum Number of Elements in Subset/Solution.py | {
"start": 0,
"end": 361
} | class ____:
def maximumLength(self, nums: List[int]) -> int:
cnt = Counter(nums)
ans = cnt[1] - (cnt[1] % 2 ^ 1)
del cnt[1]
for x in cnt:
t = 0
while cnt[x] > 1:
x = x * x
t += 2
t += 1 if cnt[x] else -1
ans = max(ans, t)
return ans
| Solution |
python | doocs__leetcode | solution/2700-2799/2770.Maximum Number of Jumps to Reach the Last Index/Solution.py | {
"start": 0,
"end": 446
} | class ____:
def maximumJumps(self, nums: List[int], target: int) -> int:
@cache
def dfs(i: int) -> int:
if i == n - 1:
return 0
ans = -inf
for j in range(i + 1, n):
if abs(nums[i] - nums[j]) <= target:
ans = max(ans, 1 + dfs(j))
return ans
n = len(nums)
ans = dfs(0)
return -1 if ans < 0 else ans
| Solution |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 71910,
"end": 72314
} | class ____:
xlLegendPositionBottom = -4107 # from enum XlLegendPosition
xlLegendPositionCorner = 2 # from enum XlLegendPosition
xlLegendPositionCustom = -4161 # from enum XlLegendPosition
xlLegendPositionLeft = -4131 # from enum XlLegendPosition
xlLegendPositionRight = -4152 # from enum XlLegendPosition
xlLegendPositionTop = -4160 # from enum XlLegendPosition
| LegendPosition |
python | sympy__sympy | sympy/stats/joint_rv_types.py | {
"start": 12400,
"end": 15105
} | class ____(JointDistribution):
_argnames = ('mu', 'lamda', 'alpha', 'beta')
is_Continuous=True
@staticmethod
def check(mu, lamda, alpha, beta):
_value_check(mu.is_real, "Location must be real.")
_value_check(lamda > 0, "Lambda must be positive")
_value_check(alpha > 0, "alpha must be positive")
_value_check(beta > 0, "beta must be positive")
@property
def set(self):
return S.Reals*Interval(0, S.Infinity)
def pdf(self, x, tau):
beta, alpha, lamda = self.beta, self.alpha, self.lamda
mu = self.mu
return beta**alpha*sqrt(lamda)/(gamma(alpha)*sqrt(2*pi))*\
tau**(alpha - S.Half)*exp(-1*beta*tau)*\
exp(-1*(lamda*tau*(x - mu)**2)/S(2))
def _marginal_distribution(self, indices, *sym):
if len(indices) == 2:
return self.pdf(*sym)
if indices[0] == 0:
#For marginal over `x`, return non-standardized Student-T's
#distribution
x = sym[0]
v, mu, sigma = self.alpha - S.Half, self.mu, \
S(self.beta)/(self.lamda * self.alpha)
return Lambda(sym, gamma((v + 1)/2)/(gamma(v/2)*sqrt(pi*v)*sigma)*\
(1 + 1/v*((x - mu)/sigma)**2)**((-v -1)/2))
#For marginal over `tau`, return Gamma distribution as per construction
from sympy.stats.crv_types import GammaDistribution
return Lambda(sym, GammaDistribution(self.alpha, self.beta)(sym[0]))
def NormalGamma(sym, mu, lamda, alpha, beta):
"""
Creates a bivariate joint random variable with multivariate Normal gamma
distribution.
Parameters
==========
sym : A symbol/str
For identifying the random variable.
mu : A real number
The mean of the normal distribution
lamda : A positive integer
Parameter of joint distribution
alpha : A positive integer
Parameter of joint distribution
beta : A positive integer
Parameter of joint distribution
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import density, NormalGamma
>>> from sympy import symbols
>>> X = NormalGamma('x', 0, 1, 2, 3)
>>> y, z = symbols('y z')
>>> density(X)(y, z)
9*sqrt(2)*z**(3/2)*exp(-3*z)*exp(-y**2*z/2)/(2*sqrt(pi))
References
==========
.. [1] https://en.wikipedia.org/wiki/Normal-gamma_distribution
"""
return multivariate_rv(NormalGammaDistribution, sym, mu, lamda, alpha, beta)
#-------------------------------------------------------------------------------
# Multivariate Beta/Dirichlet distribution -------------------------------------
| NormalGammaDistribution |
python | sqlalchemy__sqlalchemy | test/sql/test_defaults.py | {
"start": 38717,
"end": 42312
} | class ____(fixtures.TestBase):
"""test process_result_value in conjunction with primary key columns.
Also tests that "autoincrement" checks are against
column.type._type_affinity, rather than the class of "type" itself.
"""
__sparse_driver_backend__ = True
@classmethod
def setup_test_class(cls):
class MyInteger(TypeDecorator):
impl = Integer
cache_ok = True
def process_bind_param(self, value, dialect):
if value is None:
return None
return int(value[4:])
def process_result_value(self, value, dialect):
if value is None:
return None
return "INT_%d" % value
cls.MyInteger = MyInteger
@testing.provide_metadata
def _run_test(self, *arg, **kw):
metadata = self.metadata
implicit_returning = kw.pop("implicit_returning", True)
kw["primary_key"] = True
if kw.get("autoincrement", True):
kw["test_needs_autoincrement"] = True
t = Table(
"x",
metadata,
Column("y", self.MyInteger, *arg, **kw),
Column("data", Integer),
implicit_returning=implicit_returning,
)
with testing.db.begin() as conn:
t.create(conn)
r = conn.execute(t.insert().values(data=5))
expected_result = "INT_" + str(
testing.db.dialect.default_sequence_base
if (arg and isinstance(arg[0], Sequence))
else 1
)
# we don't pre-fetch 'server_default'.
if "server_default" in kw and (
not testing.db.dialect.insert_returning
or not implicit_returning
):
eq_(r.inserted_primary_key, (None,))
else:
eq_(
r.inserted_primary_key,
(expected_result,),
)
eq_(
conn.execute(t.select()).first(),
(expected_result, 5),
)
def test_plain(self):
# among other things, tests that autoincrement
# is enabled.
self._run_test()
def test_literal_default_label(self):
self._run_test(
default=literal("INT_1", type_=self.MyInteger).label("foo")
)
def test_literal_default_no_label(self):
self._run_test(default=literal("INT_1", type_=self.MyInteger))
def test_literal_column_default_no_label(self):
self._run_test(default=literal_column("1", type_=self.MyInteger))
def test_sequence(self):
self._run_test(normalize_sequence(config, Sequence("foo_seq")))
def test_text_clause_default_no_type(self):
self._run_test(default=text("1"))
def test_server_default(self):
self._run_test(server_default="1")
def test_server_default_no_autoincrement(self):
self._run_test(server_default="1", autoincrement=False)
@testing.crashes(
"+mariadbconnector", "https://jira.mariadb.org/browse/CONPY-206"
)
def test_clause(self):
stmt = select(cast("INT_1", type_=self.MyInteger)).scalar_subquery()
self._run_test(default=stmt)
@testing.requires.insert_returning
def test_no_implicit_returning(self):
self._run_test(implicit_returning=False)
@testing.requires.insert_returning
def test_server_default_no_implicit_returning(self):
self._run_test(server_default="1", autoincrement=False)
| SpecialTypePKTest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/eq_without_hash.py | {
"start": 1525,
"end": 1685
} | class ____:
if ...:
...
else:
with ...:
for _ in ...:
def __eq__(self, other): ...
### OK
| MaybeEqDeeplyNested |
python | sqlalchemy__sqlalchemy | test/orm/test_assorted_eager.py | {
"start": 16477,
"end": 18660
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"departments",
metadata,
Column(
"department_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("name", String(50)),
)
Table(
"employees",
metadata,
Column(
"person_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("name", String(50)),
Column(
"department_id",
Integer,
ForeignKey("departments.department_id"),
),
)
@classmethod
def setup_classes(cls):
class Department(cls.Basic):
pass
class Employee(cls.Basic):
pass
def test_basic(self):
Department, Employee, employees, departments = (
self.classes.Department,
self.classes.Employee,
self.tables.employees,
self.tables.departments,
)
self.mapper_registry.map_imperatively(Employee, employees)
self.mapper_registry.map_imperatively(
Department,
departments,
properties=dict(
employees=relationship(
Employee, lazy="joined", backref="department"
)
),
)
d1 = Department(name="One")
for e in "Jim", "Jack", "John", "Susan":
d1.employees.append(Employee(name=e))
d2 = Department(name="Two")
for e in "Joe", "Bob", "Mary", "Wally":
d2.employees.append(Employee(name=e))
sess = fixture_session()
sess.add_all((d1, d2))
sess.flush()
q = (
sess.query(Department)
.join(Department.employees)
.filter(Employee.name.startswith("J"))
.distinct()
.order_by(sa.desc(Department.name))
)
eq_(q.count(), 2)
assert q[0] is d2
| EagerTest4 |
python | spyder-ide__spyder | external-deps/python-lsp-server/pylsp/plugins/pycodestyle_lint.py | {
"start": 2225,
"end": 4011
} | class ____(pycodestyle.BaseReport):
def __init__(self, options) -> None:
self.diagnostics = []
super().__init__(options=options)
def error(self, line_number, offset, text, check):
code = text[:4]
if self._ignore_code(code):
return
# Don't care about expected errors or warnings
if code in self.expected:
return
# PyCodeStyle will sometimes give you an error the line after the end of the file
# e.g. no newline at end of file
# In that case, the end offset should just be some number ~100
# (because why not? There's nothing to underline anyways)
err_range = {
"start": {"line": line_number - 1, "character": offset},
"end": {
# FIXME: It's a little naiive to mark until the end of the line, can we not easily do better?
"line": line_number - 1,
"character": 100
if line_number > len(self.lines)
else len(self.lines[line_number - 1]),
},
}
diagnostic = {
"source": "pycodestyle",
"range": err_range,
"message": text,
"code": code,
# Are style errors really ever errors?
"severity": _get_severity(code),
}
if code.startswith("W6"):
diagnostic["tags"] = [lsp.DiagnosticTag.Deprecated]
self.diagnostics.append(diagnostic)
def _get_severity(code):
# Are style errors ever really errors?
if code[0] == "E" or code[0] == "W":
return lsp.DiagnosticSeverity.Warning
# If no severity is specified, why wouldn't this be informational only?
return lsp.DiagnosticSeverity.Information
| PyCodeStyleDiagnosticReport |
python | wandb__wandb | wandb/sdk/internal/job_builder.py | {
"start": 2074,
"end": 2233
} | class ____(TypedDict):
git: GitInfo
entrypoint: List[str]
notebook: bool
build_context: Optional[str]
dockerfile: Optional[str]
| GitSourceDict |
python | realpython__materials | django-diary/source_code_final/entries/views.py | {
"start": 531,
"end": 598
} | class ____(LockedView, DetailView):
model = Entry
| EntryDetailView |
python | ray-project__ray | python/ray/dashboard/subprocesses/routes.py | {
"start": 260,
"end": 3758
} | class ____(BaseRouteTable):
"""
A route table to bind http route to SubprocessModuleHandle and SubprocessModule.
This class is used in cls object: all the decorator methods are @classmethod, and
the routes are binded to the cls object.
Note we have 2 handlers:
1. the child side handler, that is `handler` that contains real logic and
is executed in the child process. It's added with __route_method__ and
__route_path__ attributes. The child process runs a standalone aiohttp
server.
2. the parent side handler, that just sends the request to the
SubprocessModuleHandle at cls._bind_map[method][path].instance.
With modifications:
- __route_method__ and __route_path__ are added to both side's handlers.
- method and path are added to self._bind_map.
Lifecycle of a request:
1. Parent receives an aiohttp request.
2. Router finds by [method][path] and calls parent_side_handler.
3. `parent_side_handler` bookkeeps the request with a Future and sends a
request to the subprocess.
4. Subprocesses receives the response and sends it back to the parent.
5. Parent responds to the aiohttp request with the response from the subprocess.
"""
_bind_map = collections.defaultdict(dict)
_routes = aiohttp.web.RouteTableDef()
@classmethod
def bind(cls, instance: "SubprocessModuleHandle"):
# __route_method__ and __route_path__ are added to SubprocessModule's methods,
# not the SubprocessModuleHandle's methods.
def predicate(o):
if inspect.isfunction(o):
return hasattr(o, "__route_method__") and hasattr(o, "__route_path__")
return False
handler_routes = inspect.getmembers(instance.module_cls, predicate)
for _, h in handler_routes:
cls._bind_map[h.__route_method__][h.__route_path__].instance = instance
@classmethod
def _register_route(
cls, method, path, resp_type: ResponseType = ResponseType.HTTP, **kwargs
):
"""
Register a route to the module and return the decorated handler.
"""
def _wrapper(handler):
if path in cls._bind_map[method]:
bind_info = cls._bind_map[method][path]
raise Exception(
f"Duplicated route path: {path}, "
f"previous one registered at "
f"{bind_info.filename}:{bind_info.lineno}"
)
bind_info = cls._BindInfo(
handler.__code__.co_filename, handler.__code__.co_firstlineno, None
)
cls._bind_map[method][path] = bind_info
async def parent_side_handler(
request: aiohttp.web.Request,
) -> aiohttp.web.Response:
bind_info = cls._bind_map[method][path]
subprocess_module_handle = bind_info.instance
return await subprocess_module_handle.proxy_request(request, resp_type)
# Used in bind().
handler.__route_method__ = method
handler.__route_path__ = path
# Used in bound_routes().
parent_side_handler.__route_method__ = method
parent_side_handler.__route_path__ = path
parent_side_handler.__name__ = handler.__name__
cls._routes.route(method, path)(parent_side_handler)
return handler
return _wrapper
| SubprocessRouteTable |
python | plotly__plotly.py | tests/test_core/test_figure_messages/test_batch_animate.py | {
"start": 101,
"end": 2259
} | class ____(TestCase):
def setUp(self):
# Construct initial scatter object
self.figure = go.Figure(
data=[
go.Scatter(y=[3, 2, 1], marker={"color": "green"}),
go.Bar(y=[3, 2, 1, 0, -1], marker={"opacity": 0.5}),
],
layout={"xaxis": {"range": [-1, 4]}},
frames=[go.Frame(layout={"yaxis": {"title": "f1"}})],
)
# Mock out the message method
self.figure._send_animate_msg = MagicMock()
def test_batch_animate(self):
with self.figure.batch_animate(easing="elastic", duration=1200):
# Assign trace property
self.figure.data[0].marker.color = "yellow"
self.figure.data[1].marker.opacity = 0.9
# Assign layout property
self.figure.layout.xaxis.range = [10, 20]
# Assign frame property
self.figure.frames[0].layout.yaxis.title.text = "f2"
# Make sure that trace/layout assignments haven't been applied yet
self.assertEqual(self.figure.data[0].marker.color, "green")
self.assertEqual(self.figure.data[1].marker.opacity, 0.5)
self.assertEqual(self.figure.layout.xaxis.range, (-1, 4))
# Expect the frame update to be applied immediately
self.assertEqual(self.figure.frames[0].layout.yaxis.title.text, "f2")
# Make sure that trace/layout assignments have been applied after
# context exits
self.assertEqual(self.figure.data[0].marker.color, "yellow")
self.assertEqual(self.figure.data[1].marker.opacity, 0.9)
self.assertEqual(self.figure.layout.xaxis.range, (10, 20))
# Check that update message was sent
self.figure._send_animate_msg.assert_called_once_with(
styles_data=[{"marker.color": "yellow"}, {"marker.opacity": 0.9}],
relayout_data={"xaxis.range": [10, 20]},
trace_indexes=[0, 1],
animation_opts={
"transition": {"easing": "elastic", "duration": 1200},
"frame": {"duration": 1200},
},
)
| TestBatchAnimateMessage |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/common_transformers/anf.py | {
"start": 1271,
"end": 1758
} | class ____:
"""A dumb gensym that suffixes a stem by sequential numbers from 1000."""
def __init__(self):
# A proper implementation needs to account for:
# * ctx.info.namespace
# * all the symbols defined in the AST
# * the symbols generated so far
self._idx = 0
def new_name(self, stem='tmp'):
self._idx += 1
return stem + '_' + str(1000 + self._idx)
REPLACE = lambda _1, _2, _3: True
LEAVE = lambda _1, _2, _3: False
ANY = object()
| DummyGensym |
python | pypa__virtualenv | src/virtualenv/config/cli/parser.py | {
"start": 314,
"end": 1246
} | class ____(Namespace):
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
self._src = None
self._sources = {}
def set_src(self, key, value, src):
setattr(self, key, value)
if src.startswith("env var"):
src = "env var"
self._sources[key] = src
def __setattr__(self, key, value) -> None:
if getattr(self, "_src", None) is not None:
self._sources[key] = self._src
super().__setattr__(key, value)
def get_source(self, key):
return self._sources.get(key)
@property
def verbosity(self):
if not hasattr(self, "verbose") and not hasattr(self, "quiet"):
return None
return max(self.verbose - self.quiet, 0)
def __repr__(self) -> str:
return f"{type(self).__name__}({', '.join(f'{k}={v}' for k, v in vars(self).items() if not k.startswith('_'))})"
| VirtualEnvOptions |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_variables.py | {
"start": 7110,
"end": 11054
} | class ____:
async def test_no_results(
self,
client: AsyncClient,
):
res = await client.post(
"/variables/filter",
)
assert res.status_code == 200
assert len(res.json()) == 0
async def test_no_filter(
self,
client: AsyncClient,
variables,
):
res = await client.post(
"/variables/filter",
)
assert res.status_code == 200
res = parse_obj_as(List[core.Variable], res.json())
assert len(res) == len(variables)
assert {v.id for v in res} == {v.id for v in variables}
async def test_filter_name(
self,
client: AsyncClient,
variables,
):
# any filter
res = await client.post(
"/variables/filter",
json=dict(
variables=VariableFilter(
name=VariableFilterName(any_=["variable1"])
).model_dump(mode="json")
),
)
assert res.status_code == 200
res = parse_obj_as(List[core.Variable], res.json())
assert len(res) == 1
assert {v.id for v in res} == {v.id for v in variables if v.name == "variable1"}
# like filter
res = await client.post(
"/variables/filter",
json=dict(
variables=VariableFilter(
name=VariableFilterName(like_="variable1%")
).model_dump(mode="json")
),
)
assert res.status_code == 200
res = parse_obj_as(List[core.Variable], res.json())
assert len(res) == 2
assert {v.id for v in res} == {v.id for v in variables if "variable1" in v.name}
async def test_filter_id(
self,
client: AsyncClient,
variables,
):
variable = variables[0]
# any filter
res = await client.post(
"/variables/filter",
json=dict(
variables=VariableFilter(
id=VariableFilterId(any_=[variable.id])
).model_dump(mode="json")
),
)
assert res.status_code == 200
res = parse_obj_as(List[core.Variable], res.json())
assert len(res) == 1
assert {v.id for v in res} == {variable.id}
async def test_filter_tags(
self,
client: AsyncClient,
variables,
):
# any filter
res = await client.post(
"/variables/filter",
json=dict(
variables=VariableFilter(
tags=VariableFilterTags(all_=["tag1"])
).model_dump(mode="json")
),
)
assert res.status_code == 200
res = parse_obj_as(List[core.Variable], res.json())
assert len(res) == 2
assert {v.id for v in res} == {v.id for v in variables if "tag1" in v.tags}
async def test_name_sorted_forwards(
self,
client: AsyncClient,
variables,
):
# name sorted forwards
res = await client.post(
"/variables/filter",
json={"sort": sorting.VariableSort.NAME_ASC},
)
assert res.status_code == 200
res = parse_obj_as(List[core.Variable], res.json())
assert len(res) == len(variables)
assert [v.name for v in res] == sorted([v.name for v in variables])
async def test_name_sorted_backwards(
self,
client: AsyncClient,
variables,
):
# name sorted backwards
res = await client.post(
"/variables/filter",
json={"sort": sorting.VariableSort.NAME_DESC},
)
assert res.status_code == 200
res = parse_obj_as(List[core.Variable], res.json())
assert len(res) == len(variables)
assert [v.name for v in res] == sorted(
[v.name for v in variables], reverse=True
)
| TestReadVariables |
python | gevent__gevent | src/gevent/tests/test__core_callback.py | {
"start": 87,
"end": 618
} | class ____(greentest.TestCase):
def test(self):
loop = get_hub().loop
called = []
def f():
called.append(1)
x = loop.run_callback(f)
assert x, x
gevent.sleep(0)
assert called == [1], called
assert not x, (x, bool(x))
x = loop.run_callback(f)
assert x, x
x.stop()
assert not x, x
gevent.sleep(0)
assert called == [1], called
assert not x, x
if __name__ == '__main__':
greentest.main()
| Test |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_dynamodb.py | {
"start": 998,
"end": 4473
} | class ____:
def setup_method(self):
self.table_name = "test_airflow"
self.pk_name = "PK"
self.pk_value = "PKTest"
self.sk_name = "SK"
self.sk_value = "SKTest"
self.attribute_name = "Foo"
self.attribute_value = "Bar"
self.sensor_pk_sk = DynamoDBValueSensor(
task_id="dynamodb_value_sensor",
table_name=self.table_name,
partition_key_name=self.pk_name,
partition_key_value=self.pk_value,
attribute_name=self.attribute_name,
attribute_value=self.attribute_value,
sort_key_name=self.sk_name,
sort_key_value=self.sk_value,
)
self.sensor_pk = DynamoDBValueSensor(
task_id="dynamodb_value_sensor",
table_name=self.table_name,
partition_key_name=self.pk_name,
partition_key_value=self.pk_value,
attribute_name=self.attribute_name,
attribute_value=self.attribute_value,
)
@mock_aws
def test_sensor_with_pk(self):
hook = DynamoDBHook(table_name=self.table_name, table_keys=[self.pk_name])
hook.conn.create_table(
TableName=self.table_name,
KeySchema=[{"AttributeName": self.pk_name, "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": self.pk_name, "AttributeType": "S"}],
ProvisionedThroughput={"ReadCapacityUnits": 10, "WriteCapacityUnits": 10},
)
assert not self.sensor_pk.poke(None)
items = [{self.pk_name: self.pk_value, self.attribute_name: self.attribute_value}]
hook.write_batch_data(items)
assert self.sensor_pk.poke(None)
@mock_aws
def test_sensor_with_pk_and_sk(self):
hook = DynamoDBHook(table_name=self.table_name, table_keys=[self.pk_name, self.sk_name])
hook.conn.create_table(
TableName=self.table_name,
KeySchema=[
{"AttributeName": self.pk_name, "KeyType": "HASH"},
{"AttributeName": self.sk_name, "KeyType": "RANGE"},
],
AttributeDefinitions=[
{"AttributeName": self.pk_name, "AttributeType": "S"},
{"AttributeName": self.sk_name, "AttributeType": "S"},
],
ProvisionedThroughput={"ReadCapacityUnits": 10, "WriteCapacityUnits": 10},
)
assert not self.sensor_pk_sk.poke(None)
items = [
{
self.pk_name: self.pk_value,
self.sk_name: self.sk_value,
self.attribute_name: self.attribute_value,
}
]
hook.write_batch_data(items)
assert self.sensor_pk_sk.poke(None)
@mock_aws
def test_sensor_with_client_error(self):
hook = DynamoDBHook(table_name=self.table_name, table_keys=[self.pk_name])
hook.conn.create_table(
TableName=self.table_name,
KeySchema=[{"AttributeName": self.pk_name, "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": self.pk_name, "AttributeType": "S"}],
ProvisionedThroughput={"ReadCapacityUnits": 10, "WriteCapacityUnits": 10},
)
items = [{self.pk_name: self.pk_value, self.attribute_name: self.attribute_value}]
hook.write_batch_data(items)
self.sensor_pk.partition_key_name = "no such key"
assert self.sensor_pk.poke(None) is False
| TestDynamoDBValueSensor |
python | run-llama__llama_index | llama-index-integrations/voice_agents/llama-index-voice-agents-elevenlabs/llama_index/voice_agents/elevenlabs/events.py | {
"start": 273,
"end": 390
} | class ____(BaseVoiceAgentEvent):
model_config = ConfigDict(extra="allow")
base_64_encoded_audio: str
| AudioEvent |
python | tensorflow__tensorflow | tensorflow/python/autograph/operators/control_flow_test.py | {
"start": 29407,
"end": 35936
} | class ____(testing.AutoGraphTestCase):
def test_tensor(self):
def test_fn(cond):
def body():
nonlocal i
i = constant_op.constant(1)
def orelse():
nonlocal i
i = constant_op.constant(-1)
def set_state(cond_vars):
nonlocal i
i, = cond_vars
i = None
control_flow.if_stmt(
cond=cond,
body=body,
orelse=orelse,
get_state=lambda: (i,),
set_state=set_state,
symbol_names=('i',),
nouts=1)
return i
self.assertEqual(test_fn(constant_op.constant(True)), 1)
self.assertEqual(test_fn(constant_op.constant(False)), -1)
self.assertOpCreated('StatelessIf')
def test_tensor_no_outputs(self):
def test_fn(cond):
def body():
nonlocal i
i = constant_op.constant(1)
def orelse():
nonlocal i
i = constant_op.constant(-1.0)
def set_state(cond_vars):
nonlocal i
i, = cond_vars
i = None
control_flow.if_stmt(
cond=cond,
body=body,
orelse=orelse,
get_state=lambda: (i,),
set_state=set_state,
symbol_names=('i',),
nouts=0)
return i
self.assertIsNone(test_fn(constant_op.constant(True)))
self.assertIsNone(test_fn(constant_op.constant(False)))
self.assertOpCreated('StatelessIf')
def test_tensor_multiple_returns(self):
def test_fn(cond):
def body():
nonlocal i, j
i = constant_op.constant(1)
j = constant_op.constant(2)
def orelse():
nonlocal i, j
i = constant_op.constant(-1)
j = constant_op.constant(-2)
def set_state(cond_vars):
nonlocal i, j
i, j = cond_vars
i, j = None, None
control_flow.if_stmt(
cond=cond,
body=body,
orelse=orelse,
get_state=lambda: (i, j),
set_state=set_state,
symbol_names=('i', 'j'),
nouts=2)
return i, j
self.assertEqual(test_fn(constant_op.constant(True)), (1, 2))
self.assertEqual(test_fn(constant_op.constant(False)), (-1, -2))
self.assertOpCreated('StatelessIf')
def test_python(self):
def test_fn(cond):
def body():
nonlocal i
i = 1
def orelse():
nonlocal i
i = -1
i = None
control_flow.if_stmt(
cond=cond,
body=body,
orelse=orelse,
get_state=None,
set_state=None,
symbol_names=('i',),
nouts=1)
return i
self.assertEqual(test_fn(True), 1)
self.assertEqual(test_fn(False), -1)
self.assertNoOpsCreated()
def test_python_multiple_returns(self):
def test_fn(cond):
def body():
nonlocal i, j
i = 1
j = 2
def orelse():
nonlocal i, j
i = -1
j = -2
i, j = None, None
control_flow.if_stmt(
cond=cond,
body=body,
orelse=orelse,
get_state=None,
set_state=None,
symbol_names=('i', 'j'),
nouts=2)
return i, j
self.assertEqual(test_fn(True), (1, 2))
self.assertEqual(test_fn(False), (-1, -2))
self.assertNoOpsCreated()
def _basic_cond(self, body_fn, else_fn):
def body():
nonlocal x
x = body_fn()
def orelse():
nonlocal x
x = else_fn()
def set_state(cond_vars):
nonlocal x
x, = cond_vars
x = 0
control_flow.if_stmt(
cond=constant_op.constant(True),
body=body,
orelse=orelse,
get_state=lambda: (x,),
set_state=set_state,
symbol_names=('x',),
nouts=1)
return x
def test_tensor_none_output(self):
with self.assertRaisesRegex(
ValueError, "'x' is None at the end of the main branch"):
self._basic_cond(lambda: None, lambda: 1)
with self.assertRaisesRegex(
ValueError, "'x' is None at the end of the else branch"):
self._basic_cond(lambda: 1, lambda: None)
def test_tensor_undefined_output(self):
with self.assertRaisesRegex(
ValueError, "'x' must also be initialized in the main branch"):
self._basic_cond(lambda: variable_operators.Undefined('x'), lambda: 1)
with self.assertRaisesRegex(
ValueError, "'x' must also be initialized in the else branch"):
self._basic_cond(lambda: 1, lambda: variable_operators.Undefined('s'))
def test_tensor_dtype_change(self):
with self.assertRaisesRegex(
TypeError, "'x' has dtype int32.*but.*float32"):
self._basic_cond(lambda: 1, lambda: 1.0)
def _fixed_cond(self, cond_val):
def body():
nonlocal x
x = 1
def orelse():
nonlocal x
x = -1
def set_state(cond_vars):
nonlocal x
x, = cond_vars
x = 0
control_flow.if_stmt(
cond=cond_val,
body=body,
orelse=orelse,
get_state=lambda: (x,),
set_state=set_state,
symbol_names=('x',),
nouts=1)
return x
def _assertFixedCondResult(self, cond, expected):
def test_fn():
return self._fixed_cond(cond)
self.assertEqual(test_fn(), expected)
def test_tensor_legal_cond_scalar(self):
self._assertFixedCondResult(constant_op.constant(True), 1)
self._assertFixedCondResult(constant_op.constant(False), -1)
def test_tensor_legal_cond_single_element_nd(self):
self._assertFixedCondResult(constant_op.constant([[True]]), 1)
self._assertFixedCondResult(constant_op.constant([[False]]), -1)
self._assertFixedCondResult(_unranked_item(True), 1)
self._assertFixedCondResult(_unranked_item(False), -1)
def _assertCondCheckFails(self, cond):
with self.assertRaisesRegex(
ValueError, 'condition of if statement expected to be `tf.bool`'):
self._fixed_cond(cond)
def test_tensor_illegal_cond_not_bool(self):
self._assertCondCheckFails(constant_op.constant(1))
def test_tensor_illegal_cond_not_single_element(self):
self._assertCondCheckFails(constant_op.constant([1, 2, 3]))
self._assertCondCheckFails(constant_op.constant([True, False]))
def test_tensor_illegal_cond_not_single_element_dynamic_shape(self):
self._fixed_cond(_partial_shaped_bools())
# TODO(mdan): This error is quite bad. Measure the cost of an assertion.
self.assertRaisesRuntime(
errors_impl.InvalidArgumentError, 'requested shape has 1')
if __name__ == '__main__':
test.main()
| IfStmtTest |
python | kamyu104__LeetCode-Solutions | Python/zigzag-grid-traversal-with-skip.py | {
"start": 41,
"end": 475
} | class ____(object):
def zigzagTraversal(self, grid):
"""
:type grid: List[List[int]]
:rtype: List[int]
"""
result = []
for i in xrange(len(grid)):
if i%2 == 0:
result.extend(grid[i][j] for j in xrange(0, len(grid[0]), 2))
else:
result.extend(grid[i][j] for j in reversed(xrange(1, len(grid[0]), 2)))
return result
| Solution |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/serializers/group_open_period_serializer.py | {
"start": 503,
"end": 629
} | class ____(TypedDict):
id: str
type: str
value: str | None
dateCreated: datetime
| GroupOpenPeriodActivityResponse |
python | urllib3__urllib3 | src/urllib3/contrib/socks.py | {
"start": 2341,
"end": 2530
} | class ____(typing.TypedDict):
socks_version: int
proxy_host: str | None
proxy_port: str | None
username: str | None
password: str | None
rdns: bool
| _TYPE_SOCKS_OPTIONS |
python | readthedocs__readthedocs.org | readthedocs/projects/views/mixins.py | {
"start": 1648,
"end": 3032
} | class ____:
"""Injects ``subprojects_and_urls`` into the context."""
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["subprojects_and_urls"] = self._get_subprojects_and_urls()
return context
def _get_subprojects_and_urls(self):
"""
Get a tuple of subprojects and its absolute URls.
All subprojects share the domain from the parent,
so instead of resolving the domain and path for each subproject,
we resolve only the path of each one.
"""
subprojects_and_urls = []
project = self.get_project()
subprojects = project.subprojects.select_related("child")
if not subprojects.exists():
return subprojects_and_urls
resolver = Resolver()
main_domain = resolver.get_domain(project)
parsed_main_domain = urlparse(main_domain)
for subproject in subprojects:
subproject_path = resolver.resolve_path(subproject.child)
parsed_subproject_domain = parsed_main_domain._replace(
path=subproject_path,
)
subprojects_and_urls.append(
(
subproject,
parsed_subproject_domain.geturl(),
)
)
return subprojects_and_urls
| ProjectRelationListMixin |
python | django-guardian__django-guardian | guardian/testapp/tests/test_utils.py | {
"start": 921,
"end": 1065
} | class ____(TestCase):
def test(self):
anon = get_anonymous_user()
self.assertTrue(isinstance(anon, User))
| GetAnonymousUserTest |
python | facebook__pyre-check | tools/generate_taint_models/model_generator.py | {
"start": 908,
"end": 1318
} | class ____(ABC, Generic[T]):
@abstractmethod
def compute_models(
self, functions_to_model: Iterable[Callable[..., object]]
) -> Iterable[T]:
pass
@abstractmethod
def gather_functions_to_model(self) -> Iterable[Callable[..., object]]:
pass
def generate_models(self) -> Iterable[T]:
return self.compute_models(self.gather_functions_to_model())
| ModelGenerator |
python | walkccc__LeetCode | solutions/681. Next Closest Time/681.py | {
"start": 0,
"end": 640
} | class ____:
def nextClosestTime(self, time: str) -> str:
ans = list(time)
digits = sorted(ans)
def nextClosest(digit: str, limit: str) -> str:
next = bisect_right(digits, digit)
return digits[0] if next == 4 or digits[next] > limit else digits[next]
ans[4] = nextClosest(ans[4], '9')
if time[4] < ans[4]:
return ''.join(ans)
ans[3] = nextClosest(ans[3], '5')
if time[3] < ans[3]:
return ''.join(ans)
ans[1] = nextClosest(ans[1], '3' if ans[0] == '2' else '9')
if time[1] < ans[1]:
return ''.join(ans)
ans[0] = nextClosest(ans[0], '2')
return ''.join(ans)
| Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_django/DJ012.py | {
"start": 2333,
"end": 2705
} | class ____(models.Model):
"""Model that contains multiple out-of-order field definitions in a row."""
class Meta:
verbose_name = "test"
first_name = models.CharField(max_length=32)
last_name = models.CharField(max_length=32)
def get_absolute_url(self):
pass
middle_name = models.CharField(max_length=32)
| MultipleConsecutiveFields |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/events.py | {
"start": 10271,
"end": 13479
} | class ____(EventWithMetadata, IHaveNew):
asset_key: AssetKey
description: Optional[str]
metadata: Mapping[str, MetadataValue]
partition: Optional[str]
tags: Mapping[str, str]
failure_type: AssetMaterializationFailureType
reason: AssetMaterializationFailureReason
"""Event that indicates that an asset failed to materialize.
Args:
asset_key (Union[str, List[str], AssetKey]): A key to identify the asset.
partition (Optional[str]): The name of a partition of the asset.
tags (Optional[Mapping[str, str]]): A mapping containing tags for the failure event.
metadata (Optional[Dict[str, Union[str, float, int, MetadataValue]]]):
Arbitrary metadata about the asset. Keys are displayed string labels, and values are
one of the following: string, float, int, JSON-serializable dict, JSON-serializable
list, and one of the data classes returned by a MetadataValue static method.
failure_type: (AssetMaterializationFailureType): An enum indicating the type of failure.
reason: (AssetMaterializationFailureReason): An enum indicating why the asset failed to
materialize.
"""
def __new__(
cls,
asset_key: CoercibleToAssetKey,
failure_type: AssetMaterializationFailureType,
reason: AssetMaterializationFailureReason,
description: Optional[str] = None,
metadata: Optional[Mapping[str, RawMetadataValue]] = None,
partition: Optional[str] = None,
tags: Optional[Mapping[str, str]] = None,
):
if isinstance(asset_key, AssetKey):
check.inst_param(asset_key, "asset_key", AssetKey)
elif isinstance(asset_key, str):
asset_key = AssetKey(parse_asset_key_string(asset_key))
else:
check.sequence_param(asset_key, "asset_key", of_type=str)
asset_key = AssetKey(asset_key)
validate_asset_event_tags(tags)
normed_metadata = normalize_metadata(
check.opt_mapping_param(metadata, "metadata", key_type=str),
)
return super().__new__(
cls,
asset_key=asset_key,
description=description,
metadata=normed_metadata,
tags=tags or {},
partition=partition,
failure_type=failure_type,
reason=reason,
)
@property
def label(self) -> str:
return " ".join(self.asset_key.path)
@property
def data_version(self) -> Optional[str]:
return self.tags.get(DATA_VERSION_TAG)
def with_metadata(
self, metadata: Optional[Mapping[str, RawMetadataValue]]
) -> "AssetMaterializationFailure":
return AssetMaterializationFailure(
asset_key=self.asset_key,
description=self.description,
metadata=metadata,
partition=self.partition,
tags=self.tags,
reason=self.reason,
failure_type=self.failure_type,
)
@whitelist_for_serdes(
storage_field_names={"metadata": "metadata_entries"},
field_serializers={"metadata": MetadataFieldSerializer},
)
@public
| AssetMaterializationFailure |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/hooks/test_logs.py | {
"start": 1004,
"end": 4341
} | class ____:
@pytest.mark.parametrize(
("get_log_events_response", "num_skip_events", "expected_num_events", "end_time"),
[
# 3 empty responses with different tokens
(
[
{"nextForwardToken": "1", "events": []},
{"nextForwardToken": "2", "events": []},
{"nextForwardToken": "3", "events": []},
],
0,
0,
None,
),
# 2 events on the second response with same token
(
[
{"nextForwardToken": "", "events": []},
{"nextForwardToken": "", "events": [{}, {}]},
],
0,
2,
None,
),
# Different tokens, 2 events on the second response then 3 empty responses
(
[
{"nextForwardToken": "1", "events": []},
{"nextForwardToken": "2", "events": [{}, {}]},
{"nextForwardToken": "3", "events": []},
{"nextForwardToken": "4", "events": []},
{"nextForwardToken": "5", "events": []},
# This one is ignored
{"nextForwardToken": "6", "events": [{}, {}]},
],
0,
2,
10,
),
# 2 events on the second response, then 2 empty responses, then 2 consecutive responses with
# 2 events with the same token
(
[
{"nextForwardToken": "1", "events": []},
{"nextForwardToken": "2", "events": [{}, {}]},
{"nextForwardToken": "3", "events": []},
{"nextForwardToken": "4", "events": []},
{"nextForwardToken": "6", "events": [{}, {}]},
{"nextForwardToken": "6", "events": [{}, {}]},
# This one is ignored
{"nextForwardToken": "6", "events": [{}, {}]},
],
0,
6,
20,
),
],
)
@patch("airflow.providers.amazon.aws.hooks.logs.AwsLogsHook.conn", new_callable=mock.PropertyMock)
def test_get_log_events(
self, mock_conn, get_log_events_response, num_skip_events, expected_num_events, end_time
):
mock_conn().get_log_events.side_effect = get_log_events_response
log_group_name = "example-group"
log_stream_name = "example-log-stream"
hook = AwsLogsHook(aws_conn_id="aws_default", region_name="us-east-1")
events = hook.get_log_events(
log_group=log_group_name,
log_stream_name=log_stream_name,
skip=num_skip_events,
end_time=end_time,
)
events = list(events)
assert len(events) == expected_num_events
kwargs = {
"logGroupName": log_group_name,
"logStreamName": log_stream_name,
"startFromHead": True,
"startTime": 0,
"nextToken": ANY,
}
if end_time:
kwargs["endTime"] = end_time
mock_conn().get_log_events.assert_called_with(**kwargs)
| TestAwsLogsHook |
python | ray-project__ray | doc/source/serve/doc_code/http_guide/http_guide.py | {
"start": 1579,
"end": 1970
} | class ____:
pass
serve.run(FastAPIWrapper.bind(), route_prefix="/")
resp = requests.get("http://localhost:8000/")
assert resp.json() == "Hello from the root!"
# __end_byo_fastapi__
# __begin_fastapi_factory_pattern__
import requests
from fastapi import FastAPI
from ray import serve
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
@serve.deployment
| FastAPIWrapper |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_numeric.py | {
"start": 5444,
"end": 6454
} | class ____:
def test_valid(self) -> None:
prop = bcpn.Percent()
assert prop.is_valid(0)
assert prop.is_valid(1)
assert prop.is_valid(0.0)
assert prop.is_valid(1.0)
assert prop.is_valid(0.5)
def test_invalid(self) -> None:
prop = bcpn.Percent()
assert not prop.is_valid(None)
assert not prop.is_valid(False)
assert not prop.is_valid(True)
assert not prop.is_valid(1.0+1.0j)
assert not prop.is_valid("")
assert not prop.is_valid(())
assert not prop.is_valid([])
assert not prop.is_valid({})
assert not prop.is_valid(_TestHasProps())
assert not prop.is_valid(_TestModel())
assert not prop.is_valid(-0.001)
assert not prop.is_valid( 1.001)
def test_has_ref(self) -> None:
prop = bcpn.Percent()
assert not prop.has_ref
def test_str(self) -> None:
prop = bcpn.Percent()
assert str(prop) == "Percent"
| Test_Percent |
python | tensorflow__tensorflow | third_party/xla/build_tools/configure/configure.py | {
"start": 6565,
"end": 6683
} | class ____(ArgparseableEnum):
CPU = enum.auto()
CUDA = enum.auto()
ROCM = enum.auto()
SYCL = enum.auto()
| Backend |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/styles/style_transformation.py | {
"start": 1770,
"end": 2947
} | class ____(StyleTransformation):
"""
Turn dark colors into light colors and the other way around.
This is meant to make color schemes that work on a dark background usable
on a light background (and the other way around).
Notice that this doesn't swap foreground and background like "reverse"
does. It turns light green into dark green and the other way around.
Foreground and background colors are considered individually.
Also notice that when <reverse> is used somewhere and no colors are given
in particular (like what is the default for the bottom toolbar), then this
doesn't change anything. This is what makes sense, because when the
'default' color is chosen, it's what works best for the terminal, and
reverse works good with that.
"""
def transform_attrs(self, attrs: Attrs) -> Attrs:
"""
Return the `Attrs` used when opposite luminosity should be used.
"""
# Reverse colors.
attrs = attrs._replace(color=get_opposite_color(attrs.color))
attrs = attrs._replace(bgcolor=get_opposite_color(attrs.bgcolor))
return attrs
| SwapLightAndDarkStyleTransformation |
python | scrapy__scrapy | tests/test_command_runspider.py | {
"start": 8994,
"end": 9543
} | class ____(scrapy.Spider):
name = 'myspider'
async def start(self):
self.logger.debug('FEEDS: {}'.format(self.settings.getdict('FEEDS')))
return
yield
"""
args = ["-o", "-:json"]
log = self.get_log(tmp_path, spider_code, args=args)
assert "[myspider] DEBUG: FEEDS: {'stdout:': {'format': 'json'}}" in log
@pytest.mark.parametrize("arg", ["output.json:json", "output.json"])
def test_absolute_path(self, tmp_path: Path, arg: str) -> None:
spider_code = """
import scrapy
| MySpider |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/transfers/s3_to_sql.py | {
"start": 1233,
"end": 4967
} | class ____(BaseOperator):
"""
Load Data from S3 into a SQL Database.
You need to provide a parser function that takes a filename as an input
and returns an iterable of rows
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:S3ToSqlOperator`
:param schema: reference to a specific schema in SQL database
:param table: reference to a specific table in SQL database
:param s3_bucket: reference to a specific S3 bucket
:param s3_key: reference to a specific S3 key
:param sql_conn_id: reference to a specific SQL database. Must be of type DBApiHook
:param sql_hook_params: Extra config params to be passed to the underlying hook.
Should match the desired hook constructor params.
:param aws_conn_id: reference to a specific S3 / AWS connection
:param column_list: list of column names to use in the insert SQL.
:param commit_every: The maximum number of rows to insert in one
transaction. Set to `0` to insert all rows in one transaction.
:param parser: parser function that takes a filepath as input and returns an iterable.
e.g. to use a CSV parser that yields rows line-by-line, pass the following
function:
.. code-block:: python
def parse_csv(filepath):
import csv
with open(filepath, newline="") as file:
yield from csv.reader(file)
"""
template_fields: Sequence[str] = (
"s3_bucket",
"s3_key",
"schema",
"table",
"column_list",
"sql_conn_id",
)
template_ext: Sequence[str] = ()
ui_color = "#f4a460"
def __init__(
self,
*,
s3_key: str,
s3_bucket: str,
table: str,
parser: Callable[[str], Iterable[Iterable]],
column_list: list[str] | None = None,
commit_every: int = 1000,
schema: str | None = None,
sql_conn_id: str = "sql_default",
sql_hook_params: dict | None = None,
aws_conn_id: str | None = "aws_default",
**kwargs,
) -> None:
super().__init__(**kwargs)
self.s3_bucket = s3_bucket
self.s3_key = s3_key
self.table = table
self.schema = schema
self.aws_conn_id = aws_conn_id
self.sql_conn_id = sql_conn_id
self.column_list = column_list
self.commit_every = commit_every
self.parser = parser
self.sql_hook_params = sql_hook_params
def execute(self, context: Context) -> None:
self.log.info("Loading %s to SQL table %s...", self.s3_key, self.table)
s3_hook = S3Hook(aws_conn_id=self.aws_conn_id)
s3_obj = s3_hook.get_key(key=self.s3_key, bucket_name=self.s3_bucket)
with NamedTemporaryFile() as local_tempfile:
s3_obj.download_fileobj(local_tempfile)
local_tempfile.flush()
local_tempfile.seek(0)
self.db_hook.insert_rows(
table=self.table,
schema=self.schema,
target_fields=self.column_list,
rows=self.parser(local_tempfile.name),
commit_every=self.commit_every,
)
@cached_property
def db_hook(self):
self.log.debug("Get connection for %s", self.sql_conn_id)
conn = BaseHook.get_connection(self.sql_conn_id)
hook = conn.get_hook(hook_params=self.sql_hook_params)
if not callable(getattr(hook, "insert_rows", None)):
raise AirflowException(
"This hook is not supported. The hook class must have an `insert_rows` method."
)
return hook
| S3ToSqlOperator |
python | google__pytype | pytype/pytd/pytd.py | {
"start": 17604,
"end": 17785
} | class ____(GenericType):
"""Special generic type for heterogeneous tuples.
A tuple with length len(self.parameters), whose item type is specified at
each index.
"""
| TupleType |
python | django__django | tests/decorators/test_csrf.py | {
"start": 380,
"end": 672
} | class ____:
def get_request(self, token=CSRF_TOKEN):
request = HttpRequest()
request.method = "POST"
if token:
request.POST["csrfmiddlewaretoken"] = token
request.COOKIES[settings.CSRF_COOKIE_NAME] = token
return request
| CsrfTestMixin |
python | walkccc__LeetCode | solutions/587. Erect the Fence/587.py | {
"start": 0,
"end": 764
} | class ____:
def outerTrees(self, trees: list[list[int]]) -> list[list[int]]:
hull = []
trees.sort(key=lambda x: (x[0], x[1]))
def cross(p: list[int], q: list[int], r: list[int]) -> int:
return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])
# Build the lower hull: left-to-right scan.
for tree in trees:
while len(hull) > 1 and cross(hull[-1], hull[-2], tree) > 0:
hull.pop()
hull.append(tuple(tree))
hull.pop()
# Build the upper hull: right-to-left scan.
for tree in reversed(trees):
while len(hull) > 1 and cross(hull[-1], hull[-2], tree) > 0:
hull.pop()
hull.append(tuple(tree))
# Remove the redundant elements from the stack.
return list(set(hull))
| Solution |
python | spyder-ide__spyder | spyder/widgets/browser.py | {
"start": 1745,
"end": 2455
} | class ____(QWebEnginePage):
"""
Web page subclass to manage hyperlinks for WebEngine
Note: This can't be used for WebKit because the
acceptNavigationRequest method has a different
functionality for it.
"""
linkClicked = Signal(QUrl)
def acceptNavigationRequest(self, url, navigation_type, isMainFrame):
"""
Overloaded method to handle links ourselves
"""
link_clicked = QWebEnginePage.NavigationType.NavigationTypeLinkClicked
if navigation_type == link_clicked:
self.linkClicked.emit(url)
return False
return super().acceptNavigationRequest(
url, navigation_type, isMainFrame
)
| WebPage |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 240587,
"end": 245578
} | class ____(Response):
"""
Response of tasks.delete_many endpoint.
:param succeeded:
:type succeeded: Sequence[dict]
:param failed:
:type failed: Sequence[dict]
"""
_service = "tasks"
_action = "delete_many"
_version = "2.23"
_schema = {
"definitions": {
"task_urls": {
"properties": {
"artifact_urls": {
"items": {"type": "string"},
"type": ["array", "null"],
},
"event_urls": {
"items": {"type": "string"},
"type": ["array", "null"],
},
"model_urls": {
"items": {"type": "string"},
"type": ["array", "null"],
},
},
"type": "object",
}
},
"properties": {
"failed": {
"items": {
"properties": {
"error": {
"description": "Error info",
"properties": {
"codes": {
"items": {"type": "integer"},
"type": "array",
},
"data": {
"additionalProperties": True,
"type": "object",
},
"msg": {"type": "string"},
},
"type": "object",
},
"id": {
"description": "ID of the failed entity",
"type": "string",
},
},
"type": "object",
},
"type": ["array", "null"],
},
"succeeded": {
"items": {
"properties": {
"deleted": {
"description": "Indicates whether the task was deleted",
"type": "boolean",
},
"deleted_models": {
"description": "Number of deleted output models",
"type": "integer",
},
"deleted_versions": {
"description": "Number of deleted dataset versions",
"type": "integer",
},
"id": {
"description": "ID of the succeeded entity",
"type": "string",
},
"updated_children": {
"description": "Number of child tasks whose parent property was updated",
"type": ["integer", "null"],
},
"updated_models": {
"description": "Number of models whose task property was updated",
"type": ["integer", "null"],
},
"urls": {
"oneOf": [{"$ref": "#/definitions/task_urls"}, {"type": "null"}],
"description": (
"The urls of the files that were uploaded by the task. Returned if the"
" 'return_file_urls' was set to 'true'"
),
},
},
"type": "object",
},
"type": ["array", "null"],
},
},
"type": "object",
}
def __init__(self, succeeded=None, failed=None, **kwargs):
super(DeleteManyResponse, self).__init__(**kwargs)
self.succeeded = succeeded
self.failed = failed
@schema_property("succeeded")
def succeeded(self):
return self._property_succeeded
@succeeded.setter
def succeeded(self, value):
if value is None:
self._property_succeeded = None
return
self.assert_isinstance(value, "succeeded", (list, tuple))
self.assert_isinstance(value, "succeeded", (dict,), is_array=True)
self._property_succeeded = value
@schema_property("failed")
def failed(self):
return self._property_failed
@failed.setter
def failed(self, value):
if value is None:
self._property_failed = None
return
self.assert_isinstance(value, "failed", (list, tuple))
self.assert_isinstance(value, "failed", (dict,), is_array=True)
self._property_failed = value
| DeleteManyResponse |
python | getsentry__sentry | src/sentry/auth/providers/google/provider.py | {
"start": 672,
"end": 1430
} | class ____(OAuth2Login):
authorize_url = AUTHORIZE_URL
scope = SCOPE
def __init__(self, client_id: str, domains: list[str] | None = None) -> None:
self.domains = domains
super().__init__(client_id=client_id)
def get_authorize_params(self, state: str, redirect_uri: str) -> dict[str, str | None]:
params = super().get_authorize_params(state, redirect_uri)
# TODO(dcramer): ideally we could look at the current resulting state
# when an existing auth happens, and if they're missing a refresh_token
# we should re-prompt them a second time with ``approval_prompt=force``
params["approval_prompt"] = "force"
params["access_type"] = "offline"
return params
| GoogleOAuth2Login |
python | great-expectations__great_expectations | docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/column_aggregate_expectation_template.py | {
"start": 2541,
"end": 6082
} | class ____(ColumnAggregateExpectation):
# </snippet>
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_aggregate_expectation_template.py docstring">
"""TODO: add a docstring here"""
# </snippet>
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_aggregate_expectation_template.py examples">
examples = []
# </snippet>
# This is a tuple consisting of all Metrics necessary to evaluate the Expectation.
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_aggregate_expectation_template.py metric_dependencies">
metric_dependencies = ("METRIC NAME GOES HERE",)
# </snippet>
# This a tuple of parameter names that can affect whether the Expectation evaluates to True or False.
success_keys = ("min_value", "strict_min", "max_value", "strict_max")
def validate_configuration(
self, configuration: Optional[ExpectationConfiguration]
) -> None:
"""
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation.
Args:
configuration (OPTIONAL[ExpectationConfiguration]): \
An optional Expectation Configuration entry that will be used to configure the expectation
Returns:
None. Raises InvalidExpectationConfigurationError if the config is not validated successfully
"""
super().validate_configuration(configuration)
configuration = configuration or self.configuration
# # Check other things in configuration.kwargs and raise Exceptions if needed
# try:
# assert (
# ...
# ), "message"
# assert (
# ...
# ), "message"
# except AssertionError as e:
# raise InvalidExpectationConfigurationError(str(e))
# This method performs a validation of your metrics against your success keys, returning a dict indicating the success or failure of the Expectation.
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_aggregate_expectation_template.py validate">
def _validate(
self,
metrics: Dict,
runtime_configuration: Optional[dict] = None,
execution_engine: ExecutionEngine = None,
):
# </snippet>
raise NotImplementedError
# This object contains metadata for display in the public Gallery
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_aggregate_expectation_template.py library_metadata">
library_metadata = {
"tags": [], # Tags for this Expectation in the Gallery
"contributors": [ # Github handles for all contributors to this Expectation.
"@your_name_here", # Don't forget to add your github handle here!
],
}
# </snippet>
if __name__ == "__main__":
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_aggregate_expectation_template.py diagnostics">
ExpectColumnAggregateToMatchSomeCriteria().print_diagnostic_checklist()
# </snippet>
| ExpectColumnAggregateToMatchSomeCriteria |
python | django__django | django/contrib/gis/gdal/geometries.py | {
"start": 24874,
"end": 24969
} | class ____(OGRGeometry):
geos_support = False
# Geometry Collection base class.
| CompoundCurve |
python | PrefectHQ__prefect | tests/test_waiters.py | {
"start": 296,
"end": 4301
} | class ____:
@pytest.fixture(autouse=True)
def teardown(self):
yield
FlowRunWaiter.instance().stop()
def test_instance_returns_singleton(self):
assert FlowRunWaiter.instance() is FlowRunWaiter.instance()
def test_instance_returns_instance_after_stop(self):
instance = FlowRunWaiter.instance()
instance.stop()
assert FlowRunWaiter.instance() is not instance
@pytest.mark.timeout(20)
async def test_wait_for_flow_run(
self, prefect_client: PrefectClient, emitting_events_pipeline: EventsPipeline
):
"""This test will fail with a timeout error if waiting is not working correctly."""
@flow
async def test_flow():
await asyncio.sleep(1)
flow_run = await prefect_client.create_flow_run(test_flow, state=Pending())
asyncio.create_task(run_flow_async(flow=test_flow, flow_run=flow_run))
await FlowRunWaiter.wait_for_flow_run(flow_run.id)
await emitting_events_pipeline.process_events()
flow_run = await prefect_client.read_flow_run(flow_run.id)
assert flow_run.state
assert flow_run.state.is_completed()
async def test_wait_for_flow_run_with_timeout(self, prefect_client: PrefectClient):
@flow
async def test_flow():
await asyncio.sleep(5)
flow_run = await prefect_client.create_flow_run(test_flow, state=Pending())
run = asyncio.create_task(run_flow_async(flow=test_flow, flow_run=flow_run))
await FlowRunWaiter.wait_for_flow_run(flow_run.id, timeout=1)
# FlowRunWaiter stopped waiting before the task finished
assert not run.done()
await run
@pytest.mark.timeout(20)
async def test_non_singleton_mode(
self, prefect_client: PrefectClient, emitting_events_pipeline: EventsPipeline
):
waiter = FlowRunWaiter()
assert waiter is not FlowRunWaiter.instance()
@flow
async def test_flow():
await asyncio.sleep(1)
flow_run = await prefect_client.create_flow_run(test_flow, state=Pending())
asyncio.create_task(run_flow_async(flow=test_flow, flow_run=flow_run))
await waiter.wait_for_flow_run(flow_run.id)
await emitting_events_pipeline.process_events()
flow_run = await prefect_client.read_flow_run(flow_run.id)
assert flow_run.state
assert flow_run.state.is_completed()
waiter.stop()
@pytest.mark.timeout(20)
async def test_handles_concurrent_task_runs(
self, prefect_client: PrefectClient, emitting_events_pipeline: EventsPipeline
):
@flow
async def fast_flow():
await asyncio.sleep(1)
@flow
async def slow_flow():
await asyncio.sleep(5)
flow_run_1 = await prefect_client.create_flow_run(fast_flow, state=Pending())
flow_run_2 = await prefect_client.create_flow_run(slow_flow, state=Pending())
asyncio.create_task(run_flow_async(flow=fast_flow, flow_run=flow_run_1))
asyncio.create_task(run_flow_async(flow=slow_flow, flow_run=flow_run_2))
await FlowRunWaiter.wait_for_flow_run(flow_run_1.id)
await emitting_events_pipeline.process_events()
flow_run_1 = await prefect_client.read_flow_run(flow_run_1.id)
flow_run_2 = await prefect_client.read_flow_run(flow_run_2.id)
assert flow_run_1.state
assert flow_run_1.state.is_completed()
assert flow_run_2.state
assert not flow_run_2.state.is_completed()
await FlowRunWaiter.wait_for_flow_run(flow_run_2.id)
await emitting_events_pipeline.process_events()
flow_run_1 = await prefect_client.read_flow_run(flow_run_1.id)
flow_run_2 = await prefect_client.read_flow_run(flow_run_2.id)
assert flow_run_1.state
assert flow_run_1.state.is_completed()
assert flow_run_2.state
assert flow_run_2.state.is_completed()
| TestFlowRunWaiter |
python | bokeh__bokeh | src/bokeh/sphinxext/_internal/bokehjs_content.py | {
"start": 3705,
"end": 9531
} | class ____(CodeBlock):
has_content = True
optional_arguments = 1
required_arguments = 0
option_spec = CodeBlock.option_spec
option_spec.update(title=unchanged)
option_spec.update(js_file=unchanged)
option_spec.update(include_html=unchanged)
option_spec.update(disable_codepen=unchanged)
def get_codeblock_node(self, code, language):
"""this is copied from sphinx.directives.code.CodeBlock.run
it has been changed to accept code and language as an arguments instead
of reading from self
"""
document = self.state.document
location = self.state_machine.get_source_and_line(self.lineno)
linespec = self.options.get("emphasize-lines")
if linespec:
try:
nlines = len(code.split("\n"))
hl_lines = parselinenos(linespec, nlines)
if any(i >= nlines for i in hl_lines):
emph_lines = self.options["emphasize-lines"]
log.warning(__(f"line number spec is out of range(1-{nlines}): {emph_lines!r}"), location=location)
hl_lines = [x + 1 for x in hl_lines if x < nlines]
except ValueError as err:
return [document.reporter.warning(str(err), line=self.lineno)]
else:
hl_lines = None
if "dedent" in self.options:
location = self.state_machine.get_source_and_line(self.lineno)
lines = code.split("\n")
lines = dedent_lines(lines, self.options["dedent"], location=location)
code = "\n".join(lines)
literal = nodes.literal_block(code, code)
literal["language"] = language
literal["linenos"] = "linenos" in self.options or "lineno-start" in self.options
literal["classes"] += self.options.get("class", [])
extra_args = literal["highlight_args"] = {}
if hl_lines is not None:
extra_args["hl_lines"] = hl_lines
if "lineno-start" in self.options:
extra_args["linenostart"] = self.options["lineno-start"]
set_source_info(self, literal)
caption = self.options.get("caption")
if caption:
try:
literal = container_wrapper(self, literal, caption)
except ValueError as exc:
return [document.reporter.warning(str(exc), line=self.lineno)]
# literal will be note_implicit_target that is linked from caption and numref.
# when options['name'] is provided, it should be primary ID.
self.add_name(literal)
return [literal]
def get_js_source(self):
js_file = self.options.get("js_file", False)
# js_file *or* js code content, but not both
if js_file and self.content:
raise SphinxError("bokehjs-content:: directive can't have both js_file and content")
if js_file:
log.debug(f"[bokehjs-content] handling external example in {self.env.docname!r}: {js_file}")
path = js_file
if not js_file.startswith("/"):
path = join(self.env.app.srcdir, path)
js_source = open(path).read()
else:
log.debug(f"[bokehjs-content] handling inline example in {self.env.docname!r}")
js_source = "\n".join(self.content)
return js_source
def get_code_language(self):
# This is largely copied from bokeh_plot
js_source = self.get_js_source()
if self.options.get("include_html", False):
resources = get_sphinx_resources(include_bokehjs_api=True)
html_source = BJS_HTML.render(css_files=resources.css_files, js_files=resources.js_files, hashes=resources.hashes, bjs_script=js_source)
return [html_source, "html"]
else:
return [js_source, "javascript"]
def run(self):
rst_source = self.state_machine.node.document["source"]
rst_filename = basename(rst_source)
serial_no = self.env.new_serialno("ccb")
target_id = f"{rst_filename}.ccb-{serial_no}"
target_id = target_id.replace(".", "-")
target_node = nodes.target("", "", ids=[target_id])
node = bokehjs_content()
node["target_id"] = target_id
node["title"] = self.options.get("title", "bokehjs example")
node["include_bjs_header"] = False
node["disable_codepen"] = self.options.get("disable_codepen", False)
node["js_source"] = self.get_js_source()
source_doc = self.state_machine.node.document
if not hasattr(source_doc, "bjs_seen"):
# we only want to inject the CODEPEN_INIT on one
# bokehjs-content block per page, here we check to see if
# bjs_seen exists, if not set it to true, and set
# node['include_bjs_header'] to true. This way the
# CODEPEN_INIT is only injected once per document (html
# page)
source_doc.bjs_seen = True
node["include_bjs_header"] = True
code_content, language = self.get_code_language()
cb = self.get_codeblock_node(code_content, language)
node.setup_child(cb[0])
node.children.append(cb[0])
return [target_node, node]
def setup(app):
""" Required Sphinx extension setup function. """
app.add_node(bokehjs_content, html=bokehjs_content.html)
app.add_directive("bokehjs-content", BokehJSContent)
return PARALLEL_SAFE
# -----------------------------------------------------------------------------
# Private API
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# Code
# -----------------------------------------------------------------------------
| BokehJSContent |
python | huggingface__transformers | src/transformers/models/eomt/image_processing_eomt.py | {
"start": 1553,
"end": 7676
} | class ____(ImagesKwargs, total=False):
"""
do_split_image (`bool`, *optional*, defaults to `False`):
Whether to split the input images into overlapping patches for semantic segmentation. If set to `True`, the
input images will be split into patches of size `size["shortest_edge"]` with an overlap between patches.
Otherwise, the input images will be padded to the target size.
ignore_index (`int`, *optional*):
Label to be assigned to background pixels in segmentation maps. If provided, segmentation map pixels
denoted with 0 (background) will be replaced with `ignore_index`.
"""
do_split_image: bool
ignore_index: Optional[int]
# Adapted from transformers.models.maskformer.image_processing_maskformer.convert_segmentation_map_to_binary_masks
def convert_segmentation_map_to_binary_masks(
segmentation_map: np.ndarray,
instance_id_to_semantic_id: Optional[dict[int, int]] = None,
ignore_index: Optional[int] = None,
):
if ignore_index is not None:
segmentation_map = np.where(segmentation_map == 0, ignore_index, segmentation_map - 1)
# Get unique ids (class or instance ids based on input)
all_labels = np.unique(segmentation_map)
# Drop background label if applicable
if ignore_index is not None:
all_labels = all_labels[all_labels != ignore_index]
# Generate a binary mask for each object instance
binary_masks = [(segmentation_map == i) for i in all_labels]
# Stack the binary masks
if binary_masks:
binary_masks = np.stack(binary_masks, axis=0)
else:
binary_masks = np.zeros((0, *segmentation_map.shape))
# Convert instance ids to class ids
if instance_id_to_semantic_id is not None:
labels = np.zeros(all_labels.shape[0])
for label in all_labels:
class_id = instance_id_to_semantic_id[label + 1 if ignore_index is not None else label]
labels[all_labels == label] = class_id - 1 if ignore_index is not None else class_id
else:
labels = all_labels
return binary_masks.astype(np.float32), labels.astype(np.int64)
def remove_low_and_no_objects(masks, scores, labels, object_mask_threshold, num_labels):
"""
Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and
`labels`.
Args:
masks (`torch.Tensor`):
A tensor of shape `(num_queries, height, width)`.
scores (`torch.Tensor`):
A tensor of shape `(num_queries)`.
labels (`torch.Tensor`):
A tensor of shape `(num_queries)`.
object_mask_threshold (`float`):
A number between 0 and 1 used to binarize the masks.
Raises:
`ValueError`: Raised when the first dimension doesn't match in all input tensors.
Returns:
`tuple[`torch.Tensor`, `torch.Tensor`, `torch.Tensor`]`: The `masks`, `scores` and `labels` without the region
< `object_mask_threshold`.
"""
if not (masks.shape[0] == scores.shape[0] == labels.shape[0]):
raise ValueError("mask, scores and labels must have the same shape!")
to_keep = labels.ne(num_labels) & (scores > object_mask_threshold)
return masks[to_keep], scores[to_keep], labels[to_keep]
def check_segment_validity(mask_labels, mask_probs, k, mask_threshold=0.5, overlap_mask_area_threshold=0.8):
# Get the mask associated with the k class
mask_k = mask_labels == k
mask_k_area = mask_k.sum()
# Compute the area of all the stuff in query k
original_mask = mask_probs[k] >= mask_threshold
original_area = original_mask.sum()
final_mask = mask_k & original_mask
final_mask_area = final_mask.sum()
mask_exists = mask_k_area > 0 and original_area > 0 and final_mask_area > 0
if mask_exists:
area_ratio = mask_k_area / original_area
if not area_ratio.item() > overlap_mask_area_threshold:
mask_exists = False
return mask_exists, final_mask
def compute_segments(
mask_probs,
pred_scores,
pred_labels,
stuff_classes,
mask_threshold: float = 0.5,
overlap_mask_area_threshold: float = 0.8,
target_size: Optional[tuple[int, int]] = None,
):
height = mask_probs.shape[1] if target_size is None else target_size[0]
width = mask_probs.shape[2] if target_size is None else target_size[1]
segmentation = torch.zeros((height, width), dtype=torch.long, device=mask_probs.device) - 1
segments: list[dict] = []
# Compute per-pixel assignment based on weighted mask scores
mask_probs = mask_probs.sigmoid()
mask_labels = (pred_scores[:, None, None] * mask_probs).argmax(0)
# Keep track of instances of each class
current_segment_id = 0
stuff_memory_list: dict[str, int] = {}
for k in range(pred_labels.shape[0]):
pred_class = pred_labels[k].item()
# Check if mask exists and large enough to be a segment
mask_exists, final_mask = check_segment_validity(
mask_labels, mask_probs, k, mask_threshold, overlap_mask_area_threshold
)
if not mask_exists:
continue
if stuff_classes and pred_class in stuff_classes:
if pred_class in stuff_memory_list:
segmentation[final_mask] = stuff_memory_list[pred_class]
continue
else:
stuff_memory_list[pred_class] = current_segment_id
segmentation[final_mask] = current_segment_id
segment_score = round(pred_scores[k].item(), 6)
segments.append(
{
"id": current_segment_id,
"label_id": pred_class,
"score": segment_score,
}
)
current_segment_id += 1
return segmentation, segments
def get_target_size(size_dict: dict[str, int]) -> tuple[int, int]:
"""Returns the height and width from a size dict."""
target_height = size_dict["shortest_edge"]
target_width = size_dict.get("longest_edge") or target_height
return target_height, target_width
| EomtImageProcessorKwargs |
python | tensorflow__tensorflow | tensorflow/python/distribute/collective_util.py | {
"start": 4634,
"end": 6504
} | class ____(object):
"""Implementation of OptionsInterface."""
def __init__(self,
bytes_per_pack=0,
timeout_seconds=None,
implementation=CommunicationImplementation.AUTO):
if bytes_per_pack < 0:
raise ValueError(
f"Argument `bytes_per_pack` must be >=0, Received {bytes_per_pack}.")
if isinstance(implementation, str):
implementation = CommunicationImplementation(implementation.upper())
if not isinstance(implementation, CommunicationImplementation):
raise ValueError(
"Argument `implementation` must be instance of "
"`tf.distribute.experimental.CommunicationImplementation`.")
self.bytes_per_pack = bytes_per_pack
self.timeout_seconds = timeout_seconds
self.implementation = implementation
__init__.__doc__ = _OptionsExported.__init__.__doc__
def merge(self, options):
"""Merges with another options and returns a new one.
Values specified in the `options` takes precedence if they're not the
default.
Args:
options: a `tf.distribute.experimental.CollectiveCommunication`.
Returns:
A new `tf.distribute.experimental.CollectiveCommunication`.
"""
merged = copy.deepcopy(self)
if options is None:
return merged
if options.bytes_per_pack != 0:
merged.bytes_per_pack = options.bytes_per_pack
if options.timeout_seconds is not None:
merged.timeout_seconds = options.timeout_seconds
if options.implementation != CommunicationImplementation.AUTO:
merged.implementation = options.implementation
return merged
def __str__(self):
return (f"Options(bytes_per_pack={self.bytes_per_pack},"
f"timeout_seconds={self.timeout_seconds}, "
f"implementation={self.implementation})")
@tf_export("distribute.experimental.CollectiveHints")
| Options |
python | networkx__networkx | networkx/algorithms/bipartite/tests/test_matching.py | {
"start": 320,
"end": 7698
} | class ____:
"""Tests for bipartite matching algorithms."""
def setup_method(self):
"""Creates a bipartite graph for use in testing matching algorithms.
The bipartite graph has a maximum cardinality matching that leaves
vertex 1 and vertex 10 unmatched. The first six numbers are the left
vertices and the next six numbers are the right vertices.
"""
self.simple_graph = nx.complete_bipartite_graph(2, 3)
self.simple_solution = {0: 2, 1: 3, 2: 0, 3: 1}
edges = [(0, 7), (0, 8), (2, 6), (2, 9), (3, 8), (4, 8), (4, 9), (5, 11)]
self.top_nodes = set(range(6))
self.graph = nx.Graph()
self.graph.add_nodes_from(range(12))
self.graph.add_edges_from(edges)
# Example bipartite graph from issue 2127
G = nx.Graph()
G.add_nodes_from(
[
(1, "C"),
(1, "B"),
(0, "G"),
(1, "F"),
(1, "E"),
(0, "C"),
(1, "D"),
(1, "I"),
(0, "A"),
(0, "D"),
(0, "F"),
(0, "E"),
(0, "H"),
(1, "G"),
(1, "A"),
(0, "I"),
(0, "B"),
(1, "H"),
]
)
G.add_edge((1, "C"), (0, "A"))
G.add_edge((1, "B"), (0, "A"))
G.add_edge((0, "G"), (1, "I"))
G.add_edge((0, "G"), (1, "H"))
G.add_edge((1, "F"), (0, "A"))
G.add_edge((1, "F"), (0, "C"))
G.add_edge((1, "F"), (0, "E"))
G.add_edge((1, "E"), (0, "A"))
G.add_edge((1, "E"), (0, "C"))
G.add_edge((0, "C"), (1, "D"))
G.add_edge((0, "C"), (1, "I"))
G.add_edge((0, "C"), (1, "G"))
G.add_edge((0, "C"), (1, "H"))
G.add_edge((1, "D"), (0, "A"))
G.add_edge((1, "I"), (0, "A"))
G.add_edge((1, "I"), (0, "E"))
G.add_edge((0, "A"), (1, "G"))
G.add_edge((0, "A"), (1, "H"))
G.add_edge((0, "E"), (1, "G"))
G.add_edge((0, "E"), (1, "H"))
self.disconnected_graph = G
def check_match(self, matching):
"""Asserts that the matching is what we expect from the bipartite graph
constructed in the :meth:`setup` fixture.
"""
# For the sake of brevity, rename `matching` to `M`.
M = matching
matched_vertices = frozenset(itertools.chain(*M.items()))
# Assert that the maximum number of vertices (10) is matched.
assert matched_vertices == frozenset(range(12)) - {1, 10}
# Assert that no vertex appears in two edges, or in other words, that
# the matching (u, v) and (v, u) both appear in the matching
# dictionary.
assert all(u == M[M[u]] for u in range(12) if u in M)
def check_vertex_cover(self, vertices):
"""Asserts that the given set of vertices is the vertex cover we
expected from the bipartite graph constructed in the :meth:`setup`
fixture.
"""
# By Konig's theorem, the number of edges in a maximum matching equals
# the number of vertices in a minimum vertex cover.
assert len(vertices) == 5
# Assert that the set is truly a vertex cover.
for u, v in self.graph.edges():
assert u in vertices or v in vertices
# TODO Assert that the vertices are the correct ones.
def test_eppstein_matching(self):
"""Tests that David Eppstein's implementation of the Hopcroft--Karp
algorithm produces a maximum cardinality matching.
"""
self.check_match(eppstein_matching(self.graph, self.top_nodes))
def test_hopcroft_karp_matching(self):
"""Tests that the Hopcroft--Karp algorithm produces a maximum
cardinality matching in a bipartite graph.
"""
self.check_match(hopcroft_karp_matching(self.graph, self.top_nodes))
def test_to_vertex_cover(self):
"""Test for converting a maximum matching to a minimum vertex cover."""
matching = maximum_matching(self.graph, self.top_nodes)
vertex_cover = to_vertex_cover(self.graph, matching, self.top_nodes)
self.check_vertex_cover(vertex_cover)
def test_eppstein_matching_simple(self):
match = eppstein_matching(self.simple_graph)
assert match == self.simple_solution
def test_hopcroft_karp_matching_simple(self):
match = hopcroft_karp_matching(self.simple_graph)
assert match == self.simple_solution
def test_eppstein_matching_disconnected(self):
with pytest.raises(nx.AmbiguousSolution):
match = eppstein_matching(self.disconnected_graph)
def test_hopcroft_karp_matching_disconnected(self):
with pytest.raises(nx.AmbiguousSolution):
match = hopcroft_karp_matching(self.disconnected_graph)
def test_issue_2127(self):
"""Test from issue 2127"""
# Build the example DAG
G = nx.DiGraph()
G.add_edge("A", "C")
G.add_edge("A", "B")
G.add_edge("C", "E")
G.add_edge("C", "D")
G.add_edge("E", "G")
G.add_edge("E", "F")
G.add_edge("G", "I")
G.add_edge("G", "H")
tc = nx.transitive_closure(G)
btc = nx.Graph()
# Create a bipartite graph based on the transitive closure of G
for v in tc.nodes():
btc.add_node((0, v))
btc.add_node((1, v))
for u, v in tc.edges():
btc.add_edge((0, u), (1, v))
top_nodes = {n for n in btc if n[0] == 0}
matching = hopcroft_karp_matching(btc, top_nodes)
vertex_cover = to_vertex_cover(btc, matching, top_nodes)
independent_set = set(G) - {v for _, v in vertex_cover}
assert {"B", "D", "F", "I", "H"} == independent_set
def test_vertex_cover_issue_2384(self):
G = nx.Graph([(0, 3), (1, 3), (1, 4), (2, 3)])
matching = maximum_matching(G)
vertex_cover = to_vertex_cover(G, matching)
for u, v in G.edges():
assert u in vertex_cover or v in vertex_cover
def test_vertex_cover_issue_3306(self):
G = nx.Graph()
edges = [(0, 2), (1, 0), (1, 1), (1, 2), (2, 2)]
G.add_edges_from([((i, "L"), (j, "R")) for i, j in edges])
matching = maximum_matching(G)
vertex_cover = to_vertex_cover(G, matching)
for u, v in G.edges():
assert u in vertex_cover or v in vertex_cover
def test_unorderable_nodes(self):
a = object()
b = object()
c = object()
d = object()
e = object()
G = nx.Graph([(a, d), (b, d), (b, e), (c, d)])
matching = maximum_matching(G)
vertex_cover = to_vertex_cover(G, matching)
for u, v in G.edges():
assert u in vertex_cover or v in vertex_cover
def test_eppstein_matching():
"""Test in accordance to issue #1927"""
G = nx.Graph()
G.add_nodes_from(["a", 2, 3, 4], bipartite=0)
G.add_nodes_from([1, "b", "c"], bipartite=1)
G.add_edges_from([("a", 1), ("a", "b"), (2, "b"), (2, "c"), (3, "c"), (4, 1)])
matching = eppstein_matching(G)
assert len(matching) == len(maximum_matching(G))
assert all(x in set(matching.keys()) for x in set(matching.values()))
| TestMatching |
python | ray-project__ray | rllib/utils/filter.py | {
"start": 2221,
"end": 9735
} | class ____:
def __init__(self, shape=()):
"""Initializes a `RunningStat` instance."""
# Keep always a state and a delta from all attributes. Note,
# we use the state for filtering and the delta for updates.
# All deltas will be zero(s) after a state synchronization
# across different actors.
self.num_pushes = 0
self.num_pushes_delta = 0
# Stores the mean.
self.mean_array = np.zeros(shape)
self.mean_delta_array = np.zeros(shape)
# Stores the sum of squared demeaned observations. Note, this
# follows Wellington's algorithm.
self.sum_sq_diff_array = np.zeros(shape)
self.sum_sq_diff_delta_array = np.zeros(shape)
def copy(self):
"""Copies a `RunningStat`."""
# Copy all attributes by creating a new `RunningStat` instance.
other = RunningStat(self.shape)
other.num_pushes = self.num_pushes
other.num_pushes_delta = self.num_pushes_delta
other.mean_array = np.copy(self.mean_array)
other.mean_delta_array = np.copy(self.mean_delta_array)
other.sum_sq_diff_array = np.copy(self.sum_sq_diff_array)
other.sum_sq_diff_delta_array = np.copy(self.sum_sq_diff_delta_array)
return other
def push(self, x):
"""Updates a `RunningStat` instance by a new value.
Args:
x: A new value to update mean and sum of squares by. Must have the
same shape like the mean.
Raises:
`ValueError` in case of a shape mismatch.
"""
x = np.asarray(x)
if x.shape != self.mean_array.shape:
raise ValueError(
"Unexpected input shape {}, expected {}, value = {}".format(
x.shape, self.mean_array.shape, x
)
)
# Store old mean for Welford's sum of squares update.
old_mean = np.copy(self.mean_array)
self.num_pushes += 1
# Also increase the delta counter since the last merge.
self.num_pushes_delta += 1
if self.num_pushes == 1:
self.mean_array[...] = x
self.mean_delta_array[...] = x
# sum_sq_diff_array remains 0 for the first element
else:
# Welford's update for mean
delta = x - old_mean
self.mean_array[...] += delta / self.num_pushes
# Update the mean delta.
self.mean_delta_array[...] += delta / self.num_pushes
# Welford's update for sum of squared differences (S)
# S_k = S_{k-1} + (x_k - M_k)(x_k - M_{k-1}).
self.sum_sq_diff_array[...] += delta * (x - self.mean_array)
# Update the mean sum of squares.
self.sum_sq_diff_delta_array[...] += delta * (x - self.mean_array)
def update(self, other):
"""Update this `RunningStat` instance by another one.
Args:
other: Another `RunningStat` instance whose state should me
merged with `self`.
"""
# Make this explicitly for future changes to avoid ever turning `num_pushes` into
# a float (this was a problem in earlier versions).
n1_int = self.num_pushes
# Note, we use only the delta for the updates, this reduces the risk of numerical
# instabilities significantly.
n2_int = other.num_pushes_delta
# For higher precision use float versions of the counters.
n1_flt = float(self.num_pushes)
n2_flt = float(other.num_pushes_delta)
n_flt = n1_flt + n2_flt
# If none of the two `RunningStat`s has seen values, yet, return.
if n1_int + n2_int == 0:
# Avoid divide by zero, which creates nans
return
# Numerically stable formula for combining means
# M_combined = (n1*M1 + n2*M2) / (n1+n2)
# This is equivalent to M1 + delta * n2 / n
delta_mean = other.mean_delta_array - self.mean_array
self.mean_array += delta_mean * n2_flt / n_flt
# Numerically stable formula for combining sums of squared differences (S)
# S_combined = S1 + S2 + (n1*n2 / (n1+n2)) * (M1 - M2)^2 [6]
delta_mean_sq = delta_mean * delta_mean
self.sum_sq_diff_array += other.sum_sq_diff_delta_array + delta_mean_sq * (
n1_flt * n2_flt / n_flt
)
# Update the counter with the interger versions of the two counters.
self.num_pushes = n1_int + n2_int
def __repr__(self):
"""Represents a `RunningStat` instance.
Note, a `RunningStat` is represented by its mean, its standard deviation
and the number `n` of values used to compute the two statistics.
"""
return "(n={}, mean_mean={}, mean_std={})".format(
self.n, np.mean(self.mean), np.mean(self.std)
)
@property
def n(self):
"""Returns the number of values seen by a `RunningStat` instance."""
return self.num_pushes
@property
def mean(self):
"""Returns the (vector) mean estimate of a `RunningStat` instance."""
return self.mean_array
@property
def var(self):
"""Returns the (unbiased vector) variance estimate of a `RunningStat` instance."""
# For n=0 or n=1, variance is typically undefined or 0.
# Returning 0 for n <= 1 is a common convention for running variance.
if self.num_pushes <= 1:
return np.zeros_like(self.mean_array).astype(np.float32)
# Variance = S / (n-1) for sample variance
return (self.sum_sq_diff_array / (float(self.num_pushes) - 1)).astype(
np.float32
)
@property
def std(self):
"""Returns the (unbiased vector) std estimate of a `RunningStat` instance.ance."""
# Ensure variance is non-negative before sqrt
return np.sqrt(np.maximum(0, self.var))
@property
def shape(self):
"""Returns the shape of the `RunningStat` instance."""
return self.mean_array.shape
def to_state(self):
"""Returns the pickable state of a `RunningStat` instance."""
return {
"num_pushes": self.num_pushes,
"num_pushes_delta": self.num_pushes_delta,
"mean_array": _serialize_ndarray(self.mean_array),
"mean_delta_array": _serialize_ndarray(self.mean_delta_array),
"sum_sq_diff_array": _serialize_ndarray(self.sum_sq_diff_array),
"sum_sq_diff_delta_array": _serialize_ndarray(self.sum_sq_diff_delta_array),
}
@staticmethod
def from_state(state):
"""Builds a `RunningStat` instance from a pickable state."""
# Need to pass shape to constructor for proper initialization
# Assuming shape can be inferred from mean_array in state
shape = _deserialize_ndarray(state["mean_array"]).shape
running_stats = RunningStat(shape)
running_stats.num_pushes = state["num_pushes"]
running_stats.num_pushes_delta = state["num_pushes_delta"]
running_stats.mean_array = _deserialize_ndarray(state["mean_array"])
running_stats.mean_delta_array = _deserialize_ndarray(state["mean_delta_array"])
running_stats.sum_sq_diff_array = _deserialize_ndarray(
state["sum_sq_diff_array"]
)
running_stats.sum_sq_diff_delta_array = _deserialize_ndarray(
state["sum_sq_diff_delta_array"]
)
return running_stats
@OldAPIStack
| RunningStat |
python | matplotlib__matplotlib | lib/mpl_toolkits/axisartist/axislines.py | {
"start": 8756,
"end": 8881
} | class ____: # Backcompat.
Fixed = _FixedAxisArtistHelperBase
Floating = _FloatingAxisArtistHelperBase
| AxisArtistHelper |
python | numba__numba | numba/core/compiler_machinery.py | {
"start": 2447,
"end": 2612
} | class ____(object):
""" Mixin to indicate a pass is SSA form compliant. Nothing is asserted
about this condition at present.
"""
pass
| SSACompliantMixin |
python | crytic__slither | slither/utils/command_line.py | {
"start": 757,
"end": 13491
} | class ____(enum.Enum):
PEDANTIC = "pedantic"
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
NONE = "none"
# Those are the flags shared by the command line and the config file
defaults_flag_in_config = {
"codex": False,
"codex_contracts": "all",
"codex_model": "text-davinci-003",
"codex_temperature": 0,
"codex_max_tokens": 300,
"codex_log": False,
"detectors_to_run": "all",
"printers_to_run": None,
"detectors_to_exclude": None,
"detectors_to_include": None,
"exclude_dependencies": False,
"exclude_informational": False,
"exclude_optimization": False,
"exclude_low": False,
"exclude_medium": False,
"exclude_high": False,
"fail_on": FailOnLevel.PEDANTIC,
"json": None,
"sarif": None,
"json-types": ",".join(DEFAULT_JSON_OUTPUT_TYPES),
"disable_color": False,
"filter_paths": None,
"include_paths": None,
"generate_patches": False,
# debug command
"skip_assembly": False,
"legacy_ast": False,
"zip": None,
"zip_type": "lzma",
"show_ignored_findings": False,
"no_fail": False,
"sarif_input": "export.sarif",
"sarif_triage": "export.sarif.sarifexplorer",
"triage_database": "slither.db.json",
**DEFAULTS_FLAG_IN_CONFIG_CRYTIC_COMPILE,
}
def read_config_file(args: argparse.Namespace) -> None:
# No config file was provided as an argument
if args.config_file is None:
# Check whether the default config file is present
if os.path.exists("slither.config.json"):
# The default file exists, use it
args.config_file = "slither.config.json"
else:
return
if os.path.isfile(args.config_file):
try:
with open(args.config_file, encoding="utf8") as f:
config = json.load(f)
for key, elem in config.items():
if key not in defaults_flag_in_config:
logger.info(
yellow(f"{args.config_file} has an unknown key: {key} : {elem}")
)
continue
if getattr(args, key) == defaults_flag_in_config[key]:
setattr(args, key, elem)
except json.decoder.JSONDecodeError as e:
logger.error(red(f"Impossible to read {args.config_file}, please check the file {e}"))
else:
logger.error(red(f"File {args.config_file} is not a file or does not exist"))
logger.error(yellow("Falling back to the default settings..."))
def output_to_markdown(
detector_classes: List[Type[AbstractDetector]],
printer_classes: List[Type[AbstractPrinter]],
filter_wiki: str,
) -> None:
def extract_help(cls: Union[Type[AbstractDetector], Type[AbstractPrinter]]) -> str:
if cls.WIKI == "":
return cls.HELP
return f"[{cls.HELP}]({cls.WIKI})"
detectors_list = []
print(filter_wiki)
for detector in detector_classes:
argument = detector.ARGUMENT
# dont show the backdoor example
if argument == "backdoor":
continue
if not filter_wiki in detector.WIKI:
continue
help_info = extract_help(detector)
impact = detector.IMPACT
confidence = classification_txt[detector.CONFIDENCE]
detectors_list.append((argument, help_info, impact, confidence))
# Sort by impact, confidence, and name
detectors_list = sorted(
detectors_list, key=lambda element: (element[2], element[3], element[0])
)
idx = 1
for (argument, help_info, impact, confidence) in detectors_list:
print(f"{idx} | `{argument}` | {help_info} | {classification_txt[impact]} | {confidence}")
idx = idx + 1
print()
printers_list = []
for printer in printer_classes:
argument = printer.ARGUMENT
help_info = extract_help(printer)
printers_list.append((argument, help_info))
# Sort by impact, confidence, and name
printers_list = sorted(printers_list, key=lambda element: (element[0]))
idx = 1
for (argument, help_info) in printers_list:
print(f"{idx} | `{argument}` | {help_info}")
idx = idx + 1
def get_level(l: str) -> int:
tab = l.count("\t") + 1
if l.replace("\t", "").startswith(" -"):
tab = tab + 1
if l.replace("\t", "").startswith("-"):
tab = tab + 1
return tab
def convert_result_to_markdown(txt: str) -> str:
# -1 to remove the last \n
lines = txt[0:-1].split("\n")
ret = []
level = 0
for l in lines:
next_level = get_level(l)
prefix = "<li>"
if next_level < level:
prefix = "</ul>" * (level - next_level) + prefix
if next_level > level:
prefix = "<ul>" * (next_level - level) + prefix
level = next_level
ret.append(prefix + l)
return "".join(ret)
def output_results_to_markdown(
all_results: List[Dict], checklistlimit: str, show_ignored_findings: bool
) -> None:
checks = defaultdict(list)
info: Dict = defaultdict(dict)
for results_ in all_results:
checks[results_["check"]].append(results_)
info[results_["check"]] = {
"impact": results_["impact"],
"confidence": results_["confidence"],
}
if not show_ignored_findings:
print(
"**THIS CHECKLIST IS NOT COMPLETE**. Use `--show-ignored-findings` to show all the results."
)
print("Summary")
for check_ in checks:
print(
f" - [{check_}](#{check_}) ({len(checks[check_])} results) ({info[check_]['impact']})"
)
counter = 0
for (check, results) in checks.items():
print(f"## {check}")
print(f'Impact: {info[check]["impact"]}')
print(f'Confidence: {info[check]["confidence"]}')
additional = False
if checklistlimit and len(results) > 5:
results = results[0:5]
additional = True
for result in results:
print(" - [ ] ID-" + f"{counter}")
counter = counter + 1
print(result["markdown"])
if result["first_markdown_element"]:
print(result["first_markdown_element"])
print("\n")
if additional:
print(f"**More results were found, check [{checklistlimit}]({checklistlimit})**")
def output_wiki(detector_classes: List[Type[AbstractDetector]], filter_wiki: str) -> None:
# Sort by impact, confidence, and name
detectors_list = sorted(
detector_classes,
key=lambda element: (element.IMPACT, element.CONFIDENCE, element.ARGUMENT),
)
for detector in detectors_list:
argument = detector.ARGUMENT
# dont show the backdoor example
if argument == "backdoor":
continue
if not filter_wiki in detector.WIKI:
continue
check = detector.ARGUMENT
impact = classification_txt[detector.IMPACT]
confidence = classification_txt[detector.CONFIDENCE]
title = detector.WIKI_TITLE
description = detector.WIKI_DESCRIPTION
exploit_scenario = detector.WIKI_EXPLOIT_SCENARIO
recommendation = detector.WIKI_RECOMMENDATION
print(f"\n## {title}")
print("### Configuration")
print(f"* Check: `{check}`")
print(f"* Severity: `{impact}`")
print(f"* Confidence: `{confidence}`")
print("\n### Description")
print(description)
if exploit_scenario:
print("\n### Exploit Scenario:")
print(exploit_scenario)
print("\n### Recommendation")
print(recommendation)
def output_detectors(detector_classes: List[Type[AbstractDetector]]) -> None:
detectors_list = []
for detector in detector_classes:
argument = detector.ARGUMENT
# dont show the backdoor example
if argument == "backdoor":
continue
help_info = detector.HELP
impact = detector.IMPACT
confidence = classification_txt[detector.CONFIDENCE]
detectors_list.append((argument, help_info, impact, confidence))
table = MyPrettyTable(["Num", "Check", "What it Detects", "Impact", "Confidence"])
# Sort by impact, confidence, and name
detectors_list = sorted(
detectors_list, key=lambda element: (element[2], element[3], element[0])
)
idx = 1
for (argument, help_info, impact, confidence) in detectors_list:
table.add_row([str(idx), argument, help_info, classification_txt[impact], confidence])
idx = idx + 1
print(table)
# pylint: disable=too-many-locals
def output_detectors_json(
detector_classes: List[Type[AbstractDetector]],
) -> List[Dict]:
detectors_list = []
for detector in detector_classes:
argument = detector.ARGUMENT
# dont show the backdoor example
if argument == "backdoor":
continue
help_info = detector.HELP
impact = detector.IMPACT
confidence = classification_txt[detector.CONFIDENCE]
wiki_url = detector.WIKI
wiki_description = detector.WIKI_DESCRIPTION
wiki_exploit_scenario = detector.WIKI_EXPLOIT_SCENARIO
wiki_recommendation = detector.WIKI_RECOMMENDATION
detectors_list.append(
(
argument,
help_info,
impact,
confidence,
wiki_url,
wiki_description,
wiki_exploit_scenario,
wiki_recommendation,
)
)
# Sort by impact, confidence, and name
detectors_list = sorted(
detectors_list, key=lambda element: (element[2], element[3], element[0])
)
idx = 1
table = []
for (
argument,
help_info,
impact,
confidence,
wiki_url,
description,
exploit,
recommendation,
) in detectors_list:
table.append(
{
"index": idx,
"check": argument,
"title": help_info,
"impact": classification_txt[impact],
"confidence": confidence,
"wiki_url": wiki_url,
"description": description,
"exploit_scenario": exploit,
"recommendation": recommendation,
}
)
idx = idx + 1
return table
def output_printers(printer_classes: List[Type[AbstractPrinter]]) -> None:
printers_list = []
for printer in printer_classes:
argument = printer.ARGUMENT
help_info = printer.HELP
printers_list.append((argument, help_info))
table = MyPrettyTable(["Num", "Printer", "What it Does"])
# Sort by impact, confidence, and name
printers_list = sorted(printers_list, key=lambda element: (element[0]))
idx = 1
for (argument, help_info) in printers_list:
# Clean multi line HELP info
table.add_row([str(idx), argument, " ".join(x.strip() for x in help_info.splitlines())])
idx = idx + 1
print(table)
def output_printers_json(printer_classes: List[Type[AbstractPrinter]]) -> List[Dict]:
printers_list = []
for printer in printer_classes:
argument = printer.ARGUMENT
help_info = printer.HELP
printers_list.append((argument, help_info))
# Sort by name
printers_list = sorted(printers_list, key=lambda element: (element[0]))
idx = 1
table = []
for (argument, help_info) in printers_list:
table.append({"index": idx, "check": argument, "title": help_info})
idx = idx + 1
return table
def check_and_sanitize_markdown_root(markdown_root: str) -> str:
# Regex to check whether the markdown_root is a GitHub URL
match = re.search(
r"(https://)github.com/([a-zA-Z-]+)([:/][A-Za-z0-9_.-]+[:/]?)([A-Za-z0-9_.-]*)(.*)",
markdown_root,
)
if match:
if markdown_root[-1] != "/":
logger.warning("Appending '/' in markdown_root url for better code referencing")
markdown_root = markdown_root + "/"
if not match.group(4):
logger.warning(
"Appending 'master/tree/' in markdown_root url for better code referencing"
)
markdown_root = markdown_root + "master/tree/"
elif match.group(4) == "tree":
logger.warning(
"Replacing 'tree' with 'blob' in markdown_root url for better code referencing"
)
positions = match.span(4)
markdown_root = f"{markdown_root[:positions[0]]}blob{markdown_root[positions[1]:]}"
return markdown_root
| FailOnLevel |
python | donnemartin__system-design-primer | solutions/system_design/mint/mint_snippets.py | {
"start": 290,
"end": 967
} | class ____(object):
def __init__(self, seller_category_map, seller_category_overrides_map):
self.seller_category_map = seller_category_map
self.seller_category_overrides_map = seller_category_overrides_map
def categorize(self, transaction):
if transaction.seller in self.seller_category_map:
return self.seller_category_map[transaction.seller]
if transaction.seller in self.seller_category_overrides_map:
seller_category_map[transaction.seller] = \
self.manual_overrides[transaction.seller].peek_min()
return self.seller_category_map[transaction.seller]
return None
| Categorizer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType28.py | {
"start": 2003,
"end": 2070
} | class ____(Class6[Sequence[T_co], Sequence[T_co]]): ...
| Class6_Child5 |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 99108,
"end": 106111
} | class ____(rv_continuous):
r"""A generalized extreme value continuous random variable.
%(before_notes)s
See Also
--------
gumbel_r
Notes
-----
For :math:`c=0`, `genextreme` is equal to `gumbel_r` with
probability density function
.. math::
f(x) = \exp(-\exp(-x)) \exp(-x),
where :math:`-\infty < x < \infty`.
For :math:`c \ne 0`, the probability density function for `genextreme` is:
.. math::
f(x, c) = \exp(-(1-c x)^{1/c}) (1-c x)^{1/c-1},
where :math:`-\infty < x \le 1/c` if :math:`c > 0` and
:math:`1/c \le x < \infty` if :math:`c < 0`.
Note that several sources and software packages use the opposite
convention for the sign of the shape parameter :math:`c`.
`genextreme` takes ``c`` as a shape parameter for :math:`c`.
%(after_notes)s
%(example)s
"""
def _argcheck(self, c):
return np.isfinite(c)
def _shape_info(self):
return [_ShapeInfo("c", False, (-np.inf, np.inf), (False, False))]
def _get_support(self, c):
_b = np.where(c > 0, 1.0 / np.maximum(c, _XMIN), np.inf)
_a = np.where(c < 0, 1.0 / np.minimum(c, -_XMIN), -np.inf)
return _a, _b
def _loglogcdf(self, x, c):
# Returns log(-log(cdf(x, c)))
return xpx.apply_where(
(x == x) & (c != 0), (x, c),
lambda x, c: sc.log1p(-c*x)/c,
fill_value=-x)
def _pdf(self, x, c):
# genextreme.pdf(x, c) =
# exp(-exp(-x))*exp(-x), for c==0
# exp(-(1-c*x)**(1/c))*(1-c*x)**(1/c-1), for x \le 1/c, c > 0
return np.exp(self._logpdf(x, c))
def _logpdf(self, x, c):
# Suppress warnings 0 * inf
cx = xpx.apply_where((x == x) & (c != 0), (c, x),
operator.mul, fill_value=0.0)
logex2 = sc.log1p(-cx)
logpex2 = self._loglogcdf(x, c)
pex2 = np.exp(logpex2)
# Handle special cases
np.putmask(logpex2, (c == 0) & (x == -np.inf), 0.0)
logpdf = xpx.apply_where(
~((cx == 1) | (cx == -np.inf)),
(pex2, logpex2, logex2),
lambda pex2, lpex2, lex2: -pex2 + lpex2 - lex2,
fill_value=-np.inf)
np.putmask(logpdf, (c == 1) & (x == 1), 0.0)
return logpdf
def _logcdf(self, x, c):
return -np.exp(self._loglogcdf(x, c))
def _cdf(self, x, c):
return np.exp(self._logcdf(x, c))
def _sf(self, x, c):
return -sc.expm1(self._logcdf(x, c))
def _ppf(self, q, c):
x = -np.log(-np.log(q))
return xpx.apply_where(
(x == x) & (c != 0), (x, c),
lambda x, c: -sc.expm1(-c * x) / c,
fill_value=x)
def _isf(self, q, c):
x = -np.log(-sc.log1p(-q))
return xpx.apply_where(
(x == x) & (c != 0), (x, c),
lambda x, c: -sc.expm1(-c * x) / c,
fill_value=x)
def _stats(self, c):
def g(n):
return sc.gamma(n * c + 1)
g1 = g(1)
g2 = g(2)
g3 = g(3)
g4 = g(4)
g2mg12 = np.where(abs(c) < 1e-7, (c*np.pi)**2.0/6.0, g2-g1**2.0)
def gam2k_f(c):
return sc.expm1(sc.gammaln(2.0*c+1.0)-2*sc.gammaln(c + 1.0))/c**2.0
gam2k = xpx.apply_where(abs(c) >= 1e-7, c, gam2k_f, fill_value=np.pi**2.0/6.0)
eps = 1e-14
def gamk_f(c):
return sc.expm1(sc.gammaln(c + 1))/c
gamk = xpx.apply_where(abs(c) >= eps, c, gamk_f, fill_value=-_EULER)
# mean
m = np.where(c < -1.0, np.nan, -gamk)
# variance
v = np.where(c < -0.5, np.nan, g1**2.0*gam2k)
# skewness
def sk1_eval(c, *args):
def sk1_eval_f(c, g1, g2, g3, g2mg12):
return np.sign(c)*(-g3 + (g2 + 2*g2mg12)*g1)/g2mg12**1.5
return xpx.apply_where(c >= -1./3, (c, *args),
sk1_eval_f, fill_value=np.nan)
sk_fill = 12*np.sqrt(6)*_ZETA3/np.pi**3
args = (g1, g2, g3, g2mg12)
sk = xpx.apply_where(abs(c) > eps**0.29, (c, *args),
sk1_eval, fill_value=sk_fill)
# kurtosis
def ku1_eval(c, *args):
def ku1_eval_f(g1, g2, g3, g4, g2mg12):
return (g4 + (-4*g3 + 3*(g2 + g2mg12)*g1)*g1)/g2mg12**2 - 3
return xpx.apply_where(c >= -1./4, args, ku1_eval_f, fill_value=np.nan)
args = (g1, g2, g3, g4, g2mg12)
ku = xpx.apply_where(abs(c) > eps**0.23, (c, *args),
ku1_eval, fill_value=12.0/5.0)
return m, v, sk, ku
def _fitstart(self, data):
if isinstance(data, CensoredData):
data = data._uncensor()
# This is better than the default shape of (1,).
g = _skew(data)
if g < 0:
a = 0.5
else:
a = -0.5
return super()._fitstart(data, args=(a,))
def _munp(self, n, c):
k = np.arange(0, n+1)
vals = 1.0/c**n * np.sum(
sc.comb(n, k) * (-1)**k * sc.gamma(c*k + 1),
axis=0)
return np.where(c*n > -1, vals, np.inf)
def _entropy(self, c):
return _EULER*(1 - c) + 1
genextreme = genextreme_gen(name='genextreme')
def _digammainv(y):
"""Inverse of the digamma function (real positive arguments only).
This function is used in the `fit` method of `gamma_gen`.
The function uses either optimize.fsolve or optimize.newton
to solve `sc.digamma(x) - y = 0`. There is probably room for
improvement, but currently it works over a wide range of y:
>>> import numpy as np
>>> rng = np.random.default_rng()
>>> y = 64*rng.standard_normal(1000000)
>>> y.min(), y.max()
(-311.43592651416662, 351.77388222276869)
>>> x = [_digammainv(t) for t in y]
>>> np.abs(sc.digamma(x) - y).max()
1.1368683772161603e-13
"""
_em = 0.5772156649015328606065120
def func(x):
return sc.digamma(x) - y
if y > -0.125:
x0 = np.exp(y) + 0.5
if y < 10:
# Some experimentation shows that newton reliably converges
# must faster than fsolve in this y range. For larger y,
# newton sometimes fails to converge.
value = optimize.newton(func, x0, tol=1e-10)
return value
elif y > -3:
x0 = np.exp(y/2.332) + 0.08661
else:
x0 = 1.0 / (-y - _em)
value, info, ier, mesg = optimize.fsolve(func, x0, xtol=1e-11,
full_output=True)
if ier != 1:
raise RuntimeError(f"_digammainv: fsolve failed, y = {y!r}")
return value[0]
## Gamma (Use MATLAB and MATHEMATICA (b=theta=scale, a=alpha=shape) definition)
## gamma(a, loc, scale) with a an integer is the Erlang distribution
## gamma(1, loc, scale) is the Exponential distribution
## gamma(df/2, 0, 2) is the chi2 distribution with df degrees of freedom.
| genextreme_gen |
python | jazzband__django-oauth-toolkit | oauth2_provider/migrations/0011_refreshtoken_token_family.py | {
"start": 142,
"end": 564
} | class ____(migrations.Migration):
dependencies = [
('oauth2_provider', '0010_application_allowed_origins'),
migrations.swappable_dependency(oauth2_settings.REFRESH_TOKEN_MODEL)
]
operations = [
migrations.AddField(
model_name='refreshtoken',
name='token_family',
field=models.UUIDField(blank=True, editable=False, null=True),
),
]
| Migration |
python | walkccc__LeetCode | solutions/1498. Number of Subsequences That Satisfy the Given Sum Condition/1498.py | {
"start": 0,
"end": 326
} | class ____:
def numSubseq(self, nums: list[int], target: int) -> int:
MOD = 1_000_000_007
n = len(nums)
ans = 0
nums.sort()
l = 0
r = n - 1
while l <= r:
if nums[l] + nums[r] <= target:
ans += pow(2, r - l, MOD)
l += 1
else:
r -= 1
return ans % MOD
| Solution |
python | getsentry__sentry | src/sentry/plugins/sentry_useragents/models.py | {
"start": 110,
"end": 1042
} | class ____(TagPlugin):
version = sentry.VERSION
author = "Sentry Team"
author_url = "https://github.com/getsentry/sentry"
project_default_enabled = True
def get_tag_values(self, event) -> list[str]:
contexts = event.interfaces.get("contexts")
# disable tagging if contexts are present
if contexts:
return []
http = event.interfaces.get("request")
if not http:
return []
if not http.headers:
return []
headers = http.headers
# XXX: transitional support for workers
if isinstance(headers, dict):
headers = headers.items()
output = []
for key, value in headers:
if key != "User-Agent":
continue
result = self.get_tag_from_ua(Parse(value))
if result:
output.append(result)
return output
| UserAgentPlugin |
python | pytorch__pytorch | torch/_library/utils.py | {
"start": 14637,
"end": 19489
} | class ____:
"""
Check if an operator mutated its arguments.
Usage:
checker = MutationChecker(op, flat_args, args_spec)
op(*args, **kwargs)
checker.check()
"""
def __init__(self, op, flat_args, args_spec):
self.op = op
self.args_spec = args_spec
self.flat_args = flat_args
self.real_pre_hashes = [
hash_tensor(a) if isinstance(a, torch.Tensor) else None for a in flat_args
]
def check(self):
real_post_hashes = [
hash_tensor(a) if isinstance(a, torch.Tensor) else None
for a in self.flat_args
]
was_mutated = [
not torch.equal(pre, post)
and not (pre.isnan().all() and post.isnan().all())
if isinstance(pre, torch.Tensor) and isinstance(post, torch.Tensor)
else None
for pre, post in zip(self.real_pre_hashes, real_post_hashes)
]
was_mutated_args, was_mutated_kwargs = pytree.tree_unflatten(
was_mutated, self.args_spec
)
for info, was_mutated in zip_schema(
self.op._schema, was_mutated_args, was_mutated_kwargs
):
def check_one(info, was_mutated):
if info.is_write == was_mutated:
return
raise RuntimeError(
f"{self.op._name}: for argument '{info.name}': the operator's schema "
f"{self.op._schema} specified that "
f"the operator {'mutates' if info.is_write else 'does not mutate'} "
f"the argument, but this seems to be empirically wrong. "
f"Please make the schema and operator behavior consistent. "
f"You can specify that an operator mutates a Tensor by "
f"e.g. changing its schema type from 'Tensor name' to 'Tensor(a!) name'"
f"(use different identifiers (a, b, c, ...) for different Tensors)"
)
if is_tensor_like_type(info.type):
check_one(info, was_mutated)
elif is_tensorlist_like_type(info.type):
was_any_mutated = False if was_mutated is None else any(was_mutated)
check_one(info, was_any_mutated)
def hash_tensor(t: torch.Tensor) -> torch.Tensor:
"""Some inexpensive hash. Used as a quick and dirty indicator for tensor mutation"""
return t.detach().float().mean()
def has_fake_kernel(op: torch._ops.OpOverload) -> bool:
"""If an operator (that stays alive until FakeTensorMode) has a Fake kernel.
Don't use this if the operator decomposes before FakeTensorMode.
"""
if can_generate_trivial_fake_impl(op):
return True
name = op._name
if torch._C._dispatch_has_kernel_for_dispatch_key(
name, "CompositeImplicitAutograd"
):
return True
opdef = torch._library.custom_ops._maybe_get_opdef(name)
if opdef is None:
# the non-torch.library.custom_op path
if torch._C._dispatch_has_kernel_for_dispatch_key(
name, "CompositeExplicitAutograd"
):
return True
entry = torch._library.simple_registry.singleton.find(name)
if entry.fake_impl.kernel is not None:
return True
if torch._C._dispatch_has_kernel_for_dispatch_key(name, "Meta"):
return True
else:
# the torch.library.custom_op path
if opdef._abstract_fn is not None:
return True
return False
def mutated_args_kwargs(schema: _C.FunctionSchema) -> tuple[list[int], list[str]]:
idxs = []
keys = []
for i, info in enumerate(schema.arguments):
if info.alias_info is not None and info.alias_info.is_write:
if info.kwarg_only:
keys.append(info.name)
else:
idxs.append(i)
return idxs, keys
tags_by_priority = [
_C.Tag.needs_exact_strides,
_C.Tag.needs_contiguous_strides,
_C.Tag.needs_fixed_stride_order,
_C.Tag.flexible_layout,
]
# Case 1: with_default=True (or omitted). Return type is guaranteed to be a Tag.
@overload
def get_layout_constraint_tag(
fn: Any, *, with_default: Literal[True] = True
) -> _C.Tag: ...
# Case 2: with_default=False. Return type can be a Tag or None.
@overload
def get_layout_constraint_tag(
fn: Any, *, with_default: Literal[False]
) -> Optional[_C.Tag]: ...
def get_layout_constraint_tag(fn, *, with_default=True):
for tag in tags_by_priority:
if tag in fn.tags:
return tag
if with_default:
if is_builtin(fn):
return _C.Tag.flexible_layout
import torch._functorch
from torch._functorch import config
return getattr(torch._C.Tag, config.custom_op_default_layout_constraint)
return None
| MutationChecker |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP044.py | {
"start": 545,
"end": 776
} | class ____(TypedDict):
x: int
y: int
# OK
def f(name: str, /, **kwargs: Unpack[KwargsDict]) -> None:
pass
# OK
def f() -> object:
return Unpack[tuple[int, ...]]
# OK
def f(x: Unpack[int]) -> object: ...
| KwargsDict |
python | Pylons__pyramid | src/pyramid/security.py | {
"start": 7046,
"end": 9537
} | class ____:
"""Mixin for Request class providing auth-related properties."""
@property
def identity(self):
"""
Return an opaque object identifying the current user or ``None`` if no
user is authenticated or there is no :term:`security policy` in effect.
"""
policy = _get_security_policy(self)
if policy is None:
return None
return policy.identity(self)
@property
def authenticated_userid(self):
"""
Return the :term:`userid` of the currently authenticated user or
``None`` if there is no :term:`security policy` in effect or there is
no currently authenticated user.
.. versionchanged:: 2.0
This property delegates to the effective :term:`security policy`,
ignoring old-style :term:`authentication policy`.
"""
policy = _get_security_policy(self)
if policy is None:
return None
return policy.authenticated_userid(self)
@property
def is_authenticated(self):
"""Return ``True`` if a user is authenticated for this request."""
return self.authenticated_userid is not None
def has_permission(self, permission, context=None):
"""Given a permission and an optional context, returns an instance of
:data:`pyramid.security.Allowed` if the permission is granted to this
request with the provided context, or the context already associated
with the request. Otherwise, returns an instance of
:data:`pyramid.security.Denied`. This method delegates to the current
security policy. Returns
:data:`pyramid.security.Allowed` unconditionally if no security
policy has been registered for this request. If ``context`` is not
supplied or is supplied as ``None``, the context used is the
``request.context`` attribute.
:param permission: Does this request have the given permission?
:type permission: str
:param context: A resource object or ``None``
:type context: object
:returns: Either :class:`pyramid.security.Allowed` or
:class:`pyramid.security.Denied`.
"""
if context is None:
context = self.context
policy = _get_security_policy(self)
if policy is None:
return Allowed('No security policy in use.')
return policy.permits(self, context, permission)
| SecurityAPIMixin |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/too_many_public_methods.py | {
"start": 485,
"end": 797
} | class ____:
def __init__(self):
pass
def _private(self):
pass
def method1(self):
pass
def method2(self):
pass
def method3(self):
pass
def method4(self):
pass
def method5(self):
pass
def method6(self):
pass
| Small |
python | graphql-python__graphene | graphene/relay/tests/test_mutation.py | {
"start": 1863,
"end": 1919
} | class ____(ObjectType):
something = String()
| RootQuery |
python | facelessuser__pymdown-extensions | pymdownx/tilde.py | {
"start": 3311,
"end": 4177
} | class ____(util.PatternSequenceProcessor):
"""Emphasis processor for handling delete and subscript matches."""
PATTERNS = [
util.PatSeqItem(re.compile(DEL_SUB, re.DOTALL | re.UNICODE), 'double', 'del,sub'),
util.PatSeqItem(re.compile(SUB_DEL, re.DOTALL | re.UNICODE), 'double', 'sub,del'),
util.PatSeqItem(re.compile(DEL_SUB2, re.DOTALL | re.UNICODE), 'double', 'del,sub'),
util.PatSeqItem(re.compile(DEL_SUB3, re.DOTALL | re.UNICODE), 'double2', 'del,sub'),
util.PatSeqItem(re.compile(DEL, re.DOTALL | re.UNICODE), 'single', 'del'),
util.PatSeqItem(re.compile(SUB_DEL2, re.DOTALL | re.UNICODE), 'double2', 'sub,del'),
util.PatSeqItem(re.compile(SUB2, re.DOTALL | re.UNICODE), 'single', 'sub', True),
util.PatSeqItem(re.compile(SUB, re.DOTALL | re.UNICODE), 'single', 'sub')
]
| TildeProcessor |
python | doocs__leetcode | lcci/10.02.Group Anagrams/Solution.py | {
"start": 0,
"end": 228
} | class ____:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
d = defaultdict(list)
for s in strs:
k = ''.join(sorted(s))
d[k].append(s)
return list(d.values())
| Solution |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 29767,
"end": 29963
} | class ____(PrefectBaseModel):
"""Filter by `Artifact.id`."""
any_: Optional[List[UUID]] = Field(
default=None, description="A list of artifact ids to include"
)
| ArtifactFilterId |
python | numpy__numpy | tools/swig/test/testVector.py | {
"start": 11163,
"end": 11428
} | class ____(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "short"
self.typeCode = "h"
######################################################################
| shortTestCase |
python | sphinx-doc__sphinx | sphinx/transforms/compact_bullet_list.py | {
"start": 1495,
"end": 2861
} | class ____(SphinxTransform):
"""Change refonly bullet lists to use compact_paragraphs.
Specifically implemented for 'Indices and Tables' section, which looks
odd when html_compact_lists is false.
"""
default_priority = 100
def apply(self, **kwargs: Any) -> None:
if self.config.html_compact_lists:
return
def check_refonly_list(node: Node) -> bool:
"""Check for list with only references in it."""
visitor = RefOnlyListChecker(self.document)
try:
node.walk(visitor)
except nodes.NodeFound:
return False
else:
return True
for node in self.document.findall(nodes.bullet_list):
if check_refonly_list(node):
for item in node.findall(nodes.list_item):
para = cast('nodes.paragraph', item[0])
ref = cast('nodes.reference', para[0])
compact_para = addnodes.compact_paragraph()
compact_para += ref
item.replace(para, compact_para)
def setup(app: Sphinx) -> ExtensionMetadata:
app.add_transform(RefOnlyBulletListTransform)
return {
'version': 'builtin',
'parallel_read_safe': True,
'parallel_write_safe': True,
}
| RefOnlyBulletListTransform |
python | pytorch__pytorch | torch/utils/data/datapipes/datapipe.py | {
"start": 1419,
"end": 10131
} | class ____(IterableDataset[_T_co], metaclass=_IterDataPipeMeta):
r"""
Iterable-style DataPipe.
All DataPipes that represent an iterable of data samples should subclass this.
This style of DataPipes is particularly useful when data come from a stream, or
when the number of samples is too large to fit them all in memory. ``IterDataPipe`` is lazily initialized and its
elements are computed only when ``next()`` is called on the iterator of an ``IterDataPipe``.
All subclasses should overwrite :meth:`__iter__`, which would return an
iterator of samples in this DataPipe. Calling ``__iter__`` of an ``IterDataPipe`` automatically invokes its
method ``reset()``, which by default performs no operation. When writing a custom ``IterDataPipe``, users should
override ``reset()`` if necessary. The common usages include resetting buffers, pointers,
and various state variables within the custom ``IterDataPipe``.
Note:
Only `one` iterator can be valid for each ``IterDataPipe`` at a time,
and the creation a second iterator will invalidate the first one. This constraint is necessary because
some ``IterDataPipe`` have internal buffers, whose states can become invalid if there are multiple iterators.
The code example below presents details on how this constraint looks in practice.
If you have any feedback related to this constraint, please see `GitHub IterDataPipe Single Iterator Issue`_.
These DataPipes can be invoked in two ways, using the class constructor or applying their
functional form onto an existing ``IterDataPipe`` (recommended, available to most but not all DataPipes).
You can chain multiple `IterDataPipe` together to form a pipeline that will perform multiple
operations in succession.
.. _GitHub IterDataPipe Single Iterator Issue:
https://github.com/pytorch/data/issues/45
Note:
When a subclass is used with :class:`~torch.utils.data.DataLoader`, each
item in the DataPipe will be yielded from the :class:`~torch.utils.data.DataLoader`
iterator. When :attr:`num_workers > 0`, each worker process will have a
different copy of the DataPipe object, so it is often desired to configure
each copy independently to avoid having duplicate data returned from the
workers. :func:`~torch.utils.data.get_worker_info`, when called in a worker
process, returns information about the worker. It can be used in either the
dataset's :meth:`__iter__` method or the :class:`~torch.utils.data.DataLoader` 's
:attr:`worker_init_fn` option to modify each copy's behavior.
Examples:
General Usage:
>>> # xdoctest: +SKIP
>>> from torchdata.datapipes.iter import IterableWrapper, Mapper
>>> dp = IterableWrapper(range(10))
>>> map_dp_1 = Mapper(dp, lambda x: x + 1) # Using class constructor
>>> map_dp_2 = dp.map(
... lambda x: x + 1
... ) # Using functional form (recommended)
>>> list(map_dp_1)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(map_dp_2)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> filter_dp = map_dp_1.filter(lambda x: x % 2 == 0)
>>> list(filter_dp)
[2, 4, 6, 8, 10]
Single Iterator Constraint Example:
>>> from torchdata.datapipes.iter import IterableWrapper, Mapper
>>> source_dp = IterableWrapper(range(10))
>>> it1 = iter(source_dp)
>>> list(it1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> it1 = iter(source_dp)
>>> it2 = iter(
... source_dp
... ) # The creation of a new iterator invalidates `it1`
>>> next(it2)
0
>>> next(it1) # Further usage of `it1` will raise a `RunTimeError`
"""
functions: dict[str, Callable] = {}
reduce_ex_hook: Callable | None = None
getstate_hook: Callable | None = None
str_hook: Callable | None = None
repr_hook: Callable | None = None
_valid_iterator_id: int | None = None
_number_of_samples_yielded: int = 0
_snapshot_state: _SnapshotState = _SnapshotState.NotStarted
_fast_forward_iterator: Iterator | None = None
def __iter__(self) -> Iterator[_T_co]:
# pyrefly: ignore [bad-return]
return self
def __getattr__(self, attribute_name):
if attribute_name in IterDataPipe.functions:
if attribute_name in _iter_deprecated_functional_names:
kwargs = _iter_deprecated_functional_names[attribute_name]
_deprecation_warning(**kwargs)
f = IterDataPipe.functions[attribute_name]
function = functools.partial(f, self)
functools.update_wrapper(wrapper=function, wrapped=f, assigned=("__doc__",))
return function
else:
raise AttributeError(
f"'{self.__class__.__name__}' object has no attribute '{attribute_name}"
)
@classmethod
def register_function(cls, function_name, function) -> None:
cls.functions[function_name] = function
@classmethod
def register_datapipe_as_function(
cls, function_name, cls_to_register, enable_df_api_tracing=False
) -> None:
if function_name in cls.functions:
raise Exception( # noqa: TRY002
f"Unable to add DataPipe function name {function_name} as it is already taken"
)
def class_function(cls, enable_df_api_tracing, source_dp, *args, **kwargs):
result_pipe = cls(source_dp, *args, **kwargs)
if isinstance(result_pipe, IterDataPipe):
if enable_df_api_tracing or isinstance(source_dp, DFIterDataPipe):
if function_name not in UNTRACABLE_DATAFRAME_PIPES:
result_pipe = result_pipe.trace_as_dataframe()
return result_pipe
function = functools.partial(
class_function, cls_to_register, enable_df_api_tracing
)
functools.update_wrapper(
wrapper=function, wrapped=cls_to_register, assigned=("__doc__",)
)
cls.functions[function_name] = function
def __getstate__(self):
"""
Serialize `lambda` functions when `dill` is available.
If this doesn't cover your custom DataPipe's use case, consider writing custom methods for
`__getstate__` and `__setstate__`, or use `pickle.dumps` for serialization.
"""
state = self.__dict__
if IterDataPipe.getstate_hook is not None:
return IterDataPipe.getstate_hook(state)
return state
def __reduce_ex__(self, *args, **kwargs):
if IterDataPipe.reduce_ex_hook is not None:
try:
return IterDataPipe.reduce_ex_hook(self)
except NotImplementedError:
pass
return super().__reduce_ex__(*args, **kwargs)
@classmethod
def set_getstate_hook(cls, hook_fn) -> None:
if IterDataPipe.getstate_hook is not None and hook_fn is not None:
raise RuntimeError("Attempt to override existing getstate_hook")
IterDataPipe.getstate_hook = hook_fn
@classmethod
def set_reduce_ex_hook(cls, hook_fn) -> None:
if IterDataPipe.reduce_ex_hook is not None and hook_fn is not None:
raise RuntimeError("Attempt to override existing reduce_ex_hook")
IterDataPipe.reduce_ex_hook = hook_fn
def __repr__(self) -> str:
if self.repr_hook is not None:
return self.repr_hook(self)
# Instead of showing <torch. ... .MapperIterDataPipe object at 0x.....>, return the class name
return str(self.__class__.__qualname__)
def __str__(self) -> str:
if self.str_hook is not None:
return self.str_hook(self)
# Instead of showing <torch. ... .MapperIterDataPipe object at 0x.....>, return the class name
return str(self.__class__.__qualname__)
def __dir__(self):
# for auto-completion in a REPL (e.g. Jupyter notebook)
return list(super().__dir__()) + list(self.functions.keys())
def reset(self) -> None:
r"""
Reset the `IterDataPipe` to the initial state.
By default, no-op. For subclasses of `IterDataPipe`, depending on their functionalities,
they may want to override this method with implementations that
may clear the buffers and reset pointers of the DataPipe.
The `reset` method is always called when `__iter__` is called as part of `hook_iterator`.
"""
| IterDataPipe |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 105559,
"end": 110464
} | class ____(SendrecvmsgServerTimeoutBase):
# Tests for sendmsg() which can use any socket type and do not
# involve recvmsg() or recvmsg_into().
def testSendmsg(self):
# Send a simple message with sendmsg().
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
def _testSendmsg(self):
self.assertEqual(self.sendmsgToServer([MSG]), len(MSG))
def testSendmsgDataGenerator(self):
# Send from buffer obtained from a generator (not a sequence).
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
def _testSendmsgDataGenerator(self):
self.assertEqual(self.sendmsgToServer((o for o in [MSG])),
len(MSG))
def testSendmsgAncillaryGenerator(self):
# Gather (empty) ancillary data from a generator.
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
def _testSendmsgAncillaryGenerator(self):
self.assertEqual(self.sendmsgToServer([MSG], (o for o in [])),
len(MSG))
def testSendmsgArray(self):
# Send data from an array instead of the usual bytes object.
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
def _testSendmsgArray(self):
self.assertEqual(self.sendmsgToServer([array.array("B", MSG)]),
len(MSG))
def testSendmsgGather(self):
# Send message data from more than one buffer (gather write).
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
def _testSendmsgGather(self):
self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG))
def testSendmsgBadArgs(self):
# Check that sendmsg() rejects invalid arguments.
self.assertEqual(self.serv_sock.recv(1000), b"done")
def _testSendmsgBadArgs(self):
self.assertRaises(TypeError, self.cli_sock.sendmsg)
self.assertRaises(TypeError, self.sendmsgToServer,
b"not in an iterable")
self.assertRaises(TypeError, self.sendmsgToServer,
object())
self.assertRaises(TypeError, self.sendmsgToServer,
[object()])
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG, object()])
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], object())
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [], object())
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [], 0, object())
self.sendToServer(b"done")
def testSendmsgBadCmsg(self):
# Check that invalid ancillary data items are rejected.
self.assertEqual(self.serv_sock.recv(1000), b"done")
def _testSendmsgBadCmsg(self):
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [object()])
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [(object(), 0, b"data")])
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [(0, object(), b"data")])
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [(0, 0, object())])
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [(0, 0)])
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [(0, 0, b"data", 42)])
self.sendToServer(b"done")
@requireAttrs(socket, "CMSG_SPACE")
def testSendmsgBadMultiCmsg(self):
# Check that invalid ancillary data items are rejected when
# more than one item is present.
self.assertEqual(self.serv_sock.recv(1000), b"done")
@testSendmsgBadMultiCmsg.client_skip
def _testSendmsgBadMultiCmsg(self):
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [0, 0, b""])
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [(0, 0, b""), object()])
self.sendToServer(b"done")
def testSendmsgExcessCmsgReject(self):
# Check that sendmsg() rejects excess ancillary data items
# when the number that can be sent is limited.
self.assertEqual(self.serv_sock.recv(1000), b"done")
def _testSendmsgExcessCmsgReject(self):
if not hasattr(socket, "CMSG_SPACE"):
# Can only send one item
with self.assertRaises(OSError) as cm:
self.sendmsgToServer([MSG], [(0, 0, b""), (0, 0, b"")])
self.assertIsNone(cm.exception.errno)
self.sendToServer(b"done")
def testSendmsgAfterClose(self):
# Check that sendmsg() fails on a closed socket.
pass
def _testSendmsgAfterClose(self):
self.cli_sock.close()
self.assertRaises(OSError, self.sendmsgToServer, [MSG])
| SendmsgTests |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/origin.py | {
"start": 451,
"end": 2894
} | class ____(
NamedTuple(
"_RepositoryPythonOrigin",
[
("executable_path", str),
("code_pointer", CodePointer),
("container_image", Optional[str]),
("entry_point", Optional[Sequence[str]]),
("container_context", Optional[Mapping[str, Any]]),
],
),
):
"""Args:
executable_path (str): The Python executable of the user process.
code_pointer (CodePoitner): Once the process has started, an object that can be used to
find and load the repository in code.
container_image (Optinonal[str]): The image to use when creating a new container that
loads the repository. Only used in execution environments that start containers.
entry_point (Optional[List[str]]): The entry point to use when starting a new process
to load the repository. Defaults to ["dagster"] (and may differ from the executable_path).
container_context (Optional[Dict[str, Any]]): Additional context to use when creating a new
container that loads the repository. Keys can be specific to a given compute substrate
(for example, "docker", "k8s", etc.).
"""
def __new__(
cls,
executable_path: str,
code_pointer: CodePointer,
container_image: Optional[str] = None,
entry_point: Optional[Sequence[str]] = None,
container_context: Optional[Mapping[str, Any]] = None,
):
return super().__new__(
cls,
check.str_param(executable_path, "executable_path"),
check.inst_param(code_pointer, "code_pointer", CodePointer),
check.opt_str_param(container_image, "container_image"),
(
check.sequence_param(entry_point, "entry_point", of_type=str)
if entry_point is not None
else None
),
(
check.opt_mapping_param(container_context, "container_context")
if container_context is not None
else None
),
)
def get_id(self) -> str:
return create_snapshot_id(self)
def get_job_origin(self, job_name: str) -> "JobPythonOrigin":
check.str_param(job_name, "pipeline_name")
return JobPythonOrigin(job_name, self)
@whitelist_for_serdes(
storage_name="PipelinePythonOrigin",
storage_field_names={"job_name": "pipeline_name"},
)
| RepositoryPythonOrigin |
python | django__django | tests/select_related_onetoone/models.py | {
"start": 399,
"end": 601
} | class ____(models.Model):
user = models.OneToOneField(User, models.CASCADE, primary_key=True)
posts = models.IntegerField()
results = models.ForeignKey(UserStatResult, models.CASCADE)
| UserStat |
python | facebook__pyre-check | client/tests/coverage_data_tests.py | {
"start": 44744,
"end": 50072
} | class ____(testslide.TestCase):
def test_empty_containers__literal(self) -> None:
self.assertEqual(
coverage_data.collect_empty_containers(
parse_code(
"""
a = []
b = {}
not_c = [1]
not_d = {1: 1}
not_e = {1}
not_f = (1,)
not_g = ()
"""
)
),
[
EmptyContainerInfo(
kind=EmptyContainerKind.LIST_LITERAL,
location=Location(
start_line=2,
start_column=0,
end_line=2,
end_column=6,
),
),
EmptyContainerInfo(
kind=EmptyContainerKind.DICT_LITERAL,
location=Location(
start_line=3,
start_column=0,
end_line=3,
end_column=6,
),
),
],
)
def test_empty_containers__call(self) -> None:
self.assertEqual(
coverage_data.collect_empty_containers(
parse_code(
"""
a = set()
b = frozenset()
c = list()
d = dict()
not_empty = set([1])
"""
)
),
[
EmptyContainerInfo(
kind=EmptyContainerKind.SET_CALL,
location=Location(
start_line=2,
start_column=0,
end_line=2,
end_column=9,
),
),
EmptyContainerInfo(
kind=EmptyContainerKind.FROZENSET_CALL,
location=Location(
start_line=3,
start_column=0,
end_line=3,
end_column=15,
),
),
EmptyContainerInfo(
kind=EmptyContainerKind.LIST_CALL,
location=Location(
start_line=4,
start_column=0,
end_line=4,
end_column=10,
),
),
EmptyContainerInfo(
kind=EmptyContainerKind.DICT_CALL,
location=Location(
start_line=5,
start_column=0,
end_line=5,
end_column=10,
),
),
],
)
def test_empty_containers__multi_assign(self) -> None:
# This test mostly exists to note that un-annotated assignments can have multiple targets,
# but they only produce a single EmptyContainerInfo.
self.assertEqual(
coverage_data.collect_empty_containers(
parse_code(
"""
a = b = []
c = d = dict()
"""
),
),
[
EmptyContainerInfo(
kind=EmptyContainerKind.LIST_LITERAL,
location=Location(
start_line=2,
start_column=0,
end_line=2,
end_column=10,
),
),
EmptyContainerInfo(
kind=EmptyContainerKind.DICT_CALL,
location=Location(
start_line=3,
start_column=0,
end_line=3,
end_column=14,
),
),
],
)
def test_empty_containers__false_positive(self) -> None:
self.assertEqual(
coverage_data.collect_empty_containers(
parse_code(
"""
a: list[int] = []
a = [] # false positive because a is annotated
"""
)
),
[
EmptyContainerInfo(
kind=EmptyContainerKind.LIST_LITERAL,
location=Location(
start_line=3,
start_column=0,
end_line=3,
end_column=6,
),
),
],
)
def test_empty_containers__complex_names(self) -> None:
self.assertEqual(
len(
coverage_data.collect_empty_containers(
parse_code(
"""
s[:] = [] # clearing a list
a.b = dict() # assigning to an attribute
d["key"] = {}
"""
)
)
),
0,
)
| EmptyContainerCollectorTest |
python | pytorch__pytorch | test/quantization/eager/test_quantize_eager_ptq.py | {
"start": 1706,
"end": 10957
} | class ____(QuantizationTestCase):
@override_qengines
def _test_reference_module_impl(
self,
float_module_class,
quantized_module_class,
extra_module_kwargs,
input_size,
):
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = float_module_class(**extra_module_kwargs)
self.quant = QuantStub()
self.dequant = DeQuantStub()
def forward(self, x):
x = self.quant(x)
x = self.conv(x)
x = self.dequant(x)
return x
class RefM(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = float_module_class(**extra_module_kwargs)
self.quant1 = QuantStub()
self.dequant1 = DeQuantStub()
self.quant2 = QuantStub()
self.dequant2 = DeQuantStub()
def forward(self, x):
x = self.quant1(x)
x = self.dequant1(x)
x = self.conv(x)
x = self.quant2(x)
x = self.dequant2(x)
return x
qengine = torch.backends.quantized.engine
if qengine not in supported_qengines or qengine == "qnnpack":
return # qnnpack does not support nnq.ConvTranspose3d
data = torch.randn(*input_size, dtype=torch.float)
original_m = M()
original_ref_m = RefM()
original_ref_m.conv.weight = torch.nn.Parameter(original_m.conv.weight.detach())
original_ref_m.conv.bias = torch.nn.Parameter(original_m.conv.bias.detach())
original_m.qconfig = torch.ao.quantization.default_qconfig
m = prepare(original_m)
# calibration
m(data)
m = convert(m)
# check if the module is properly quantized
self.assertEqual(type(m.quant), nnq.Quantize)
self.assertEqual(type(m.conv), quantized_module_class)
self.assertEqual(type(m.dequant), nnq.DeQuantize)
res = m(data)
# quantize the reference model
original_ref_m.eval()
original_ref_m.qconfig = torch.ao.quantization.default_qconfig
ref_m = prepare(original_ref_m)
ref_m(data)
ref_m = convert(ref_m, is_reference=True)
ref_res = ref_m(data)
self.assertEqual(res, ref_res)
def test_conv_1d(self):
self._test_reference_module_impl(
nn.Conv1d,
nnq.Conv1d,
{"in_channels": 1, "out_channels": 1, "kernel_size": 1},
(16, 1, 1),
)
def test_conv_2d(self):
self._test_reference_module_impl(
nn.Conv2d,
nnq.Conv2d,
{"in_channels": 1, "out_channels": 1, "kernel_size": 1},
(16, 1, 10, 10),
)
def test_conv_3d(self):
self._test_reference_module_impl(
nn.Conv3d,
nnq.Conv3d,
{"in_channels": 1, "out_channels": 1, "kernel_size": 1},
(16, 1, 10, 10, 10),
)
def test_conv_transpose_1d(self):
self._test_reference_module_impl(
nn.ConvTranspose1d,
nnq.ConvTranspose1d,
{"in_channels": 1, "out_channels": 1, "kernel_size": 1},
(16, 1, 1),
)
def test_conv_transpose_2d(self):
self._test_reference_module_impl(
nn.ConvTranspose2d,
nnq.ConvTranspose2d,
{"in_channels": 1, "out_channels": 1, "kernel_size": 1},
(16, 1, 10, 10),
)
def test_conv_transpose_3d(self):
self._test_reference_module_impl(
nn.ConvTranspose3d,
nnq.ConvTranspose3d,
{"in_channels": 1, "out_channels": 1, "kernel_size": 1},
(16, 1, 10, 10, 10),
)
def test_linear(self):
self._test_reference_module_impl(
nn.Linear, nnq.Linear, {"in_features": 5, "out_features": 10}, (16, 5)
)
@override_qengines
def test_int16_reference_module(self):
class RefM(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = nn.ConvTranspose2d(1, 1, 1)
self.quant1 = QuantStub()
self.dequant1 = DeQuantStub()
self.quant2 = QuantStub()
self.dequant2 = DeQuantStub()
def forward(self, x):
x = self.quant1(x)
x = self.dequant1(x)
x = self.conv(x)
x = self.quant2(x)
x = self.dequant2(x)
return x
input_size = (16, 1, 10, 10)
data = torch.randn(*input_size, dtype=torch.float)
original_ref_m = RefM()
rand_w = torch.randn_like(original_ref_m.conv.weight)
rand_b = torch.randn_like(original_ref_m.conv.bias)
original_ref_m.conv.weight = torch.nn.Parameter(rand_w, requires_grad=False)
original_ref_m.conv.bias = torch.nn.Parameter(rand_b, requires_grad=False)
qengine = torch.backends.quantized.engine
if qengine not in supported_qengines:
return
from torch.ao.quantization.observer import MovingAverageMinMaxObserver
weight_obs = MovingAverageMinMaxObserver.with_args(
dtype=torch.qint32,
# set qmin and qmax to represent qint16
quant_min=-1 * (2**15),
quant_max=(2**15) - 1,
qscheme=torch.per_tensor_symmetric,
)
act_obs = MovingAverageMinMaxObserver.with_args(
dtype=torch.qint32,
quant_min=-1 * (2**15),
quant_max=(2**15) - 1,
)
custom_qconfig = QConfig(activation=act_obs, weight=weight_obs)
# quantize the reference model
original_ref_m.eval()
original_ref_m.qconfig = custom_qconfig
ref_m = prepare(original_ref_m)
# calibration
ref_m(torch.randn(*input_size, dtype=torch.float))
ref_m = convert(ref_m, is_reference=True)
myobs = MovingAverageMinMaxObserver(
averaging_constant=0.5,
dtype=torch.qint32,
# set qmin and qmax to represent qint16
quant_min=-1 * (2**15),
quant_max=(2**15) - 1,
qscheme=torch.per_tensor_symmetric,
)
result = myobs(rand_w)
qparams = myobs.calculate_qparams()
self.assertEqual(ref_m.conv.weight_scale, qparams[0])
def _test_activation_op_impl(
self, float_module_class, quantized_module_class, extra_module_kwargs
):
"""Implementation for testing common activation ops like leaky relu
Args:
extra_module_kwargs: keyword args to instantiate the float module
"""
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.activation_op = float_module_class(**extra_module_kwargs)
self.quant = QuantStub()
self.dequant = DeQuantStub()
def forward(self, x):
x = self.quant(x)
x = self.activation_op(x)
x = self.dequant(x)
return x
m = M().eval()
m.qconfig = default_qconfig
m = prepare(m)
self.checkObservers(m)
m = convert(m)
self.assertEqual(type(m.activation_op), quantized_module_class)
def test_leaky_relu(self):
self._test_activation_op_impl(
nn.LeakyReLU, nnq.LeakyReLU, {"negative_slope": 0.1, "inplace": False}
)
def test_relu(self):
self._test_activation_op_impl(nn.ReLU, nn.ReLU, {"inplace": False})
# Histogram Observers are slow, so have no-deadline to ensure test doesn't time out
@given(train_mode=st.booleans())
def test_functional_module(self, train_mode):
model = ModelWithFunctionals()
x = torch.rand(10, 1, dtype=torch.float)
xq = torch.quantize_per_tensor(x, 0.01, 30, torch.quint8)
self.checkScriptable(model, [[x]], check_save_load=True)
if train_mode:
model.qconfig = torch.ao.quantization.get_default_qat_qconfig("fbgemm")
model = prepare_qat(model)
else:
model.qconfig = torch.ao.quantization.get_default_qconfig("qnnpack")
model = prepare(model)
# Check if observers and quant/dequant nodes are inserted
self.checkNoPrepModules(model)
self.checkObservers(model)
# Calibrate
model(xq.dequantize())
model = convert(model)
def checkQuantized(model):
self.checkNoPrepModules(model)
self.assertEqual(type(model.myadd), torch.ao.nn.quantized.QFunctional)
self.assertEqual(type(model.mycat), torch.ao.nn.quantized.QFunctional)
self.assertEqual(type(model.myadd_relu), torch.ao.nn.quantized.QFunctional)
self.assertEqual(type(model.mymatmul), torch.ao.nn.quantized.QFunctional)
self.checkNoQconfig(model)
checkQuantized(model)
self.checkScriptable(model, [[xq]], check_save_load=True)
| TestQuantizeEagerOps |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 506480,
"end": 507518
} | class ____(BinopNode):
def analyse_types(self, env):
node = BinopNode.analyse_types(self, env)
if node.is_py_operation():
node.type = PyrexTypes.error_type
return node
def py_operation_function(self, code):
return ""
def calculate_result_code(self):
return "(%s %s %s)" % (
self.operand1.result(),
self.operator,
self.operand2.result())
def compute_c_result_type(self, type1, type2):
cpp_type = None
if type1.is_cpp_class or type1.is_ptr:
cpp_type = type1.find_cpp_operation_type(self.operator, type2)
if cpp_type is None and (type2.is_cpp_class or type2.is_ptr):
cpp_type = type2.find_cpp_operation_type(self.operator, type1)
# FIXME: do we need to handle other cases here?
return cpp_type
def c_binop_constructor(operator):
def make_binop_node(pos, **operands):
return CBinopNode(pos, operator=operator, **operands)
return make_binop_node
| CBinopNode |
python | crytic__slither | slither/vyper_parsing/ast/types.py | {
"start": 2514,
"end": 2598
} | class ____(ASTNode):
left: ASTNode
op: str
right: ASTNode
@dataclass
| BinOp |
python | tensorflow__tensorflow | tensorflow/python/ops/image_ops_test.py | {
"start": 11603,
"end": 15881
} | class ____(test_util.TensorFlowTestCase):
def test_adjust_gamma_less_zero_float32(self):
"""White image should be returned for gamma equal to zero"""
with self.cached_session():
x_data = np.random.uniform(0, 1.0, (8, 8))
x_np = np.array(x_data, dtype=np.float32)
x = constant_op.constant(x_np, shape=x_np.shape)
err_msg = "Gamma should be a non-negative real number"
with self.assertRaisesRegex(
(ValueError, errors.InvalidArgumentError), err_msg):
image_ops.adjust_gamma(x, gamma=-1)
def test_adjust_gamma_less_zero_uint8(self):
"""White image should be returned for gamma equal to zero"""
with self.cached_session():
x_data = np.random.uniform(0, 255, (8, 8))
x_np = np.array(x_data, dtype=np.uint8)
x = constant_op.constant(x_np, shape=x_np.shape)
err_msg = "Gamma should be a non-negative real number"
with self.assertRaisesRegex(
(ValueError, errors.InvalidArgumentError), err_msg):
image_ops.adjust_gamma(x, gamma=-1)
def test_adjust_gamma_less_zero_tensor(self):
"""White image should be returned for gamma equal to zero"""
with self.cached_session():
x_data = np.random.uniform(0, 1.0, (8, 8))
x_np = np.array(x_data, dtype=np.float32)
x = constant_op.constant(x_np, shape=x_np.shape)
y = constant_op.constant(-1.0, dtype=dtypes.float32)
err_msg = "Gamma should be a non-negative real number"
with self.assertRaisesRegex(
(ValueError, errors.InvalidArgumentError), err_msg):
image = image_ops.adjust_gamma(x, gamma=y)
self.evaluate(image)
def _test_adjust_gamma_uint8(self, gamma):
"""Verifying the output with expected results for gamma
correction for uint8 images
"""
with self.cached_session():
x_np = np.random.uniform(0, 255, (8, 8)).astype(np.uint8)
x = constant_op.constant(x_np, shape=x_np.shape)
y = image_ops.adjust_gamma(x, gamma=gamma)
y_tf = np.trunc(self.evaluate(y))
# calculate gamma correction using numpy
# firstly, transform uint8 to float representation
# then perform correction
y_np = np.power(x_np / 255.0, gamma)
# convert correct numpy image back to uint8 type
y_np = np.trunc(np.clip(y_np * 255.5, 0, 255.0))
self.assertAllClose(y_tf, y_np, 1e-6)
def _test_adjust_gamma_float32(self, gamma):
"""Verifying the output with expected results for gamma
correction for float32 images
"""
with self.cached_session():
x_np = np.random.uniform(0, 1.0, (8, 8))
x = constant_op.constant(x_np, shape=x_np.shape)
y = image_ops.adjust_gamma(x, gamma=gamma)
y_tf = self.evaluate(y)
y_np = np.clip(np.power(x_np, gamma), 0, 1.0)
self.assertAllClose(y_tf, y_np, 1e-6)
def test_adjust_gamma_one_float32(self):
"""Same image should be returned for gamma equal to one"""
self._test_adjust_gamma_float32(1.0)
def test_adjust_gamma_one_uint8(self):
self._test_adjust_gamma_uint8(1.0)
def test_adjust_gamma_zero_uint8(self):
"""White image should be returned for gamma equal
to zero for uint8 images
"""
self._test_adjust_gamma_uint8(gamma=0.0)
def test_adjust_gamma_less_one_uint8(self):
"""Verifying the output with expected results for gamma
correction with gamma equal to half for uint8 images
"""
self._test_adjust_gamma_uint8(gamma=0.5)
def test_adjust_gamma_greater_one_uint8(self):
"""Verifying the output with expected results for gamma
correction for uint8 images
"""
self._test_adjust_gamma_uint8(gamma=1.0)
def test_adjust_gamma_less_one_float32(self):
"""Verifying the output with expected results for gamma
correction with gamma equal to half for float32 images
"""
self._test_adjust_gamma_float32(0.5)
def test_adjust_gamma_greater_one_float32(self):
"""Verifying the output with expected results for gamma
correction with gamma equal to two for float32 images
"""
self._test_adjust_gamma_float32(1.0)
def test_adjust_gamma_zero_float32(self):
"""White image should be returned for gamma equal
to zero for float32 images
"""
self._test_adjust_gamma_float32(0.0)
| AdjustGamma |
python | getsentry__sentry | tests/snuba/test_metrics_layer.py | {
"start": 902,
"end": 33070
} | class ____(TestCase, BaseMetricsTestCase):
def ts(self, dt: datetime) -> int:
return int(dt.timestamp())
def setUp(self) -> None:
super().setUp()
self.generic_metrics: Mapping[str, Literal["counter", "set", "distribution", "gauge"]] = {
TransactionMRI.DURATION.value: "distribution",
TransactionMRI.USER.value: "set",
TransactionMRI.COUNT_PER_ROOT_PROJECT.value: "counter",
"g:transactions/test_gauge@none": "gauge",
}
self.metrics: Mapping[str, Literal["counter", "set", "distribution"]] = {
SessionMRI.RAW_DURATION.value: "distribution",
SessionMRI.RAW_USER.value: "set",
SessionMRI.RAW_SESSION.value: "counter",
}
self.now = datetime.now(tz=timezone.utc).replace(microsecond=0)
self.hour_ago = self.now - timedelta(hours=1)
self.org_id = self.project.organization_id
for mri, metric_type in self.generic_metrics.items():
assert metric_type in {"counter", "distribution", "set", "gauge"}
for i in range(10):
value: int | dict[str, int]
if metric_type == "gauge":
value = {
"min": i,
"max": i,
"sum": i,
"count": i,
"last": i,
}
else:
value = i
self.store_metric(
org_id=self.org_id,
project_id=self.project.id,
mri=mri,
tags={
"transaction": f"transaction_{i % 2}",
"status_code": "500" if i % 3 == 0 else "200",
"device": "BlackBerry" if i % 2 == 0 else "Nokia",
},
timestamp=self.ts(self.hour_ago + timedelta(minutes=1 * i)),
value=value,
sampling_weight=10,
)
for mri, metric_type in self.metrics.items():
assert metric_type in {"counter", "distribution", "set"}
for i in range(10):
value = i
self.store_metric(
self.org_id,
self.project.id,
mri,
{
"release": "release_even" if i % 2 == 0 else "release_odd",
},
self.ts(self.hour_ago + timedelta(minutes=1 * i)),
value,
)
def test_basic_generic_metrics(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
"transaction.duration",
TransactionMRI.DURATION.value,
),
aggregate="max",
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.TRANSACTIONS.value,
),
)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert len(result["data"]) == 10
rows = result["data"]
for i in range(10):
assert rows[i]["aggregate_value"] == i
assert (
rows[i]["time"]
== (
self.hour_ago.replace(second=0, microsecond=0) + timedelta(minutes=1 * i)
).isoformat()
)
def test_basic_bulk_generic_metrics(self) -> None:
query = MetricsQuery(
query=None,
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.TRANSACTIONS.value,
),
)
query1 = query.set_query(
Timeseries(
metric=Metric(
"transaction.duration",
TransactionMRI.DURATION.value,
),
aggregate="max",
)
)
query2 = query.set_query(
Timeseries(
metric=Metric(
public_name=None,
mri=TransactionMRI.USER.value,
),
aggregate="uniq",
)
)
request1 = Request(
dataset="generic_metrics",
app_id="tests",
query=query1,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
request2 = Request(
dataset="generic_metrics",
app_id="tests",
query=query2,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
results = bulk_run_query([request1, request2])
assert len(results) == 2
result = results[0] # Distribution
rows = result["data"]
for i in range(10):
assert rows[i]["aggregate_value"] == i
assert (
rows[i]["time"]
== (
self.hour_ago.replace(second=0, microsecond=0) + timedelta(minutes=1 * i)
).isoformat()
)
def test_groupby_generic_metrics(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
"transaction.duration",
TransactionMRI.DURATION.value,
),
aggregate="quantiles",
aggregate_params=[0.5, 0.99],
groupby=[Column("transaction")],
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.TRANSACTIONS.value,
),
)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert len(result["data"]) == 10
rows = result["data"]
for i in range(10):
assert rows[i]["aggregate_value"] == [i, i]
assert rows[i]["transaction"] == f"transaction_{i % 2}"
assert (
rows[i]["time"]
== (
self.hour_ago.replace(second=0, microsecond=0) + timedelta(minutes=1 * i)
).isoformat()
)
def test_filters_generic_metrics(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
"transaction.duration",
TransactionMRI.DURATION.value,
),
aggregate="quantiles",
aggregate_params=[0.5],
filters=[
Condition(Column("status_code"), Op.EQ, "500"),
Condition(Column("device"), Op.EQ, "BlackBerry"),
],
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.TRANSACTIONS.value,
),
)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert len(result["data"]) == 2
rows = result["data"]
# TODO: Snuba is going to start returning 0 instead of [0] for single value aggregates
# For now handle both cases for backwards compatibility
assert rows[0]["aggregate_value"] in ([0], 0)
assert rows[1]["aggregate_value"] in ([6.0], 6)
def test_complex_generic_metrics(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
"transaction.duration",
TransactionMRI.DURATION.value,
),
aggregate="quantiles",
aggregate_params=[0.5],
filters=[
Condition(Column("status_code"), Op.EQ, "500"),
Condition(Column("device"), Op.EQ, "BlackBerry"),
],
groupby=[Column("transaction")],
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.TRANSACTIONS.value,
),
)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert len(result["data"]) == 2
rows = result["data"]
# TODO: Snuba is going to start returning 0 instead of [0] for single value aggregates
# For now handle both cases for backwards compatibility
assert rows[0]["aggregate_value"] in ([0], 0)
assert rows[0]["transaction"] == "transaction_0"
assert rows[1]["aggregate_value"] in ([6.0], 6)
assert rows[1]["transaction"] == "transaction_0"
def test_totals(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
"transaction.duration",
TransactionMRI.DURATION.value,
),
aggregate="max",
filters=[Condition(Column("status_code"), Op.EQ, "200")],
groupby=[Column("transaction")],
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(totals=True, granularity=60, orderby=Direction.ASC),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.TRANSACTIONS.value,
),
)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert len(result["data"]) == 2
rows = result["data"]
assert rows[0]["aggregate_value"] == 7.0
assert rows[1]["aggregate_value"] == 8.0
def test_meta_data_in_response(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
"transaction.duration",
TransactionMRI.DURATION.value,
),
aggregate="max",
filters=[Condition(Column("status_code"), Op.EQ, "200")],
groupby=[Column("transaction")],
),
start=self.hour_ago.replace(minute=16, second=59),
end=self.now.replace(minute=16, second=59),
rollup=Rollup(interval=60, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.TRANSACTIONS.value,
),
)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert result["modified_start"] == self.hour_ago.replace(minute=16, second=0)
assert result["modified_end"] == self.now.replace(minute=17, second=0)
assert result["indexer_mappings"] == {
"d:transactions/duration@millisecond": 9223372036854775909,
"status_code": 10000,
"transaction": 9223372036854776020,
}
def test_bad_query(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
"transaction.duration",
"not a real MRI",
),
aggregate="max",
),
start=self.hour_ago.replace(minute=16, second=59),
end=self.now.replace(minute=16, second=59),
rollup=Rollup(interval=60, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.TRANSACTIONS.value,
),
)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
with pytest.raises(InvalidParams):
run_query(request)
def test_interval_with_totals(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
"transaction.duration",
TransactionMRI.DURATION.value,
),
aggregate="max",
filters=[Condition(Column("status_code"), Op.EQ, "200")],
groupby=[Column("transaction")],
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, totals=True, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.TRANSACTIONS.value,
),
)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert len(result["data"]) == 6
assert result["totals"]["aggregate_value"] == 8.0
def test_automatic_granularity(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
"transaction.duration",
TransactionMRI.DURATION.value,
),
aggregate="max",
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=120),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
),
)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
# There's a flaky off by one error here that is very difficult to track down
# TODO: figure out why this is flaky and assert to one specific value
assert len(result["data"]) in [5, 6]
def test_automatic_dataset(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
None,
SessionMRI.RAW_DURATION.value,
),
aggregate="max",
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.SESSIONS.value,
),
)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert request.dataset == "metrics"
assert len(result["data"]) == 10
def test_gauges(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
None,
"g:transactions/test_gauge@none",
),
aggregate="last",
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, totals=True, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
),
)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert len(result["data"]) == 10
assert result["totals"]["aggregate_value"] == 9.0
def test_metrics_groupby(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
None,
SessionMRI.RAW_DURATION.value,
),
aggregate="max",
groupby=[Column("release")],
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.SESSIONS.value,
),
)
request = Request(
dataset="metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert request.dataset == "metrics"
assert len(result["data"]) == 10
for data_point in result["data"]:
assert data_point["release"] == "release_even" or data_point["release"] == "release_odd"
def test_metrics_filters(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
None,
SessionMRI.RAW_USER.value,
),
aggregate="count",
filters=[
Condition(Column("release"), Op.EQ, "release_even"),
],
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.SESSIONS.value,
),
)
request = Request(
dataset="metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert request.dataset == "metrics"
assert len(result["data"]) == 5
def test_metrics_complex(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
None,
SessionMRI.RAW_SESSION.value,
),
aggregate="count",
groupby=[Column("release")],
filters=[
Condition(Column("release"), Op.EQ, "release_even"),
],
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.SESSIONS.value,
),
)
request = Request(
dataset="metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert request.dataset == "metrics"
assert len(result["data"]) == 5
assert any(data_point["release"] == "release_even" for data_point in result["data"])
def test_metrics_correctly_reverse_resolved(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
None,
SessionMRI.RAW_SESSION.value,
),
aggregate="count",
groupby=[Column("release"), Column("project_id")],
filters=[
Condition(Column("release"), Op.EQ, "release_even"),
Condition(Column("project_id"), Op.EQ, self.project.id),
],
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.SESSIONS.value,
),
)
request = Request(
dataset="metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert request.dataset == "metrics"
assert len(result["data"]) == 5
assert any(data_point["release"] == "release_even" for data_point in result["data"])
assert any(data_point["project_id"] == self.project.id for data_point in result["data"])
def test_failure_rate(self) -> None:
query = MetricsQuery(
query=Formula(
ArithmeticOperator.DIVIDE.value,
[
Timeseries(
metric=Metric(
mri=TransactionMRI.DURATION.value,
),
aggregate="count",
filters=[
Condition(
Column(TransactionTagsKey.TRANSACTION_STATUS.value),
Op.NOT_IN,
[
TransactionStatusTagValue.OK.value,
TransactionStatusTagValue.CANCELLED.value,
TransactionStatusTagValue.UNKNOWN.value,
],
)
],
),
Timeseries(
metric=Metric(
mri=TransactionMRI.DURATION.value,
),
aggregate="count",
),
],
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, totals=True, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
),
)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert len(result["data"]) == 10
assert result["totals"]["aggregate_value"] == 1.0
def test_aggregate_aliases(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
"transaction.duration",
TransactionMRI.DURATION.value,
),
aggregate="p95",
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.TRANSACTIONS.value,
),
)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert len(result["data"]) == 10
rows = result["data"]
for i in range(10):
# TODO: Snuba is going to start returning 0 instead of [0] for single value aggregates
# For now handle both cases for backwards compatibility
assert rows[i]["aggregate_value"] in ([i], i)
assert (
rows[i]["time"]
== (
self.hour_ago.replace(second=0, microsecond=0) + timedelta(minutes=1 * i)
).isoformat()
)
def test_dataset_correctness(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
"transaction.duration",
TransactionMRI.DURATION.value,
),
aggregate="quantiles",
aggregate_params=[0.5, 0.99],
groupby=[Column("transaction")],
filters=[
Condition(Column("transaction"), Op.IN, ["transaction_0", "transaction_1"])
],
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.TRANSACTIONS.value,
),
)
request = Request(
dataset="metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert len(result["data"]) == 10
rows = result["data"]
for i in range(10):
assert rows[i]["aggregate_value"] == [i, i]
assert rows[i]["transaction"] == f"transaction_{i % 2}"
assert (
rows[i]["time"]
== (
self.hour_ago.replace(second=0, microsecond=0) + timedelta(minutes=1 * i)
).isoformat()
)
def test_resolve_all_mris(self) -> None:
for mri in [
"d:transactions/sentry.event_manager.save@second",
"d:transactions/sentry.event_manager.save_generic_events@second",
]:
self.store_metric(
self.org_id,
self.project.id,
mri,
{
"transaction": "transaction_1",
"status_code": "200",
"device": "BlackBerry",
},
self.ts(self.hour_ago + timedelta(minutes=5)),
1,
)
query = MetricsQuery(
query=Formula(
function_name="plus",
parameters=[
Timeseries(
metric=Metric(
mri="d:transactions/sentry.event_manager.save@second",
),
aggregate="avg",
),
Timeseries(
metric=Metric(
mri="d:transactions/sentry.event_manager.save_generic_events@second",
),
aggregate="avg",
),
],
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=None, totals=True, orderby=None, granularity=10),
scope=MetricsScope(
org_ids=[self.org_id], project_ids=[self.project.id], use_case_id="transactions"
),
limit=Limit(20),
offset=None,
)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert len(result["data"]) == 1
def test_formulas_with_scalar_formulas(self) -> None:
query = MetricsQuery(
query=f"sum({TransactionMRI.DURATION.value}) + (24 * 3600)",
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.TRANSACTIONS.value,
),
)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert len(result["data"]) == 10
for row in result["data"]:
assert row["aggregate_value"] >= 86400
def test_extrapolated_generic_metrics(self) -> None:
query = MetricsQuery(
query=Timeseries(
metric=Metric(
"transaction.duration",
TransactionMRI.DURATION.value,
),
aggregate="sum",
filters=[
Condition(Column("status_code"), Op.EQ, "500"),
Condition(Column("device"), Op.EQ, "BlackBerry"),
],
groupby=[Column("transaction")],
),
start=self.hour_ago,
end=self.now,
rollup=Rollup(interval=60, granularity=60),
scope=MetricsScope(
org_ids=[self.org_id],
project_ids=[self.project.id],
use_case_id=UseCaseID.TRANSACTIONS.value,
),
)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert len(result["data"]) == 2
rows = result["data"]
assert rows[0]["aggregate_value"] in ([0], 0)
assert rows[0]["transaction"] == "transaction_0"
assert rows[1]["aggregate_value"] in ([6.00], 6)
assert rows[1]["transaction"] == "transaction_0"
# Set extrapolate flag to True. Since the sampling weight is set to 10, the extrapolated value should be 6*10
query = query.set_extrapolate(True)
request = Request(
dataset="generic_metrics",
app_id="tests",
query=query,
tenant_ids={"referrer": "metrics.testing.test", "organization_id": self.org_id},
)
result = run_query(request)
assert len(result["data"]) == 2
rows = result["data"]
assert rows[0]["aggregate_value"] in ([0], 0)
assert rows[0]["transaction"] == "transaction_0"
assert rows[1]["aggregate_value"] in ([60.00], 60)
assert rows[1]["transaction"] == "transaction_0"
| MQLTest |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/constant_op_eager_test.py | {
"start": 17123,
"end": 19226
} | class ____(test.TestCase):
def _Ones(self, shape):
ret = array_ops.ones(shape)
self.assertEqual(shape, ret.get_shape())
return ret.numpy()
def testConst(self):
self.assertTrue(np.array_equal(self._Ones([2, 3]), np.array([[1] * 3] * 2)))
def testScalar(self):
self.assertEqual(1, self._Ones([]))
self.assertEqual(1, self._Ones(()))
scalar = array_ops.ones(constant_op.constant([], dtype=dtypes_lib.int32))
self.assertEqual(1, scalar.numpy())
def testDynamicSizes(self):
np_ans = np.array([[1] * 3] * 2)
# Creates a tensor of 2 x 3.
d = array_ops.fill([2, 3], 12., name="fill")
# Constructs a tensor of ones of the same dimensions as "d".
z = array_ops.ones(array_ops.shape(d))
out = z.numpy()
self.assertAllEqual(np_ans, out)
self.assertShapeEqual(np_ans, d)
self.assertShapeEqual(np_ans, z)
def testDtype(self):
d = array_ops.fill([2, 3], 12., name="fill")
self.assertEqual(d.get_shape(), [2, 3])
# Test default type for both constant size and dynamic size
z = array_ops.ones([2, 3])
self.assertEqual(z.dtype, dtypes_lib.float32)
self.assertEqual([2, 3], z.get_shape())
self.assertAllEqual(z.numpy(), np.ones([2, 3]))
z = array_ops.ones(array_ops.shape(d))
self.assertEqual(z.dtype, dtypes_lib.float32)
self.assertEqual([2, 3], z.get_shape())
self.assertAllEqual(z.numpy(), np.ones([2, 3]))
# Test explicit type control
for dtype in (dtypes_lib.float32, dtypes_lib.float64, dtypes_lib.int32,
dtypes_lib.uint8, dtypes_lib.int16, dtypes_lib.int8,
dtypes_lib.complex64, dtypes_lib.complex128, dtypes_lib.int64,
dtypes_lib.bool):
z = array_ops.ones([2, 3], dtype=dtype)
self.assertEqual(z.dtype, dtype)
self.assertEqual([2, 3], z.get_shape())
self.assertAllEqual(z.numpy(), np.ones([2, 3]))
z = array_ops.ones(array_ops.shape(d), dtype=dtype)
self.assertEqual(z.dtype, dtype)
self.assertEqual([2, 3], z.get_shape())
self.assertAllEqual(z.numpy(), np.ones([2, 3]))
| OnesTest |
python | realpython__materials | python-serialize/schema-based/avro-demo/models.py | {
"start": 126,
"end": 223
} | class ____(StrEnum):
DE = "de"
EN = "en"
ES = "es"
FR = "fr"
IT = "it"
| Language |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-iterable/source_iterable/streams.py | {
"start": 9307,
"end": 9874
} | class ____(IterableExportStream, ABC):
"""
This class use RangeSliceGenerator class to break single request into
ranges with same (or less for final range) number of days. By default it 90
days.
"""
def stream_slices(
self,
sync_mode: SyncMode,
cursor_field: List[str] = None,
stream_state: Mapping[str, Any] = None,
) -> Iterable[Optional[StreamSlice]]:
start_datetime = self.get_start_date(stream_state)
return RangeSliceGenerator(start_datetime, self._end_date)
| IterableExportStreamRanged |
python | apache__airflow | airflow-core/src/airflow/cli/commands/info_command.py | {
"start": 3903,
"end": 4525
} | class ____(Enum):
"""Operating system."""
WINDOWS = "Windows"
LINUX = "Linux"
MACOSX = "Mac OS"
CYGWIN = "Cygwin"
UNKNOWN = "Unknown"
@staticmethod
def get_current() -> OperatingSystem:
"""Get current operating system."""
if os.name == "nt":
return OperatingSystem.WINDOWS
if "linux" in sys.platform:
return OperatingSystem.LINUX
if "darwin" in sys.platform:
return OperatingSystem.MACOSX
if "cygwin" in sys.platform:
return OperatingSystem.CYGWIN
return OperatingSystem.UNKNOWN
| OperatingSystem |
python | ray-project__ray | python/ray/train/tests/test_backend.py | {
"start": 2507,
"end": 19253
} | class ____(Backend):
def on_start(self, worker_group: WorkerGroup, backend_config: TestConfig):
pass
def on_shutdown(self, worker_group: WorkerGroup, backend_config: TestConfig):
pass
original_add_workers = WorkerGroup.add_workers
def mock_add_workers(self, num_workers):
original_add_workers(self, num_workers)
for i, worker in enumerate(self.workers):
metadata = WorkerMetadata(
node_id=str(i % 2),
node_ip=str(i % 2),
hostname=0,
resource_ids={"GPU": ["0"]},
pid=0,
)
worker.metadata = metadata
def mock_add_workers_to_nodes_with_same_ip(self, num_workers):
original_add_workers(self, num_workers)
for i, worker in enumerate(self.workers):
metadata = WorkerMetadata(
node_id=str(i % 2),
node_ip=0,
hostname=0,
resource_ids={"GPU": ["0"]},
pid=0,
)
worker.metadata = metadata
def test_start(ray_start_2_cpus):
config = TestConfig()
e = BackendExecutor(config, num_workers=2)
with pytest.raises(InactiveWorkerGroupError):
_start_training(e, lambda: 1)
e.start()
assert len(e.worker_group) == 2
def test_initialization_hook(ray_start_2_cpus):
config = TestConfig()
e = BackendExecutor(config, num_workers=2)
def init_hook():
import os
os.environ["TEST"] = "1"
e.start(initialization_hook=init_hook)
def check():
import os
return os.getenv("TEST", "0")
_start_training(e, check)
assert e.finish_training() == ["1", "1"]
def test_shutdown(ray_start_2_cpus):
config = TestConfig()
e = BackendExecutor(config, num_workers=2)
e.start()
assert len(e.worker_group) == 2
e.shutdown()
with pytest.raises(InactiveWorkerGroupError):
_start_training(e, lambda: 1)
def test_train(ray_start_2_cpus):
config = TestConfig()
e = BackendExecutor(config, num_workers=2)
e.start()
_start_training(e, lambda: 1)
assert e.finish_training() == [1, 1]
def test_local_ranks(ray_start_2_cpus):
config = TestConfig()
e = BackendExecutor(config, num_workers=2)
e.start()
def train_func():
return train.get_context().get_local_rank()
_start_training(e, train_func)
assert set(e.finish_training()) == {0, 1}
def test_local_ranks_with_same_ip_nodes(ray_2_node_2_cpu):
config = TestConfig()
e = BackendExecutor(config, num_workers=4)
e.start()
def train_func():
return train.get_context().get_local_rank()
_start_training(e, train_func)
assert list(e.finish_training()) == [0, 1, 0, 1]
def test_local_world_size(ray_2_node_2_cpu):
config = TestConfig()
with patch.object(WorkerGroup, "add_workers", mock_add_workers):
e = BackendExecutor(config, num_workers=3)
e.start()
def train_func():
return train.get_context().get_local_world_size()
_start_training(e, train_func)
assert list(e.finish_training()) == [2, 2, 1]
def test_local_world_size_with_same_ip_nodes(ray_2_node_2_cpu):
config = TestConfig()
with patch.object(
WorkerGroup, "add_workers", mock_add_workers_to_nodes_with_same_ip
):
e = BackendExecutor(config, num_workers=3)
e.start()
def train_func():
return train.get_context().get_local_world_size()
_start_training(e, train_func)
assert list(e.finish_training()) == [2, 2, 1]
def test_node_ranks(ray_2_node_2_cpu):
config = TestConfig()
with patch.object(WorkerGroup, "add_workers", mock_add_workers):
e = BackendExecutor(config, num_workers=3)
e.start()
def train_func():
return train.get_context().get_node_rank()
_start_training(e, train_func)
assert list(e.finish_training()) == [0, 0, 1]
def test_node_ranks_with_same_ip_nodes(ray_2_node_2_cpu):
config = TestConfig()
with patch.object(
WorkerGroup, "add_workers", mock_add_workers_to_nodes_with_same_ip
):
e = BackendExecutor(config, num_workers=3)
e.start()
def train_func():
return train.get_context().get_node_rank()
_start_training(e, train_func)
assert list(e.finish_training()) == [0, 0, 1]
def test_train_failure(ray_start_2_cpus):
config = TestConfig()
e = BackendExecutor(config, num_workers=2)
e.start()
with pytest.raises(StartTraceback) as exc:
e.get_next_results()
assert isinstance(exc.value.__cause__, TrainBackendError)
with pytest.raises(StartTraceback) as exc:
e.pause_reporting()
assert isinstance(exc.value.__cause__, TrainBackendError)
with pytest.raises(StartTraceback) as exc:
e.finish_training()
assert isinstance(exc.value.__cause__, TrainBackendError)
_start_training(e, lambda: 1)
with pytest.raises(StartTraceback) as exc:
_start_training(e, lambda: 2)
assert isinstance(exc.value.__cause__, TrainBackendError)
assert e.finish_training() == [1, 1]
def test_single_worker_user_failure(ray_start_2_cpus):
"""Tests if training fails immediately if one worker raises an Exception
while executing the user training code."""
config = TestConfig()
e = BackendExecutor(config, num_workers=2)
e.start()
def single_worker_user_failure():
if train.get_context().get_world_rank() == 0:
raise RuntimeError
else:
time.sleep(1000000)
_start_training(e, single_worker_user_failure)
with pytest.raises(StartTraceback) as exc:
e.get_next_results()
assert isinstance(exc.value.__cause__, RuntimeError)
def test_single_worker_actor_failure(ray_start_2_cpus):
"""Tests is training fails immediately if one worker actor dies."""
config = TestConfig()
e = BackendExecutor(config, num_workers=2)
e.start()
def single_worker_actor_failure():
if train.get_context().get_world_rank() == 0:
# Simulate actor failure
os._exit(1)
else:
time.sleep(1000)
_start_training(e, single_worker_actor_failure)
with pytest.raises(TrainingWorkerError):
e.get_next_results()
@pytest.mark.skipif(
sys.version_info >= (3, 12), reason="tensorflow is not supported in python 3.12+"
)
def test_tensorflow_start(ray_start_2_cpus):
from ray.train.tensorflow import TensorflowConfig
num_workers = 2
tensorflow_config = TensorflowConfig()
e = BackendExecutor(tensorflow_config, num_workers=num_workers)
e.start()
def get_tf_config():
import json
import os
return json.loads(os.environ["TF_CONFIG"])
_start_training(e, get_tf_config)
results = e.finish_training()
assert len(results) == num_workers
workers = [result["cluster"]["worker"] for result in results]
assert all(worker == workers[0] for worker in workers)
indexes = [result["task"]["index"] for result in results]
assert len(set(indexes)) == num_workers
@pytest.mark.parametrize("init_method", ["env", "tcp"])
def test_torch_start_shutdown(ray_start_2_cpus, init_method):
torch_config = TorchConfig(backend="gloo", init_method=init_method)
e = BackendExecutor(torch_config, num_workers=2)
e.start()
def check_process_group():
import torch
return (
torch.distributed.is_initialized()
and torch.distributed.get_world_size() == 2
)
_start_training(e, check_process_group)
assert all(e.finish_training())
e._backend.on_shutdown(e.worker_group, e._backend_config)
_start_training(e, check_process_group)
assert not any(e.finish_training())
@pytest.mark.parametrize(
"init_method, timeout_s", [("env", 5), ("tcp", 5), ("env", 0), ("tcp", 0)]
)
def test_torch_process_group_shutdown_timeout(
ray_start_2_cpus, monkeypatch, init_method, timeout_s
):
monkeypatch.setenv(TORCH_PROCESS_GROUP_SHUTDOWN_TIMEOUT_S, timeout_s)
torch_config = TorchConfig(backend="gloo", init_method=init_method)
e = BackendExecutor(torch_config, num_workers=2)
e.start()
_start_training(e, lambda: 1)
assert e.finish_training() == [1, 1]
# Verify that we do not raise an exception even if we time out
e._backend.on_shutdown(e.worker_group, e._backend_config)
@pytest.mark.parametrize(
"worker_results",
[
(1, [[0]]),
(2, [[0, 1]] * 2),
(3, [[0]] + [[0, 1]] * 2),
(4, [[0, 1]] * 4),
],
)
def test_cuda_visible_devices(ray_2_node_2_gpu, worker_results):
config = TestConfig()
def get_resources():
cuda_visible_devices = os.environ["CUDA_VISIBLE_DEVICES"]
# Sort the cuda visible devices to have exact match with expected result.
sorted_devices = [
int(device) for device in sorted(cuda_visible_devices.split(","))
]
return sorted_devices
num_workers, expected_results = worker_results
os.environ[ENABLE_SHARE_CUDA_VISIBLE_DEVICES_ENV] = "1"
e = BackendExecutor(
config, num_workers=num_workers, resources_per_worker={"GPU": 1}
)
e.start()
_start_training(e, get_resources)
results = e.finish_training()
results.sort()
assert results == expected_results
@pytest.mark.parametrize(
"worker_results",
[
(1, [[0]]),
(
2,
[[0]] * 2,
),
(3, [[0, 1]] * 3),
(4, [[0, 1]] * 4),
(5, [[0]] + [[0, 1]] * 4),
(6, [[0]] * 2 + [[0, 1]] * 4),
(7, [[0, 1]] * 7),
(8, [[0, 1]] * 8),
],
)
def test_cuda_visible_devices_fractional(ray_2_node_2_gpu, worker_results):
config = TestConfig()
if worker_results[0] != len(worker_results[1]):
raise ValueError(
"Invalid test parameter. Length of expected result should "
"match number of workers."
)
def get_resources():
cuda_visible_devices = os.environ["CUDA_VISIBLE_DEVICES"]
# Sort the cuda visible devices to have exact match with expected result.
sorted_devices = [
int(device) for device in sorted(cuda_visible_devices.split(","))
]
return sorted_devices
num_workers, expected_results = worker_results
os.environ[ENABLE_SHARE_CUDA_VISIBLE_DEVICES_ENV] = "1"
e = BackendExecutor(
config, num_workers=num_workers, resources_per_worker={"GPU": 0.5}
)
e.start()
_start_training(e, get_resources)
results = e.finish_training()
results.sort()
assert results == expected_results
@pytest.mark.parametrize(
"worker_results",
[
(1, [[0, 1]]),
(2, [[0, 1, 2, 3]] * 2),
(3, [[0, 1]] + [[0, 1, 2, 3]] * 2),
(4, [[0, 1, 2, 3]] * 4),
],
)
def test_cuda_visible_devices_multiple(ray_2_node_4_gpu, worker_results):
config = TestConfig()
def get_resources():
cuda_visible_devices = os.environ["CUDA_VISIBLE_DEVICES"]
# Sort the cuda visible devices to have exact match with expected result.
sorted_devices = [
int(device) for device in sorted(cuda_visible_devices.split(","))
]
return sorted_devices
if worker_results[0] != len(worker_results[1]):
raise ValueError(
"Invalid test parameter. Length of expected result should "
"match number of workers."
)
num_workers, expected_results = worker_results
os.environ[ENABLE_SHARE_CUDA_VISIBLE_DEVICES_ENV] = "1"
e = BackendExecutor(
config, num_workers=num_workers, resources_per_worker={"GPU": 2}
)
e.start()
_start_training(e, get_resources)
results = e.finish_training()
results.sort()
assert results == expected_results
@pytest.mark.parametrize(
"worker_results",
[
(1, [[0]]),
(2, [[0, 1]] * 2),
(3, [[0]] + [[0, 1]] * 2),
(4, [[0, 1]] * 4),
],
)
def test_neuron_core_accelerator_ids(ray_2_node_2_neuron_cores, worker_results):
config = TestConfig()
def get_resources():
neuron_resource_ids = os.environ[NEURON_RT_VISIBLE_CORES_ENV_VAR]
# Sort the runtime ids to have exact match with expected result.
sorted_devices = [
int(device) for device in sorted(neuron_resource_ids.split(","))
]
return sorted_devices
num_workers, expected_results = worker_results
# sharing enabled by default
os.environ.pop(ENABLE_SHARE_NEURON_CORES_ACCELERATOR_ENV, None)
e = BackendExecutor(
config,
num_workers=num_workers,
resources_per_worker={"neuron_cores": 1},
)
e.start()
_start_training(e, get_resources)
results = e.finish_training()
results.sort()
assert results == expected_results
@pytest.mark.parametrize(
"worker_results",
[
(1, [[0]]),
(2, [[0]] + [[1]]),
(3, [[0]] * 2 + [[1]]),
(4, [[0]] * 2 + [[1]] * 2),
],
)
def test_neuron_core_accelerator_ids_sharing_disabled(
ray_2_node_2_neuron_cores, worker_results
):
config = TestConfig()
def get_resources():
neuron_resource_ids = os.environ[NEURON_RT_VISIBLE_CORES_ENV_VAR]
# Sort the runtime ids to have exact match with expected result.
sorted_devices = [
int(device) for device in sorted(neuron_resource_ids.split(","))
]
return sorted_devices
num_workers, expected_results = worker_results
os.environ[ENABLE_SHARE_NEURON_CORES_ACCELERATOR_ENV] = "0"
e = BackendExecutor(
config,
num_workers=num_workers,
resources_per_worker={"neuron_cores": 1},
)
e.start()
_start_training(e, get_resources)
results = e.finish_training()
results.sort()
assert results == expected_results
def get_node_id_set() -> Set[str]:
return {a.node_id for a in list_actors()}
@pytest.mark.parametrize("num_workers", [3, 4, 5])
def test_placement_group_pack(ray_4_node_4_cpu, num_workers):
"""Tests that workers are packed on nodes."""
config = TestConfig()
e = BackendExecutor(config, num_workers=num_workers)
e.start()
node_id_set = get_node_id_set()
assert len(node_id_set) == math.ceil(num_workers / 4)
@pytest.mark.parametrize("num_workers", [3, 4, 5])
def test_placement_group_spread(ray_4_node_4_cpu, num_workers):
"""Tests that workers are spread across nodes."""
os.environ[TRAIN_ENABLE_WORKER_SPREAD_ENV] = "1"
config = TestConfig()
e = BackendExecutor(config, num_workers=num_workers)
e.start()
node_id_set = get_node_id_set()
assert len(node_id_set) == min(num_workers, 4)
@pytest.mark.parametrize("placement_group_capture_child_tasks", [True, False])
def test_placement_group_parent(ray_4_node_4_cpu, placement_group_capture_child_tasks):
"""Tests that parent placement group will be used."""
num_workers = 2
bundle = {"CPU": 1}
bundles = [bundle.copy() for _ in range(num_workers + 1)]
placement_group = ray.util.placement_group(bundles)
def train_func():
return get_current_placement_group().id
@ray.remote
def test():
config = TestConfig()
e = BackendExecutor(config, num_workers=2)
e.start()
_start_training(e, train_func)
return e.finish_training()
results_future = test.options(
scheduling_strategy=PlacementGroupSchedulingStrategy(
placement_group=placement_group,
placement_group_capture_child_tasks=placement_group_capture_child_tasks,
),
).remote()
results = ray.get(results_future)
for worker_result in results:
if placement_group_capture_child_tasks:
assert worker_result == placement_group.id
else:
assert worker_result != placement_group.id
@pytest.mark.parametrize("timeout_s", [5, 0])
@pytest.mark.skipif(
sys.version_info >= (3, 12),
reason="Current jax version is not supported in python 3.12+",
)
def test_jax_distributed_shutdown_timeout(ray_start_2_cpus, monkeypatch, timeout_s):
"""Test that JAX distributed shutdown respects the timeout env var."""
monkeypatch.setenv(JAX_DISTRIBUTED_SHUTDOWN_TIMEOUT_S, str(timeout_s))
jax_config = JaxConfig(use_tpu=True)
e = BackendExecutor(jax_config, num_workers=2)
e.start()
_start_training(e, lambda: 1)
assert e.finish_training() == [1, 1]
# Verify that we do not raise an exception even if we time out
e._backend.on_shutdown(e.worker_group, e._backend_config)
if __name__ == "__main__":
import sys
import pytest
sys.exit(pytest.main(["-v", "-x", __file__]))
| TestBackend |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/_shared.py | {
"start": 11148,
"end": 11318
} | class ____(str, Enum):
"""Enumeration for HNSW iterative scan modes."""
off = "off"
relaxed = "relaxed_order"
strict = "strict_order"
| HNSWIterativeScanMode |
python | python-pillow__Pillow | src/PIL/ImageFile.py | {
"start": 3051,
"end": 14980
} | class ____(Image.Image):
"""Base class for image file format handlers."""
def __init__(
self, fp: StrOrBytesPath | IO[bytes], filename: str | bytes | None = None
) -> None:
super().__init__()
self._min_frame = 0
self.custom_mimetype: str | None = None
self.tile: list[_Tile] = []
""" A list of tile descriptors """
self.readonly = 1 # until we know better
self.decoderconfig: tuple[Any, ...] = ()
self.decodermaxblock = MAXBLOCK
if is_path(fp):
# filename
self.fp = open(fp, "rb")
self.filename = os.fspath(fp)
self._exclusive_fp = True
else:
# stream
self.fp = cast(IO[bytes], fp)
self.filename = filename if filename is not None else ""
# can be overridden
self._exclusive_fp = False
try:
try:
self._open()
except (
IndexError, # end of data
TypeError, # end of data (ord)
KeyError, # unsupported mode
EOFError, # got header but not the first frame
struct.error,
) as v:
raise SyntaxError(v) from v
if not self.mode or self.size[0] <= 0 or self.size[1] <= 0:
msg = "not identified by this driver"
raise SyntaxError(msg)
except BaseException:
# close the file only if we have opened it this constructor
if self._exclusive_fp:
self.fp.close()
raise
def _open(self) -> None:
pass
def _close_fp(self):
if getattr(self, "_fp", False) and not isinstance(self._fp, DeferredError):
if self._fp != self.fp:
self._fp.close()
self._fp = DeferredError(ValueError("Operation on closed image"))
if self.fp:
self.fp.close()
def close(self) -> None:
"""
Closes the file pointer, if possible.
This operation will destroy the image core and release its memory.
The image data will be unusable afterward.
This function is required to close images that have multiple frames or
have not had their file read and closed by the
:py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for
more information.
"""
try:
self._close_fp()
self.fp = None
except Exception as msg:
logger.debug("Error closing: %s", msg)
super().close()
def get_child_images(self) -> list[ImageFile]:
child_images = []
exif = self.getexif()
ifds = []
if ExifTags.Base.SubIFDs in exif:
subifd_offsets = exif[ExifTags.Base.SubIFDs]
if subifd_offsets:
if not isinstance(subifd_offsets, tuple):
subifd_offsets = (subifd_offsets,)
for subifd_offset in subifd_offsets:
ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset))
ifd1 = exif.get_ifd(ExifTags.IFD.IFD1)
if ifd1 and ifd1.get(ExifTags.Base.JpegIFOffset):
assert exif._info is not None
ifds.append((ifd1, exif._info.next))
offset = None
for ifd, ifd_offset in ifds:
assert self.fp is not None
current_offset = self.fp.tell()
if offset is None:
offset = current_offset
fp = self.fp
if ifd is not None:
thumbnail_offset = ifd.get(ExifTags.Base.JpegIFOffset)
if thumbnail_offset is not None:
thumbnail_offset += getattr(self, "_exif_offset", 0)
self.fp.seek(thumbnail_offset)
length = ifd.get(ExifTags.Base.JpegIFByteCount)
assert isinstance(length, int)
data = self.fp.read(length)
fp = io.BytesIO(data)
with Image.open(fp) as im:
from . import TiffImagePlugin
if thumbnail_offset is None and isinstance(
im, TiffImagePlugin.TiffImageFile
):
im._frame_pos = [ifd_offset]
im._seek(0)
im.load()
child_images.append(im)
if offset is not None:
assert self.fp is not None
self.fp.seek(offset)
return child_images
def get_format_mimetype(self) -> str | None:
if self.custom_mimetype:
return self.custom_mimetype
if self.format is not None:
return Image.MIME.get(self.format.upper())
return None
def __getstate__(self) -> list[Any]:
return super().__getstate__() + [self.filename]
def __setstate__(self, state: list[Any]) -> None:
self.tile = []
if len(state) > 5:
self.filename = state[5]
super().__setstate__(state)
def verify(self) -> None:
"""Check file integrity"""
# raise exception if something's wrong. must be called
# directly after open, and closes file when finished.
if self._exclusive_fp:
self.fp.close()
self.fp = None
def load(self) -> Image.core.PixelAccess | None:
"""Load image data based on tile list"""
if not self.tile and self._im is None:
msg = "cannot load this image"
raise OSError(msg)
pixel = Image.Image.load(self)
if not self.tile:
return pixel
self.map: mmap.mmap | None = None
use_mmap = self.filename and len(self.tile) == 1
readonly = 0
# look for read/seek overrides
if hasattr(self, "load_read"):
read = self.load_read
# don't use mmap if there are custom read/seek functions
use_mmap = False
else:
read = self.fp.read
if hasattr(self, "load_seek"):
seek = self.load_seek
use_mmap = False
else:
seek = self.fp.seek
if use_mmap:
# try memory mapping
decoder_name, extents, offset, args = self.tile[0]
if isinstance(args, str):
args = (args, 0, 1)
if (
decoder_name == "raw"
and isinstance(args, tuple)
and len(args) >= 3
and args[0] == self.mode
and args[0] in Image._MAPMODES
):
if offset < 0:
msg = "Tile offset cannot be negative"
raise ValueError(msg)
try:
# use mmap, if possible
import mmap
with open(self.filename) as fp:
self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)
if offset + self.size[1] * args[1] > self.map.size():
msg = "buffer is not large enough"
raise OSError(msg)
self.im = Image.core.map_buffer(
self.map, self.size, decoder_name, offset, args
)
readonly = 1
# After trashing self.im,
# we might need to reload the palette data.
if self.palette:
self.palette.dirty = 1
except (AttributeError, OSError, ImportError):
self.map = None
self.load_prepare()
err_code = -3 # initialize to unknown error
if not self.map:
# sort tiles in file order
self.tile.sort(key=_tilesort)
# FIXME: This is a hack to handle TIFF's JpegTables tag.
prefix = getattr(self, "tile_prefix", b"")
# Remove consecutive duplicates that only differ by their offset
self.tile = [
list(tiles)[-1]
for _, tiles in itertools.groupby(
self.tile, lambda tile: (tile[0], tile[1], tile[3])
)
]
for i, (decoder_name, extents, offset, args) in enumerate(self.tile):
seek(offset)
decoder = Image._getdecoder(
self.mode, decoder_name, args, self.decoderconfig
)
try:
decoder.setimage(self.im, extents)
if decoder.pulls_fd:
decoder.setfd(self.fp)
err_code = decoder.decode(b"")[1]
else:
b = prefix
while True:
read_bytes = self.decodermaxblock
if i + 1 < len(self.tile):
next_offset = self.tile[i + 1].offset
if next_offset > offset:
read_bytes = next_offset - offset
try:
s = read(read_bytes)
except (IndexError, struct.error) as e:
# truncated png/gif
if LOAD_TRUNCATED_IMAGES:
break
else:
msg = "image file is truncated"
raise OSError(msg) from e
if not s: # truncated jpeg
if LOAD_TRUNCATED_IMAGES:
break
else:
msg = (
"image file is truncated "
f"({len(b)} bytes not processed)"
)
raise OSError(msg)
b = b + s
n, err_code = decoder.decode(b)
if n < 0:
break
b = b[n:]
finally:
# Need to cleanup here to prevent leaks
decoder.cleanup()
self.tile = []
self.readonly = readonly
self.load_end()
if self._exclusive_fp and self._close_exclusive_fp_after_loading:
self.fp.close()
self.fp = None
if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0:
# still raised if decoder fails to return anything
raise _get_oserror(err_code, encoder=False)
return Image.Image.load(self)
def load_prepare(self) -> None:
# create image memory if necessary
if self._im is None:
self.im = Image.core.new(self.mode, self.size)
# create palette (optional)
if self.mode == "P":
Image.Image.load(self)
def load_end(self) -> None:
# may be overridden
pass
# may be defined for contained formats
# def load_seek(self, pos: int) -> None:
# pass
# may be defined for blocked formats (e.g. PNG)
# def load_read(self, read_bytes: int) -> bytes:
# pass
def _seek_check(self, frame: int) -> bool:
if (
frame < self._min_frame
# Only check upper limit on frames if additional seek operations
# are not required to do so
or (
not (hasattr(self, "_n_frames") and self._n_frames is None)
and frame >= getattr(self, "n_frames") + self._min_frame
)
):
msg = "attempt to seek outside sequence"
raise EOFError(msg)
return self.tell() != frame
| ImageFile |
python | lazyprogrammer__machine_learning_examples | rl/optimistic_initial_values.py | {
"start": 454,
"end": 1755
} | class ____:
def __init__(self, m, upper_limit):
self.m = m
self.mean = upper_limit
self.N = 1
def pull(self):
return np.random.randn() + self.m
def update(self, x):
self.N += 1
self.mean = (1 - 1.0/self.N)*self.mean + 1.0/self.N*x
def run_experiment(m1, m2, m3, N, upper_limit=10):
bandits = [Bandit(m1, upper_limit), Bandit(m2, upper_limit), Bandit(m3, upper_limit)]
data = np.empty(N)
for i in range(N):
# optimistic initial values
j = np.argmax([b.mean for b in bandits])
x = bandits[j].pull()
bandits[j].update(x)
# for the plot
data[i] = x
cumulative_average = np.cumsum(data) / (np.arange(N) + 1)
# plot moving average ctr
plt.plot(cumulative_average)
plt.plot(np.ones(N)*m1)
plt.plot(np.ones(N)*m2)
plt.plot(np.ones(N)*m3)
plt.xscale('log')
plt.show()
for b in bandits:
print(b.mean)
return cumulative_average
if __name__ == '__main__':
c_1 = run_experiment_eps(1.0, 2.0, 3.0, 0.1, 100000)
oiv = run_experiment(1.0, 2.0, 3.0, 100000)
# log scale plot
plt.plot(c_1, label='eps = 0.1')
plt.plot(oiv, label='optimistic')
plt.legend()
plt.xscale('log')
plt.show()
# linear plot
plt.plot(c_1, label='eps = 0.1')
plt.plot(oiv, label='optimistic')
plt.legend()
plt.show()
| Bandit |
python | doocs__leetcode | solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution.py | {
"start": 192,
"end": 499
} | class ____:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
def dfs(root):
if root is None:
return
dfs(root.left)
dfs(root.right)
ans.append(root.val)
ans = []
dfs(root)
return ans
| Solution |
python | tornadoweb__tornado | tornado/test/httpserver_test.py | {
"start": 37550,
"end": 38227
} | class ____(AsyncHTTPTestCase):
def get_app(self):
return Application([("/", EchoHandler)])
def post_gzip(self, body):
bytesio = BytesIO()
gzip_file = gzip.GzipFile(mode="w", fileobj=bytesio)
gzip_file.write(utf8(body))
gzip_file.close()
compressed_body = bytesio.getvalue()
return self.fetch(
"/",
method="POST",
body=compressed_body,
headers={"Content-Encoding": "gzip"},
)
def test_uncompressed(self):
response = self.fetch("/", method="POST", body="foo=bar")
self.assertEqual(json_decode(response.body), {"foo": ["bar"]})
| GzipBaseTest |
python | Textualize__textual | tests/css/test_screen_css.py | {
"start": 774,
"end": 1108
} | class ____(App):
"""Base app for testing screen CSS when pushing screens."""
CSS = """
#app-css {
background: #00ff00;
}
#screen-css-path {
background: #00ff00;
}
#screen-css {
background: #00ff00;
}
"""
def on_mount(self):
self.push_screen(BaseScreen())
| BaseApp |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-gcs/source_gcs/helpers.py | {
"start": 1551,
"end": 2631
} | class ____(UploadableRemoteFile):
"""
Extends RemoteFile instance with displayed_uri attribute.
displayed_uri is being used by Cursor to identify files with temporal local path in their uri attribute.
"""
blob: Any
displayed_uri: str = None
def __init__(self, blob: Any, displayed_uri: str = None, **kwargs):
super().__init__(**kwargs)
self.blob = blob
self.displayed_uri = displayed_uri
self.id = self.blob.id
self.created_at = self.blob.time_created.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
self.updated_at = self.blob.updated.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
@property
def size(self) -> int:
return self.blob.size
def download_to_local_directory(self, local_file_path: str) -> None:
self.blob.download_to_filename(local_file_path)
@property
def source_file_relative_path(self) -> str:
return urllib.parse.unquote(self.blob.path)
@property
def file_uri_for_logging(self) -> str:
return urllib.parse.unquote(self.blob.path)
| GCSUploadableRemoteFile |
python | huggingface__transformers | src/transformers/integrations/ggml.py | {
"start": 13640,
"end": 15485
} | class ____:
def __init__(self, dict_):
for k, v in dict_.items():
setattr(self, k, v)
if not hasattr(self, "merges"):
if not hasattr(self, "tokens") or not hasattr(self, "scores"):
raise ValueError(
"tokens and scores need to be passed for a LLaMa tokenizer without merges to be instantiated."
)
tokens = self.tokens
scores = self.scores
vocab = {t: scores[i] for i, t in enumerate(tokens)}
logger.warning("Merges were not in checkpoint, building merges on the fly.")
merges = []
for merge, piece_score in tqdm(vocab.items()):
local = []
for index in range(1, len(merge)):
piece_l, piece_r = merge[:index], merge[index:]
if piece_l in tokens and piece_r in tokens:
local.append((piece_l, piece_r, piece_score))
local = sorted(local, key=lambda x: (vocab[x[0]], vocab[x[1]]), reverse=True)
merges.extend(local)
merges = sorted(merges, key=lambda val: val[2], reverse=True)
merges = [(val[0], val[1]) for val in merges]
self.merges = merges
else:
self.merges = [tuple(merge.split(" ")) for merge in self.merges]
if not hasattr(self, "scores"):
self.scores = [None for _ in range(len(self.tokens))]
if not hasattr(self, "added_tokens"):
self.added_tokens = []
if not hasattr(self, "unk_token_id"):
self.unk_token_id = None
# Llama2 uses the field `unknown_token_id`
if hasattr(self, "unknown_token_id") and self.unk_token_id is None:
self.unk_token_id = self.unknown_token_id
| GGUFTokenizerSkeleton |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 282750,
"end": 283728
} | class ____(sgqlc.types.Input):
"""Parameters to be used for the repository_name condition"""
__schema__ = github_schema
__field_names__ = ("exclude", "include", "protected")
exclude = sgqlc.types.Field(sgqlc.types.non_null(sgqlc.types.list_of(sgqlc.types.non_null(String))), graphql_name="exclude")
"""Array of repository names or patterns to exclude. The condition
will not pass if any of these patterns match.
"""
include = sgqlc.types.Field(sgqlc.types.non_null(sgqlc.types.list_of(sgqlc.types.non_null(String))), graphql_name="include")
"""Array of repository names or patterns to include. One of these
patterns must match for the condition to pass. Also accepts `~ALL`
to include all repositories.
"""
protected = sgqlc.types.Field(Boolean, graphql_name="protected")
"""Target changes that match these patterns will be prevented except
by those with bypass permissions.
"""
| RepositoryNameConditionTargetInput |
python | apache__thrift | lib/py/test/test_sslsocket.py | {
"start": 3591,
"end": 3984
} | class ____(object):
def __init__(self, expected):
self._expected = expected
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
if not exc_type or not issubclass(exc_type, self._expected):
raise Exception('fail')
return True
@unittest.skip("failing SSL test to be fixed in subsequent pull request")
| AssertRaises |
python | huggingface__transformers | src/transformers/models/luke/modeling_luke.py | {
"start": 72827,
"end": 78720
} | class ____(LukePreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.luke = LukeModel(config)
self.dropout = nn.Dropout(
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
token_type_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
entity_ids: Optional[torch.LongTensor] = None,
entity_attention_mask: Optional[torch.FloatTensor] = None,
entity_token_type_ids: Optional[torch.LongTensor] = None,
entity_position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.FloatTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, LukeSequenceClassifierOutput]:
r"""
entity_ids (`torch.LongTensor` of shape `(batch_size, entity_length)`):
Indices of entity tokens in the entity vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
entity_attention_mask (`torch.FloatTensor` of shape `(batch_size, entity_length)`, *optional*):
Mask to avoid performing attention on padding entity token indices. Mask values selected in `[0, 1]`:
- 1 for entity tokens that are **not masked**,
- 0 for entity tokens that are **masked**.
entity_token_type_ids (`torch.LongTensor` of shape `(batch_size, entity_length)`, *optional*):
Segment token indices to indicate first and second portions of the entity token inputs. Indices are
selected in `[0, 1]`:
- 0 corresponds to a *portion A* entity token,
- 1 corresponds to a *portion B* entity token.
entity_position_ids (`torch.LongTensor` of shape `(batch_size, entity_length, max_mention_length)`, *optional*):
Indices of positions of each input entity in the position embeddings. Selected in the range `[0,
config.max_position_embeddings - 1]`.
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.luke(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
entity_ids=entity_ids,
entity_attention_mask=entity_attention_mask,
entity_token_type_ids=entity_token_type_ids,
entity_position_ids=entity_position_ids,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=True,
)
pooled_output = outputs.pooler_output
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
loss = None
if labels is not None:
# move labels to correct device
labels = labels.to(logits.device)
if self.config.problem_type is None:
if self.num_labels == 1:
self.config.problem_type = "regression"
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
self.config.problem_type = "single_label_classification"
else:
self.config.problem_type = "multi_label_classification"
if self.config.problem_type == "regression":
loss_fct = MSELoss()
if self.num_labels == 1:
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif self.config.problem_type == "single_label_classification":
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
elif self.config.problem_type == "multi_label_classification":
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if not return_dict:
return tuple(
v
for v in [loss, logits, outputs.hidden_states, outputs.entity_hidden_states, outputs.attentions]
if v is not None
)
return LukeSequenceClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
entity_hidden_states=outputs.entity_hidden_states,
attentions=outputs.attentions,
)
@auto_docstring(
custom_intro="""
The LUKE Model with a token classification head on top (a linear layer on top of the hidden-states output). To
solve Named-Entity Recognition (NER) task using LUKE, `LukeForEntitySpanClassification` is more suitable than this
class.
"""
)
| LukeForSequenceClassification |
python | huggingface__transformers | src/transformers/models/flex_olmo/modular_flex_olmo.py | {
"start": 1384,
"end": 10133
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`FlexOlmoModel`]. It is used to instantiate an FlexOlmo
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the [allenai/FlexOlmo-7x7B-1T](https://huggingface.co/allenai/FlexOlmo-7x7B-1T).
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 100352):
Vocabulary size of the FlexOlmo model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`FlexOlmoModel`]
hidden_size (`int`, *optional*, defaults to 4096):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 11008):
Dimension of the MLP representations.
num_hidden_layers (`int`, *optional*, defaults to 32):
Number of hidden layers in the Transformer decoder.
num_attention_heads (`int`, *optional*, defaults to 32):
Number of attention heads for each attention layer in the Transformer decoder.
num_key_value_heads (`int`, *optional*):
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
by meanpooling all the original heads within that group. For more details, check out [this
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
`num_attention_heads`.
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
The non-linear activation function (function or string) in the decoder.
max_position_embeddings (`int`, *optional*, defaults to 4096):
The maximum sequence length that this model might ever be used with.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
The epsilon used by the rms normalization layers.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if `config.is_decoder=True`.
pad_token_id (`int`, *optional*, defaults to 100277):
Padding token id.
bos_token_id (`int`, *optional*):
Beginning of stream token id.
eos_token_id (`int`, *optional*, defaults to 100257):
End of stream token id.
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
Whether to tie weight embeddings
rope_parameters (`RopeParameters`, *optional*):
Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
with longer `max_position_embeddings`.
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
Whether to use a bias in the query, key, value and output projection layers during self-attention.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
num_experts_per_tok (`int`, *optional*, defaults to 5):
Number of selected experts.
num_experts (`int`, *optional*, defaults to 7):
Number of routed experts.
output_router_logits (`bool`, *optional*, defaults to `False`):
Whether or not the router logits should be returned by the model. Enabling this will also
allow the model to output the auxiliary loss, including load balancing loss and router z-loss.
router_aux_loss_coef (`float`, *optional*, defaults to 0.01):
The aux loss factor for the total loss.
norm_topk_prob (`bool`, *optional*, defaults to `False`):
Whether to normalize the topk probabilities.
```python
>>> from transformers import FlexOlmoModel, FlexOlmoConfig
>>> # Initializing a FlexOlmo style configuration
>>> configuration = FlexOlmoConfig()
>>> # Initializing a model from the FlexOlmo style configuration
>>> model = FlexOlmoModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "flex_olmo"
keys_to_ignore_at_inference = ["past_key_values"]
attribute_map = {"num_local_experts": "num_experts"}
default_theta = 500000.0
base_model_tp_plan = {
"layers.*.self_attn.q_proj": "colwise_rep", # we need to replicate here due to the added norm on q and k
"layers.*.self_attn.k_proj": "colwise_rep", # we need to replicate here due to the added norm on q and k
"layers.*.self_attn.v_proj": "colwise_rep", # we need to replicate here due to the added norm on q and k
"layers.*.self_attn.o_proj": "rowwise_rep", # we need to replicate here due to the added norm on q and k
"layers.*.mlp.experts.gate_up_proj": "local_rowwise",
"layers.*.mlp.experts.down_proj": "local_rowwise",
"layers.*.mlp.experts": "gather",
}
base_model_pp_plan = {
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
"norm": (["hidden_states"], ["hidden_states"]),
}
def __init__(
self,
vocab_size: Optional[int] = 100352,
hidden_size: Optional[int] = 4096,
intermediate_size: Optional[int] = 11008,
num_hidden_layers: Optional[int] = 32,
num_attention_heads: Optional[int] = 32,
num_key_value_heads: Optional[int] = None,
hidden_act: Optional[str] = "silu",
max_position_embeddings: Optional[int] = 4096,
initializer_range: Optional[float] = 0.02,
rms_norm_eps: Optional[float] = 1e-06,
use_cache: Optional[bool] = True,
pad_token_id: Optional[int] = 100277,
bos_token_id: Optional[int] = None,
eos_token_id: Optional[int] = 100257,
tie_word_embeddings: Optional[bool] = False,
rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None,
attention_bias: Optional[bool] = False,
attention_dropout: Optional[float] = 0.0,
num_experts_per_tok: Optional[int] = 5,
num_experts: Optional[int] = 7,
output_router_logits: Optional[bool] = False,
router_aux_loss_coef: Optional[float] = 0.01,
norm_topk_prob: Optional[bool] = False,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
# for backward compatibility
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.attention_bias = attention_bias
self.attention_dropout = attention_dropout
self.num_experts_per_tok = num_experts_per_tok
self.num_experts = num_experts
self.output_router_logits = output_router_logits
self.router_aux_loss_coef = router_aux_loss_coef
self.norm_topk_prob = norm_topk_prob
self.rope_parameters = rope_parameters
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
# FlexOlmo RMS norm reuses Olmo2 RMS norm, which handles low precision slightly differently than the original Olmoe.
| FlexOlmoConfig |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | experiments/Solve_LunarLander/A3C.py | {
"start": 914,
"end": 5434
} | class ____(object):
def __init__(self, scope, globalAC=None):
if scope == GLOBAL_NET_SCOPE: # get global network
with tf.variable_scope(scope):
self.s = tf.placeholder(tf.float32, [None, N_S], 'S')
self._build_net(N_A)
self.a_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope + '/actor')
self.c_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope + '/critic')
else: # local net, calculate losses
with tf.variable_scope(scope):
self.s = tf.placeholder(tf.float32, [None, N_S], 'S')
self.a_his = tf.placeholder(tf.int32, [None, ], 'A')
self.v_target = tf.placeholder(tf.float32, [None, 1], 'Vtarget')
self.a_prob, self.v = self._build_net(N_A)
td = tf.subtract(self.v_target, self.v, name='TD_error')
with tf.name_scope('c_loss'):
self.c_loss = tf.reduce_mean(tf.square(td))
with tf.name_scope('a_loss'):
log_prob = tf.reduce_sum(tf.log(self.a_prob) * tf.one_hot(self.a_his, N_A, dtype=tf.float32), axis=1, keep_dims=True)
exp_v = log_prob * td
entropy = -tf.reduce_sum(self.a_prob * tf.log(self.a_prob), axis=1, keep_dims=True) # encourage exploration
self.exp_v = ENTROPY_BETA * entropy + exp_v
self.a_loss = tf.reduce_mean(-self.exp_v)
with tf.name_scope('local_grad'):
self.a_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope + '/actor')
self.c_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope + '/critic')
self.a_grads = tf.gradients(self.a_loss, self.a_params)
self.c_grads = tf.gradients(self.c_loss, self.c_params)
with tf.name_scope('sync'):
with tf.name_scope('pull'):
self.pull_a_params_op = [l_p.assign(g_p) for l_p, g_p in zip(self.a_params, globalAC.a_params)]
self.pull_c_params_op = [l_p.assign(g_p) for l_p, g_p in zip(self.c_params, globalAC.c_params)]
with tf.name_scope('push'):
self.update_a_op = OPT_A.apply_gradients(zip(self.a_grads, globalAC.a_params))
self.update_c_op = OPT_C.apply_gradients(zip(self.c_grads, globalAC.c_params))
def _build_net(self, n_a):
w_init = tf.random_normal_initializer(0., .01)
with tf.variable_scope('critic'):
cell_size = 64
s = tf.expand_dims(self.s, axis=1,
name='timely_input') # [time_step, feature] => [time_step, batch, feature]
rnn_cell = tf.contrib.rnn.BasicRNNCell(cell_size)
self.init_state = rnn_cell.zero_state(batch_size=1, dtype=tf.float32)
outputs, self.final_state = tf.nn.dynamic_rnn(
cell=rnn_cell, inputs=s, initial_state=self.init_state, time_major=True)
cell_out = tf.reshape(outputs, [-1, cell_size], name='flatten_rnn_outputs') # joined state representation
l_c = tf.layers.dense(cell_out, 200, tf.nn.relu6, kernel_initializer=w_init, name='lc')
v = tf.layers.dense(l_c, 1, kernel_initializer=w_init, name='v') # state value
with tf.variable_scope('actor'):
cell_out = tf.stop_gradient(cell_out, name='c_cell_out')
l_a = tf.layers.dense(cell_out, 300, tf.nn.relu6, kernel_initializer=w_init, name='la')
a_prob = tf.layers.dense(l_a, n_a, tf.nn.softmax, kernel_initializer=w_init, name='ap')
return a_prob, v
def update_global(self, feed_dict): # run by a local
SESS.run([self.update_a_op, self.update_c_op], feed_dict) # local grads applies to global net
def pull_global(self): # run by a local
SESS.run([self.pull_a_params_op, self.pull_c_params_op])
def choose_action(self, s, cell_state): # run by a local
prob_weights, cell_state = SESS.run([self.a_prob, self.final_state], feed_dict={self.s: s[np.newaxis, :],
self.init_state: cell_state})
action = np.random.choice(range(prob_weights.shape[1]),
p=prob_weights.ravel()) # select action w.r.t the actions prob
return action, cell_state
| ACNet |
python | pandas-dev__pandas | pandas/tests/frame/test_api.py | {
"start": 362,
"end": 13088
} | class ____:
def test_getitem_pop_assign_name(self, float_frame):
s = float_frame["A"]
assert s.name == "A"
s = float_frame.pop("A")
assert s.name == "A"
s = float_frame.loc[:, "B"]
assert s.name == "B"
s2 = s.loc[:]
assert s2.name == "B"
def test_get_axis(self, float_frame):
f = float_frame
assert f._get_axis_number(0) == 0
assert f._get_axis_number(1) == 1
assert f._get_axis_number("index") == 0
assert f._get_axis_number("rows") == 0
assert f._get_axis_number("columns") == 1
assert f._get_axis_name(0) == "index"
assert f._get_axis_name(1) == "columns"
assert f._get_axis_name("index") == "index"
assert f._get_axis_name("rows") == "index"
assert f._get_axis_name("columns") == "columns"
assert f._get_axis(0) is f.index
assert f._get_axis(1) is f.columns
with pytest.raises(ValueError, match="No axis named"):
f._get_axis_number(2)
with pytest.raises(ValueError, match="No axis.*foo"):
f._get_axis_name("foo")
with pytest.raises(ValueError, match="No axis.*None"):
f._get_axis_name(None)
with pytest.raises(ValueError, match="No axis named"):
f._get_axis_number(None)
def test_column_contains_raises(self, float_frame):
with pytest.raises(TypeError, match="unhashable type: 'Index'"):
float_frame.columns in float_frame
def test_tab_completion(self):
# DataFrame whose columns are identifiers shall have them in __dir__.
df = DataFrame([list("abcd"), list("efgh")], columns=list("ABCD"))
for key in list("ABCD"):
assert key in dir(df)
assert isinstance(df.__getitem__("A"), Series)
# DataFrame whose first-level columns are identifiers shall have
# them in __dir__.
df = DataFrame(
[list("abcd"), list("efgh")],
columns=pd.MultiIndex.from_tuples(list(zip("ABCD", "EFGH"))),
)
for key in list("ABCD"):
assert key in dir(df)
for key in list("EFGH"):
assert key not in dir(df)
assert isinstance(df.__getitem__("A"), DataFrame)
def test_display_max_dir_items(self):
# display.max_dir_items increases the number of columns that are in __dir__.
columns = ["a" + str(i) for i in range(420)]
values = [range(420), range(420)]
df = DataFrame(values, columns=columns)
# The default value for display.max_dir_items is 100
assert "a99" in dir(df)
assert "a100" not in dir(df)
with option_context("display.max_dir_items", 300):
df = DataFrame(values, columns=columns)
assert "a299" in dir(df)
assert "a300" not in dir(df)
with option_context("display.max_dir_items", None):
df = DataFrame(values, columns=columns)
assert "a419" in dir(df)
def test_not_hashable(self):
empty_frame = DataFrame()
df = DataFrame([1])
msg = "unhashable type: 'DataFrame'"
with pytest.raises(TypeError, match=msg):
hash(df)
with pytest.raises(TypeError, match=msg):
hash(empty_frame)
@pytest.mark.xfail(
using_string_dtype() and HAS_PYARROW, reason="surrogates not allowed"
)
def test_column_name_contains_unicode_surrogate(self):
# GH 25509
colname = "\ud83d"
df = DataFrame({colname: []})
# this should not crash
assert colname not in dir(df)
assert df.columns[0] == colname
def test_new_empty_index(self):
df1 = DataFrame(np.random.default_rng(2).standard_normal((0, 3)))
df2 = DataFrame(np.random.default_rng(2).standard_normal((0, 3)))
df1.index.name = "foo"
assert df2.index.name is None
def test_get_agg_axis(self, float_frame):
cols = float_frame._get_agg_axis(0)
assert cols is float_frame.columns
idx = float_frame._get_agg_axis(1)
assert idx is float_frame.index
msg = r"Axis must be 0 or 1 \(got 2\)"
with pytest.raises(ValueError, match=msg):
float_frame._get_agg_axis(2)
def test_empty(self, float_frame, float_string_frame):
empty_frame = DataFrame()
assert empty_frame.empty
assert not float_frame.empty
assert not float_string_frame.empty
# corner case
df = DataFrame({"A": [1.0, 2.0, 3.0], "B": ["a", "b", "c"]}, index=np.arange(3))
del df["A"]
assert not df.empty
def test_len(self, float_frame):
assert len(float_frame) == len(float_frame.index)
# single block corner case
arr = float_frame[["A", "B"]].values
expected = float_frame.reindex(columns=["A", "B"]).values
tm.assert_almost_equal(arr, expected)
def test_axis_aliases(self, float_frame):
f = float_frame
# reg name
expected = f.sum(axis=0)
result = f.sum(axis="index")
tm.assert_series_equal(result, expected)
expected = f.sum(axis=1)
result = f.sum(axis="columns")
tm.assert_series_equal(result, expected)
def test_class_axis(self):
# GH 18147
# no exception and no empty docstring
assert pydoc.getdoc(DataFrame.index)
assert pydoc.getdoc(DataFrame.columns)
def test_series_put_names(self, float_string_frame):
series = float_string_frame._series
for k, v in series.items():
assert v.name == k
def test_empty_nonzero(self):
df = DataFrame([1, 2, 3])
assert not df.empty
df = DataFrame(index=[1], columns=[1])
assert not df.empty
df = DataFrame(index=["a", "b"], columns=["c", "d"]).dropna()
assert df.empty
assert df.T.empty
@pytest.mark.parametrize(
"df",
[
DataFrame(),
DataFrame(index=[1]),
DataFrame(columns=[1]),
DataFrame({1: []}),
],
)
def test_empty_like(self, df):
assert df.empty
assert df.T.empty
def test_with_datetimelikes(self):
df = DataFrame(
{
"A": date_range("20130101", periods=10),
"B": timedelta_range("1 day", periods=10),
}
)
t = df.T
result = t.dtypes.value_counts()
expected = Series({np.dtype("object"): 10}, name="count")
tm.assert_series_equal(result, expected)
def test_deepcopy(self, float_frame):
cp = deepcopy(float_frame)
cp.loc[0, "A"] = 10
assert not float_frame.equals(cp)
def test_inplace_return_self(self):
# GH 1893
data = DataFrame(
{"a": ["foo", "bar", "baz", "qux"], "b": [0, 0, 1, 1], "c": [1, 2, 3, 4]}
)
def _check_none(base, f):
result = f(base)
assert result is None
def _check_return(base, f):
result = f(base)
assert result is base
# -----DataFrame-----
# set_index
f = lambda x: x.set_index("a", inplace=True)
_check_none(data.copy(), f)
# reset_index
f = lambda x: x.reset_index(inplace=True)
_check_none(data.set_index("a"), f)
# drop_duplicates
f = lambda x: x.drop_duplicates(inplace=True)
_check_none(data.copy(), f)
# sort
f = lambda x: x.sort_values("b", inplace=True)
_check_none(data.copy(), f)
# sort_index
f = lambda x: x.sort_index(inplace=True)
_check_none(data.copy(), f)
# fillna
f = lambda x: x.fillna(0, inplace=True)
_check_return(data.copy(), f)
# replace
f = lambda x: x.replace(1, 0, inplace=True)
_check_return(data.copy(), f)
# rename
f = lambda x: x.rename({1: "foo"}, inplace=True)
_check_none(data.copy(), f)
# -----Series-----
d = data.copy()["c"]
# reset_index
f = lambda x: x.reset_index(inplace=True, drop=True)
_check_none(data.set_index("a")["c"], f)
# fillna
f = lambda x: x.fillna(0, inplace=True)
_check_return(d.copy(), f)
# replace
f = lambda x: x.replace(1, 0, inplace=True)
_check_return(d.copy(), f)
# rename
f = lambda x: x.rename({1: "foo"}, inplace=True)
_check_none(d.copy(), f)
def test_tab_complete_warning(self, ip, frame_or_series):
# GH 16409
pytest.importorskip("IPython", minversion="6.0.0")
from IPython.core.completer import provisionalcompleter
if frame_or_series is DataFrame:
code = "from pandas import DataFrame; obj = DataFrame()"
else:
code = "from pandas import Series; obj = Series(dtype=object)"
ip.run_cell(code)
# GH 31324 newer jedi version raises Deprecation warning;
# appears resolved 2021-02-02
with tm.assert_produces_warning(None, raise_on_extra_warnings=False):
with provisionalcompleter("ignore"):
list(ip.Completer.completions("obj.", 1))
def test_attrs(self):
df = DataFrame({"A": [2, 3]})
assert df.attrs == {}
df.attrs["version"] = 1
result = df.rename(columns=str)
assert result.attrs == {"version": 1}
def test_attrs_is_deepcopy(self):
df = DataFrame({"A": [2, 3]})
assert df.attrs == {}
df.attrs["tags"] = {"spam", "ham"}
result = df.rename(columns=str)
assert result.attrs == df.attrs
assert result.attrs["tags"] is not df.attrs["tags"]
def test_attrs_concat(self):
# concat propagates attrs if all input attrs are equal
df1 = DataFrame({"A": [2, 3]})
df1.attrs = {"a": 1, "b": 2}
df2 = DataFrame({"A": [4, 5]})
df2.attrs = df1.attrs.copy()
df3 = DataFrame({"A": [6, 7]})
df3.attrs = df1.attrs.copy()
assert pd.concat([df1, df2, df3]).attrs == df1.attrs
# concat does not propagate attrs if input attrs are different
df2.attrs = {"c": 3}
assert pd.concat([df1, df2, df3]).attrs == {}
def test_attrs_merge(self):
# merge propagates attrs if all input attrs are equal
df1 = DataFrame({"key": ["a", "b"], "val1": [1, 2]})
df1.attrs = {"a": 1, "b": 2}
df2 = DataFrame({"key": ["a", "b"], "val2": [3, 4]})
df2.attrs = df1.attrs.copy()
assert pd.merge(df1, df2).attrs == df1.attrs
# merge does not propagate attrs if input attrs are different
df2.attrs = {"c": 3}
assert pd.merge(df1, df2).attrs == {}
@pytest.mark.parametrize("allows_duplicate_labels", [True, False, None])
def test_set_flags(
self,
allows_duplicate_labels,
frame_or_series,
):
obj = DataFrame({"A": [1, 2]})
key = (0, 0)
if frame_or_series is Series:
obj = obj["A"]
key = 0
result = obj.set_flags(allows_duplicate_labels=allows_duplicate_labels)
if allows_duplicate_labels is None:
# We don't update when it's not provided
assert result.flags.allows_duplicate_labels is True
else:
assert result.flags.allows_duplicate_labels is allows_duplicate_labels
# We made a copy
assert obj is not result
# We didn't mutate obj
assert obj.flags.allows_duplicate_labels is True
# But we didn't copy data
if frame_or_series is Series:
assert np.may_share_memory(obj.values, result.values)
else:
assert np.may_share_memory(obj["A"].values, result["A"].values)
result.iloc[key] = 0
assert obj.iloc[key] == 1
# Now we do copy.
result = obj.set_flags(allows_duplicate_labels=allows_duplicate_labels)
result.iloc[key] = 10
assert obj.iloc[key] == 1
def test_constructor_expanddim(self):
# GH#33628 accessing _constructor_expanddim should not raise NotImplementedError
# GH38782 pandas has no container higher than DataFrame (two-dim), so
# DataFrame._constructor_expand_dim, doesn't make sense, so is removed.
df = DataFrame()
msg = "'DataFrame' object has no attribute '_constructor_expanddim'"
with pytest.raises(AttributeError, match=msg):
df._constructor_expanddim(np.arange(27).reshape(3, 3, 3))
def test_inspect_getmembers(self):
# GH38740
df = DataFrame()
inspect.getmembers(df)
| TestDataFrameMisc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.