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 | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 182714,
"end": 183443
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"project_id",
"item_id",
"field_id",
"value",
"client_mutation_id",
)
project_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectId")
item_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="itemId")
field_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="fieldId")
value = sgqlc.types.Field(
sgqlc.types.non_null(ProjectV2FieldValue), graphql_name="value"
)
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
| UpdateProjectV2ItemFieldValueInput |
python | ray-project__ray | python/ray/dag/dag_operation_future.py | {
"start": 1174,
"end": 4961
} | class ____(DAGOperationFuture[Any]):
"""
A future for a GPU event on a CUDA stream.
This future wraps a buffer, and records an event on the given stream
when it is created. When the future is waited on, it makes the current
CUDA stream wait on the event, then returns the buffer.
The buffer must be a GPU tensor produced by an earlier operation launched
on the given stream, or it could be CPU data. Then the future guarantees
that when the wait() returns, the buffer is ready on the current stream.
The `wait()` does not block CPU.
"""
# Caching GPU futures ensures CUDA events associated with futures are properly
# destroyed instead of relying on garbage collection. The CUDA event contained
# in a GPU future is destroyed right before removing the future from the cache.
# The dictionary key is the future ID, which is the task idx of the dag operation
# that produced the future. When a future is created, it is immediately added to
# the cache. When a future has been waited on, it is removed from the cache.
# When adding a future, if its ID is already a key in the cache, the old future
# is removed. This can happen when an exception is thrown in a previous execution
# of the dag, in which case the old future is never waited on.
# Upon dag teardown, all pending futures produced by the dag are removed.
gpu_futures: Dict[int, "GPUFuture"] = {}
@staticmethod
def add_gpu_future(fut_id: int, fut: "GPUFuture") -> None:
"""
Cache the GPU future.
Args:
fut_id: GPU future ID.
fut: GPU future to be cached.
"""
if fut_id in GPUFuture.gpu_futures:
# The old future was not waited on because of an execution exception.
GPUFuture.gpu_futures.pop(fut_id).destroy_event()
GPUFuture.gpu_futures[fut_id] = fut
@staticmethod
def remove_gpu_future(fut_id: int) -> None:
"""
Remove the cached GPU future and destroy its CUDA event.
Args:
fut_id: GPU future ID.
"""
if fut_id in GPUFuture.gpu_futures:
GPUFuture.gpu_futures.pop(fut_id).destroy_event()
def __init__(self, buf: Any, fut_id: int, stream: Any = None):
"""
Initialize a GPU future on the given stream.
Args:
buf: The buffer to return when the future is resolved.
fut_id: The future ID to cache the future.
stream: The torch stream to record the event on, this event is waited
on when the future is resolved. If None, the current stream is used.
"""
if stream is None:
stream = AcceleratorContext.get().current_stream()
self._buf = buf
self._event = AcceleratorContext.get().create_event()
self._event.record(stream)
self._fut_id = fut_id
self._waited: bool = False
# Cache the GPU future such that its CUDA event is properly destroyed.
GPUFuture.add_gpu_future(fut_id, self)
def wait(self) -> Any:
"""
Wait for the future on the current CUDA stream and return the result from
the GPU operation. This operation does not block CPU.
"""
current_stream = AcceleratorContext.get().current_stream()
if not self._waited:
self._waited = True
current_stream.wait_event(self._event)
# Destroy the CUDA event after it is waited on.
GPUFuture.remove_gpu_future(self._fut_id)
return self._buf
def destroy_event(self) -> None:
"""
Destroy the CUDA event associated with this future.
"""
if self._event is None:
return
self._event = None
| GPUFuture |
python | PyCQA__pylint | tests/functional/n/non/non_iterator_returned.py | {
"start": 776,
"end": 899
} | class ____:
""" __iter__ returns iter(...) """
def __iter__(self):
return iter(range(10))
| FourthGoodIterator |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_datacatalog.py | {
"start": 29381,
"end": 30628
} | class ____:
@mock.patch(
"airflow.providers.google.cloud.operators.datacatalog.CloudDataCatalogHook",
**{"return_value.lookup_entry.return_value": TEST_ENTRY},
)
def test_assert_valid_hook_call(self, mock_hook) -> None:
with pytest.warns(AirflowProviderDeprecationWarning):
task = CloudDataCatalogLookupEntryOperator(
task_id="task_id",
linked_resource=TEST_LINKED_RESOURCE,
sql_resource=TEST_SQL_RESOURCE,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
task.execute(context=mock.MagicMock())
mock_hook.assert_called_once_with(
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_hook.return_value.lookup_entry.assert_called_once_with(
linked_resource=TEST_LINKED_RESOURCE,
sql_resource=TEST_SQL_RESOURCE,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
)
| TestCloudDataCatalogLookupEntryOperator |
python | sphinx-doc__sphinx | sphinx/ext/autodoc/_sentinels.py | {
"start": 157,
"end": 1018
} | class ____:
"""Create a unique sentinel object."""
__slots__ = ('_name',)
_name: str
def __new__(cls, name: str, /) -> Self:
sentinel = super().__new__(cls)
object.__setattr__(sentinel, '_name', str(name))
return sentinel
def __repr__(self) -> str:
return self._name
def __setattr__(self, key: str, value: object) -> NoReturn:
msg = f'{self._name} is immutable'
raise AttributeError(msg)
def __or__(self, other: object) -> _SpecialForm:
from typing import Union
return Union[self, other] # NoQA: UP007
def __ror__(self, other: object) -> _SpecialForm:
from typing import Union
return Union[other, self] # NoQA: UP007
def __getstate__(self) -> NoReturn:
msg = f'Cannot pickle {self._name}'
raise TypeError(msg)
| _Sentinel |
python | jazzband__django-simple-history | simple_history/tests/view.py | {
"start": 1963,
"end": 2459
} | class ____(View):
def post(self, request, *args, **kwargs):
default_user = CustomUser.objects.create_superuser(
"test_user", "test_user@example.com", "pass"
)
polls = Poll.objects.all()
for i, poll in enumerate(polls):
poll.question = str(i)
bulk_update_with_history(
polls, fields=["question"], model=Poll, default_user=default_user
)
return HttpResponse(status=201)
| PollBulkUpdateWithDefaultUserView |
python | great-expectations__great_expectations | great_expectations/data_context/templates.py | {
"start": 212,
"end": 5293
} | class ____(YAML):
"""
Get yaml dump as a string: https://yaml.readthedocs.io/en/latest/example.html#output-of-dump-as-a-string
"""
def dump(self, data, stream=None, **kw): # type: ignore[explicit-override] # FIXME
inefficient = False
if not stream:
inefficient = True
stream = StringIO()
YAML.dump(self, data, stream, **kw)
if inefficient:
return stream.getvalue()
yaml = YAMLToString()
yaml.indent(mapping=2, sequence=4, offset=4)
yaml.default_flow_style = False
# TODO: maybe bring params in via f-strings from base.ConfigDefaults or whatever
# I end up using for the base level configs. Specifically PROJECT_OPTIONAL_CONFIG_COMMENT
# and PROJECT_HELP_COMMENT
PROJECT_HELP_COMMENT = f"""
# Welcome to Great Expectations! Always know what to expect from your data.
#
# Here you can define datasources, batch kwargs generators, integrations and
# more. This file is intended to be committed to your repo. For help with
# configuration please:
# - Read our docs: https://docs.greatexpectations.io/docs/guides/connecting_to_your_data/connect_to_data_overview/#2-configure-your-datasource
# - Join our slack channel: http://greatexpectations.io/slack
# config_version refers to the syntactic version of this config file, and is used in maintaining backwards compatibility
# It is auto-generated and usually does not need to be changed.
config_version: {DataContextConfigDefaults.DEFAULT_CONFIG_VERSION.value}
""" # noqa: E501 # FIXME CoP
CONFIG_VARIABLES_INTRO = """
# This config file supports variable substitution which enables: 1) keeping
# secrets out of source control & 2) environment-based configuration changes
# such as staging vs prod.
#
# When GX encounters substitution syntax (like `my_key: ${my_value}` or
# `my_key: $my_value`) in the great_expectations.yml file, it will attempt
# to replace the value of `my_key` with the value from an environment
# variable `my_value` or a corresponding key read from this config file,
# which is defined through the `config_variables_file_path`.
# Environment variables take precedence over variables defined here.
#
# Substitution values defined here can be a simple (non-nested) value,
# nested value such as a dictionary, or an environment variable (i.e. ${ENV_VAR})
#
#
# https://docs.greatexpectations.io/docs/guides/setup/configuring_data_contexts/how_to_configure_credentials
"""
CONFIG_VARIABLES_TEMPLATE = f"{CONFIG_VARIABLES_INTRO}instance_id: {uuid.uuid4()!s}{os.linesep}"
# Create yaml strings
# NOTE: .replace("\n", "\n ")[:-2] is a hack to indent all lines two spaces,
# and remove the inserted final two spaces.
EXPECTATIONS_STORE_STRING = yaml.dump(
{"expectations_store": DataContextConfigDefaults.DEFAULT_STORES.value["expectations_store"]}
).replace("\n", "\n ")[:-2]
VALIDATIONS_STORE_STRING = yaml.dump(
{
"validation_results_store": DataContextConfigDefaults.DEFAULT_STORES.value[
"validation_results_store"
]
}
).replace("\n", "\n ")[:-2]
CHECKPOINT_STORE_STRING = yaml.dump(
{"checkpoint_store": DataContextConfigDefaults.DEFAULT_STORES.value["checkpoint_store"]}
).replace("\n", "\n ")[:-2]
VALIDATION_DEFINITION_STORE_STRING = yaml.dump(
{
"validation_definition_store": DataContextConfigDefaults.DEFAULT_STORES.value[
"validation_definition_store"
]
}
).replace("\n", "\n ")[:-2]
PROJECT_OPTIONAL_CONFIG_COMMENT = (
CONFIG_VARIABLES_INTRO
+ f"""
config_variables_file_path: {DataContextConfigDefaults.DEFAULT_CONFIG_VARIABLES_FILEPATH.value}
# The plugins_directory will be added to your python path for custom modules
# used to override and extend Great Expectations.
plugins_directory: {DataContextConfigDefaults.DEFAULT_PLUGINS_DIRECTORY.value}
stores:
# Stores are configurable places to store things like Expectations, Validations
# Data Docs, and more. These are for advanced users only - most users can simply
# leave this section alone.
{EXPECTATIONS_STORE_STRING}
{VALIDATIONS_STORE_STRING}
{CHECKPOINT_STORE_STRING}
{VALIDATION_DEFINITION_STORE_STRING}
expectations_store_name: expectations_store
validation_results_store_name: validation_results_store
checkpoint_store_name: checkpoint_store
data_docs_sites:
# Data Docs make it simple to visualize data quality in your project. These
# include Expectations, Validations & Profiles. The are built for all
# Datasources from JSON artifacts in the local repo including validations &
# profiles from the uncommitted directory. Read more at https://docs.greatexpectations.io/docs/terms/data_docs
local_site:
class_name: SiteBuilder
# set to false to hide how-to buttons in Data Docs
show_how_to_buttons: true
store_backend:
class_name: TupleFilesystemStoreBackend
base_directory: uncommitted/data_docs/local_site/
site_index_builder:
class_name: DefaultSiteIndexBuilder
"""
)
PROJECT_TEMPLATE_USAGE_STATISTICS_ENABLED = PROJECT_HELP_COMMENT + PROJECT_OPTIONAL_CONFIG_COMMENT
| YAMLToString |
python | keon__algorithms | algorithms/queues/queue.py | {
"start": 655,
"end": 1084
} | class ____(metaclass=ABCMeta):
def __init__(self):
self._size = 0
def __len__(self):
return self._size
def is_empty(self):
return self._size == 0
@abstractmethod
def enqueue(self, value):
pass
@abstractmethod
def dequeue(self):
pass
@abstractmethod
def peek(self):
pass
@abstractmethod
def __iter__(self):
pass
| AbstractQueue |
python | pytorch__pytorch | test/quantization/jit/test_ondevice_quantization.py | {
"start": 10214,
"end": 22318
} | class ____(TestCase):
def _validate_packed_params(self, model, num_nodes, per_channel=0):
quantize_forward_graph = model.quantize_forward.graph
quantize_per_tensor = quantize_per_channel = 0
linear_prepack = 0
linear_prepack_uses = 0
for n in quantize_forward_graph.nodes():
if n.kind() == "prim::SetAttr":
maybe_packed_param_value = n.inputsAt(1)
maybe_packed_param = maybe_packed_param_value.node()
if maybe_packed_param.kind() == "quantized::linear_prepack":
linear_prepack += 1
linear_prepack_uses += len(maybe_packed_param_value.uses())
if OnDevicePTQUtils.is_per_channel_quantized_packed_param(
maybe_packed_param
):
quantize_per_channel += 1
else:
quantize_per_tensor += 1
self.assertEqual(quantize_per_tensor + quantize_per_channel, num_nodes)
self.assertEqual(quantize_per_channel, per_channel)
self.assertEqual(linear_prepack, num_nodes)
self.assertEqual(linear_prepack_uses, num_nodes)
def _validate_no_linear_unpack(self, model):
quantize_forward_graph = model.quantize_forward.graph
for n in quantize_forward_graph.nodes():
if n.kind() == "quantized::linear_unpack":
return False
return True
def _validate_setattr_fp_weights(self, model, num_nodes):
quantize_forward_graph = model.quantize_forward.graph
fp_weights_setattr = 0
fp_weight_names = []
for n in quantize_forward_graph.nodes():
if n.kind() == "prim::SetAttr":
maybe_packed_param = n.inputsAt(1).node()
if maybe_packed_param.kind() == "quantized::linear_prepack":
weight_name = OnDevicePTQUtils.get_linear_packed_param_fp_weight(
maybe_packed_param
)
fp_weight_names.append(weight_name)
for n in quantize_forward_graph.nodes():
# This is basically detecting
# %x = prim::Constant
# = prim::SetAttr(<weight_name>)(module_value, x)
# Thus making sure that the original fp weights are
# reset
if n.kind() == "prim::SetAttr":
weight_name = n.s("name")
if weight_name in fp_weight_names:
maybe_constant = n.inputsAt(1).node()
if maybe_constant.kind() == "prim::Constant":
fp_weights_setattr += 1
self.assertEqual(fp_weights_setattr, num_nodes)
def _validate_quantized_forward(self, model, num_nodes):
quantized_forward_graph = model.quantized_forward.graph
quantize_per_tensor = quantize_per_channel = 0
quantized_linear_dynamic = 0
linear_packed_params = 0
num_setattr = 0
for n in quantized_forward_graph.nodes():
if "aten::quantize_per_tensor" in n.kind():
quantize_per_tensor += 1
if "aten::quantize_per_channel" in n.kind():
quantize_per_channel += 1
if "quantized::linear_dynamic" in n.kind():
quantized_linear_dynamic += 1
if n.kind() == "prim::GetAttr":
output = n.outputsAt(0)
output_type = output.type()
if "LinearPackedParamsBase" in output_type.str():
linear_packed_params += 1
if n.kind() == "prim::SetAttr":
num_setattr += 1
self.assertEqual(quantize_per_tensor, 0)
self.assertEqual(quantize_per_channel, 0)
self.assertEqual(quantized_linear_dynamic, num_nodes)
self.assertEqual(linear_packed_params, num_nodes)
# self.assertEqual(num_setattr, 0)
def _check_quantize_forward(self, model, num_nodes):
qconfig_dict = {"": default_dynamic_qconfig}
m = OnDevicePTQUtils.ptq_dynamic_quantize(model, qconfig_dict)
self._validate_packed_params(m, num_nodes)
self._validate_no_linear_unpack(m)
self._validate_setattr_fp_weights(m, num_nodes)
qconfig_dict = {"": per_channel_dynamic_qconfig}
m = OnDevicePTQUtils.ptq_dynamic_quantize(model, qconfig_dict)
self._validate_packed_params(m, num_nodes, num_nodes)
self._validate_no_linear_unpack(m)
self._validate_setattr_fp_weights(m, num_nodes)
def _check_quantized_forward(self, model, num_nodes):
qconfig_dict = {"": default_dynamic_qconfig}
m = OnDevicePTQUtils.ptq_dynamic_quantize(model, qconfig_dict)
self._validate_quantized_forward(m, num_nodes)
qconfig_dict = {"": per_channel_dynamic_qconfig}
m = OnDevicePTQUtils.ptq_dynamic_quantize(model, qconfig_dict)
self._validate_quantized_forward(m, num_nodes)
def _check_against_ref_dynamic_ptq(self, model):
model.eval()
inputs = model.get_example_inputs()
ref_m = torch.jit.script(model)
torch._C._jit_pass_inline(ref_m.graph)
qconfig_dict = {"": default_dynamic_qconfig}
ref_m = prepare_dynamic_jit(ref_m, qconfig_dict)
ref_m = convert_dynamic_jit(ref_m)
ref_output = ref_m(*inputs)
m = OnDevicePTQUtils.ptq_dynamic_quantize(model, qconfig_dict)
m.observe_forward(*inputs)
m.quantize_forward(*inputs)
output = m.quantized_forward(*inputs)
self.assertTrue(torch.allclose(ref_output, output))
thrown = False
try:
m(*inputs)
except Exception:
thrown = True
self.assertTrue(thrown)
# test with per channel quant
ref_m = torch.jit.script(model)
torch._C._jit_pass_inline(ref_m.graph)
qconfig_dict = {"": per_channel_dynamic_qconfig}
ref_m = prepare_dynamic_jit(ref_m, qconfig_dict)
ref_m = convert_dynamic_jit(ref_m)
ref_output = ref_m(*inputs)
m = OnDevicePTQUtils.ptq_dynamic_quantize(model, qconfig_dict)
m.observe_forward(*inputs)
m.quantize_forward(*inputs)
output = m.quantized_forward(*inputs)
self.assertTrue(torch.allclose(ref_output, output))
thrown = False
try:
m(*inputs)
except Exception:
thrown = True
self.assertTrue(thrown)
def _check_serdes_and_device_side_api_helper(
self, model, check_device_side_api=False
):
model.eval()
inputs = model.get_example_inputs()
ref_m = torch.jit.script(model)
torch._C._jit_pass_inline(ref_m.graph)
qconfig_dict = {"": default_dynamic_qconfig}
ref_m = prepare_dynamic_jit(ref_m, qconfig_dict)
ref_m = convert_dynamic_jit(ref_m)
buffer = io.BytesIO()
torch.jit.save(ref_m, buffer)
buffer.seek(0)
ref_m = torch.jit.load(buffer)
ref_output = ref_m(*inputs)
if not check_device_side_api:
m = OnDevicePTQUtils.ptq_dynamic_quantize(model, qconfig_dict)
buffer = io.BytesIO()
torch.jit.save(m, buffer)
buffer.seek(0)
m = torch.jit.load(buffer)
m.reset_observers_forward()
m.observe_forward(*inputs)
m.quantize_forward(*inputs)
output = m.quantized_forward(*inputs)
self.assertTrue(torch.allclose(ref_output, output))
else:
# check for lite interpreter
m = OnDevicePTQUtils.ptq_dynamic_quantize(model, qconfig_dict)
(first_input,) = inputs
rand_input = bundled_inputs.bundle_randn(
first_input.size(), dtype=first_input.dtype
)
m = bundled_inputs.bundle_inputs(m, inputs=[(rand_input,)])
buffer = io.BytesIO(m._save_to_buffer_for_lite_interpreter())
buffer.seek(0)
m = _load_for_lite_interpreter(buffer) # Error here
torch._C._quantize_ondevice_ptq_dynamic(m._c, "forward")
self.assertFalse(m.find_method("quantized_forward"))
self.assertFalse(m.find_method("quantize_forward"))
self.assertFalse(m.find_method("observe_forward"))
self.assertFalse(m.find_method("reset_observers_forward"))
output = m(*inputs)
self.assertTrue(torch.allclose(ref_output, output))
# Now serialize to flabuffer and load from fb and check
dict_: dict[str, str] = {}
bytes = torch._C._save_mobile_module_to_bytes(m._c, dict_)
m = LiteScriptModule(torch._C._load_mobile_module_from_bytes(bytes))
fb_output = m(*inputs)
self.assertTrue(torch.allclose(ref_output, fb_output))
model.eval()
inputs = model.get_example_inputs()
ref_m = torch.jit.script(model)
torch._C._jit_pass_inline(ref_m.graph)
qconfig_dict = {"": per_channel_dynamic_qconfig}
ref_m = prepare_dynamic_jit(ref_m, qconfig_dict)
ref_m = convert_dynamic_jit(ref_m)
buffer = io.BytesIO()
torch.jit.save(ref_m, buffer)
buffer.seek(0)
ref_m = torch.jit.load(buffer)
ref_output = ref_m(*inputs)
if not check_device_side_api:
m = OnDevicePTQUtils.ptq_dynamic_quantize(model, qconfig_dict)
buffer = io.BytesIO()
torch.jit.save(m, buffer)
buffer.seek(0)
m = torch.jit.load(buffer)
m.reset_observers_forward()
m.observe_forward(*inputs)
m.quantize_forward(*inputs)
output = m.quantized_forward(*inputs)
self.assertTrue(torch.allclose(ref_output, output))
else:
# check for lite interpreter
m = OnDevicePTQUtils.ptq_dynamic_quantize(model, qconfig_dict)
(first_input,) = inputs
rand_input = bundled_inputs.bundle_randn(
first_input.size(), dtype=first_input.dtype
)
m = bundled_inputs.bundle_inputs(m, inputs=[(rand_input,)])
buffer = io.BytesIO(m._save_to_buffer_for_lite_interpreter())
buffer.seek(0)
m = _load_for_lite_interpreter(buffer) # Error here
torch._C._quantize_ondevice_ptq_dynamic(m._c, "forward")
self.assertFalse(m.find_method("quantized_forward"))
self.assertFalse(m.find_method("quantize_forward"))
self.assertFalse(m.find_method("observe_forward"))
self.assertFalse(m.find_method("reset_observers_forward"))
output = m(*inputs)
self.assertTrue(torch.allclose(ref_output, output))
def _check_serialization_deserialization(self, model):
self._check_serdes_and_device_side_api_helper(model, False)
def _check_device_side_api(self, model):
self._check_serdes_and_device_side_api_helper(model, True)
def test_quantize_forward(self):
model = LinearAddModel()
self._check_quantize_forward(model, 2)
model = MyConvLinearModule()
self._check_quantize_forward(model, 3)
def test_quantized_forward(self):
model = LinearAddModel()
self._check_quantized_forward(model, 2)
model = MyConvLinearModule()
self._check_quantized_forward(model, 3)
def test_against_offdevice_dynamic_ptq(self):
model = LinearAddModel()
self._check_against_ref_dynamic_ptq(model)
model = MyConvLinearModule()
self._check_against_ref_dynamic_ptq(model)
def test_serialization_deserialization(self):
model = MyConvLinearModule()
self._check_serialization_deserialization(model)
def test_device_side_api(self):
model = MyConvLinearModule()
self._check_device_side_api(model)
if __name__ == "__main__":
raise RuntimeError(
"This test is not currently used and should be "
"enabled in discover_tests.py if required."
)
| TestOnDeviceDynamicPTQFinalize |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/translator.py | {
"start": 1308,
"end": 1854
} | class ____:
table_name: str
stream_prefix: Optional[str]
stream_name: str
json_schema: Mapping[str, Any]
connection_id: str
connection_name: str
destination_type: Optional[str]
database: Optional[str]
schema: Optional[str]
@property
def fully_qualified_table_name(self) -> Optional[str]:
return (
f"{self.database}.{self.schema}.{self.stream_name}"
if self.database and self.schema
else None
)
@whitelist_for_serdes
@record
| AirbyteConnectionTableProps |
python | django-haystack__django-haystack | haystack/query.py | {
"start": 23711,
"end": 24415
} | class ____(ValuesListSearchQuerySet):
"""
A ``SearchQuerySet`` which returns a list of dictionaries, each containing
the key/value pairs for the result, exactly like Django's
``ValuesQuerySet``.
"""
def _fill_cache(self, start, end):
query_fields = set(self._internal_fields)
query_fields.update(self._fields)
kwargs = {"fields": query_fields}
return super(ValuesListSearchQuerySet, self)._fill_cache(start, end, **kwargs)
def post_process_results(self, results):
to_cache = []
for result in results:
to_cache.append({i: getattr(result, i, None) for i in self._fields})
return to_cache
| ValuesSearchQuerySet |
python | doocs__leetcode | solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/Solution2.py | {
"start": 127,
"end": 660
} | class ____:
def __init__(self):
self.good = []
self.bad = []
def add(self, name: str, score: int) -> None:
score, node = heappushpop(self.good, (score, Node(name)))
heappush(self.bad, (-score, node.s))
def get(self) -> str:
score, name = heappop(self.bad)
heappush(self.good, (-score, Node(name)))
return self.good[0][1].s
# Your SORTracker object will be instantiated and called as such:
# obj = SORTracker()
# obj.add(name,score)
# param_2 = obj.get()
| SORTracker |
python | plotly__plotly.py | plotly/graph_objs/histogram2d/_xbins.py | {
"start": 233,
"end": 7476
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "histogram2d"
_path_str = "histogram2d.xbins"
_valid_props = {"end", "size", "start"}
@property
def end(self):
"""
Sets the end value for the x axis bins. The last bin may not
end exactly at this value, we increment the bin edge by `size`
from `start` until we reach or exceed `end`. Defaults to the
maximum data value. Like `start`, for dates use a date string,
and for category data `end` is based on the category serial
numbers.
The 'end' property accepts values of any type
Returns
-------
Any
"""
return self["end"]
@end.setter
def end(self, val):
self["end"] = val
@property
def size(self):
"""
Sets the size of each x axis bin. Default behavior: If `nbinsx`
is 0 or omitted, we choose a nice round bin size such that the
number of bins is about the same as the typical number of
samples in each bin. If `nbinsx` is provided, we choose a nice
round bin size giving no more than that many bins. For date
data, use milliseconds or "M<n>" for months, as in
`axis.dtick`. For category data, the number of categories to
bin together (always defaults to 1).
The 'size' property accepts values of any type
Returns
-------
Any
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def start(self):
"""
Sets the starting value for the x axis bins. Defaults to the
minimum data value, shifted down if necessary to make nice
round values and to remove ambiguous bin edges. For example, if
most of the data is integers we shift the bin edges 0.5 down,
so a `size` of 5 would have a default `start` of -0.5, so it is
clear that 0-4 are in the first bin, 5-9 in the second, but
continuous data gets a start of 0 and bins [0,5), [5,10) etc.
Dates behave similarly, and `start` should be a date string.
For category data, `start` is based on the category serial
numbers, and defaults to -0.5.
The 'start' property accepts values of any type
Returns
-------
Any
"""
return self["start"]
@start.setter
def start(self, val):
self["start"] = val
@property
def _prop_descriptions(self):
return """\
end
Sets the end value for the x axis bins. The last bin
may not end exactly at this value, we increment the bin
edge by `size` from `start` until we reach or exceed
`end`. Defaults to the maximum data value. Like
`start`, for dates use a date string, and for category
data `end` is based on the category serial numbers.
size
Sets the size of each x axis bin. Default behavior: If
`nbinsx` is 0 or omitted, we choose a nice round bin
size such that the number of bins is about the same as
the typical number of samples in each bin. If `nbinsx`
is provided, we choose a nice round bin size giving no
more than that many bins. For date data, use
milliseconds or "M<n>" for months, as in `axis.dtick`.
For category data, the number of categories to bin
together (always defaults to 1).
start
Sets the starting value for the x axis bins. Defaults
to the minimum data value, shifted down if necessary to
make nice round values and to remove ambiguous bin
edges. For example, if most of the data is integers we
shift the bin edges 0.5 down, so a `size` of 5 would
have a default `start` of -0.5, so it is clear that 0-4
are in the first bin, 5-9 in the second, but continuous
data gets a start of 0 and bins [0,5), [5,10) etc.
Dates behave similarly, and `start` should be a date
string. For category data, `start` is based on the
category serial numbers, and defaults to -0.5.
"""
def __init__(self, arg=None, end=None, size=None, start=None, **kwargs):
"""
Construct a new XBins object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.histogram2d.XBins`
end
Sets the end value for the x axis bins. The last bin
may not end exactly at this value, we increment the bin
edge by `size` from `start` until we reach or exceed
`end`. Defaults to the maximum data value. Like
`start`, for dates use a date string, and for category
data `end` is based on the category serial numbers.
size
Sets the size of each x axis bin. Default behavior: If
`nbinsx` is 0 or omitted, we choose a nice round bin
size such that the number of bins is about the same as
the typical number of samples in each bin. If `nbinsx`
is provided, we choose a nice round bin size giving no
more than that many bins. For date data, use
milliseconds or "M<n>" for months, as in `axis.dtick`.
For category data, the number of categories to bin
together (always defaults to 1).
start
Sets the starting value for the x axis bins. Defaults
to the minimum data value, shifted down if necessary to
make nice round values and to remove ambiguous bin
edges. For example, if most of the data is integers we
shift the bin edges 0.5 down, so a `size` of 5 would
have a default `start` of -0.5, so it is clear that 0-4
are in the first bin, 5-9 in the second, but continuous
data gets a start of 0 and bins [0,5), [5,10) etc.
Dates behave similarly, and `start` should be a date
string. For category data, `start` is based on the
category serial numbers, and defaults to -0.5.
Returns
-------
XBins
"""
super().__init__("xbins")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.histogram2d.XBins
constructor must be a dict or
an instance of :class:`plotly.graph_objs.histogram2d.XBins`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("end", arg, end)
self._set_property("size", arg, size)
self._set_property("start", arg, start)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| XBins |
python | getsentry__sentry | tests/sentry/seer/similarity/test_utils.py | {
"start": 39804,
"end": 40116
} | class ____(TestCase):
def test_filter_null_from_string(self) -> None:
string_with_null = 'String with null \x00, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" is null'
assert filter_null_from_string(string_with_null) == 'String with null , "" is null'
| SeerUtilsTest |
python | aimacode__aima-python | search.py | {
"start": 53162,
"end": 55316
} | class ____(Problem):
"""Delegates to a problem, and keeps statistics."""
def __init__(self, problem):
self.problem = problem
self.succs = self.goal_tests = self.states = 0
self.found = None
def actions(self, state):
self.succs += 1
return self.problem.actions(state)
def result(self, state, action):
self.states += 1
return self.problem.result(state, action)
def goal_test(self, state):
self.goal_tests += 1
result = self.problem.goal_test(state)
if result:
self.found = state
return result
def path_cost(self, c, state1, action, state2):
return self.problem.path_cost(c, state1, action, state2)
def value(self, state):
return self.problem.value(state)
def __getattr__(self, attr):
return getattr(self.problem, attr)
def __repr__(self):
return '<{:4d}/{:4d}/{:4d}/{}>'.format(self.succs, self.goal_tests,
self.states, str(self.found)[:4])
def compare_searchers(problems, header,
searchers=[breadth_first_tree_search,
breadth_first_graph_search,
depth_first_graph_search,
iterative_deepening_search,
depth_limited_search,
recursive_best_first_search]):
def do(searcher, problem):
p = InstrumentedProblem(problem)
searcher(p)
return p
table = [[name(s)] + [do(s, p) for p in problems] for s in searchers]
print_table(table, header)
def compare_graph_searchers():
"""Prints a table of search results."""
compare_searchers(problems=[GraphProblem('Arad', 'Bucharest', romania_map),
GraphProblem('Oradea', 'Neamt', romania_map),
GraphProblem('Q', 'WA', australia_map)],
header=['Searcher', 'romania_map(Arad, Bucharest)',
'romania_map(Oradea, Neamt)', 'australia_map'])
| InstrumentedProblem |
python | mahmoud__glom | glom/core.py | {
"start": 27027,
"end": 28618
} | class ____:
"""Spec objects serve three purposes, here they are, roughly ordered
by utility:
1. As a form of compiled or "curried" glom call, similar to
Python's built-in :func:`re.compile`.
2. A marker as an object as representing a spec rather than a
literal value in certain cases where that might be ambiguous.
3. A way to update the scope within another Spec.
In the second usage, Spec objects are the complement to
:class:`~glom.Val`, wrapping a value and marking that it
should be interpreted as a glom spec, rather than a literal value.
This is useful in places where it would be interpreted as a value
by default. (Such as T[key], Call(func) where key and func are
assumed to be literal values and not specs.)
Args:
spec: The glom spec.
scope (dict): additional values to add to the scope when
evaluating this Spec
"""
def __init__(self, spec, scope=None):
self.spec = spec
self.scope = scope or {}
def glom(self, target, **kw):
scope = dict(self.scope)
scope.update(kw.get('scope', {}))
kw['scope'] = ChainMap(scope)
glom_ = scope.get(glom, glom)
return glom_(target, self.spec, **kw)
def glomit(self, target, scope):
scope.update(self.scope)
return scope[glom](target, self.spec, scope)
def __repr__(self):
cn = self.__class__.__name__
if self.scope:
return f'{cn}({bbrepr(self.spec)}, scope={self.scope!r})'
return f'{cn}({bbrepr(self.spec)})'
| Spec |
python | zarr-developers__zarr-python | src/zarr/codecs/sharding.py | {
"start": 2594,
"end": 3122
} | class ____(_ShardingByteGetter, ByteSetter):
shard_dict: ShardMutableMapping
async def set(self, value: Buffer, byte_range: ByteRequest | None = None) -> None:
assert byte_range is None, "byte_range is not supported within shards"
self.shard_dict[self.chunk_coords] = value
async def delete(self) -> None:
del self.shard_dict[self.chunk_coords]
async def set_if_not_exists(self, default: Buffer) -> None:
self.shard_dict.setdefault(self.chunk_coords, default)
| _ShardingByteSetter |
python | weaviate__weaviate-python-client | weaviate/users/sync.py | {
"start": 296,
"end": 384
} | class ____(_UsersOIDCExecutor[ConnectionSync]):
pass
@executor.wrap("sync")
| _UsersOIDC |
python | getsentry__sentry | tests/sentry/receivers/test_data_forwarding.py | {
"start": 240,
"end": 6226
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.organization = self.create_organization()
self.project = self.create_project(organization=self.organization)
def test_auto_enrollment_when_enroll_new_projects_enabled(self) -> None:
data_forwarder = DataForwarder.objects.create(
organization=self.organization,
is_enabled=True,
enroll_new_projects=True,
provider="segment",
config={"write_key": "test_key"},
)
new_project = self.create_project(organization=self.organization, fire_project_created=True)
enrollment = DataForwarderProject.objects.filter(
data_forwarder=data_forwarder, project=new_project
).first()
assert enrollment is not None
assert enrollment.is_enabled is True
assert enrollment.overrides == {}
def test_no_enrollment_when_enroll_new_projects_disabled(self) -> None:
data_forwarder = DataForwarder.objects.create(
organization=self.organization,
is_enabled=True,
enroll_new_projects=False,
provider="segment",
config={"write_key": "test_key"},
)
new_project = self.create_project(organization=self.organization, fire_project_created=True)
# Verify the project was not enrolled
enrollment = DataForwarderProject.objects.filter(
data_forwarder=data_forwarder, project=new_project
).first()
assert enrollment is None
def test_no_enrollment_when_data_forwarder_disabled(self) -> None:
data_forwarder = DataForwarder.objects.create(
organization=self.organization,
is_enabled=False,
enroll_new_projects=True,
provider="segment",
config={"write_key": "test_key"},
)
new_project = self.create_project(organization=self.organization, fire_project_created=True)
enrollment = DataForwarderProject.objects.filter(
data_forwarder=data_forwarder, project=new_project
).first()
assert enrollment is None
def test_no_duplicate_enrollment_when_project_already_enrolled(self) -> None:
data_forwarder = DataForwarder.objects.create(
organization=self.organization,
is_enabled=True,
enroll_new_projects=True,
provider="segment",
config={"write_key": "test_key"},
)
DataForwarderProject.objects.create(
data_forwarder=data_forwarder,
project=self.project,
is_enabled=True,
overrides={"custom_key": "custom_value"},
)
project_created.send_robust(
project=self.project,
user=self.create_user(),
default_rules=True,
sender=self.__class__,
)
enrollments = DataForwarderProject.objects.filter(
data_forwarder=data_forwarder, project=self.project
)
assert enrollments.count() == 1
enrollment = enrollments.first()
assert enrollment is not None
assert enrollment.overrides == {"custom_key": "custom_value"}
def test_multiple_data_forwarders_enroll_same_project(self) -> None:
segment_forwarder = DataForwarder.objects.create(
organization=self.organization,
is_enabled=True,
enroll_new_projects=True,
provider="segment",
config={"write_key": "segment_key"},
)
sqs_forwarder = DataForwarder.objects.create(
organization=self.organization,
is_enabled=True,
enroll_new_projects=True,
provider="sqs",
config={"queue_url": "test_queue"},
)
new_project = self.create_project(organization=self.organization, fire_project_created=True)
segment_enrollment = DataForwarderProject.objects.filter(
data_forwarder=segment_forwarder, project=new_project
).first()
assert segment_enrollment is not None
assert segment_enrollment.is_enabled is True
sqs_enrollment = DataForwarderProject.objects.filter(
data_forwarder=sqs_forwarder, project=new_project
).first()
assert sqs_enrollment is not None
assert sqs_enrollment.is_enabled is True
def test_mixed_data_forwarders_only_enroll_into_some(self) -> None:
enabled_forwarder = DataForwarder.objects.create(
organization=self.organization,
is_enabled=True,
enroll_new_projects=True,
provider="segment",
config={"write_key": "segment_key"},
)
disabled_forwarder = DataForwarder.objects.create(
organization=self.organization,
is_enabled=False,
enroll_new_projects=True,
provider="sqs",
config={"queue_url": "test_queue"},
)
no_auto_enroll_forwarder = DataForwarder.objects.create(
organization=self.organization,
is_enabled=True,
enroll_new_projects=False,
provider="splunk",
config={"endpoint": "test_endpoint"},
)
new_project = self.create_project(organization=self.organization, fire_project_created=True)
enabled_enrollment = DataForwarderProject.objects.filter(
data_forwarder=enabled_forwarder, project=new_project
).first()
assert enabled_enrollment is not None
disabled_enrollment = DataForwarderProject.objects.filter(
data_forwarder=disabled_forwarder, project=new_project
).first()
assert disabled_enrollment is None
no_auto_enroll_enrollment = DataForwarderProject.objects.filter(
data_forwarder=no_auto_enroll_forwarder, project=new_project
).first()
assert no_auto_enroll_enrollment is None
| DataForwardingReceiverTest |
python | tensorflow__tensorflow | tensorflow/python/training/adadelta_test.py | {
"start": 1224,
"end": 7973
} | class ____(test.TestCase):
def doTestBasic(self, use_resource=False, use_callable_params=False):
num_updates = 4 # number of ADADELTA steps to perform
for dtype in [dtypes.half, dtypes.float32]:
for grad in [0.2, 0.1, 0.01]:
for lr in [1.0, 0.5, 0.1]:
var0_init = [1.0, 2.0]
var1_init = [3.0, 4.0]
if use_resource:
var0 = resource_variable_ops.ResourceVariable(
var0_init, dtype=dtype)
var1 = resource_variable_ops.ResourceVariable(
var1_init, dtype=dtype)
else:
var0 = variables.Variable(var0_init, dtype=dtype)
var1 = variables.Variable(var1_init, dtype=dtype)
grads = constant_op.constant([grad, grad], dtype=dtype)
accum = 0.0
accum_update = 0.0
# ADADELTA gradient optimizer
rho = 0.95
epsilon = 1e-8
if use_callable_params:
adadelta_opt = adadelta.AdadeltaOptimizer(
learning_rate=lambda: lr, # pylint: disable=cell-var-from-loop
rho=lambda: rho, # pylint: disable=cell-var-from-loop
epsilon=lambda: epsilon) # pylint: disable=cell-var-from-loop
else:
adadelta_opt = adadelta.AdadeltaOptimizer(
learning_rate=lr, rho=rho, epsilon=epsilon)
if not context.executing_eagerly():
adadelta_update = adadelta_opt.apply_gradients(
zip([grads, grads], [var0, var1]))
self.evaluate(variables.global_variables_initializer())
# TODO(lxuechen): This is hard to test in eager mode,
# since the optimizer is not fully initialized until the first
# call to `apply_gradients`
opt_vars = adadelta_opt.variables()
self.assertStartsWith(opt_vars[0].name, var0._shared_name)
self.assertStartsWith(opt_vars[1].name, var0._shared_name)
self.assertStartsWith(opt_vars[2].name, var1._shared_name)
self.assertStartsWith(opt_vars[3].name, var1._shared_name)
self.assertEqual(4, len(opt_vars))
# Assign slots
slot = [None] * 2
slot_update = [None] * 2
self.assertEqual(["accum", "accum_update"],
adadelta_opt.get_slot_names())
slot[0] = adadelta_opt.get_slot(var0, "accum")
self.assertEqual(slot[0].get_shape(), var0.get_shape())
self.assertFalse(slot[0] in variables.trainable_variables())
slot_update[0] = adadelta_opt.get_slot(var0, "accum_update")
self.assertEqual(slot_update[0].get_shape(), var0.get_shape())
self.assertFalse(slot_update[0] in variables.trainable_variables())
slot[1] = adadelta_opt.get_slot(var1, "accum")
self.assertEqual(slot[1].get_shape(), var1.get_shape())
self.assertFalse(slot[1] in variables.trainable_variables())
slot_update[1] = adadelta_opt.get_slot(var1, "accum_update")
self.assertEqual(slot_update[1].get_shape(), var1.get_shape())
self.assertFalse(slot_update[1] in variables.trainable_variables())
# Fetch params to validate initial values
self.assertAllClose(var0_init, self.evaluate(var0))
self.assertAllClose(var1_init, self.evaluate(var1))
update = [None] * num_updates
tot_update = 0
for step in range(num_updates):
# Run adadelta update for comparison
if not context.executing_eagerly():
self.evaluate(adadelta_update)
else:
adadelta_opt.apply_gradients(zip([grads, grads], [var0, var1]))
# Perform initial update without previous accum values
accum = accum * rho + (grad**2) * (1 - rho)
update[step] = (
np.sqrt(accum_update + epsilon) *
(1. / np.sqrt(accum + epsilon)) * grad)
accum_update = (
accum_update * rho + (update[step]**2) * (1.0 - rho))
tot_update += update[step] * lr
if not context.executing_eagerly():
# Check that the accumulators have been updated
# TODO(lxuechen): This is hard to test in eager mode
for slot_idx in range(2):
self.assertAllCloseAccordingToType(
np.array([accum, accum], dtype=dtype.as_numpy_dtype()),
self.evaluate(slot[slot_idx]),
rtol=1e-5)
self.assertAllCloseAccordingToType(
np.array(
[accum_update, accum_update],
dtype=dtype.as_numpy_dtype()),
self.evaluate(slot_update[slot_idx]),
rtol=1e-5)
# Check that the parameters have been updated
self.assertAllCloseAccordingToType(
np.array(
[var0_init[0] - tot_update, var0_init[1] - tot_update],
dtype=dtype.as_numpy_dtype()),
self.evaluate(var0),
rtol=1e-5)
self.assertAllCloseAccordingToType(
np.array(
[var1_init[0] - tot_update, var1_init[1] - tot_update],
dtype=dtype.as_numpy_dtype()),
self.evaluate(var1),
rtol=1e-5)
def testBasic(self):
with self.cached_session():
self.doTestBasic(use_resource=False)
@test_util.run_in_graph_and_eager_modes
def testResourceBasic(self):
self.doTestBasic(use_resource=True)
def testBasicCallableParams(self):
with context.eager_mode():
self.doTestBasic(use_resource=True, use_callable_params=True)
@test_util.run_deprecated_v1
def testMinimizeSparseResourceVariable(self):
for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:
with self.cached_session():
var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype)
x = constant_op.constant([[4.0], [5.0]], dtype=dtype)
pred = math_ops.matmul(embedding_ops.embedding_lookup([var0], [0]), x)
loss = pred * pred
sgd_op = adadelta.AdadeltaOptimizer(
1.0, 1.0, 1.0).minimize(loss)
self.evaluate(variables.global_variables_initializer())
# Fetch params to validate initial values
self.assertAllCloseAccordingToType([[1.0, 2.0]], self.evaluate(var0))
# Run 1 step of sgd
sgd_op.run()
# Validate updated params
self.assertAllCloseAccordingToType([[-111, -138]], self.evaluate(var0))
if __name__ == "__main__":
test.main()
| AdadeltaOptimizerTest |
python | doocs__leetcode | solution/2500-2599/2549.Count Distinct Numbers on Board/Solution.py | {
"start": 0,
"end": 92
} | class ____:
def distinctIntegers(self, n: int) -> int:
return max(1, n - 1)
| Solution |
python | django__django | tests/admin_views/admin.py | {
"start": 16899,
"end": 16969
} | class ____(admin.ModelAdmin):
search_fields = ("name",)
| StudentAdmin |
python | bokeh__bokeh | src/bokeh/core/validation/issue.py | {
"start": 2077,
"end": 2945
} | class ____(Issue):
_code_map: ClassVar[dict[int, Error]] = {}
_name_map: ClassVar[dict[str, Error]] = {}
def __post_init__(self) -> None:
Error._code_map[self.code] = self
Error._name_map[self.name] = self
@classmethod
def get_by_code(cls, code: int) -> Error:
return cls._code_map[code]
@classmethod
def get_by_name(cls, name: str) -> Error:
return cls._name_map[name]
@classmethod
def all(cls) -> list[Error]:
return list(cls._code_map.values())
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| Error |
python | pytorch__pytorch | torch/nn/modules/conv.py | {
"start": 72514,
"end": 75564
} | class ____(_LazyConvXdMixin, ConvTranspose2d): # type: ignore[misc]
r"""A :class:`torch.nn.ConvTranspose2d` module with lazy initialization of the ``in_channels`` argument.
The ``in_channels`` argument of the :class:`ConvTranspose2d` is inferred from
the ``input.size(1)``.
The attributes that will be lazily initialized are `weight` and `bias`.
Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
on lazy modules and their limitations.
Args:
out_channels (int): Number of channels produced by the convolution
kernel_size (int or tuple): Size of the convolving kernel
stride (int or tuple, optional): Stride of the convolution. Default: 1
padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding
will be added to both sides of each dimension in the input. Default: 0
output_padding (int or tuple, optional): Additional size added to one side
of each dimension in the output shape. Default: 0
groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``
dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
.. seealso:: :class:`torch.nn.ConvTranspose2d` and :class:`torch.nn.modules.lazy.LazyModuleMixin`
"""
# super class define this variable as None. "type: ignore[..] is required
# since we are redefining the variable.
cls_to_become = ConvTranspose2d # type: ignore[assignment]
def __init__(
self,
out_channels: int,
kernel_size: _size_2_t,
stride: _size_2_t = 1,
padding: _size_2_t = 0,
output_padding: _size_2_t = 0,
groups: int = 1,
bias: bool = True,
dilation: int = 1,
padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
device=None,
dtype=None,
) -> None:
factory_kwargs = {"device": device, "dtype": dtype}
# pyrefly: ignore [bad-argument-type]
super().__init__(
0,
0,
kernel_size,
stride,
padding,
output_padding,
groups,
# bias is hardcoded to False to avoid creating tensor
# that will soon be overwritten.
False,
dilation,
padding_mode,
**factory_kwargs,
)
# pyrefly: ignore [bad-override, bad-argument-type]
self.weight = UninitializedParameter(**factory_kwargs)
self.out_channels = out_channels
if bias:
# pyrefly: ignore [bad-override, bad-argument-type]
self.bias = UninitializedParameter(**factory_kwargs)
def _get_num_spatial_dims(self) -> int:
return 2
# LazyConvTranspose3d defines weight as a Tensor but derived class defines it as UninitializeParameter
| LazyConvTranspose2d |
python | ray-project__ray | python/ray/dashboard/modules/job/tests/test_cli_integration.py | {
"start": 3761,
"end": 5823
} | class ____:
"""
Integration version of job CLI test that ensures interaction with the
following components are working as expected:
1) Ray client: use of RAY_ADDRESS and ray.init() in job_head.py
2) Ray dashboard: `ray start --head`
"""
def test_empty_ray_address(self, ray_start_stop):
with set_env_var("RAY_ADDRESS", None):
stdout, _ = _run_cmd("ray job submit -- echo hello")
assert "hello" in stdout
assert "succeeded" in stdout
@pytest.mark.parametrize(
"ray_api_server_address,should_fail",
[
("http://127.0.0.1:8265", False), # correct API server
("127.0.0.1:8265", True), # wrong format without http
("http://127.0.0.1:9999", True), # wrong port
],
)
def test_ray_api_server_address(
self,
ray_start_stop,
ray_api_server_address: str,
should_fail: bool,
):
# Set a `RAY_ADDRESS` that would not work with the `ray job submit` CLI because it uses the `ray://` prefix.
# This verifies that the `RAY_API_SERVER_ADDRESS` env var takes precedence.
with set_env_var("RAY_ADDRESS", "ray://127.0.0.1:8265"):
with set_env_var("RAY_API_SERVER_ADDRESS", ray_api_server_address):
_run_cmd("ray job submit -- echo hello", should_fail=should_fail)
@pytest.mark.parametrize(
"ray_client_address,should_fail",
[
("127.0.0.1:8265", True),
("ray://127.0.0.1:8265", True),
("http://127.0.0.1:8265", False),
],
)
def test_ray_client_address(
self, ray_start_stop, ray_client_address: str, should_fail: bool
):
with set_env_var("RAY_ADDRESS", ray_client_address):
_run_cmd("ray job submit -- echo hello", should_fail=should_fail)
def test_valid_http_ray_address(self, ray_start_stop):
stdout, _ = _run_cmd("ray job submit -- echo hello")
assert "hello" in stdout
assert "succeeded" in stdout
| TestRayAddress |
python | TheAlgorithms__Python | divide_and_conquer/convex_hull.py | {
"start": 675,
"end": 16233
} | class ____:
"""
Defines a 2-d point for use by all convex-hull algorithms.
Parameters
----------
x: an int or a float, the x-coordinate of the 2-d point
y: an int or a float, the y-coordinate of the 2-d point
Examples
--------
>>> Point(1, 2)
(1.0, 2.0)
>>> Point("1", "2")
(1.0, 2.0)
>>> Point(1, 2) > Point(0, 1)
True
>>> Point(1, 1) == Point(1, 1)
True
>>> Point(-0.5, 1) == Point(0.5, 1)
False
>>> Point("pi", "e")
Traceback (most recent call last):
...
ValueError: could not convert string to float: 'pi'
"""
def __init__(self, x, y):
self.x, self.y = float(x), float(y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __ne__(self, other):
return not self == other
def __gt__(self, other):
if self.x > other.x:
return True
elif self.x == other.x:
return self.y > other.y
return False
def __lt__(self, other):
return not self > other
def __ge__(self, other):
if self.x > other.x:
return True
elif self.x == other.x:
return self.y >= other.y
return False
def __le__(self, other):
if self.x < other.x:
return True
elif self.x == other.x:
return self.y <= other.y
return False
def __repr__(self):
return f"({self.x}, {self.y})"
def __hash__(self):
return hash(self.x)
def _construct_points(
list_of_tuples: list[Point] | list[list[float]] | Iterable[list[float]],
) -> list[Point]:
"""
constructs a list of points from an array-like object of numbers
Arguments
---------
list_of_tuples: array-like object of type numbers. Acceptable types so far
are lists, tuples and sets.
Returns
--------
points: a list where each item is of type Point. This contains only objects
which can be converted into a Point.
Examples
-------
>>> _construct_points([[1, 1], [2, -1], [0.3, 4]])
[(1.0, 1.0), (2.0, -1.0), (0.3, 4.0)]
>>> _construct_points([1, 2])
Ignoring deformed point 1. All points must have at least 2 coordinates.
Ignoring deformed point 2. All points must have at least 2 coordinates.
[]
>>> _construct_points([])
[]
>>> _construct_points(None)
[]
"""
points: list[Point] = []
if list_of_tuples:
for p in list_of_tuples:
if isinstance(p, Point):
points.append(p)
else:
try:
points.append(Point(p[0], p[1]))
except (IndexError, TypeError):
print(
f"Ignoring deformed point {p}. All points"
" must have at least 2 coordinates."
)
return points
def _validate_input(points: list[Point] | list[list[float]]) -> list[Point]:
"""
validates an input instance before a convex-hull algorithms uses it
Parameters
---------
points: array-like, the 2d points to validate before using with
a convex-hull algorithm. The elements of points must be either lists, tuples or
Points.
Returns
-------
points: array_like, an iterable of all well-defined Points constructed passed in.
Exception
---------
ValueError: if points is empty or None, or if a wrong data structure like a scalar
is passed
TypeError: if an iterable but non-indexable object (eg. dictionary) is passed.
The exception to this a set which we'll convert to a list before using
Examples
-------
>>> _validate_input([[1, 2]])
[(1.0, 2.0)]
>>> _validate_input([(1, 2)])
[(1.0, 2.0)]
>>> _validate_input([Point(2, 1), Point(-1, 2)])
[(2.0, 1.0), (-1.0, 2.0)]
>>> _validate_input([])
Traceback (most recent call last):
...
ValueError: Expecting a list of points but got []
>>> _validate_input(1)
Traceback (most recent call last):
...
ValueError: Expecting an iterable object but got an non-iterable type 1
"""
if not hasattr(points, "__iter__"):
msg = f"Expecting an iterable object but got an non-iterable type {points}"
raise ValueError(msg)
if not points:
msg = f"Expecting a list of points but got {points}"
raise ValueError(msg)
return _construct_points(points)
def _det(a: Point, b: Point, c: Point) -> float:
"""
Computes the sign perpendicular distance of a 2d point c from a line segment
ab. The sign indicates the direction of c relative to ab.
A Positive value means c is above ab (to the left), while a negative value
means c is below ab (to the right). 0 means all three points are on a straight line.
As a side note, 0.5 * abs|det| is the area of triangle abc
Parameters
----------
a: point, the point on the left end of line segment ab
b: point, the point on the right end of line segment ab
c: point, the point for which the direction and location is desired.
Returns
--------
det: float, abs(det) is the distance of c from ab. The sign
indicates which side of line segment ab c is. det is computed as
(a_xb_y + c_xa_y + b_xc_y) - (a_yb_x + c_ya_x + b_yc_x)
Examples
----------
>>> _det(Point(1, 1), Point(1, 2), Point(1, 5))
0.0
>>> _det(Point(0, 0), Point(10, 0), Point(0, 10))
100.0
>>> _det(Point(0, 0), Point(10, 0), Point(0, -10))
-100.0
"""
det = (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x)
return det
def convex_hull_bf(points: list[Point]) -> list[Point]:
"""
Constructs the convex hull of a set of 2D points using a brute force algorithm.
The algorithm basically considers all combinations of points (i, j) and uses the
definition of convexity to determine whether (i, j) is part of the convex hull or
not. (i, j) is part of the convex hull if and only iff there are no points on both
sides of the line segment connecting the ij, and there is no point k such that k is
on either end of the ij.
Runtime: O(n^3) - definitely horrible
Parameters
---------
points: array-like of object of Points, lists or tuples.
The set of 2d points for which the convex-hull is needed
Returns
------
convex_set: list, the convex-hull of points sorted in non-decreasing order.
See Also
--------
convex_hull_recursive,
Examples
---------
>>> convex_hull_bf([[0, 0], [1, 0], [10, 1]])
[(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]
>>> convex_hull_bf([[0, 0], [1, 0], [10, 0]])
[(0.0, 0.0), (10.0, 0.0)]
>>> convex_hull_bf([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],
... [-0.75, 1]])
[(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]
>>> convex_hull_bf([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),
... (2, -1), (2, -4), (1, -3)])
[(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]
"""
points = sorted(_validate_input(points))
n = len(points)
convex_set = set()
for i in range(n - 1):
for j in range(i + 1, n):
points_left_of_ij = points_right_of_ij = False
ij_part_of_convex_hull = True
for k in range(n):
if k not in {i, j}:
det_k = _det(points[i], points[j], points[k])
if det_k > 0:
points_left_of_ij = True
elif det_k < 0:
points_right_of_ij = True
# point[i], point[j], point[k] all lie on a straight line
# if point[k] is to the left of point[i] or it's to the
# right of point[j], then point[i], point[j] cannot be
# part of the convex hull of A
elif points[k] < points[i] or points[k] > points[j]:
ij_part_of_convex_hull = False
break
if points_left_of_ij and points_right_of_ij:
ij_part_of_convex_hull = False
break
if ij_part_of_convex_hull:
convex_set.update([points[i], points[j]])
return sorted(convex_set)
def convex_hull_recursive(points: list[Point]) -> list[Point]:
"""
Constructs the convex hull of a set of 2D points using a divide-and-conquer strategy
The algorithm exploits the geometric properties of the problem by repeatedly
partitioning the set of points into smaller hulls, and finding the convex hull of
these smaller hulls. The union of the convex hull from smaller hulls is the
solution to the convex hull of the larger problem.
Parameter
---------
points: array-like of object of Points, lists or tuples.
The set of 2d points for which the convex-hull is needed
Runtime: O(n log n)
Returns
-------
convex_set: list, the convex-hull of points sorted in non-decreasing order.
Examples
---------
>>> convex_hull_recursive([[0, 0], [1, 0], [10, 1]])
[(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]
>>> convex_hull_recursive([[0, 0], [1, 0], [10, 0]])
[(0.0, 0.0), (10.0, 0.0)]
>>> convex_hull_recursive([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],
... [-0.75, 1]])
[(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]
>>> convex_hull_recursive([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),
... (2, -1), (2, -4), (1, -3)])
[(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]
"""
points = sorted(_validate_input(points))
n = len(points)
# divide all the points into an upper hull and a lower hull
# the left most point and the right most point are definitely
# members of the convex hull by definition.
# use these two anchors to divide all the points into two hulls,
# an upper hull and a lower hull.
# all points to the left (above) the line joining the extreme points belong to the
# upper hull
# all points to the right (below) the line joining the extreme points below to the
# lower hull
# ignore all points on the line joining the extreme points since they cannot be
# part of the convex hull
left_most_point = points[0]
right_most_point = points[n - 1]
convex_set = {left_most_point, right_most_point}
upper_hull = []
lower_hull = []
for i in range(1, n - 1):
det = _det(left_most_point, right_most_point, points[i])
if det > 0:
upper_hull.append(points[i])
elif det < 0:
lower_hull.append(points[i])
_construct_hull(upper_hull, left_most_point, right_most_point, convex_set)
_construct_hull(lower_hull, right_most_point, left_most_point, convex_set)
return sorted(convex_set)
def _construct_hull(
points: list[Point], left: Point, right: Point, convex_set: set[Point]
) -> None:
"""
Parameters
---------
points: list or None, the hull of points from which to choose the next convex-hull
point
left: Point, the point to the left of line segment joining left and right
right: The point to the right of the line segment joining left and right
convex_set: set, the current convex-hull. The state of convex-set gets updated by
this function
Note
----
For the line segment 'ab', 'a' is on the left and 'b' on the right.
but the reverse is true for the line segment 'ba'.
Returns
-------
Nothing, only updates the state of convex-set
"""
if points:
extreme_point = None
extreme_point_distance = float("-inf")
candidate_points = []
for p in points:
det = _det(left, right, p)
if det > 0:
candidate_points.append(p)
if det > extreme_point_distance:
extreme_point_distance = det
extreme_point = p
if extreme_point:
_construct_hull(candidate_points, left, extreme_point, convex_set)
convex_set.add(extreme_point)
_construct_hull(candidate_points, extreme_point, right, convex_set)
def convex_hull_melkman(points: list[Point]) -> list[Point]:
"""
Constructs the convex hull of a set of 2D points using the melkman algorithm.
The algorithm works by iteratively inserting points of a simple polygonal chain
(meaning that no line segments between two consecutive points cross each other).
Sorting the points yields such a polygonal chain.
For a detailed description, see http://cgm.cs.mcgill.ca/~athens/cs601/Melkman.html
Runtime: O(n log n) - O(n) if points are already sorted in the input
Parameters
---------
points: array-like of object of Points, lists or tuples.
The set of 2d points for which the convex-hull is needed
Returns
------
convex_set: list, the convex-hull of points sorted in non-decreasing order.
See Also
--------
Examples
---------
>>> convex_hull_melkman([[0, 0], [1, 0], [10, 1]])
[(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]
>>> convex_hull_melkman([[0, 0], [1, 0], [10, 0]])
[(0.0, 0.0), (10.0, 0.0)]
>>> convex_hull_melkman([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],
... [-0.75, 1]])
[(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]
>>> convex_hull_melkman([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),
... (2, -1), (2, -4), (1, -3)])
[(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]
"""
points = sorted(_validate_input(points))
n = len(points)
convex_hull = points[:2]
for i in range(2, n):
det = _det(convex_hull[1], convex_hull[0], points[i])
if det > 0:
convex_hull.insert(0, points[i])
break
elif det < 0:
convex_hull.append(points[i])
break
else:
convex_hull[1] = points[i]
i += 1
for j in range(i, n):
if (
_det(convex_hull[0], convex_hull[-1], points[j]) > 0
and _det(convex_hull[-1], convex_hull[0], points[1]) < 0
):
# The point lies within the convex hull
continue
convex_hull.insert(0, points[j])
convex_hull.append(points[j])
while _det(convex_hull[0], convex_hull[1], convex_hull[2]) >= 0:
del convex_hull[1]
while _det(convex_hull[-1], convex_hull[-2], convex_hull[-3]) <= 0:
del convex_hull[-2]
# `convex_hull` is contains the convex hull in circular order
return sorted(convex_hull[1:] if len(convex_hull) > 3 else convex_hull)
def main():
points = [
(0, 3),
(2, 2),
(1, 1),
(2, 1),
(3, 0),
(0, 0),
(3, 3),
(2, -1),
(2, -4),
(1, -3),
]
# the convex set of points is
# [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)]
results_bf = convex_hull_bf(points)
results_recursive = convex_hull_recursive(points)
assert results_bf == results_recursive
results_melkman = convex_hull_melkman(points)
assert results_bf == results_melkman
print(results_bf)
if __name__ == "__main__":
main()
| Point |
python | walkccc__LeetCode | solutions/351. Android Unlock Patterns/351.py | {
"start": 0,
"end": 911
} | class ____:
def numberOfPatterns(self, m: int, n: int) -> int:
seen = set()
accross = [[0] * 10 for _ in range(10)]
accross[1][3] = accross[3][1] = 2
accross[1][7] = accross[7][1] = 4
accross[3][9] = accross[9][3] = 6
accross[7][9] = accross[9][7] = 8
accross[1][9] = accross[9][1] = accross[2][8] = accross[8][2] = \
accross[3][7] = accross[7][3] = accross[4][6] = accross[6][4] = 5
def dfs(u: int, depth: int) -> int:
if depth > n:
return 0
seen.add(u)
ans = 1 if depth >= m else 0
for v in range(1, 10):
if v == u or v in seen:
continue
accrossed = accross[u][v]
if not accrossed or accrossed in seen:
ans += dfs(v, depth + 1)
seen.remove(u)
return ans
# 1, 3, 7, 9 are symmetric
# 2, 4, 6, 8 are symmetric
return dfs(1, 1) * 4 + dfs(2, 1) * 4 + dfs(5, 1)
| Solution |
python | getsentry__sentry | src/sentry/sentry_apps/logic.py | {
"start": 15421,
"end": 23227
} | class ____:
name: str
author: str
organization_id: int
is_internal: bool
scopes: list[str] = dataclasses.field(default_factory=list)
events: list[str] = dataclasses.field(default_factory=list)
webhook_url: str | None = None
redirect_url: str | None = None
is_alertable: bool = False
verify_install: bool = True
schema: Schema = dataclasses.field(default_factory=dict)
overview: str | None = None
allowed_origins: list[str] = dataclasses.field(default_factory=list)
popularity: int | None = None
metadata: dict | None = field(default_factory=dict)
def __post_init__(self) -> None:
if self.is_internal:
assert (
not self.verify_install
), "Internal apps should not require installation verification"
def run(
self,
*,
user: User | RpcUser,
request: HttpRequest | None = None,
skip_default_auth_token: bool = False,
) -> SentryApp:
with SentryAppInteractionEvent(
operation_type=SentryAppInteractionType.MANAGEMENT,
event_type=SentryAppEventType.APP_CREATE,
).capture():
with transaction.atomic(router.db_for_write(User)), in_test_hide_transaction_boundary():
slug = self._generate_and_validate_slug()
proxy = self._create_proxy_user(slug=slug)
api_app = self._create_api_application(proxy=proxy)
sentry_app = self._create_sentry_app(
user=user, slug=slug, proxy=proxy, api_app=api_app
)
self._create_ui_components(sentry_app=sentry_app)
self._create_integration_feature(sentry_app=sentry_app)
if self.is_internal:
install = self._install(slug=slug, user=user, request=request)
if not skip_default_auth_token:
self._create_access_token(user=user, install=install, request=request)
self.audit(request=request, sentry_app=sentry_app)
self.record_analytics(user=user, sentry_app=sentry_app)
return sentry_app
def _generate_and_validate_slug(self) -> str:
# sentry_slugify ensures the slug is not entirely numeric
slug = sentry_slugify(self.name)
# for internal, add some uuid to make it unique
if self.is_internal:
slug = f"{slug}-{default_uuid()[:UUID_CHARS_IN_SLUG]}"
# validate globally unique slug
queryset = SentryApp.with_deleted.filter(slug=slug)
if queryset.exists():
# In reality, the slug is taken but it's determined by the name field
raise ValidationError(
{"name": [f"Name {self.name} is already taken, please use another."]}
)
return slug
def _create_proxy_user(self, slug: str) -> User:
# need a proxy user name that will always be unique
username = f"{slug}-{default_uuid()}"
proxy_user = User.objects.create(
username=username, email=f"{username}@proxy-user.sentry.io", is_sentry_app=True
)
return proxy_user
def _create_api_application(self, proxy: User) -> ApiApplication:
return ApiApplication.objects.create(
owner_id=proxy.id, allowed_origins="\n".join(self.allowed_origins)
)
def _create_sentry_app(
self, user: User | RpcUser, slug: str, proxy: User, api_app: ApiApplication
) -> SentryApp:
kwargs = {
"name": self.name,
"slug": slug,
"author": self.author,
"application_id": api_app.id,
"owner_id": self.organization_id,
"proxy_user_id": proxy.id,
"events": expand_events(self.events),
"schema": self.schema or {},
"webhook_url": self.webhook_url,
"redirect_url": self.redirect_url,
"is_alertable": self.is_alertable,
"verify_install": self.verify_install,
"overview": self.overview,
"popularity": self.popularity or SentryApp._meta.get_field("popularity").default,
"creator_user_id": user.id,
"creator_label": user.email
or user.username, # email is not required for some users (sentry apps)
"metadata": self.metadata if self.metadata else {},
}
if self.scopes is not None:
kwargs["scope_list"] = self.scopes
if self.is_internal:
kwargs["status"] = SentryAppStatus.INTERNAL
return SentryApp.objects.create(**kwargs)
def _create_ui_components(self, sentry_app: SentryApp) -> None:
schema = self.schema or {}
for element in schema.get("elements", []):
SentryAppComponent.objects.create(
type=element["type"], sentry_app_id=sentry_app.id, schema=element
)
def _create_integration_feature(self, sentry_app: SentryApp) -> None:
# sentry apps must have at least one feature
# defaults to 'integrations-api'
try:
with transaction.atomic(router.db_for_write(IntegrationFeature)):
IntegrationFeature.objects.create(
target_id=sentry_app.id,
target_type=IntegrationTypes.SENTRY_APP.value,
)
except IntegrityError:
with isolation_scope() as scope:
scope.set_tag("sentry_app", sentry_app.slug)
sentry_sdk.capture_message("IntegrityError while creating IntegrationFeature")
def _install(
self, *, slug: str, user: User | RpcUser, request: HttpRequest | None
) -> SentryAppInstallation:
return SentryAppInstallationCreator(
organization_id=self.organization_id,
slug=slug,
notify=False,
).run(user=user, request=request)
def _create_access_token(
self, user: User | RpcUser, install: SentryAppInstallation, request: HttpRequest | None
) -> None:
install.api_token = SentryAppInstallationTokenCreator(sentry_app_installation=install).run(
request=request, user=user
)
install.save()
def audit(self, request: HttpRequest | None, sentry_app: SentryApp) -> None:
from sentry.utils.audit import create_audit_entry
if request:
create_audit_entry(
request=request,
organization_id=self.organization_id,
target_object=self.organization_id,
event=audit_log.get_event_id("SENTRY_APP_ADD"),
data={"sentry_app": sentry_app.name},
)
if self.is_internal:
create_audit_entry(
request=request,
organization_id=self.organization_id,
target_object=self.organization_id,
event=audit_log.get_event_id("INTERNAL_INTEGRATION_ADD"),
data={"name": sentry_app.name},
)
def record_analytics(self, user: User | RpcUser, sentry_app: SentryApp) -> None:
analytics.record(
SentryAppCreatedEvent(
user_id=user.id,
organization_id=self.organization_id,
sentry_app=sentry_app.slug,
created_alert_rule_ui_component=(
"alert-rule-action" in _get_schema_types(self.schema)
),
)
)
if self.is_internal:
analytics.record(
InternalIntegrationCreatedEvent(
user_id=user.id,
organization_id=self.organization_id,
sentry_app=sentry_app.slug,
)
)
| SentryAppCreator |
python | getsentry__sentry | src/sentry/spans/consumers/process_segments/types.py | {
"start": 732,
"end": 1298
} | class ____(SpanEvent, total=True):
"""A span that has the same fields as a kafka span, plus shimming for logic shared with the event pipeline.
This type will be removed eventually."""
exclusive_time: float
op: str
sentry_tags: dict[str, str]
# Added by `SpanGroupingResults.write_to_spans` in `_enrich_spans`
hash: NotRequired[str]
def attribute_value(span: Mapping[str, Any], key: str) -> Any:
attributes = span.get("attributes") or {}
attr: dict[str, Any] = attributes.get(key) or {}
return attr.get("value")
| CompatibleSpan |
python | spack__spack | lib/spack/spack/operating_systems/freebsd.py | {
"start": 235,
"end": 404
} | class ____(OperatingSystem):
def __init__(self):
release = py_platform.release().split("-", 1)[0]
super().__init__("freebsd", Version(release))
| FreeBSDOs |
python | zarr-developers__zarr-python | src/zarr/core/dtype/npy/complex.py | {
"start": 11812,
"end": 12928
} | class ____(BaseComplex[np.dtypes.Complex128DType, np.complex128], HasEndianness):
"""
A Zarr data type for arrays containing 64 bit complex floats.
Wraps the [`np.dtypes.Complex128DType`][numpy.dtypes.Complex128DType] data type. Scalars for this data type
are instances of [`np.complex128`][numpy.complex128].
Attributes
----------
dtype_cls : Type[np.dtypes.Complex128DType]
The numpy dtype class for this data type.
_zarr_v3_name : ClassVar[Literal["complex128"]]
The name of this data type in Zarr V3.
_zarr_v2_names : ClassVar[tuple[Literal[">c16"], Literal["<c16"]]]
The names of this data type in Zarr V2.
"""
dtype_cls = np.dtypes.Complex128DType
_zarr_v3_name: ClassVar[Literal["complex128"]] = "complex128"
_zarr_v2_names: ClassVar[tuple[Literal[">c16"], Literal["<c16"]]] = (">c16", "<c16")
@property
def item_size(self) -> int:
"""
The size of a single scalar in bytes.
Returns
-------
int
The size of a single scalar in bytes.
"""
return 16
| Complex128 |
python | numba__numba | numba/core/untyped_passes.py | {
"start": 69524,
"end": 71669
} | class ____(FunctionPass):
"""Implement the literal_unroll semantics"""
_name = "literal_unroll"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
# Determine whether to even attempt this pass... if there's no
# `literal_unroll` as a global or as a freevar then just skip.
found = False
func_ir = state.func_ir
for blk in func_ir.blocks.values():
for asgn in blk.find_insts(ir.Assign):
if isinstance(asgn.value, (ir.Global, ir.FreeVar)):
if asgn.value.value is literal_unroll:
found = True
break
if found:
break
if not found:
return False
# run as subpipeline
from numba.core.compiler_machinery import PassManager
from numba.core.typed_passes import PartialTypeInference
pm = PassManager("literal_unroll_subpipeline")
# get types where possible to help with list->tuple change
pm.add_pass(PartialTypeInference, "performs partial type inference")
# make const lists tuples
pm.add_pass(TransformLiteralUnrollConstListToTuple,
"switch const list for tuples")
# recompute partial typemap following IR change
pm.add_pass(PartialTypeInference, "performs partial type inference")
# canonicalise loops
pm.add_pass(IterLoopCanonicalization,
"switch iter loops for range driven loops")
# rewrite consts
pm.add_pass(RewriteSemanticConstants, "rewrite semantic constants")
# do the unroll
pm.add_pass(MixedContainerUnroller, "performs mixed container unroll")
# rewrite dynamic getitem to static getitem as it's possible some more
# getitems will now be statically resolvable
pm.add_pass(GenericRewrites, "Generic Rewrites")
pm.add_pass(RewriteSemanticConstants, "rewrite semantic constants")
pm.finalize()
pm.run(state)
return True
@register_pass(mutates_CFG=True, analysis_only=False)
| LiteralUnroll |
python | scrapy__scrapy | tests/test_http_request.py | {
"start": 58373,
"end": 64728
} | class ____(TestRequest):
request_class = JsonRequest
default_method = "GET"
default_headers = {
b"Content-Type": [b"application/json"],
b"Accept": [b"application/json, text/javascript, */*; q=0.01"],
}
def test_data(self):
r1 = self.request_class(url="http://www.example.com/")
assert r1.body == b""
body = b"body"
r2 = self.request_class(url="http://www.example.com/", body=body)
assert r2.body == body
data = {
"name": "value",
}
r3 = self.request_class(url="http://www.example.com/", data=data)
assert r3.body == to_bytes(json.dumps(data))
# empty data
r4 = self.request_class(url="http://www.example.com/", data=[])
assert r4.body == to_bytes(json.dumps([]))
def test_data_method(self):
# data is not passed
r1 = self.request_class(url="http://www.example.com/")
assert r1.method == "GET"
body = b"body"
r2 = self.request_class(url="http://www.example.com/", body=body)
assert r2.method == "GET"
data = {
"name": "value",
}
r3 = self.request_class(url="http://www.example.com/", data=data)
assert r3.method == "POST"
# method passed explicitly
r4 = self.request_class(url="http://www.example.com/", data=data, method="GET")
assert r4.method == "GET"
r5 = self.request_class(url="http://www.example.com/", data=[])
assert r5.method == "POST"
def test_body_data(self):
"""passing both body and data should result a warning"""
body = b"body"
data = {
"name": "value",
}
with warnings.catch_warnings(record=True) as _warnings:
r5 = self.request_class(url="http://www.example.com/", body=body, data=data)
assert r5.body == body
assert r5.method == "GET"
assert len(_warnings) == 1
assert "data will be ignored" in str(_warnings[0].message)
def test_empty_body_data(self):
"""passing any body value and data should result a warning"""
data = {
"name": "value",
}
with warnings.catch_warnings(record=True) as _warnings:
r6 = self.request_class(url="http://www.example.com/", body=b"", data=data)
assert r6.body == b""
assert r6.method == "GET"
assert len(_warnings) == 1
assert "data will be ignored" in str(_warnings[0].message)
def test_body_none_data(self):
data = {
"name": "value",
}
with warnings.catch_warnings(record=True) as _warnings:
r7 = self.request_class(url="http://www.example.com/", body=None, data=data)
assert r7.body == to_bytes(json.dumps(data))
assert r7.method == "POST"
assert len(_warnings) == 0
def test_body_data_none(self):
with warnings.catch_warnings(record=True) as _warnings:
r8 = self.request_class(url="http://www.example.com/", body=None, data=None)
assert r8.method == "GET"
assert len(_warnings) == 0
def test_dumps_sort_keys(self):
"""Test that sort_keys=True is passed to json.dumps by default"""
data = {
"name": "value",
}
with mock.patch("json.dumps", return_value=b"") as mock_dumps:
self.request_class(url="http://www.example.com/", data=data)
kwargs = mock_dumps.call_args[1]
assert kwargs["sort_keys"] is True
def test_dumps_kwargs(self):
"""Test that dumps_kwargs are passed to json.dumps"""
data = {
"name": "value",
}
dumps_kwargs = {
"ensure_ascii": True,
"allow_nan": True,
}
with mock.patch("json.dumps", return_value=b"") as mock_dumps:
self.request_class(
url="http://www.example.com/", data=data, dumps_kwargs=dumps_kwargs
)
kwargs = mock_dumps.call_args[1]
assert kwargs["ensure_ascii"] is True
assert kwargs["allow_nan"] is True
def test_replace_data(self):
data1 = {
"name1": "value1",
}
data2 = {
"name2": "value2",
}
r1 = self.request_class(url="http://www.example.com/", data=data1)
r2 = r1.replace(data=data2)
assert r2.body == to_bytes(json.dumps(data2))
def test_replace_sort_keys(self):
"""Test that replace provides sort_keys=True to json.dumps"""
data1 = {
"name1": "value1",
}
data2 = {
"name2": "value2",
}
r1 = self.request_class(url="http://www.example.com/", data=data1)
with mock.patch("json.dumps", return_value=b"") as mock_dumps:
r1.replace(data=data2)
kwargs = mock_dumps.call_args[1]
assert kwargs["sort_keys"] is True
def test_replace_dumps_kwargs(self):
"""Test that dumps_kwargs are provided to json.dumps when replace is called"""
data1 = {
"name1": "value1",
}
data2 = {
"name2": "value2",
}
dumps_kwargs = {
"ensure_ascii": True,
"allow_nan": True,
}
r1 = self.request_class(
url="http://www.example.com/", data=data1, dumps_kwargs=dumps_kwargs
)
with mock.patch("json.dumps", return_value=b"") as mock_dumps:
r1.replace(data=data2)
kwargs = mock_dumps.call_args[1]
assert kwargs["ensure_ascii"] is True
assert kwargs["allow_nan"] is True
def test_replacement_both_body_and_data_warns(self):
"""Test that we get a warning if both body and data are passed"""
body1 = None
body2 = b"body"
data1 = {
"name1": "value1",
}
data2 = {
"name2": "value2",
}
r1 = self.request_class(url="http://www.example.com/", data=data1, body=body1)
with warnings.catch_warnings(record=True) as _warnings:
r1.replace(data=data2, body=body2)
assert "Both body and data passed. data will be ignored" in str(
_warnings[0].message
)
| TestJsonRequest |
python | lepture__authlib | authlib/oidc/core/errors.py | {
"start": 2572,
"end": 2731
} | class ____(OAuth2Error):
"""The OP does not support use of the request_uri parameter."""
error = "request_uri_not_supported"
| RequestURINotSupportedError |
python | django__django | tests/syndication_tests/feeds.py | {
"start": 546,
"end": 1533
} | class ____(views.Feed):
title = "My blog"
description = "A more thorough description of my blog."
link = "/blog/"
feed_guid = "/foo/bar/1234"
author_name = "Sally Smith"
author_email = "test@example.com"
author_link = "http://www.example.com/"
categories = ("python", "django")
feed_copyright = "Copyright (c) 2007, Sally Smith"
ttl = 600
def items(self):
return Entry.objects.all()
def item_description(self, item):
return "Overridden description: %s" % item
def item_pubdate(self, item):
return item.published
def item_updateddate(self, item):
return item.updated
def item_comments(self, item):
return "%scomments" % item.get_absolute_url()
item_author_name = "Sally Smith"
item_author_email = "test@example.com"
item_author_link = "http://www.example.com/"
item_categories = ("python", "testing")
item_copyright = "Copyright (c) 2007, Sally Smith"
| TestRss2Feed |
python | pydata__xarray | xarray/tests/test_sparse.py | {
"start": 28020,
"end": 29458
} | class ____:
@pytest.mark.xfail(reason="Coercion of coords to dense")
def test_sparse_coords(self):
xr.DataArray(
sparse.COO.from_numpy(np.arange(4)),
dims=["x"],
coords={"x": sparse.COO.from_numpy([1, 2, 3, 4])},
)
@requires_dask
def test_chunk():
s = sparse.COO.from_numpy(np.array([0, 0, 1, 2]))
a = DataArray(s)
ac = a.chunk(2)
assert ac.chunks == ((2, 2),)
assert isinstance(ac.data._meta, sparse.COO)
assert_identical(ac, a)
ds = a.to_dataset(name="a")
dsc = ds.chunk(2)
assert dsc.chunks == {"dim_0": (2, 2)}
assert_identical(dsc, ds)
@requires_dask
def test_dask_token():
import dask
s = sparse.COO.from_numpy(np.array([0, 0, 1, 2]))
a = DataArray(s)
t1 = dask.base.tokenize(a)
t2 = dask.base.tokenize(a)
t3 = dask.base.tokenize(a + 1)
assert t1 == t2
assert t3 != t2
assert isinstance(a.data, sparse.COO)
ac = a.chunk(2)
t4 = dask.base.tokenize(ac)
t5 = dask.base.tokenize(ac + 1)
assert t4 != t5
assert isinstance(ac.data._meta, sparse.COO)
@requires_dask
def test_apply_ufunc_check_meta_coherence():
s = sparse.COO.from_numpy(np.array([0, 0, 1, 2]))
a = DataArray(s)
ac = a.chunk(2)
sparse_meta = ac.data._meta
result = xr.apply_ufunc(lambda x: x, ac, dask="parallelized").data._meta
assert_sparse_equal(result, sparse_meta)
| TestSparseCoords |
python | wandb__wandb | wandb/sdk/lib/printer.py | {
"start": 12062,
"end": 12284
} | class ____(DynamicText):
def __init__(self, handle: term.DynamicBlock) -> None:
self._handle = handle
@override
def set_text(self, text: str) -> None:
self._handle.set_text(text)
| _DynamicTermText |
python | huggingface__transformers | src/transformers/models/lxmert/modeling_lxmert.py | {
"start": 4777,
"end": 7736
} | class ____(ModelOutput):
r"""
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
Total loss as the sum of the masked language modeling loss and the next sequence prediction
(classification) loss.k.
question_answering_score (`torch.FloatTensor` of shape `(batch_size, n_qa_answers)`, *optional*):
Prediction scores of question answering objective (classification).
language_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for input features + one for the output of each cross-modality layer) of
shape `(batch_size, sequence_length, hidden_size)`.
vision_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for input features + one for the output of each cross-modality layer) of
shape `(batch_size, sequence_length, hidden_size)`.
language_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
the self-attention heads.
vision_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
the self-attention heads.
cross_encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
the self-attention heads.
"""
loss: Optional[torch.FloatTensor] = None
question_answering_score: Optional[torch.FloatTensor] = None
language_hidden_states: Optional[tuple[torch.FloatTensor]] = None
vision_hidden_states: Optional[tuple[torch.FloatTensor]] = None
language_attentions: Optional[tuple[torch.FloatTensor]] = None
vision_attentions: Optional[tuple[torch.FloatTensor]] = None
cross_encoder_attentions: Optional[tuple[torch.FloatTensor]] = None
@dataclass
@auto_docstring(
custom_intro="""
Output type of [`LxmertForPreTraining`].
"""
)
| LxmertForQuestionAnsweringOutput |
python | kamyu104__LeetCode-Solutions | Python/find-the-last-marked-nodes-in-tree.py | {
"start": 35,
"end": 1016
} | class ____(object):
def lastMarkedNodes(self, edges):
"""
:type edges: List[List[int]]
:rtype: List[int]
"""
def bfs(root):
new_root = -1
dist = [-1]*len(adj)
dist[root] = 0
q = [root]
while q:
new_root = q[0]
new_q = []
for u in q:
for v in adj[u]:
if dist[v] != -1:
continue
dist[v] = dist[u]+1
new_q.append(v)
q = new_q
return dist, new_root
adj = [[] for _ in xrange(len(edges)+1)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
_, u = bfs(0)
dist1, v = bfs(u)
dist2, _ = bfs(v)
return [u if dist1[w] > dist2[w] else v for w in xrange(len(adj))]
# Time: O(n)
# Space: O(n)
# bfs
| Solution |
python | getsentry__sentry | src/sentry/models/files/control_fileblobindex.py | {
"start": 278,
"end": 667
} | class ____(AbstractFileBlobIndex):
__relocation_scope__ = RelocationScope.Excluded
file = FlexibleForeignKey("sentry.ControlFile")
blob = FlexibleForeignKey("sentry.ControlFileBlob", on_delete=models.PROTECT)
class Meta:
app_label = "sentry"
db_table = "sentry_controlfileblobindex"
unique_together = (("file", "blob", "offset"),)
| ControlFileBlobIndex |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 139084,
"end": 142853
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[4, 3]"):
l_x_ = L_x_
_saved_tensors_hooks_disable = torch._C._autograd._saved_tensors_hooks_disable("torch.func.{grad, vjp, jacrev, hessian} don't yet support saved tensor hooks. Please open an issue with your use case."); _saved_tensors_hooks_disable = None
_grad_increment_nesting = torch._C._functorch._grad_increment_nesting(); _grad_increment_nesting = None
diff_primals: "f32[4, 3]" = torch._C._functorch._wrap_for_grad(l_x_, 1); l_x_ = None
set_inplace_requires_grad_allowed = torch._C._functorch.set_inplace_requires_grad_allowed(True); set_inplace_requires_grad_allowed = None
_set_tensor_requires_grad: "f32[4, 3]" = torch._functorch.eager_transforms._set_tensor_requires_grad(diff_primals); _set_tensor_requires_grad = None
set_inplace_requires_grad_allowed_1 = torch._C._functorch.set_inplace_requires_grad_allowed(False); set_inplace_requires_grad_allowed_1 = None
primals_out: "f32[4, 3]" = torch.sin(diff_primals)
results: "f32[4, 3]" = torch._C._functorch._unwrap_for_grad(primals_out, 1)
_grad_decrement_nesting = torch._C._functorch._grad_decrement_nesting(); _grad_decrement_nesting = None
_saved_tensors_hooks_enable = torch._C._autograd._saved_tensors_hooks_enable(); _saved_tensors_hooks_enable = None
tensor: "i64[1]" = torch.tensor((12,))
cumsum: "i64[1]" = tensor.cumsum(dim = 0); tensor = None
getitem: "i64[0]" = cumsum[slice(None, -1, None)]; cumsum = None
neg: "i64[0]" = getitem.neg(); getitem = None
unbind = neg.unbind(); neg = unbind = None
chunk: "f32[12, 12]" = results.new_zeros(12, 12); results = None
diagonal: "f32[12]" = chunk.diagonal(0)
fill_: "f32[12]" = diagonal.fill_(1); diagonal = fill_ = None
basis: "f32[12, 4, 3]" = chunk.view(12, 4, 3); chunk = None
lazy_load_decompositions = torch._functorch.predispatch.lazy_load_decompositions(); lazy_load_decompositions = None
_vmap_increment_nesting = torch._functorch.predispatch._vmap_increment_nesting(12, 'error'); _vmap_increment_nesting = None
_add_batch_dim: "f32[4, 3]" = torch._functorch.predispatch._add_batch_dim(basis, 0, 1); basis = None
_autograd_grad = torch._functorch.eager_transforms._autograd_grad([primals_out], [diff_primals], [_add_batch_dim], retain_graph = True, create_graph = True); primals_out = diff_primals = _add_batch_dim = None
batched_outputs: "f32[4, 3]" = _autograd_grad[0]; _autograd_grad = None
chunked_result: "f32[12, 4, 3]" = torch._functorch.predispatch._remove_batch_dim(batched_outputs, 1, 12, 0); batched_outputs = None
_vmap_decrement_nesting = torch._functorch.predispatch._vmap_decrement_nesting(); _vmap_decrement_nesting = None
split = chunked_result.split((12,), dim = 0); chunked_result = None
split_1: "f32[12, 4, 3]" = split[0]; split = None
output_input: "f32[4, 3, 4, 3]" = split_1.view((4, 3, 4, 3)); split_1 = None
return (output_input,)
""",
)
def test_jacrev_two_tensors_argnums(self):
counters.clear()
def fn(x, y):
return y.sin()
def wrapper_fn(x, y):
return torch.func.jacrev(fn, argnums=1)(x, y)
x = torch.randn(4, 3)
y = torch.randn(3, 4)
wrapped_gm = self._compile_check(wrapper_fn, (x, y))
# Dynamic shapes produce a slightly different graph.
if check_dynamic_shape_capture():
return
actual = normalize_gm(wrapped_gm.print_readable(print_output=False))
self.assertExpectedInline(
actual,
"""\
| GraphModule |
python | eth-brownie__brownie | brownie/typing.py | {
"start": 5402,
"end": 5657
} | class ____(TypedDict):
"""A dictionary representing on object on the AST."""
name: str
module: str
type: str
ast_type: str
src: str
op: "VyperAstNode"
value: Dict
test: Dict
VyperAstJson = List[VyperAstNode]
| VyperAstNode |
python | ray-project__ray | python/ray/tests/test_get_or_create_actor.py | {
"start": 1530,
"end": 3085
} | class ____:
def ping(self):
return "ok"
@ray.remote
def getter(name):
actor = Actor.options(
name="foo", lifetime="detached", namespace="n", get_if_exists=True).remote()
ray.get(actor.ping.remote())
def do_run(name):
name = "actor_" + str(name)
tasks = [getter.remote(name) for i in range(4)]
ray.get(tasks)
try:
ray.kill(ray.get_actor(name, namespace="n")) # Cleanup
except:
pass
for i in range(100):
do_run(i)
print("DONE")
"""
proc = run_string_as_driver_nonblocking(script)
out_str = proc.stdout.read().decode("ascii") + proc.stderr.read().decode("ascii")
# Check there's no excessively verbose raylet error messages due to
# actor creation races.
out = []
for line in out_str.split("\n"):
if "local Ray instance" not in line and "The object store" not in line:
out.append(line)
valid = "".join(out)
assert "DONE" in valid, out_str
def test_get_or_create_named_actor(shutdown_only):
"""
This test aggressively gets or creates a named actor and makes the actor
go out of scope immediately. Additionally, `max_restarts=-1` is set to make
the actor restartable and make the test more aggressive.
"""
@ray.remote
class Actor:
pass
for _ in range(1000):
Actor.options(
name="test-get-or-create-named-actor",
get_if_exists=True,
max_restarts=-1,
).remote()
if __name__ == "__main__":
sys.exit(pytest.main(["-sv", __file__]))
| Actor |
python | FactoryBoy__factory_boy | factory/enums.py | {
"start": 278,
"end": 557
} | class ____:
#: During attribute resolution/computation
ATTRIBUTE_RESOLUTION = 'attributes'
#: Once the target object has been built
POST_INSTANTIATION = 'post_instance'
def get_builder_phase(obj):
return getattr(obj, 'FACTORY_BUILDER_PHASE', None)
| BuilderPhase |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_tags.py | {
"start": 1837,
"end": 4790
} | class ____:
"""Common class for /dags related unit tests."""
@staticmethod
def _clear_db():
clear_db_runs()
clear_db_dags()
clear_db_dag_bundles()
clear_db_serialized_dags()
def _create_deactivated_paused_dag(self, session=None):
dag_model = DagModel(
dag_id=DAG3_ID,
bundle_name="dag_maker",
fileloc="/tmp/dag_del_1.py",
timetable_summary="2 2 * * *",
is_stale=True,
is_paused=True,
owners="test_owner,another_test_owner",
next_dagrun=datetime(2021, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
)
dagrun_failed = DagRun(
dag_id=DAG3_ID,
run_id="run1",
logical_date=datetime(2018, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
start_date=datetime(2018, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
run_type=DagRunType.SCHEDULED,
state=DagRunState.FAILED,
triggered_by=DagRunTriggeredByType.TEST,
)
dagrun_success = DagRun(
dag_id=DAG3_ID,
run_id="run2",
logical_date=datetime(2019, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
start_date=datetime(2019, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
run_type=DagRunType.MANUAL,
state=DagRunState.SUCCESS,
triggered_by=DagRunTriggeredByType.TEST,
)
session.add(dag_model)
session.add(dagrun_failed)
session.add(dagrun_success)
def _create_dag_tags(self, session=None):
session.add(DagTag(dag_id=DAG1_ID, name="tag_2"))
session.add(DagTag(dag_id=DAG2_ID, name="tag_1"))
session.add(DagTag(dag_id=DAG3_ID, name="tag_1"))
@pytest.fixture(autouse=True)
@provide_session
def setup(self, dag_maker, session=None) -> None:
self._clear_db()
with dag_maker(
DAG1_ID,
dag_display_name=DAG1_DISPLAY_NAME,
schedule=None,
start_date=datetime(2018, 6, 15, 0, 0, tzinfo=timezone.utc),
doc_md="details",
params={"foo": 1},
tags=["example"],
):
EmptyOperator(task_id=TASK_ID)
dag_maker.sync_dagbag_to_db()
dag_maker.create_dagrun(state=DagRunState.FAILED)
with dag_maker(
DAG2_ID,
schedule=None,
start_date=DAG2_START_DATE,
doc_md="details",
params={"foo": 1},
max_active_tasks=16,
max_active_runs=16,
):
EmptyOperator(task_id=TASK_ID)
self._create_deactivated_paused_dag(session)
self._create_dag_tags(session)
dag_maker.sync_dagbag_to_db()
dag_maker.dag_model.has_task_concurrency_limits = True
session.merge(dag_maker.dag_model)
session.commit()
def teardown_method(self) -> None:
self._clear_db()
| TestDagEndpoint |
python | pyinstaller__pyinstaller | tests/unit/test_modulegraph/testpkg-compatmodule/pkg/api2.py | {
"start": 147,
"end": 180
} | class ____ (object):
pass
| MyClass |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 1055711,
"end": 1056691
} | class ____(sgqlc.types.Union):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__types__ = (
AddedToProjectEvent,
AssignedEvent,
ClosedEvent,
CommentDeletedEvent,
ConnectedEvent,
ConvertedNoteToIssueEvent,
ConvertedToDiscussionEvent,
CrossReferencedEvent,
DemilestonedEvent,
DisconnectedEvent,
IssueComment,
LabeledEvent,
LockedEvent,
MarkedAsDuplicateEvent,
MentionedEvent,
MilestonedEvent,
MovedColumnsInProjectEvent,
PinnedEvent,
ReferencedEvent,
RemovedFromProjectEvent,
RenamedTitleEvent,
ReopenedEvent,
SubscribedEvent,
TransferredEvent,
UnassignedEvent,
UnlabeledEvent,
UnlockedEvent,
UnmarkedAsDuplicateEvent,
UnpinnedEvent,
UnsubscribedEvent,
UserBlockedEvent,
)
| IssueTimelineItems |
python | django__django | tests/admin_views/models.py | {
"start": 16861,
"end": 17010
} | class ____(models.Model):
owner = models.ForeignKey(User, models.SET_NULL, null=True, blank=True)
title = models.CharField(max_length=30)
| Album |
python | pytorch__pytorch | test/functorch/test_control_flow.py | {
"start": 347375,
"end": 355856
} | class ____(torch.nn.Module):
def forward(self, primals_2: "f32[3, 3]", primals_3: "f32[3]", cat: "f32[u2, 3, 3]", tangents_1: "f32[3, 3]"):
zeros: "i64[]" = torch.ops.aten.zeros.default([], dtype = torch.int64, device = device(type='cpu'), pin_memory = False)
zeros_like: "f32[3]" = torch.ops.aten.zeros_like.default(primals_3, pin_memory = False)
zeros_like_1: "f32[3, 3]" = torch.ops.aten.zeros_like.default(primals_2, pin_memory = False)
while_loop_cond_graph_1 = self.while_loop_cond_graph_1
while_loop_body_graph_1 = self.while_loop_body_graph_1
while_loop = torch.ops.higher_order.while_loop(while_loop_cond_graph_1, while_loop_body_graph_1, (zeros, tangents_1, zeros_like, zeros_like_1), (cat, primals_3, primals_2)); while_loop_cond_graph_1 = while_loop_body_graph_1 = zeros = tangents_1 = zeros_like = zeros_like_1 = cat = primals_3 = primals_2 = None
getitem_2: "f32[3, 3]" = while_loop[1]
getitem_3: "f32[3]" = while_loop[2]
getitem_4: "f32[3, 3]" = while_loop[3]; while_loop = None
return (getitem_2, getitem_4, getitem_3)
class while_loop_cond_graph_1(torch.nn.Module):
def forward(self, arg0_1: "i64[]", arg1_1: "f32[3, 3]", arg2_1: "f32[3]", arg3_1: "f32[3, 3]", arg4_1: "f32[u2, 3, 3]", arg5_1: "f32[3]", arg6_1: "f32[3, 3]"):
sym_size_int_1: "Sym(u2)" = torch.ops.aten.sym_size.int(arg4_1, 0); arg4_1 = None
lt: "b8[]" = torch.ops.aten.lt.Scalar(arg0_1, sym_size_int_1); arg0_1 = sym_size_int_1 = None
return lt
class while_loop_body_graph_1(torch.nn.Module):
def forward(self, arg0_1: "i64[]", arg1_1: "f32[3, 3]", arg2_1: "f32[3]", arg3_1: "f32[3, 3]", arg4_1: "f32[u2, 3, 3]", arg5_1: "f32[3]", arg6_1: "f32[3, 3]"):
sym_size_int_1: "Sym(u2)" = torch.ops.aten.sym_size.int(arg4_1, 0)
rsub: "i64[]" = torch.ops.aten.rsub.Scalar(arg0_1, sym_size_int_1); sym_size_int_1 = None
sub_1: "i64[]" = torch.ops.aten.sub.Tensor(rsub, 1); rsub = None
_local_scalar_dense: "Sym(u7)" = torch.ops.aten._local_scalar_dense.default(sub_1); sub_1 = None
select: "f32[3, 3]" = torch.ops.aten.select.int(arg4_1, 0, _local_scalar_dense); arg4_1 = _local_scalar_dense = None
t: "f32[3, 3]" = torch.ops.aten.t.default(arg6_1); arg6_1 = None
t_1: "f32[3, 3]" = torch.ops.aten.t.default(t); t = None
mm: "f32[3, 3]" = torch.ops.aten.mm.default(arg1_1, t_1); t_1 = None
t_2: "f32[3, 3]" = torch.ops.aten.t.default(arg1_1)
mm_1: "f32[3, 3]" = torch.ops.aten.mm.default(t_2, select); t_2 = None
t_3: "f32[3, 3]" = torch.ops.aten.t.default(mm_1); mm_1 = None
sum_1: "f32[1, 3]" = torch.ops.aten.sum.dim_IntList(arg1_1, [0], True)
view: "f32[3]" = torch.ops.aten.view.default(sum_1, [3]); sum_1 = None
t_4: "f32[3, 3]" = torch.ops.aten.t.default(t_3); t_3 = None
mul_4: "f32[3, 3]" = torch.ops.aten.mul.Tensor(arg1_1, select)
mul_5: "f32[3, 3]" = torch.ops.aten.mul.Tensor(arg1_1, select); arg1_1 = select = None
add_7: "f32[3, 3]" = torch.ops.aten.add.Tensor(mm, mul_5); mm = mul_5 = None
add_8: "f32[3, 3]" = torch.ops.aten.add.Tensor(add_7, mul_4); add_7 = mul_4 = None
add_9: "i64[]" = torch.ops.aten.add.Tensor(arg0_1, 1); arg0_1 = None
add_10: "f32[3]" = torch.ops.aten.add.Tensor(view, arg2_1); view = arg2_1 = None
add_11: "f32[3, 3]" = torch.ops.aten.add.Tensor(t_4, arg3_1); t_4 = arg3_1 = None
return (add_9, add_8, add_10, add_11)
""", # noqa: B950
)
def test_input_output_alias(self):
def fn(f, *args):
return torch.cond(args[0].sum() > 0, f, f, args)
x = torch.randn(2, 2)
for f in ALIAS_FN:
with self.assertRaisesRegex(
# Should be
# torch._dynamo.exc.Unsupported,
# "Encountered aliasing during higher order op tracing for HOP.*"
torch._dynamo.exc.UncapturedHigherOrderOpError,
"Cond doesn't work unless it is captured completely with torch.compile.*",
):
torch.compile(fn)(f, x)
def test_input_input_alias(self):
def fn(view_f, arg):
def f(arg1, arg2):
return arg1.cos(), arg2.sin()
return torch.cond(arg.sum() > 0, f, f, (arg, view_f(arg)))
x = torch.randn(2, 2)
# ALIAS_FN[0] is an identical function, cond optimizes the duplication
# as a result of auto lifting.
for view_f in ALIAS_FN[1:]:
with self.assertRaisesRegex(
# Should be
# torch._dynamo.exc.Unsupported,
# "Encountered aliasing during higher order op tracing for HOP.*"
torch._dynamo.exc.UncapturedHigherOrderOpError,
"Cond doesn't work unless it is captured completely with torch.compile.*",
):
torch.compile(fn)(view_f, x)
@parametrize("inference_mode", [True, False])
def test_input_mutation(self, inference_mode):
def fn(view_f, *args):
def mutate_f(x):
v = view_f(x)
v.add_(1)
return v.sin()
return torch.cond(args[0].sum() > 0, mutate_f, mutate_f, args)
x = torch.randn(2, 2)
for f in ALIAS_FN:
with self.assertRaisesRegex(
# Should be
# torch._dynamo.exc.Unsupported,
# "Encountered aliasing during higher order op tracing for HOP.*"
torch._dynamo.exc.UncapturedHigherOrderOpError,
"Cond doesn't work unless it is captured completely with torch.compile.*",
):
torch.compile(fn)(f, x)
with self.assertRaisesRegex(
# Should be
# torch._dynamo.exc.Unsupported,
# "Encountered aliasing during higher order op tracing for HOP.*"
torch._dynamo.exc.UncapturedHigherOrderOpError,
"Cond doesn't work unless it is captured completely with torch.compile.*",
):
with torch.inference_mode(inference_mode):
torch.compile(fn)(f, x)
@skipIfTorchDynamo("Graph is not captured correctly when test with dynamo")
def test_while_loop_unbacked_bindings(self):
m, args = WHILE_LOOP_TESTS["pytree_int_carry"]
backend = EagerAndRecordGraphs()
self._check_compile(m, args, dynamic=True, backend=backend)
self.assertEqual(len(backend.graphs), 1)
while_loop_nodes = backend.graphs[0].graph.find_nodes(
op="call_function", target=torch.ops.higher_order.while_loop
)
self.assertEqual(len(while_loop_nodes), 1)
self.assertEqual(len(while_loop_nodes[0].meta.get("unbacked_bindings")), 5)
# Return the .module() graph str result of non-strict export
def _check_export_ret_graph_str(self, fn, args, dynamic_shapes=None) -> str:
strict_ep = torch.export.export(
fn, args, dynamic_shapes=dynamic_shapes, strict=True
)
non_strict_ep = torch.export.export(
fn, args, dynamic_shapes=dynamic_shapes, strict=False
)
eager_res = fn(*args)
self.assertEqual(strict_ep.module()(*args), eager_res)
self.assertEqual(non_strict_ep.module()(*args), eager_res)
return normalize_gm(non_strict_ep.module().print_readable(print_output=False))
@skipIfTorchDynamo("Skip because dynamo cannot trace torch.export.")
def test_cond_eager_run_with_item(self):
class M(torch.nn.Module):
def forward(self, a, b1, b2, c):
def true_fn(x):
return x * b1.item()
def false_fn(x):
return x * b2.item()
r = torch.cond(a, true_fn, false_fn, (c,))
return r * 2
x = torch.randn(10, requires_grad=True)
args = (
torch.tensor(True),
torch.tensor([3]),
torch.tensor([4]),
x,
)
model = M()
torch.export.export(model, args, strict=True)
graph_str = self._check_export_ret_graph_str(model, args, None)
self.assertExpectedInline(
graph_str,
"""\
| GraphModule |
python | pytorch__pytorch | test/dynamo/test_subclasses.py | {
"start": 5576,
"end": 5802
} | class ____(torch.Tensor):
x: int = 10
size: int = 10
@classmethod
def __torch_function__(cls, func, types, args=(), kwargs=None):
return super().__torch_function__(func, types, args, kwargs)
| AttrSubclass |
python | apache__airflow | providers/common/sql/tests/unit/common/sql/operators/test_generic_transfer.py | {
"start": 5270,
"end": 7629
} | class ____:
def teardown_method(self):
tables_to_drop = ["test_postgres_to_postgres", "test_airflow"]
with PostgresHook().get_conn() as conn:
with conn.cursor() as cur:
for table in tables_to_drop:
cur.execute(f"DROP TABLE IF EXISTS {table}")
def test_postgres_to_postgres(self, dag_maker):
sql = "SELECT * FROM INFORMATION_SCHEMA.TABLES LIMIT 100;"
with dag_maker(default_args={"owner": "airflow", "start_date": DEFAULT_DATE}, serialized=True):
_ = GenericTransfer(
task_id="test_p2p",
preoperator=[
"DROP TABLE IF EXISTS test_postgres_to_postgres",
"CREATE TABLE IF NOT EXISTS test_postgres_to_postgres (LIKE INFORMATION_SCHEMA.TABLES)",
],
source_conn_id="postgres_default",
destination_conn_id="postgres_default",
destination_table="test_postgres_to_postgres",
sql=sql,
)
dr = dag_maker.create_dagrun()
dag_maker.run_ti("test_p2p", dr)
@mock.patch("airflow.providers.common.sql.hooks.sql.DbApiHook.insert_rows")
def test_postgres_to_postgres_replace(self, mock_insert, dag_maker):
sql = "SELECT id, conn_id, conn_type FROM connection LIMIT 10;"
with dag_maker(default_args={"owner": "airflow", "start_date": DEFAULT_DATE}, serialized=True):
_ = GenericTransfer(
task_id="test_p2p",
preoperator=[
"DROP TABLE IF EXISTS test_postgres_to_postgres",
"CREATE TABLE IF NOT EXISTS test_postgres_to_postgres (LIKE connection INCLUDING INDEXES)",
],
source_conn_id="postgres_default",
destination_conn_id="postgres_default",
destination_table="test_postgres_to_postgres",
sql=sql,
insert_args={
"replace": True,
"target_fields": ("id", "conn_id", "conn_type"),
"replace_index": "id",
},
)
dr = dag_maker.create_dagrun()
dag_maker.run_ti("test_p2p", dr)
assert mock_insert.called
_, kwargs = mock_insert.call_args
assert "replace" in kwargs
| TestPostgres |
python | kamyu104__LeetCode-Solutions | Python/delete-leaves-with-a-given-value.py | {
"start": 191,
"end": 611
} | class ____(object):
def removeLeafNodes(self, root, target):
"""
:type root: TreeNode
:type target: int
:rtype: TreeNode
"""
if not root:
return None
root.left = self.removeLeafNodes(root.left, target)
root.right = self.removeLeafNodes(root.right, target)
return None if root.left == root.right and root.val == target else root
| Solution |
python | pallets__werkzeug | src/werkzeug/routing/rules.py | {
"start": 9885,
"end": 32538
} | class ____(RuleFactory):
"""A Rule represents one URL pattern. There are some options for `Rule`
that change the way it behaves and are passed to the `Rule` constructor.
Note that besides the rule-string all arguments *must* be keyword arguments
in order to not break the application on Werkzeug upgrades.
`string`
Rule strings basically are just normal URL paths with placeholders in
the format ``<converter(arguments):name>`` where the converter and the
arguments are optional. If no converter is defined the `default`
converter is used which means `string` in the normal configuration.
URL rules that end with a slash are branch URLs, others are leaves.
If you have `strict_slashes` enabled (which is the default), all
branch URLs that are matched without a trailing slash will trigger a
redirect to the same URL with the missing slash appended.
The converters are defined on the `Map`.
`endpoint`
The endpoint for this rule. This can be anything. A reference to a
function, a string, a number etc. The preferred way is using a string
because the endpoint is used for URL generation.
`defaults`
An optional dict with defaults for other rules with the same endpoint.
This is a bit tricky but useful if you want to have unique URLs::
url_map = Map([
Rule('/all/', defaults={'page': 1}, endpoint='all_entries'),
Rule('/all/page/<int:page>', endpoint='all_entries')
])
If a user now visits ``http://example.com/all/page/1`` they will be
redirected to ``http://example.com/all/``. If `redirect_defaults` is
disabled on the `Map` instance this will only affect the URL
generation.
`subdomain`
The subdomain rule string for this rule. If not specified the rule
only matches for the `default_subdomain` of the map. If the map is
not bound to a subdomain this feature is disabled.
Can be useful if you want to have user profiles on different subdomains
and all subdomains are forwarded to your application::
url_map = Map([
Rule('/', subdomain='<username>', endpoint='user/homepage'),
Rule('/stats', subdomain='<username>', endpoint='user/stats')
])
`methods`
A sequence of http methods this rule applies to. If not specified, all
methods are allowed. For example this can be useful if you want different
endpoints for `POST` and `GET`. If methods are defined and the path
matches but the method matched against is not in this list or in the
list of another rule for that path the error raised is of the type
`MethodNotAllowed` rather than `NotFound`. If `GET` is present in the
list of methods and `HEAD` is not, `HEAD` is added automatically.
`strict_slashes`
Override the `Map` setting for `strict_slashes` only for this rule. If
not specified the `Map` setting is used.
`merge_slashes`
Override :attr:`Map.merge_slashes` for this rule.
`build_only`
Set this to True and the rule will never match but will create a URL
that can be build. This is useful if you have resources on a subdomain
or folder that are not handled by the WSGI application (like static data)
`redirect_to`
If given this must be either a string or callable. In case of a
callable it's called with the url adapter that triggered the match and
the values of the URL as keyword arguments and has to return the target
for the redirect, otherwise it has to be a string with placeholders in
rule syntax::
def foo_with_slug(adapter, id):
# ask the database for the slug for the old id. this of
# course has nothing to do with werkzeug.
return f'foo/{Foo.get_slug_for_id(id)}'
url_map = Map([
Rule('/foo/<slug>', endpoint='foo'),
Rule('/some/old/url/<slug>', redirect_to='foo/<slug>'),
Rule('/other/old/url/<int:id>', redirect_to=foo_with_slug)
])
When the rule is matched the routing system will raise a
`RequestRedirect` exception with the target for the redirect.
Keep in mind that the URL will be joined against the URL root of the
script so don't use a leading slash on the target URL unless you
really mean root of that domain.
`alias`
If enabled this rule serves as an alias for another rule with the same
endpoint and arguments.
`host`
If provided and the URL map has host matching enabled this can be
used to provide a match rule for the whole host. This also means
that the subdomain feature is disabled.
`websocket`
If ``True``, this rule is only matches for WebSocket (``ws://``,
``wss://``) requests. By default, rules will only match for HTTP
requests.
.. versionchanged:: 2.1
Percent-encoded newlines (``%0a``), which are decoded by WSGI
servers, are considered when routing instead of terminating the
match early.
.. versionadded:: 1.0
Added ``websocket``.
.. versionadded:: 1.0
Added ``merge_slashes``.
.. versionadded:: 0.7
Added ``alias`` and ``host``.
.. versionchanged:: 0.6.1
``HEAD`` is added to ``methods`` if ``GET`` is present.
"""
def __init__(
self,
string: str,
defaults: t.Mapping[str, t.Any] | None = None,
subdomain: str | None = None,
methods: t.Iterable[str] | None = None,
build_only: bool = False,
endpoint: t.Any | None = None,
strict_slashes: bool | None = None,
merge_slashes: bool | None = None,
redirect_to: str | t.Callable[..., str] | None = None,
alias: bool = False,
host: str | None = None,
websocket: bool = False,
) -> None:
if not string.startswith("/"):
raise ValueError(f"URL rule '{string}' must start with a slash.")
self.rule = string
self.is_leaf = not string.endswith("/")
self.is_branch = string.endswith("/")
self.map: Map = None # type: ignore
self.strict_slashes = strict_slashes
self.merge_slashes = merge_slashes
self.subdomain = subdomain
self.host = host
self.defaults = defaults
self.build_only = build_only
self.alias = alias
self.websocket = websocket
if methods is not None:
if isinstance(methods, str):
raise TypeError("'methods' should be a list of strings.")
methods = {x.upper() for x in methods}
if "HEAD" not in methods and "GET" in methods:
methods.add("HEAD")
if websocket and methods - {"GET", "HEAD", "OPTIONS"}:
raise ValueError(
"WebSocket rules can only use 'GET', 'HEAD', and 'OPTIONS' methods."
)
self.methods = methods
self.endpoint: t.Any = endpoint
self.redirect_to = redirect_to
if defaults:
self.arguments = set(map(str, defaults))
else:
self.arguments = set()
self._converters: dict[str, BaseConverter] = {}
self._trace: list[tuple[bool, str]] = []
self._parts: list[RulePart] = []
def empty(self) -> Rule:
"""
Return an unbound copy of this rule.
This can be useful if want to reuse an already bound URL for another
map. See ``get_empty_kwargs`` to override what keyword arguments are
provided to the new copy.
"""
return type(self)(self.rule, **self.get_empty_kwargs())
def get_empty_kwargs(self) -> t.Mapping[str, t.Any]:
"""
Provides kwargs for instantiating empty copy with empty()
Use this method to provide custom keyword arguments to the subclass of
``Rule`` when calling ``some_rule.empty()``. Helpful when the subclass
has custom keyword arguments that are needed at instantiation.
Must return a ``dict`` that will be provided as kwargs to the new
instance of ``Rule``, following the initial ``self.rule`` value which
is always provided as the first, required positional argument.
"""
defaults = None
if self.defaults:
defaults = dict(self.defaults)
return dict(
defaults=defaults,
subdomain=self.subdomain,
methods=self.methods,
build_only=self.build_only,
endpoint=self.endpoint,
strict_slashes=self.strict_slashes,
redirect_to=self.redirect_to,
alias=self.alias,
host=self.host,
)
def get_rules(self, map: Map) -> t.Iterator[Rule]:
yield self
def refresh(self) -> None:
"""Rebinds and refreshes the URL. Call this if you modified the
rule in place.
:internal:
"""
self.bind(self.map, rebind=True)
def bind(self, map: Map, rebind: bool = False) -> None:
"""Bind the url to a map and create a regular expression based on
the information from the rule itself and the defaults from the map.
:internal:
"""
if self.map is not None and not rebind:
raise RuntimeError(f"url rule {self!r} already bound to map {self.map!r}")
self.map = map
if self.strict_slashes is None:
self.strict_slashes = map.strict_slashes
if self.merge_slashes is None:
self.merge_slashes = map.merge_slashes
if self.subdomain is None:
self.subdomain = map.default_subdomain
self.compile()
def get_converter(
self,
variable_name: str,
converter_name: str,
args: tuple[t.Any, ...],
kwargs: t.Mapping[str, t.Any],
) -> BaseConverter:
"""Looks up the converter for the given parameter.
.. versionadded:: 0.9
"""
if converter_name not in self.map.converters:
raise LookupError(f"the converter {converter_name!r} does not exist")
return self.map.converters[converter_name](self.map, *args, **kwargs)
def _encode_query_vars(self, query_vars: t.Mapping[str, t.Any]) -> str:
items: t.Iterable[tuple[str, str]] = iter_multi_items(query_vars)
if self.map.sort_parameters:
items = sorted(items, key=self.map.sort_key)
return _urlencode(items)
def _parse_rule(self, rule: str) -> t.Iterable[RulePart]:
content = ""
static = True
argument_weights = []
static_weights: list[tuple[int, int]] = []
final = False
convertor_number = 0
pos = 0
while pos < len(rule):
match = _part_re.match(rule, pos)
if match is None:
raise ValueError(f"malformed url rule: {rule!r}")
data = match.groupdict()
if data["static"] is not None:
static_weights.append((len(static_weights), -len(data["static"])))
self._trace.append((False, data["static"]))
content += data["static"] if static else re.escape(data["static"])
if data["variable"] is not None:
if static:
# Switching content to represent regex, hence the need to escape
content = re.escape(content)
static = False
c_args, c_kwargs = parse_converter_args(data["arguments"] or "")
convobj = self.get_converter(
data["variable"], data["converter"] or "default", c_args, c_kwargs
)
self._converters[data["variable"]] = convobj
self.arguments.add(data["variable"])
if not convobj.part_isolating:
final = True
content += f"(?P<__werkzeug_{convertor_number}>{convobj.regex})"
convertor_number += 1
argument_weights.append(convobj.weight)
self._trace.append((True, data["variable"]))
if data["slash"] is not None:
self._trace.append((False, "/"))
if final:
content += "/"
else:
if not static:
content += r"\Z"
weight = Weighting(
-len(static_weights),
static_weights,
-len(argument_weights),
argument_weights,
)
yield RulePart(
content=content,
final=final,
static=static,
suffixed=False,
weight=weight,
)
content = ""
static = True
argument_weights = []
static_weights = []
final = False
convertor_number = 0
pos = match.end()
suffixed = False
if final and content[-1] == "/":
# If a converter is part_isolating=False (matches slashes) and ends with a
# slash, augment the regex to support slash redirects.
suffixed = True
content = content[:-1] + "(?<!/)(/?)"
if not static:
content += r"\Z"
weight = Weighting(
-len(static_weights),
static_weights,
-len(argument_weights),
argument_weights,
)
yield RulePart(
content=content,
final=final,
static=static,
suffixed=suffixed,
weight=weight,
)
if suffixed:
yield RulePart(
content="", final=False, static=True, suffixed=False, weight=weight
)
def compile(self) -> None:
"""Compiles the regular expression and stores it."""
assert self.map is not None, "rule not bound"
if self.map.host_matching:
domain_rule = self.host or ""
else:
domain_rule = self.subdomain or ""
self._parts = []
self._trace = []
self._converters = {}
if domain_rule == "":
self._parts = [
RulePart(
content="",
final=False,
static=True,
suffixed=False,
weight=Weighting(0, [], 0, []),
)
]
else:
self._parts.extend(self._parse_rule(domain_rule))
self._trace.append((False, "|"))
rule = self.rule
if self.merge_slashes:
rule = re.sub("/{2,}?", "/", self.rule)
self._parts.extend(self._parse_rule(rule))
self._build: t.Callable[..., tuple[str, str]]
self._build = self._compile_builder(False).__get__(self, None)
self._build_unknown: t.Callable[..., tuple[str, str]]
self._build_unknown = self._compile_builder(True).__get__(self, None)
@staticmethod
def _get_func_code(code: CodeType, name: str) -> t.Callable[..., tuple[str, str]]:
globs: dict[str, t.Any] = {}
locs: dict[str, t.Any] = {}
exec(code, globs, locs)
return locs[name] # type: ignore
def _compile_builder(
self, append_unknown: bool = True
) -> t.Callable[..., tuple[str, str]]:
defaults = self.defaults or {}
dom_ops: list[tuple[bool, str]] = []
url_ops: list[tuple[bool, str]] = []
opl = dom_ops
for is_dynamic, data in self._trace:
if data == "|" and opl is dom_ops:
opl = url_ops
continue
# this seems like a silly case to ever come up but:
# if a default is given for a value that appears in the rule,
# resolve it to a constant ahead of time
if is_dynamic and data in defaults:
data = self._converters[data].to_url(defaults[data])
opl.append((False, data))
elif not is_dynamic:
# safe = https://url.spec.whatwg.org/#url-path-segment-string
opl.append((False, quote(data, safe="!$&'()*+,/:;=@")))
else:
opl.append((True, data))
def _convert(elem: str) -> ast.Call:
ret = _prefix_names(_CALL_CONVERTER_CODE_FMT.format(elem=elem), ast.Call)
ret.args = [ast.Name(elem, ast.Load())]
return ret
def _parts(ops: list[tuple[bool, str]]) -> list[ast.expr]:
parts: list[ast.expr] = [
_convert(elem) if is_dynamic else ast.Constant(elem)
for is_dynamic, elem in ops
]
parts = parts or [ast.Constant("")]
# constant fold
ret = [parts[0]]
for p in parts[1:]:
if isinstance(p, ast.Constant) and isinstance(ret[-1], ast.Constant):
ret[-1] = ast.Constant(ret[-1].value + p.value) # type: ignore[operator]
else:
ret.append(p)
return ret
dom_parts = _parts(dom_ops)
url_parts = _parts(url_ops)
body: list[ast.stmt]
if not append_unknown:
body = []
else:
body = [_IF_KWARGS_URL_ENCODE_AST]
url_parts.extend(_URL_ENCODE_AST_NAMES)
def _join(parts: list[ast.expr]) -> ast.expr:
if len(parts) == 1: # shortcut
return parts[0]
return ast.JoinedStr(parts)
body.append(
ast.Return(ast.Tuple([_join(dom_parts), _join(url_parts)], ast.Load()))
)
pargs = [
elem
for is_dynamic, elem in dom_ops + url_ops
if is_dynamic and elem not in defaults
]
kargs = [str(k) for k in defaults]
func_ast = _prefix_names("def _(): pass", ast.FunctionDef)
func_ast.name = f"<builder:{self.rule!r}>"
func_ast.args.args.append(ast.arg(".self", None))
for arg in pargs + kargs:
func_ast.args.args.append(ast.arg(arg, None))
func_ast.args.kwarg = ast.arg(".kwargs", None)
for _ in kargs:
func_ast.args.defaults.append(ast.Constant(""))
func_ast.body = body
# Use `ast.parse` instead of `ast.Module` for better portability, since the
# signature of `ast.Module` can change.
module = ast.parse("")
module.body = [func_ast]
# mark everything as on line 1, offset 0
# less error-prone than `ast.fix_missing_locations`
# bad line numbers cause an assert to fail in debug builds
for node in ast.walk(module):
if "lineno" in node._attributes:
node.lineno = 1 # type: ignore[attr-defined]
if "end_lineno" in node._attributes:
node.end_lineno = node.lineno # type: ignore[attr-defined]
if "col_offset" in node._attributes:
node.col_offset = 0 # type: ignore[attr-defined]
if "end_col_offset" in node._attributes:
node.end_col_offset = node.col_offset # type: ignore[attr-defined]
code = compile(module, "<werkzeug routing>", "exec")
return self._get_func_code(code, func_ast.name)
def build(
self, values: t.Mapping[str, t.Any], append_unknown: bool = True
) -> tuple[str, str] | None:
"""Assembles the relative url for that rule and the subdomain.
If building doesn't work for some reasons `None` is returned.
:internal:
"""
try:
if append_unknown:
return self._build_unknown(**values)
else:
return self._build(**values)
except ValidationError:
return None
def provides_defaults_for(self, rule: Rule) -> bool:
"""Check if this rule has defaults for a given rule.
:internal:
"""
return bool(
not self.build_only
and self.defaults
and self.endpoint == rule.endpoint
and self != rule
and self.arguments == rule.arguments
)
def suitable_for(
self, values: t.Mapping[str, t.Any], method: str | None = None
) -> bool:
"""Check if the dict of values has enough data for url generation.
:internal:
"""
# if a method was given explicitly and that method is not supported
# by this rule, this rule is not suitable.
if (
method is not None
and self.methods is not None
and method not in self.methods
):
return False
defaults = self.defaults or ()
# all arguments required must be either in the defaults dict or
# the value dictionary otherwise it's not suitable
for key in self.arguments:
if key not in defaults and key not in values:
return False
# in case defaults are given we ensure that either the value was
# skipped or the value is the same as the default value.
if defaults:
for key, value in defaults.items():
if key in values and value != values[key]:
return False
return True
def build_compare_key(self) -> tuple[int, int, int]:
"""The build compare key for sorting.
:internal:
"""
return (1 if self.alias else 0, -len(self.arguments), -len(self.defaults or ()))
def __eq__(self, other: object) -> bool:
return isinstance(other, type(self)) and self._trace == other._trace
__hash__ = None # type: ignore
def __str__(self) -> str:
return self.rule
def __repr__(self) -> str:
if self.map is None:
return f"<{type(self).__name__} (unbound)>"
parts = []
for is_dynamic, data in self._trace:
if is_dynamic:
parts.append(f"<{data}>")
else:
parts.append(data)
parts_str = "".join(parts).lstrip("|")
methods = f" ({', '.join(self.methods)})" if self.methods is not None else ""
return f"<{type(self).__name__} {parts_str!r}{methods} -> {self.endpoint}>"
| Rule |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-microsoft-sharepoint/source_microsoft_sharepoint/utils.py | {
"start": 4378,
"end": 7182
} | class ____:
"""
A basic builder that constructs a URL with placeholder parameters like:
{{client_id_param}}
{{redirect_uri_param}}
etc.
These placeholders will be replaced later during Oauth flow.
"""
def __init__(self):
self._scheme = "https"
self._host = ""
self._path = ""
self._segments = [] # Each segment will become part of the query string
def set_scheme(self, scheme: str):
self._scheme = scheme
return self
def set_host(self, host: str):
self._host = host
return self
def set_path(self, path: str):
# If you want a leading slash, you can incorporate it here or let caller handle it
self._path = path
return self
def add_key_value_placeholder_param(self, param_name: str):
"""
Example:
add_key_value_placeholder_param("client_id")
=> produces "{{client_id_param}}" in the final query string.
"""
placeholder = f"{{{{{param_name}_param}}}}" # e.g. "{{client_id_param}}"
self._segments.append(placeholder)
return self
def add_literal_param(self, literal: str):
"""
If you want to add a static string like "response_type=code"
or "access_type=offline", you can do so here.
"""
self._segments.append(literal)
return self
def build(self) -> str:
"""
Joins the query segments with '&' and forms the complete URL.
Example final output might look like:
https://accounts.google.com/o/oauth2/v2/auth?{{client_id_param}}&{{redirect_uri_param}}&response_type=code
"""
query_string = "&".join(self._segments)
query_string = "?" + query_string if query_string else ""
return f"{self._scheme}://{self._host}{self._path}{query_string}"
def get_site_prefix(graph_client: GraphClient) -> Tuple[str, str]:
"""
Retrieves the SharePoint site and extracts its URL and host prefix.
Example:
For a site with `web_url` = "https://contoso.sharepoint.com/sites/example" and
`site_collection.hostname` = "contoso.sharepoint.com", this function will return:
("https://contoso.sharepoint.com/sites/example", "contoso")
Args:
graph_client (GraphClient): An instance of the Microsoft Graph client.
Returns:
Tuple[str, str]: A tuple containing (site_url, hostname_prefix).
"""
site = execute_query_with_retry(graph_client.sites.root.get())
site_url = site.web_url
host_name = site.site_collection.hostname
host_name_parts: List = host_name.split(".")
if len(host_name_parts) < 2:
raise ValueError(f"Invalid host name: {host_name}")
return site_url, host_name_parts[0]
| PlaceholderUrlBuilder |
python | pytorch__pytorch | test/torch_np/test_basic.py | {
"start": 5977,
"end": 7016
} | class ____(TestCase):
"""Smoke test of functions (array_like) -> scalar or python object."""
@parametrize("func, np_func", one_arg_scalar_funcs)
def test_toscalar_tensor(self, func, np_func):
t = torch.Tensor([[1, 2, 3], [4, 5, 6]])
ta = func(t)
tn = np_func(_np.asarray(t))
assert not isinstance(ta, w.ndarray)
assert ta == tn
@parametrize("func, np_func", one_arg_scalar_funcs)
def test_toscalar_list(self, func, np_func):
t = [[1, 2, 3], [4, 5, 6]]
ta = func(t)
tn = np_func(t)
assert not isinstance(ta, w.ndarray)
assert ta == tn
@parametrize("func, np_func", one_arg_scalar_funcs)
def test_toscalar_array(self, func, np_func):
t = w.asarray([[1, 2, 3], [4, 5, 6]])
ta = func(t)
tn = np_func(t)
assert not isinstance(ta, w.ndarray)
assert ta == tn
shape_funcs = [w.zeros, w.empty, w.ones, functools.partial(w.full, fill_value=42)]
@instantiate_parametrized_tests
| TestOneArrToScalar |
python | numba__numba | numba/tests/test_indexing.py | {
"start": 23539,
"end": 35390
} | class ____(TestCase):
"""
Test basic indexed store into an array.
Note fancy indexing is tested in test_fancy_indexing.
"""
def test_conversion_setitem(self, flags=enable_pyobj_flags):
""" this used to work, and was used in one of the tutorials """
from numba import jit
def pyfunc(array):
for index in range(len(array)):
array[index] = index % decimal.Decimal(100)
cfunc = jit("void(i8[:])", **flags)(pyfunc)
udt = np.arange(100, dtype='i1')
control = udt.copy()
pyfunc(control)
cfunc(udt)
self.assertPreciseEqual(udt, control)
def test_1d_slicing_set(self, flags=enable_pyobj_flags):
"""
1d to 1d slice assignment
"""
pyfunc = slicing_1d_usecase_set
# Note heterogeneous types for the source and destination arrays
# (int16[:] -> int32[:])
dest_type = types.Array(types.int32, 1, 'C')
src_type = types.Array(types.int16, 1, 'A')
argtys = (dest_type, src_type, types.int32, types.int32, types.int32)
cfunc = jit(argtys, **flags)(pyfunc)
N = 10
arg = np.arange(N, dtype='i2') + 40
bounds = [0, 2, N - 2, N, N + 1, N + 3,
-2, -N + 2, -N, -N - 1, -N - 3]
def make_dest():
return np.zeros_like(arg, dtype='i4')
for start, stop in itertools.product(bounds, bounds):
for step in (1, 2, -1, -2):
args = start, stop, step
index = slice(*args)
pyleft = pyfunc(make_dest(), arg[index], *args)
cleft = cfunc(make_dest(), arg[index], *args)
self.assertPreciseEqual(pyleft, cleft)
# Mismatching input size and slice length
with self.assertRaises(ValueError):
cfunc(np.zeros_like(arg, dtype=np.int32), arg, 0, 0, 1)
def check_1d_slicing_set_sequence(self, flags, seqty, seq):
"""
Generic sequence to 1d slice assignment
"""
pyfunc = slicing_1d_usecase_set
dest_type = types.Array(types.int32, 1, 'C')
argtys = (dest_type, seqty, types.int32, types.int32, types.int32)
# This emulates the use of `compile_result`. The args that are passed
# into this checking function are not as advertised in argtys and
# implicit casting is required.
cfunc = jit(argtys, **flags)(pyfunc).overloads[argtys].entry_point
N = 10
k = len(seq)
arg = np.arange(N, dtype=np.int32)
args = (seq, 1, -N + k + 1, 1)
expected = pyfunc(arg.copy(), *args)
got = cfunc(arg.copy(), *args)
self.assertPreciseEqual(expected, got)
args = (seq, 1, -N + k, 1)
with self.assertRaises(ValueError) as raises:
cfunc(arg.copy(), *args)
if flags.get('nopython', False):
# if in nopython mode, check the error message from Numba
slice_size = len(arg[slice(1, -N + k, 1)])
msg = (f"cannot assign slice of shape ({k},) from input of shape "
f"({slice_size},)")
self.assertIn(msg, str(raises.exception))
def test_1d_slicing_set_tuple(self, flags=enable_pyobj_flags):
"""
Tuple to 1d slice assignment
"""
self.check_1d_slicing_set_sequence(
flags, types.UniTuple(types.int16, 2), (8, -42))
def test_1d_slicing_set_list(self, flags=enable_pyobj_flags):
"""
List to 1d slice assignment
"""
self.check_1d_slicing_set_sequence(
flags, types.List(types.int16), [8, -42])
def test_1d_slicing_broadcast(self, flags=enable_pyobj_flags):
"""
scalar to 1d slice assignment
"""
pyfunc = slicing_1d_usecase_set
arraytype = types.Array(types.int32, 1, 'C')
# Note heterogeneous types for the source scalar and the destination
# array (int16 -> int32[:])
argtys = (arraytype, types.int16, types.int32, types.int32, types.int32)
cfunc = jit(argtys, **flags)(pyfunc)
N = 10
arg = np.arange(N, dtype='i4')
val = 42
bounds = [0, 2, N - 2, N, N + 1, N + 3,
-2, -N + 2, -N, -N - 1, -N - 3]
for start, stop in itertools.product(bounds, bounds):
for step in (1, 2, -1, -2):
args = val, start, stop, step
pyleft = pyfunc(arg.copy(), *args)
cleft = cfunc(arg.copy(), *args)
self.assertPreciseEqual(pyleft, cleft)
def test_1d_slicing_add(self, flags=enable_pyobj_flags):
pyfunc = slicing_1d_usecase_add
arraytype = types.Array(types.int32, 1, 'C')
argtys = (arraytype, arraytype, types.int32, types.int32)
cfunc = jit(argtys, **flags)(pyfunc)
arg = np.arange(10, dtype='i4')
for test in ((0, 10), (2, 5)):
pyleft = pyfunc(np.zeros_like(arg), arg[slice(*test)], *test)
cleft = cfunc(np.zeros_like(arg), arg[slice(*test)], *test)
self.assertPreciseEqual(pyleft, cleft)
def test_1d_slicing_set_npm(self):
self.test_1d_slicing_set(flags=Noflags)
def test_1d_slicing_set_list_npm(self):
self.test_1d_slicing_set_list(flags=Noflags)
def test_1d_slicing_set_tuple_npm(self):
self.test_1d_slicing_set_tuple(flags=Noflags)
def test_1d_slicing_broadcast_npm(self):
self.test_1d_slicing_broadcast(flags=Noflags)
def test_1d_slicing_add_npm(self):
self.test_1d_slicing_add(flags=Noflags)
def test_2d_slicing_set(self, flags=enable_pyobj_flags):
"""
2d to 2d slice assignment
"""
pyfunc = slicing_2d_usecase_set
arraytype = types.Array(types.int32, 2, 'A')
argtys = (arraytype, arraytype, types.int32, types.int32, types.int32,
types.int32, types.int32, types.int32)
cfunc = jit(argtys, **flags)(pyfunc)
arg = np.arange(10*10, dtype='i4').reshape(10,10)
tests = [
(0, 10, 1, 0, 10, 1),
(2, 3, 1, 2, 3, 1),
(10, 0, 1, 10, 0, 1),
(0, 10, -1, 0, 10, -1),
(0, 10, 2, 0, 10, 2),
]
for test in tests:
pyleft = pyfunc(np.zeros_like(arg), arg[slice(*test[0:3]), slice(*test[3:6])], *test)
cleft = cfunc(np.zeros_like(arg), arg[slice(*test[0:3]), slice(*test[3:6])], *test)
self.assertPreciseEqual(cleft, pyleft)
def test_2d_slicing_broadcast(self, flags=enable_pyobj_flags):
"""
scalar to 2d slice assignment
"""
pyfunc = slicing_2d_usecase_set
arraytype = types.Array(types.int32, 2, 'C')
# Note heterogeneous types for the source scalar and the destination
# array (int16 -> int32[:])
argtys = (arraytype, types.int16, types.int32, types.int32, types.int32,
types.int32, types.int32, types.int32)
cfunc = jit(argtys, **flags)(pyfunc)
arg = np.arange(10*10, dtype='i4').reshape(10,10)
val = 42
tests = [
(0, 10, 1, 0, 10, 1),
(2, 3, 1, 2, 3, 1),
(10, 0, 1, 10, 0, 1),
(0, 10, -1, 0, 10, -1),
(0, 10, 2, 0, 10, 2),
]
for test in tests:
pyleft = pyfunc(arg.copy(), val, *test)
cleft = cfunc(arg.copy(), val, *test)
self.assertPreciseEqual(cleft, pyleft)
def test_2d_slicing_set_npm(self):
self.test_2d_slicing_set(flags=Noflags)
def test_2d_slicing_broadcast_npm(self):
self.test_2d_slicing_broadcast(flags=Noflags)
def test_setitem(self):
"""
scalar indexed assignment
"""
arr = np.arange(5)
setitem_usecase(arr, 1, 42)
self.assertEqual(arr.tolist(), [0, 42, 2, 3, 4])
# Using a 0-d array as scalar index
setitem_usecase(arr, np.array(3).astype(np.uint16), 8)
self.assertEqual(arr.tolist(), [0, 42, 2, 8, 4])
# Scalar Broadcasting
arr = np.arange(9).reshape(3, 3)
setitem_usecase(arr, 1, 42)
self.assertEqual(arr.tolist(), [[0, 1, 2], [42, 42, 42], [6, 7, 8]])
def test_setitem_broadcast(self):
"""
broadcasted array assignment
"""
# Scalar Broadcasting
dst = np.arange(5)
setitem_broadcast_usecase(dst, 42)
self.assertEqual(dst.tolist(), [42] * 5)
# 1D -> 2D Array Broadcasting
dst = np.arange(6).reshape(2, 3)
setitem_broadcast_usecase(dst, np.arange(1, 4))
self.assertEqual(dst.tolist(), [[1, 2, 3], [1, 2, 3]])
# 2D -> 2D Array Broadcasting
dst = np.arange(6).reshape(2, 3)
setitem_broadcast_usecase(dst, np.arange(1, 4).reshape(1, 3))
self.assertEqual(dst.tolist(), [[1, 2, 3], [1, 2, 3]])
# 2D -> 4D Array Broadcasting
dst = np.arange(12).reshape(2, 1, 2, 3)
setitem_broadcast_usecase(dst, np.arange(1, 4).reshape(1, 3))
inner2 = [[1, 2, 3], [1, 2, 3]]
self.assertEqual(dst.tolist(), [[inner2]] * 2)
# 2D -> 1D Array Broadcasting
dst = np.arange(5)
setitem_broadcast_usecase(dst, np.arange(1, 6).reshape(1, 5))
self.assertEqual(dst.tolist(), [1, 2, 3, 4, 5])
# 4D -> 2D Array Broadcasting
dst = np.arange(6).reshape(2, 3)
setitem_broadcast_usecase(dst, np.arange(1, 1 + dst.size).reshape(1, 1, 2, 3))
self.assertEqual(dst.tolist(), [[1, 2, 3], [4, 5, 6]])
def test_setitem_broadcast_error(self):
# higher dim assigned into lower dim
# 2D -> 1D
dst = np.arange(5)
src = np.arange(10).reshape(2, 5)
with self.assertRaises(ValueError) as raises:
setitem_broadcast_usecase(dst, src)
errmsg = str(raises.exception)
self.assertEqual('cannot broadcast source array for assignment',
errmsg)
# 3D -> 2D
dst = np.arange(5).reshape(1, 5)
src = np.arange(10).reshape(1, 2, 5)
with self.assertRaises(ValueError) as raises:
setitem_broadcast_usecase(dst, src)
errmsg = str(raises.exception)
self.assertEqual(('cannot assign slice of shape (2, 5) from input of' +
' shape (1, 5)'),
errmsg)
# lower to higher
# 1D -> 2D
dst = np.arange(10).reshape(2, 5)
src = np.arange(4)
with self.assertRaises(ValueError) as raises:
setitem_broadcast_usecase(dst, src)
errmsg = str(raises.exception)
self.assertEqual(('cannot assign slice of shape (2, 4) from input of' +
' shape (2, 5)'),
errmsg)
def test_slicing_1d_broadcast(self):
# 1D -> 2D sliced (1)
dst = np.arange(6).reshape(3, 2)
src = np.arange(1, 3)
slicing_1d_usecase_set(dst, src, 0, 2, 1)
self.assertEqual(dst.tolist(), [[1, 2], [1, 2], [4, 5]])
# 1D -> 2D sliced (2)
dst = np.arange(6).reshape(3, 2)
src = np.arange(1, 3)
slicing_1d_usecase_set(dst, src, 0, None, 2)
self.assertEqual(dst.tolist(), [[1, 2], [2, 3], [1, 2]])
# 2D -> 2D sliced (3)
dst = np.arange(6).reshape(3, 2)
src = np.arange(1, 5).reshape(2, 2)
slicing_1d_usecase_set(dst, src, None, 2, 1)
self.assertEqual(dst.tolist(), [[1, 2], [3, 4], [4, 5]])
def test_setitem_readonly(self):
arr = np.arange(5)
arr.flags.writeable = False
with self.assertRaises((TypeError, errors.TypingError)) as raises:
setitem_usecase(arr, 1, 42)
self.assertIn("Cannot modify readonly array of type:",
str(raises.exception))
| TestSetItem |
python | kamyu104__LeetCode-Solutions | Python/diagonal-traverse-ii.py | {
"start": 688,
"end": 1120
} | class ____(object):
def findDiagonalOrder(self, nums):
"""
:type nums: List[List[int]]
:rtype: List[int]
"""
result = []
for r, row in enumerate(nums):
for c, num in enumerate(row):
if len(result) <= r+c:
result.append([])
result[r+c].append(num)
return [num for row in result for num in reversed(row)]
| Solution2 |
python | openai__openai-python | src/openai/types/beta/threads/runs/code_interpreter_tool_call.py | {
"start": 1102,
"end": 1473
} | class ____(BaseModel):
input: str
"""The input to the Code Interpreter tool call."""
outputs: List[CodeInterpreterOutput]
"""The outputs from the Code Interpreter tool call.
Code Interpreter can output one or more items, including text (`logs`) or images
(`image`). Each of these are represented by a different object type.
"""
| CodeInterpreter |
python | google__jax | jax/_src/custom_derivatives.py | {
"start": 3355,
"end": 16584
} | class ____(Generic[ReturnValue]):
"""Set up a JAX-transformable function for a custom JVP rule definition.
This class is meant to be used as a function decorator. Instances are
callables that behave similarly to the underlying function to which the
decorator was applied, except when a differentiation transformation (like
:py:func:`jax.jvp` or :py:func:`jax.grad`) is applied, in which case a custom
user-supplied JVP rule function is used instead of tracing into and
performing automatic differentiation of the underlying function's
implementation.
There are two instance methods available for defining the custom JVP rule:
:py:func:`~jax.custom_jvp.defjvp` for defining a *single* custom JVP rule for
all the function's inputs, and for convenience
:py:func:`~jax.custom_jvp.defjvps`, which wraps
:py:func:`~jax.custom_jvp.defjvp`, and allows you to provide separate
definitions for the partial derivatives of the function w.r.t. each of its
arguments.
For example::
@jax.custom_jvp
def f(x, y):
return jnp.sin(x) * y
@f.defjvp
def f_jvp(primals, tangents):
x, y = primals
x_dot, y_dot = tangents
primal_out = f(x, y)
tangent_out = jnp.cos(x) * x_dot * y + jnp.sin(x) * y_dot
return primal_out, tangent_out
For a more detailed introduction, see the tutorial_.
.. _tutorial: https://docs.jax.dev/en/latest/notebooks/Custom_derivative_rules_for_Python_code.html
"""
fun: Callable[..., ReturnValue]
nondiff_argnums: Sequence[int]
nondiff_argnames: Sequence[str]
jvp: Callable[..., tuple[ReturnValue, ReturnValue]] | None = None
symbolic_zeros: bool = False
def __init__(self,
fun: Callable[..., ReturnValue],
nondiff_argnums: Sequence[int] = (),
nondiff_argnames: Sequence[str] = (),
):
update_wrapper(self, fun)
self.fun = fun
nondiff_argnums_: set[int] = set()
if nondiff_argnames:
sig = fun_signature(self.fun)
assert sig is not None
inferred_nondiff_argnums, _ = infer_argnums_and_argnames(
sig, None, nondiff_argnames
)
nondiff_argnums_.update(inferred_nondiff_argnums)
if nondiff_argnums:
nondiff_argnums_.update(nondiff_argnums)
self.nondiff_argnums = tuple(sorted(nondiff_argnums_))
__getattr__ = custom_api_util.forward_attr
def defjvp(self,
jvp: Callable[..., tuple[ReturnValue, ReturnValue]],
symbolic_zeros: bool = False,
) -> Callable[..., tuple[ReturnValue, ReturnValue]]:
"""Define a custom JVP rule for the function represented by this instance.
Args:
jvp: a Python callable representing the custom JVP rule. When there are no
``nondiff_argnums``, the ``jvp`` function should accept two arguments,
where the first is a tuple of primal inputs and the second is a tuple of
tangent inputs. The lengths of both tuples are equal to the number of
parameters of the :class:`~jax.custom_jvp` function. The ``jvp`` function
should produce as output a pair where the first element is the primal
output and the second element is the tangent output. Elements of the
input and output tuples may be arrays or any nested tuples/lists/dicts
thereof.
symbolic_zeros: boolean, indicating whether the rule should be passed
objects representing static symbolic zeros in its tangent argument in
correspondence with unperturbed values; otherwise, only standard JAX
types (e.g. array-likes) are passed. Setting this option to ``True``
allows a JVP rule to detect whether certain inputs are not involved in
differentiation, but at the cost of needing special handling for these
objects (which e.g. can't be passed into jax.numpy functions). Default
``False``.
Returns:
Returns ``jvp`` so that ``defjvp`` can be used as a decorator.
Examples:
>>> @jax.custom_jvp
... def f(x, y):
... return jnp.sin(x) * y
...
>>> @f.defjvp
... def f_jvp(primals, tangents):
... x, y = primals
... x_dot, y_dot = tangents
... primal_out = f(x, y)
... tangent_out = jnp.cos(x) * x_dot * y + jnp.sin(x) * y_dot
... return primal_out, tangent_out
>>> x = jnp.float32(1.0)
>>> y = jnp.float32(2.0)
>>> with jnp.printoptions(precision=2):
... print(jax.value_and_grad(f)(x, y))
(Array(1.68, dtype=float32), Array(1.08, dtype=float32))
"""
self.jvp = jvp
self.symbolic_zeros = symbolic_zeros
return jvp
def defjvps(self, *jvps: Callable[..., ReturnValue] | None) -> None:
"""Convenience wrapper for defining JVPs for each argument separately.
This convenience wrapper cannot be used together with ``nondiff_argnums``.
Args:
*jvps: a sequence of functions, one for each positional argument of the
:class:`~jax.custom_jvp` function. Each function takes as arguments
the tangent value for the corresponding primal input, the primal
output, and the primal inputs. See the example below.
Returns:
None.
Examples:
>>> @jax.custom_jvp
... def f(x, y):
... return jnp.sin(x) * y
...
>>> f.defjvps(lambda x_dot, primal_out, x, y: jnp.cos(x) * x_dot * y,
... lambda y_dot, primal_out, x, y: jnp.sin(x) * y_dot)
>>> x = jnp.float32(1.0)
>>> y = jnp.float32(2.0)
>>> with jnp.printoptions(precision=2):
... print(jax.value_and_grad(f)(x, y))
(Array(1.68, dtype=float32), Array(1.08, dtype=float32))
"""
if self.nondiff_argnums:
raise TypeError("Can't use ``defjvps`` with ``nondiff_argnums``.")
def jvp(primals, tangents):
primal_out = self(*primals)
zeros = _zeros_like_pytree(primal_out)
all_tangents_out = [jvp(t, primal_out, *primals) if jvp else zeros
for t, jvp in zip(tangents, jvps)]
tangent_out = tree_map(_sum_tangents, primal_out, *all_tangents_out)
return primal_out, tangent_out
self.defjvp(jvp)
@partial(traceback_util.api_boundary,
repro_api_name="jax.custom_jvp.__call__")
def __call__(self, *args: Any, **kwargs: Any) -> ReturnValue: # pytype: disable=invalid-annotation
debug = debug_info("custom_jvp fun", self.fun, args, kwargs,
static_argnums=self.nondiff_argnums)
primal_name = debug.func_name
if not self.jvp:
msg = f"No JVP defined for custom_jvp function {primal_name} using defjvp."
raise AttributeError(msg)
try:
args = resolve_kwargs(self.fun, args, kwargs)
except TypeError as e:
raise TypeError(
"The input arguments to the custom_jvp-decorated function "
f"{primal_name} could not be resolved to positional-only arguments. "
f"Binding failed with the error:\n{e}"
) from e
if self.nondiff_argnums:
args = tuple(_stop_gradient(x) if i in self.nondiff_argnums else x
for i, x in enumerate(args))
diff_argnums = [i for i in range(len(args)) if i not in self.nondiff_argnums]
f_, dyn_args = argnums_partial(lu.wrap_init(self.fun, debug_info=debug),
diff_argnums, args,
require_static_args_hashable=False)
static_args = [args[i] for i in self.nondiff_argnums]
diff_args = [args[i] for i, a in enumerate(args) if i not in self.nondiff_argnums]
debug_jvp = debug_info("custom_jvp jvp", self.jvp,
(*static_args, diff_args, diff_args),
{},
static_argnums=tuple(range(len(static_args))))
jvp = prepend_static_args(lu.wrap_init(self.jvp,
debug_info=debug_jvp), static_args)
else:
f_, dyn_args = lu.wrap_init(self.fun, debug_info=debug), args
debug_jvp = debug_info("custom_jvp jvp", self.jvp,
(args, args),
{})
jvp = lu.wrap_init(self.jvp, debug_info=debug_jvp)
args_flat, in_tree = tree_flatten(dyn_args)
flat_fun, out_type1 = _flatten_fun_nokwargs(f_, in_tree)
flat_jvp, out_type2 = _flatten_jvp(jvp, primal_name, debug_jvp.func_name,
in_tree, out_type1)
out_flat = custom_jvp_call_p.bind(flat_fun, flat_jvp, *args_flat,
symbolic_zeros=self.symbolic_zeros)
_, (out_tree, _, _) = lu.merge_linear_aux(out_type1, out_type2)
return tree_unflatten(out_tree, out_flat)
@partial(lu.transformation_with_aux2, use_eq_store=True)
def _flatten_jvp(f, store, primal_name, jvp_name, in_tree, maybe_out_type, *args):
primals_in, tangents_in = split_list(args, [len(args) // 2])
py_primals = tree_unflatten(in_tree, primals_in)
py_tangents = tree_unflatten(in_tree, tangents_in)
pair_out = f(py_primals, py_tangents)
if not isinstance(pair_out, (list, tuple)) or len(pair_out) != 2:
msg = (f"Custom JVP rule {jvp_name} for function {primal_name} "
"must produce a pair (list or tuple of length two) representing "
f"primal and tangent outputs, but got {pair_out}.")
raise TypeError(msg)
py_primals_out, py_tangents_out = pair_out
primals_out, out_tree = tree_flatten(py_primals_out)
tangents_out, out_tree2 = tree_flatten(py_tangents_out)
primal_avals = [core.get_aval(x) for x in primals_out]
if out_tree != out_tree2:
msg = (f"Custom JVP rule {jvp_name} for function {primal_name} must "
"produce primal and tangent outputs with equal container (pytree) "
f"structures, but got {out_tree} and {out_tree2} respectively.")
raise TypeError(msg)
# If the primal function already ran, check out_tree agreement.
try: out_type_ = maybe_out_type()
except lu.StoreException: out_type_ = None
if out_type_ is not None:
out_tree_, primal_avals_, () = out_type_
ty_tree = tree_unflatten(out_tree , [a.str_short() for a in primal_avals])
ty_tree_ = tree_unflatten(out_tree_, [a.str_short() for a in primal_avals_])
if out_tree_ != out_tree:
m = (f"Custom JVP rule {jvp_name} for function {primal_name} must "
"produce a pair (list or tuple of length two) "
"where the first element represents the primal output "
"(equal in value to the output of the custom_jvp-decorated function "
f"{primal_name}, "
"and in particular of the same container/pytree structure), but "
"instead the JVP rule output's first element had container/pytree "
"structure:\n"
f""" {str(ty_tree ).replace("'", "")}\n"""
f"while the custom_jvp-decorated function {primal_name} had output "
"container/pytree structure:\n"
f""" {str(ty_tree_).replace("'", "")}.""")
raise TypeError(m)
if not all(map(core.typematch, primal_avals, primal_avals_)):
m = (f"Custom JVP rule {jvp_name} for function {primal_name} must "
"produce a pair (list or tuple of length two) "
"where the first element represents the primal output "
"(equal in value to the output of the custom_jvp-decorated function "
f"{primal_name}, "
"and in particular with leaves of the same shape/dtype), but "
"instead the JVP rule output's first element had shapes/dtypes of:\n"
f""" {str(ty_tree ).replace("'", "")}\n"""
f"while the custom_jvp-decorated function {primal_name} had output "
"shapes/dtypes of:\n"
f""" {str(ty_tree_).replace("'", "")}""")
raise TypeError(m)
primal_avals_out = [core.get_aval(x).strip_weak_type() for x in primals_out]
expected_tangent_avals_out = [
core.get_aval(x).strip_weak_type().to_tangent_aval()
for x in primals_out]
tangent_avals_out = [core.get_aval(t).strip_weak_type()
if type(t) is not SymbolicZero else t.aval.strip_weak_type()
for t in tangents_out]
if not all(map(core.typematch, expected_tangent_avals_out, tangent_avals_out)):
if len(expected_tangent_avals_out) == 1:
(av_p,), (av_et,), (av_t,) = primal_avals_out, expected_tangent_avals_out, tangent_avals_out
msg = ("Custom JVP rule must produce primal and tangent outputs with "
"corresponding shapes and dtypes. Expected {} (tangent type of {}) but got {}.")
raise TypeError(msg.format(av_et.str_short(), av_p.str_short(), av_t.str_short()))
else:
msg = ("Custom JVP rule must produce primal and tangent outputs with "
"corresponding shapes and dtypes, but got:\n{}")
disagreements = (
f" primal {av_p.str_short()} with tangent {av_t.str_short()}, expecting tangent {av_et}"
for av_p, av_et, av_t in zip(primal_avals_out, expected_tangent_avals_out, tangent_avals_out)
if av_et != av_t)
raise TypeError(msg.format('\n'.join(disagreements)))
store.store((out_tree, primal_avals, ()))
return primals_out + tangents_out
| custom_jvp |
python | sphinx-doc__sphinx | sphinx/ext/doctest.py | {
"start": 1620,
"end": 5291
} | class ____(SphinxDirective):
"""Base class for doctest-related directives."""
has_content = True
required_arguments = 0
optional_arguments = 1
final_argument_whitespace = True
def run(self) -> list[Node]:
# use ordinary docutils nodes for test code: they get special attributes
# so that our builder recognizes them, and the other builders are happy.
code = '\n'.join(self.content)
test = None
if self.name == 'doctest':
if '<BLANKLINE>' in code:
# convert <BLANKLINE>s to ordinary blank lines for presentation
test = code
code = blankline_re.sub('', code)
if (
doctestopt_re.search(code)
and 'no-trim-doctest-flags' not in self.options
):
if not test:
test = code
code = doctestopt_re.sub('', code)
nodetype: type[TextElement] = nodes.literal_block
if self.name in {'testsetup', 'testcleanup'} or 'hide' in self.options:
nodetype = nodes.comment
if self.arguments:
groups = [x.strip() for x in self.arguments[0].split(',')]
else:
groups = ['default']
node = nodetype(code, code, testnodetype=self.name, groups=groups)
self.set_source_info(node)
if test is not None:
# only save if it differs from code
node['test'] = test
if self.name == 'doctest':
node['language'] = 'pycon'
elif self.name == 'testcode':
node['language'] = 'python'
elif self.name == 'testoutput':
# don't try to highlight output
node['language'] = 'none'
node['options'] = {}
if self.name in {'doctest', 'testoutput'} and 'options' in self.options:
# parse doctest-like output comparison flags
option_strings = self.options['options'].replace(',', ' ').split()
for option in option_strings:
prefix, option_name = option[0], option[1:]
if prefix not in '+-':
self.state.document.reporter.warning(
__("missing '+' or '-' in '%s' option.") % option,
line=self.lineno,
)
continue
if option_name not in doctest.OPTIONFLAGS_BY_NAME:
self.state.document.reporter.warning(
__("'%s' is not a valid option.") % option_name,
line=self.lineno,
)
continue
flag = doctest.OPTIONFLAGS_BY_NAME[option[1:]]
node['options'][flag] = option[0] == '+'
if self.name == 'doctest' and 'pyversion' in self.options:
try:
spec = self.options['pyversion']
python_version = '.'.join(map(str, sys.version_info[:3]))
if not is_allowed_version(spec, python_version):
flag = doctest.OPTIONFLAGS_BY_NAME['SKIP']
node['options'][flag] = True # Skip the test
except InvalidSpecifier:
self.state.document.reporter.warning(
__("'%s' is not a valid pyversion option") % spec, line=self.lineno
)
if 'skipif' in self.options:
node['skipif'] = self.options['skipif']
if 'trim-doctest-flags' in self.options:
node['trim_flags'] = True
elif 'no-trim-doctest-flags' in self.options:
node['trim_flags'] = False
return [node]
| TestDirective |
python | joblib__joblib | joblib/externals/cloudpickle/cloudpickle.py | {
"start": 19482,
"end": 43594
} | class ____:
"""Sentinel for empty closures."""
@classmethod
def __reduce__(cls):
return cls.__name__
def _make_function(code, globals, name, argdefs, closure):
# Setting __builtins__ in globals is needed for nogil CPython.
globals["__builtins__"] = __builtins__
return types.FunctionType(code, globals, name, argdefs, closure)
def _make_empty_cell():
if False:
# trick the compiler into creating an empty cell in our lambda
cell = None
raise AssertionError("this route should not be executed")
return (lambda: cell).__closure__[0]
def _make_cell(value=_empty_cell_value):
cell = _make_empty_cell()
if value is not _empty_cell_value:
cell.cell_contents = value
return cell
def _make_skeleton_class(
type_constructor, name, bases, type_kwargs, class_tracker_id, extra
):
"""Build dynamic class with an empty __dict__ to be filled once memoized
If class_tracker_id is not None, try to lookup an existing class definition
matching that id. If none is found, track a newly reconstructed class
definition under that id so that other instances stemming from the same
class id will also reuse this class definition.
The "extra" variable is meant to be a dict (or None) that can be used for
forward compatibility shall the need arise.
"""
# We need to intern the keys of the type_kwargs dict to avoid having
# different pickles for the same dynamic class depending on whether it was
# dynamically created or reconstructed from a pickled stream.
type_kwargs = {sys.intern(k): v for k, v in type_kwargs.items()}
skeleton_class = types.new_class(
name, bases, {"metaclass": type_constructor}, lambda ns: ns.update(type_kwargs)
)
return _lookup_class_or_track(class_tracker_id, skeleton_class)
def _make_skeleton_enum(
bases, name, qualname, members, module, class_tracker_id, extra
):
"""Build dynamic enum with an empty __dict__ to be filled once memoized
The creation of the enum class is inspired by the code of
EnumMeta._create_.
If class_tracker_id is not None, try to lookup an existing enum definition
matching that id. If none is found, track a newly reconstructed enum
definition under that id so that other instances stemming from the same
class id will also reuse this enum definition.
The "extra" variable is meant to be a dict (or None) that can be used for
forward compatibility shall the need arise.
"""
# enums always inherit from their base Enum class at the last position in
# the list of base classes:
enum_base = bases[-1]
metacls = enum_base.__class__
classdict = metacls.__prepare__(name, bases)
for member_name, member_value in members.items():
classdict[member_name] = member_value
enum_class = metacls.__new__(metacls, name, bases, classdict)
enum_class.__module__ = module
enum_class.__qualname__ = qualname
return _lookup_class_or_track(class_tracker_id, enum_class)
def _make_typevar(name, bound, constraints, covariant, contravariant, class_tracker_id):
tv = typing.TypeVar(
name,
*constraints,
bound=bound,
covariant=covariant,
contravariant=contravariant,
)
return _lookup_class_or_track(class_tracker_id, tv)
def _decompose_typevar(obj):
return (
obj.__name__,
obj.__bound__,
obj.__constraints__,
obj.__covariant__,
obj.__contravariant__,
_get_or_create_tracker_id(obj),
)
def _typevar_reduce(obj):
# TypeVar instances require the module information hence why we
# are not using the _should_pickle_by_reference directly
module_and_name = _lookup_module_and_qualname(obj, name=obj.__name__)
if module_and_name is None:
return (_make_typevar, _decompose_typevar(obj))
elif _is_registered_pickle_by_value(module_and_name[0]):
return (_make_typevar, _decompose_typevar(obj))
return (getattr, module_and_name)
def _get_bases(typ):
if "__orig_bases__" in getattr(typ, "__dict__", {}):
# For generic types (see PEP 560)
# Note that simply checking `hasattr(typ, '__orig_bases__')` is not
# correct. Subclasses of a fully-parameterized generic class does not
# have `__orig_bases__` defined, but `hasattr(typ, '__orig_bases__')`
# will return True because it's defined in the base class.
bases_attr = "__orig_bases__"
else:
# For regular class objects
bases_attr = "__bases__"
return getattr(typ, bases_attr)
def _make_dict_keys(obj, is_ordered=False):
if is_ordered:
return OrderedDict.fromkeys(obj).keys()
else:
return dict.fromkeys(obj).keys()
def _make_dict_values(obj, is_ordered=False):
if is_ordered:
return OrderedDict((i, _) for i, _ in enumerate(obj)).values()
else:
return {i: _ for i, _ in enumerate(obj)}.values()
def _make_dict_items(obj, is_ordered=False):
if is_ordered:
return OrderedDict(obj).items()
else:
return obj.items()
# COLLECTION OF OBJECTS __getnewargs__-LIKE METHODS
# -------------------------------------------------
def _class_getnewargs(obj):
type_kwargs = {}
if "__module__" in obj.__dict__:
type_kwargs["__module__"] = obj.__module__
__dict__ = obj.__dict__.get("__dict__", None)
if isinstance(__dict__, property):
type_kwargs["__dict__"] = __dict__
return (
type(obj),
obj.__name__,
_get_bases(obj),
type_kwargs,
_get_or_create_tracker_id(obj),
None,
)
def _enum_getnewargs(obj):
members = {e.name: e.value for e in obj}
return (
obj.__bases__,
obj.__name__,
obj.__qualname__,
members,
obj.__module__,
_get_or_create_tracker_id(obj),
None,
)
# COLLECTION OF OBJECTS RECONSTRUCTORS
# ------------------------------------
def _file_reconstructor(retval):
return retval
# COLLECTION OF OBJECTS STATE GETTERS
# -----------------------------------
def _function_getstate(func):
# - Put func's dynamic attributes (stored in func.__dict__) in state. These
# attributes will be restored at unpickling time using
# f.__dict__.update(state)
# - Put func's members into slotstate. Such attributes will be restored at
# unpickling time by iterating over slotstate and calling setattr(func,
# slotname, slotvalue)
slotstate = {
# Hack to circumvent non-predictable memoization caused by string interning.
# See the inline comment in _class_setstate for details.
"__name__": "".join(func.__name__),
"__qualname__": "".join(func.__qualname__),
"__annotations__": func.__annotations__,
"__kwdefaults__": func.__kwdefaults__,
"__defaults__": func.__defaults__,
"__module__": func.__module__,
"__doc__": func.__doc__,
"__closure__": func.__closure__,
}
f_globals_ref = _extract_code_globals(func.__code__)
f_globals = {k: func.__globals__[k] for k in f_globals_ref if k in func.__globals__}
if func.__closure__ is not None:
closure_values = list(map(_get_cell_contents, func.__closure__))
else:
closure_values = ()
# Extract currently-imported submodules used by func. Storing these modules
# in a smoke _cloudpickle_subimports attribute of the object's state will
# trigger the side effect of importing these modules at unpickling time
# (which is necessary for func to work correctly once depickled)
slotstate["_cloudpickle_submodules"] = _find_imported_submodules(
func.__code__, itertools.chain(f_globals.values(), closure_values)
)
slotstate["__globals__"] = f_globals
# Hack to circumvent non-predictable memoization caused by string interning.
# See the inline comment in _class_setstate for details.
state = {"".join(k): v for k, v in func.__dict__.items()}
return state, slotstate
def _class_getstate(obj):
clsdict = _extract_class_dict(obj)
clsdict.pop("__weakref__", None)
if issubclass(type(obj), abc.ABCMeta):
# If obj is an instance of an ABCMeta subclass, don't pickle the
# cache/negative caches populated during isinstance/issubclass
# checks, but pickle the list of registered subclasses of obj.
clsdict.pop("_abc_cache", None)
clsdict.pop("_abc_negative_cache", None)
clsdict.pop("_abc_negative_cache_version", None)
registry = clsdict.pop("_abc_registry", None)
if registry is None:
# The abc caches and registered subclasses of a
# class are bundled into the single _abc_impl attribute
clsdict.pop("_abc_impl", None)
(registry, _, _, _) = abc._get_dump(obj)
clsdict["_abc_impl"] = [subclass_weakref() for subclass_weakref in registry]
else:
# In the above if clause, registry is a set of weakrefs -- in
# this case, registry is a WeakSet
clsdict["_abc_impl"] = [type_ for type_ in registry]
if "__slots__" in clsdict:
# pickle string length optimization: member descriptors of obj are
# created automatically from obj's __slots__ attribute, no need to
# save them in obj's state
if isinstance(obj.__slots__, str):
clsdict.pop(obj.__slots__)
else:
for k in obj.__slots__:
clsdict.pop(k, None)
clsdict.pop("__dict__", None) # unpicklable property object
if sys.version_info >= (3, 14):
# PEP-649/749: __annotate_func__ contains a closure that references the class
# dict. We need to exclude it from pickling. Python will recreate it when
# __annotations__ is accessed at unpickling time.
clsdict.pop("__annotate_func__", None)
return (clsdict, {})
def _enum_getstate(obj):
clsdict, slotstate = _class_getstate(obj)
members = {e.name: e.value for e in obj}
# Cleanup the clsdict that will be passed to _make_skeleton_enum:
# Those attributes are already handled by the metaclass.
for attrname in [
"_generate_next_value_",
"_member_names_",
"_member_map_",
"_member_type_",
"_value2member_map_",
]:
clsdict.pop(attrname, None)
for member in members:
clsdict.pop(member)
# Special handling of Enum subclasses
return clsdict, slotstate
# COLLECTIONS OF OBJECTS REDUCERS
# -------------------------------
# A reducer is a function taking a single argument (obj), and that returns a
# tuple with all the necessary data to re-construct obj. Apart from a few
# exceptions (list, dict, bytes, int, etc.), a reducer is necessary to
# correctly pickle an object.
# While many built-in objects (Exceptions objects, instances of the "object"
# class, etc), are shipped with their own built-in reducer (invoked using
# obj.__reduce__), some do not. The following methods were created to "fill
# these holes".
def _code_reduce(obj):
"""code object reducer."""
# If you are not sure about the order of arguments, take a look at help
# of the specific type from types, for example:
# >>> from types import CodeType
# >>> help(CodeType)
# Hack to circumvent non-predictable memoization caused by string interning.
# See the inline comment in _class_setstate for details.
co_name = "".join(obj.co_name)
# Create shallow copies of these tuple to make cloudpickle payload deterministic.
# When creating a code object during load, copies of these four tuples are
# created, while in the main process, these tuples can be shared.
# By always creating copies, we make sure the resulting payload is deterministic.
co_names = tuple(name for name in obj.co_names)
co_varnames = tuple(name for name in obj.co_varnames)
co_freevars = tuple(name for name in obj.co_freevars)
co_cellvars = tuple(name for name in obj.co_cellvars)
if hasattr(obj, "co_exceptiontable"):
# Python 3.11 and later: there are some new attributes
# related to the enhanced exceptions.
args = (
obj.co_argcount,
obj.co_posonlyargcount,
obj.co_kwonlyargcount,
obj.co_nlocals,
obj.co_stacksize,
obj.co_flags,
obj.co_code,
obj.co_consts,
co_names,
co_varnames,
obj.co_filename,
co_name,
obj.co_qualname,
obj.co_firstlineno,
obj.co_linetable,
obj.co_exceptiontable,
co_freevars,
co_cellvars,
)
elif hasattr(obj, "co_linetable"):
# Python 3.10 and later: obj.co_lnotab is deprecated and constructor
# expects obj.co_linetable instead.
args = (
obj.co_argcount,
obj.co_posonlyargcount,
obj.co_kwonlyargcount,
obj.co_nlocals,
obj.co_stacksize,
obj.co_flags,
obj.co_code,
obj.co_consts,
co_names,
co_varnames,
obj.co_filename,
co_name,
obj.co_firstlineno,
obj.co_linetable,
co_freevars,
co_cellvars,
)
elif hasattr(obj, "co_nmeta"): # pragma: no cover
# "nogil" Python: modified attributes from 3.9
args = (
obj.co_argcount,
obj.co_posonlyargcount,
obj.co_kwonlyargcount,
obj.co_nlocals,
obj.co_framesize,
obj.co_ndefaultargs,
obj.co_nmeta,
obj.co_flags,
obj.co_code,
obj.co_consts,
co_varnames,
obj.co_filename,
co_name,
obj.co_firstlineno,
obj.co_lnotab,
obj.co_exc_handlers,
obj.co_jump_table,
co_freevars,
co_cellvars,
obj.co_free2reg,
obj.co_cell2reg,
)
else:
# Backward compat for 3.8 and 3.9
args = (
obj.co_argcount,
obj.co_posonlyargcount,
obj.co_kwonlyargcount,
obj.co_nlocals,
obj.co_stacksize,
obj.co_flags,
obj.co_code,
obj.co_consts,
co_names,
co_varnames,
obj.co_filename,
co_name,
obj.co_firstlineno,
obj.co_lnotab,
co_freevars,
co_cellvars,
)
return types.CodeType, args
def _cell_reduce(obj):
"""Cell (containing values of a function's free variables) reducer."""
try:
obj.cell_contents
except ValueError: # cell is empty
return _make_empty_cell, ()
else:
return _make_cell, (obj.cell_contents,)
def _classmethod_reduce(obj):
orig_func = obj.__func__
return type(obj), (orig_func,)
def _file_reduce(obj):
"""Save a file."""
import io
if not hasattr(obj, "name") or not hasattr(obj, "mode"):
raise pickle.PicklingError(
"Cannot pickle files that do not map to an actual file"
)
if obj is sys.stdout:
return getattr, (sys, "stdout")
if obj is sys.stderr:
return getattr, (sys, "stderr")
if obj is sys.stdin:
raise pickle.PicklingError("Cannot pickle standard input")
if obj.closed:
raise pickle.PicklingError("Cannot pickle closed files")
if hasattr(obj, "isatty") and obj.isatty():
raise pickle.PicklingError("Cannot pickle files that map to tty objects")
if "r" not in obj.mode and "+" not in obj.mode:
raise pickle.PicklingError(
"Cannot pickle files that are not opened for reading: %s" % obj.mode
)
name = obj.name
retval = io.StringIO()
try:
# Read the whole file
curloc = obj.tell()
obj.seek(0)
contents = obj.read()
obj.seek(curloc)
except OSError as e:
raise pickle.PicklingError(
"Cannot pickle file %s as it cannot be read" % name
) from e
retval.write(contents)
retval.seek(curloc)
retval.name = name
return _file_reconstructor, (retval,)
def _getset_descriptor_reduce(obj):
return getattr, (obj.__objclass__, obj.__name__)
def _mappingproxy_reduce(obj):
return types.MappingProxyType, (dict(obj),)
def _memoryview_reduce(obj):
return bytes, (obj.tobytes(),)
def _module_reduce(obj):
if _should_pickle_by_reference(obj):
return subimport, (obj.__name__,)
else:
# Some external libraries can populate the "__builtins__" entry of a
# module's `__dict__` with unpicklable objects (see #316). For that
# reason, we do not attempt to pickle the "__builtins__" entry, and
# restore a default value for it at unpickling time.
state = obj.__dict__.copy()
state.pop("__builtins__", None)
return dynamic_subimport, (obj.__name__, state)
def _method_reduce(obj):
return (types.MethodType, (obj.__func__, obj.__self__))
def _logger_reduce(obj):
return logging.getLogger, (obj.name,)
def _root_logger_reduce(obj):
return logging.getLogger, ()
def _property_reduce(obj):
return property, (obj.fget, obj.fset, obj.fdel, obj.__doc__)
def _weakset_reduce(obj):
return weakref.WeakSet, (list(obj),)
def _dynamic_class_reduce(obj):
"""Save a class that can't be referenced as a module attribute.
This method is used to serialize classes that are defined inside
functions, or that otherwise can't be serialized as attribute lookups
from importable modules.
"""
if Enum is not None and issubclass(obj, Enum):
return (
_make_skeleton_enum,
_enum_getnewargs(obj),
_enum_getstate(obj),
None,
None,
_class_setstate,
)
else:
return (
_make_skeleton_class,
_class_getnewargs(obj),
_class_getstate(obj),
None,
None,
_class_setstate,
)
def _class_reduce(obj):
"""Select the reducer depending on the dynamic nature of the class obj."""
if obj is type(None): # noqa
return type, (None,)
elif obj is type(Ellipsis):
return type, (Ellipsis,)
elif obj is type(NotImplemented):
return type, (NotImplemented,)
elif obj in _BUILTIN_TYPE_NAMES:
return _builtin_type, (_BUILTIN_TYPE_NAMES[obj],)
elif not _should_pickle_by_reference(obj):
return _dynamic_class_reduce(obj)
return NotImplemented
def _dict_keys_reduce(obj):
# Safer not to ship the full dict as sending the rest might
# be unintended and could potentially cause leaking of
# sensitive information
return _make_dict_keys, (list(obj),)
def _dict_values_reduce(obj):
# Safer not to ship the full dict as sending the rest might
# be unintended and could potentially cause leaking of
# sensitive information
return _make_dict_values, (list(obj),)
def _dict_items_reduce(obj):
return _make_dict_items, (dict(obj),)
def _odict_keys_reduce(obj):
# Safer not to ship the full dict as sending the rest might
# be unintended and could potentially cause leaking of
# sensitive information
return _make_dict_keys, (list(obj), True)
def _odict_values_reduce(obj):
# Safer not to ship the full dict as sending the rest might
# be unintended and could potentially cause leaking of
# sensitive information
return _make_dict_values, (list(obj), True)
def _odict_items_reduce(obj):
return _make_dict_items, (dict(obj), True)
def _dataclass_field_base_reduce(obj):
return _get_dataclass_field_type_sentinel, (obj.name,)
# COLLECTIONS OF OBJECTS STATE SETTERS
# ------------------------------------
# state setters are called at unpickling time, once the object is created and
# it has to be updated to how it was at unpickling time.
def _function_setstate(obj, state):
"""Update the state of a dynamic function.
As __closure__ and __globals__ are readonly attributes of a function, we
cannot rely on the native setstate routine of pickle.load_build, that calls
setattr on items of the slotstate. Instead, we have to modify them inplace.
"""
state, slotstate = state
obj.__dict__.update(state)
obj_globals = slotstate.pop("__globals__")
obj_closure = slotstate.pop("__closure__")
# _cloudpickle_subimports is a set of submodules that must be loaded for
# the pickled function to work correctly at unpickling time. Now that these
# submodules are depickled (hence imported), they can be removed from the
# object's state (the object state only served as a reference holder to
# these submodules)
slotstate.pop("_cloudpickle_submodules")
obj.__globals__.update(obj_globals)
obj.__globals__["__builtins__"] = __builtins__
if obj_closure is not None:
for i, cell in enumerate(obj_closure):
try:
value = cell.cell_contents
except ValueError: # cell is empty
continue
obj.__closure__[i].cell_contents = value
for k, v in slotstate.items():
setattr(obj, k, v)
def _class_setstate(obj, state):
state, slotstate = state
registry = None
for attrname, attr in state.items():
if attrname == "_abc_impl":
registry = attr
else:
# Note: setting attribute names on a class automatically triggers their
# interning in CPython:
# https://github.com/python/cpython/blob/v3.12.0/Objects/object.c#L957
#
# This means that to get deterministic pickling for a dynamic class that
# was initially defined in a different Python process, the pickler
# needs to ensure that dynamic class and function attribute names are
# systematically copied into a non-interned version to avoid
# unpredictable pickle payloads.
#
# Indeed the Pickler's memoizer relies on physical object identity to break
# cycles in the reference graph of the object being serialized.
setattr(obj, attrname, attr)
if sys.version_info >= (3, 13) and "__firstlineno__" in state:
# Set the Python 3.13+ only __firstlineno__ attribute one more time, as it
# will be automatically deleted by the `setattr(obj, attrname, attr)` call
# above when `attrname` is "__firstlineno__". We assume that preserving this
# information might be important for some users and that it not stale in the
# context of cloudpickle usage, hence legitimate to propagate. Furthermore it
# is necessary to do so to keep deterministic chained pickling as tested in
# test_deterministic_str_interning_for_chained_dynamic_class_pickling.
obj.__firstlineno__ = state["__firstlineno__"]
if registry is not None:
for subclass in registry:
obj.register(subclass)
# PEP-649/749: During pickling, we excluded the __annotate_func__ attribute but it
# will be created by Python. Subsequently, annotations will be recreated when
# __annotations__ is accessed.
return obj
# COLLECTION OF DATACLASS UTILITIES
# ---------------------------------
# There are some internal sentinel values whose identity must be preserved when
# unpickling dataclass fields. Each sentinel value has a unique name that we can
# use to retrieve its identity at unpickling time.
_DATACLASSE_FIELD_TYPE_SENTINELS = {
dataclasses._FIELD.name: dataclasses._FIELD,
dataclasses._FIELD_CLASSVAR.name: dataclasses._FIELD_CLASSVAR,
dataclasses._FIELD_INITVAR.name: dataclasses._FIELD_INITVAR,
}
def _get_dataclass_field_type_sentinel(name):
return _DATACLASSE_FIELD_TYPE_SENTINELS[name]
| _empty_cell_value |
python | ray-project__ray | python/ray/_private/worker.py | {
"start": 5127,
"end": 5660
} | class ____(HasOptions, Generic[R, T0, T1, T2]):
def __init__(self, function: Callable[[T0, T1, T2], R]) -> None:
pass
def remote(
self,
__arg0: "Union[T0, ObjectRef[T0]]",
__arg1: "Union[T1, ObjectRef[T1]]",
__arg2: "Union[T2, ObjectRef[T2]]",
) -> "ObjectRef[R]":
...
def bind(
self,
__arg0: "Union[T0, DAGNode[T0]]",
__arg1: "Union[T1, DAGNode[T1]]",
__arg2: "Union[T2, DAGNode[T2]]",
) -> "DAGNode[R]":
...
| RemoteFunction2 |
python | pytorch__pytorch | torch/_dynamo/utils.py | {
"start": 5140,
"end": 10192
} | class ____:
_values: collections.defaultdict[str, int] = collections.defaultdict(int)
# Track sizes of known not re-inplaced tensors (exclude dynamic shapes).
@classmethod
def add_missed_bytes(cls, trigger: ReInplaceTrigger, bytes: int) -> None:
if bytes != 0:
cls._values[f"missed_bytes_{trigger.name}"] += bytes
# Track number of not re-inplaced tensors.
@classmethod
def add_missed_opportunities(cls, trigger: ReInplaceTrigger, count: int) -> None:
if count != 0:
cls._values[f"missed_tensors_{trigger}"] += count
@classmethod
def clear(cls) -> None:
cls._values.clear()
@classmethod
def get_total_missed(cls) -> int:
sum = 0
for trigger in ReInplaceTrigger:
sum += cls._values.get(f"missed_tensors_{trigger}", 0)
return sum
@classmethod
def get_total_missed_bytes(cls) -> int:
sum = 0
for trigger in ReInplaceTrigger:
sum += cls._values.get(f"missed_bytes_{trigger.name}", 0)
return sum
@classmethod
def log(cls) -> None:
# if not empty log.
if cls._values:
signpost_event("inductor", "reinplace_counters", cls._values)
def tabulate(
rows: Union[list[tuple[str, Any]], list[list[Any]]],
headers: Union[tuple[str, ...], list[str]],
) -> str:
try:
import tabulate
return tabulate.tabulate(rows, headers=headers)
except ImportError:
return "\n".join(
", ".join(map(str, row)) for row in itertools.chain([headers], rows)
)
curr_frame = 0
# Note: Called for you by dynamo - you almost never ever want to invoke this yourself.
def increment_frame() -> None:
global curr_frame
curr_frame = curr_frame + 1
# Note: Called for you by dynamo - you almost never ever want to invoke this yourself.
def reset_frame_count() -> None:
global curr_frame
cumulative_time_spent_ns.clear()
compilation_time_metrics.clear()
curr_frame = 0
_recompile_user_contexts: Optional[list[Callable[[], str]]] = None
def register_hook_for_recompile_user_context(hook: Callable[[], str]) -> None:
"""
Register a hook to be called when a recompile is triggered. The hook
should return a string describing user contexts that are not available
to the compiler, such as the current training epoch. This is useful for
debugging and data analysis for recompile. For data retention purposes,
the user context string is capped at 256 characters.
"""
global _recompile_user_contexts
if _recompile_user_contexts is None:
_recompile_user_contexts = []
_recompile_user_contexts.append(hook)
def get_hook_for_recompile_user_context() -> Optional[list[Callable[[], str]]]:
return _recompile_user_contexts
op_count = 0
def increment_op_count(cnt: int) -> None:
global op_count
op_count += cnt
# Get the total time in seconds for each "phase"
# For example, {'entire_frame_compile':8.574629999999999, 'backend_compile':5.26806}
def calculate_time_spent() -> dict[str, float]:
total_by_key = {}
for phase, timing in cumulative_time_spent_ns.items():
# pyrefly: ignore [unsupported-operation]
total_by_key[phase] = timing / 1e9
total_by_key["total_wall_time"] = total_by_key.get(
"entire_frame_compile", 0
) + total_by_key.get("entire_backward_compile", 0)
# pyrefly: ignore [bad-return]
return total_by_key
# Print a report of time spent so far
# Ex:
# TIMING:
# entire_frame_compile:8.574629999999999
# backend_compile:5.26806
def print_time_report() -> None:
total_by_key = calculate_time_spent()
out = "TIMING:"
for key, value in total_by_key.items():
out = f"{out} {key}:{round(value, 5)}"
print(out)
# Use the following singleton to capture and log CompilationMetrics. Entering the context
# manager allocates a new record to be logged when it exits. (You should not need to use
# this directly unless you introduce a new code path where compilation metrics would be
# gathered). While compiling, use the setters or timer in MetricsContext to update fields
# in the current context. For example:
#
# To set a single field once (use overwrite=True to overwrite):
# get_metrics_context().set("metric_name", value)
#
# To set multiple fields at once (use overwrite=True to overwrite):
# get_metrics_context().update({"name1": val1, "name2": val2})
#
# To increment an integer field:
# get_metrics_context().increment("metric_name", value)
#
# To record execution time, MetricsContext works with dynamo_timed:
# def foo(...):
# # Updates the "metric_us" field.
# with dynamo_timed("metric", dynamo_compile_column_us="metric_us")
# ...
#
_METRICS_CONTEXT: MetricsContext
_RUNTIME_METRICS_CONTEXT: RuntimeMetricsContext
def get_metrics_context() -> MetricsContext:
return _METRICS_CONTEXT
def get_runtime_metrics_context() -> RuntimeMetricsContext:
return _RUNTIME_METRICS_CONTEXT
| ReinplaceCounters |
python | huggingface__transformers | src/transformers/models/gemma3/modular_gemma3.py | {
"start": 16409,
"end": 16489
} | class ____(PaliGemmaCausalLMOutputWithPast):
pass
| Gemma3CausalLMOutputWithPast |
python | tensorflow__tensorflow | tensorflow/python/saved_model/registration/registration_test.py | {
"start": 4587,
"end": 7640
} | class ____(test.TestCase):
def test_invalid_registration(self):
with self.assertRaisesRegex(TypeError, "must be string"):
registration.register_checkpoint_saver(
package=None,
name="test",
predicate=lambda: None,
save_fn=lambda: None,
restore_fn=lambda: None)
with self.assertRaisesRegex(TypeError, "must be string"):
registration.register_checkpoint_saver(
name=None,
predicate=lambda: None,
save_fn=lambda: None,
restore_fn=lambda: None)
with self.assertRaisesRegex(ValueError,
"Invalid registered checkpoint saver."):
registration.register_checkpoint_saver(
package="package",
name="t/est",
predicate=lambda: None,
save_fn=lambda: None,
restore_fn=lambda: None)
with self.assertRaisesRegex(ValueError,
"Invalid registered checkpoint saver."):
registration.register_checkpoint_saver(
package="package",
name="t/est",
predicate=lambda: None,
save_fn=lambda: None,
restore_fn=lambda: None)
with self.assertRaisesRegex(
TypeError,
"The predicate registered to a checkpoint saver must be callable"
):
registration.register_checkpoint_saver(
name="test",
predicate=None,
save_fn=lambda: None,
restore_fn=lambda: None)
with self.assertRaisesRegex(TypeError, "The save_fn must be callable"):
registration.register_checkpoint_saver(
name="test",
predicate=lambda: None,
save_fn=None,
restore_fn=lambda: None)
with self.assertRaisesRegex(TypeError, "The restore_fn must be callable"):
registration.register_checkpoint_saver(
name="test",
predicate=lambda: None,
save_fn=lambda: None,
restore_fn=None)
def test_registration(self):
registration.register_checkpoint_saver(
package="Testing",
name="test_predicate",
predicate=lambda x: hasattr(x, "check_attr"),
save_fn=lambda: "save",
restore_fn=lambda: "restore")
x = base.Trackable()
self.assertIsNone(registration.get_registered_saver_name(x))
x.check_attr = 1
saver_name = registration.get_registered_saver_name(x)
self.assertEqual(saver_name, "Testing.test_predicate")
self.assertEqual(registration.get_save_function(saver_name)(), "save")
self.assertEqual(registration.get_restore_function(saver_name)(), "restore")
registration.validate_restore_function(x, "Testing.test_predicate")
with self.assertRaisesRegex(ValueError, "saver cannot be found"):
registration.validate_restore_function(x, "Invalid.name")
x2 = base.Trackable()
with self.assertRaisesRegex(ValueError, "saver cannot be used"):
registration.validate_restore_function(x2, "Testing.test_predicate")
if __name__ == "__main__":
test.main()
| CheckpointSaverRegistrationTest |
python | django-haystack__django-haystack | test_haystack/whoosh_tests/test_whoosh_backend.py | {
"start": 1840,
"end": 2300
} | class ____(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
name = indexes.CharField(model_attr="author", indexed=False)
pub_date = indexes.DateTimeField(model_attr="pub_date")
sites = indexes.MultiValueField()
seen_count = indexes.IntegerField(indexed=False)
is_active = indexes.BooleanField(default=True)
def get_model(self):
return MockModel
| AllTypesWhooshMockSearchIndex |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 40995,
"end": 41709
} | class ____(FieldValues):
"""
Check that empty string ('', ' ') is acceptable value for the DecimalField
if allow_null=True and there are max/min validators
"""
valid_inputs = {
None: None,
'': None,
' ': None,
' ': None,
5: Decimal('5'),
'0': Decimal('0'),
'10': Decimal('10'),
}
invalid_inputs = {
-1: ['Ensure this value is greater than or equal to 0.'],
11: ['Ensure this value is less than or equal to 10.'],
}
outputs = {
None: '',
}
field = serializers.DecimalField(max_digits=3, decimal_places=1, allow_null=True, min_value=0, max_value=10)
| TestAllowEmptyStrDecimalFieldWithValidators |
python | pytorch__pytorch | test/dynamo/test_logging.py | {
"start": 3029,
"end": 34028
} | class ____(LoggingTestCase):
test_bytecode = multi_record_test(2, bytecode=True)
test_output_code = multi_record_test(3, output_code=True)
test_aot_graphs = multi_record_test(3, aot_graphs=True)
@requires_gpu
@make_logging_test(schedule=True)
def test_schedule(self, records):
fn_opt = torch.compile(inductor_schedule_fn, backend="inductor")
fn_opt(torch.ones(1000, 1000, device=device_type))
self.assertGreater(len(records), 0)
self.assertLess(len(records), 5)
@requires_gpu
@make_logging_test(fusion=True)
def test_fusion(self, records):
fn_opt = torch.compile(inductor_schedule_fn, backend="inductor")
fn_opt(torch.ones(1000, 1000, device=device_type))
self.assertGreater(len(records), 0)
# LOAF will add an extra round of fusion and result in more logs
self.assertLess(
len(records), 8 * (1 + torch._inductor.config.loop_ordering_after_fusion)
)
@requires_cuda_and_triton
@make_logging_test(cudagraphs=True)
def test_cudagraphs(self, records):
fn_opt = torch.compile(mode="reduce-overhead")(inductor_schedule_fn)
fn_opt(torch.ones(1000, 1000, device=device_type))
self.assertGreater(len(records), 0)
self.assertLess(len(records), 8)
@make_logging_test(recompiles=True)
def test_recompiles(self, records):
def fn(x, y):
return torch.add(x, y)
fn_opt = torch.compile(fn, backend="inductor")
fn_opt(torch.ones(1000, 1000), torch.ones(1000, 1000))
fn_opt(torch.ones(1000, 1000), 1)
self.assertGreater(len(records), 0)
test_dynamo_debug = within_range_record_test(30, 90, dynamo=logging.DEBUG)
test_dynamo_info = within_range_record_test(2, 10, dynamo=logging.INFO)
@skipIfTorchDynamo("too slow")
@make_logging_test(dynamo=logging.DEBUG)
def test_dynamo_debug_default_off_artifacts(self, records):
fn_opt = torch.compile(example_fn, backend="inductor")
fn_opt(torch.ones(1000, 1000))
self.assertEqual(len([r for r in records if ".__bytecode" in r.name]), 0)
self.assertEqual(len([r for r in records if ".__output_code" in r.name]), 0)
@make_logging_test(hierarchical_compile=True)
def test_hierarchical_compile(self, records):
from torch._higher_order_ops.invoke_subgraph import mark_compile_region
@mark_compile_region
def gn(x):
return x * 2
def fn(x):
return gn(x)
fn_opt = torch.compile(fn, backend="inductor")
fn_opt(torch.ones(1000, 1000))
fn_opt(torch.ones(1000, 1000))
self.assertGreater(len(records), 0)
@make_logging_test()
def test_dynamo_error(self, records):
try:
fn_opt = torch.compile(dynamo_error_fn, backend="inductor")
fn_opt(*ARGS)
except Exception:
pass
record = self.getRecord(records, "WON'T CONVERT")
self.assertExpectedInline(
munge_exc(record.getMessage()),
"""\
WON'T CONVERT dynamo_error_fn test_logging.py line N
due to:
Traceback (most recent call last):
torch._dynamo.exc.TorchRuntimeError: Dynamo failed to run FX node with fake tensors: call_method add(*(FakeTensor(..., size=(1000, 1000), grad_fn=<MulBackward0>), FakeTensor(..., size=(10, 10))), **{}): got RuntimeError('Attempting to broadcast a dimension of length 10 at -1! Mismatching argument at index 1 had torch.Size([10, 10]); but expected shape should be broadcastable to [1000, 1000]')
from user code:
File "test_logging.py", line N, in dynamo_error_fn
output = output.add(torch.ones(10, 10))""", # noqa: B950
)
test_aot = within_range_record_test(2, 6, aot=logging.INFO)
test_inductor_debug = within_range_record_test(3, 28, inductor=logging.DEBUG)
test_inductor_info = within_range_record_test(2, 10, inductor=logging.INFO)
@make_logging_test()
def test_inductor_error(self, records):
exitstack = contextlib.ExitStack()
import torch._inductor.lowering
def throw(x):
raise AssertionError
# inject an error in the lowerings
dict_entries = {}
for x in list(torch._inductor.lowering.lowerings.keys()):
if "round" in x.__name__:
dict_entries[x] = throw
exitstack.enter_context(
unittest.mock.patch.dict(torch._inductor.lowering.lowerings, dict_entries)
)
try:
fn_opt = torch.compile(inductor_error_fn, backend="inductor")
fn_opt(*ARGS)
except Exception:
pass
record = self.getRecord(records, "WON'T CONVERT")
self.assertExpectedInline(
munge_exc(record.getMessage()),
"""\
WON'T CONVERT inductor_error_fn test_logging.py line N
due to:
Traceback (most recent call last):
File "test_logging.py", line N, in throw
raise AssertionError
torch._inductor.exc.InductorError: LoweringException: AssertionError:
target: aten.round.default
args[0]: TensorBox(StorageBox(
InputBuffer(name='primals_1', layout=FixedLayout('cpu', torch.float32, size=[1000, 1000], stride=[1000, 1]))
))""",
)
exitstack.close()
@requires_distributed()
@requires_cuda_and_triton
@make_logging_test(ddp_graphs=True)
def test_ddp_graphs(self, records):
class ToyModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.layers = torch.nn.Sequential(
torch.nn.Linear(1024, 1024),
torch.nn.Linear(1024, 1024),
)
def forward(self, x):
return self.layers(x)
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = str(find_free_port())
dist.init_process_group("gloo", rank=0, world_size=1)
model = DDP(ToyModel().to("cuda:0"), device_ids=[0], bucket_cap_mb=4)
ddp_model = torch.compile(model, backend="inductor")
ddp_model(torch.randn(1024, 1024, device="cuda:0"))
dist.destroy_process_group()
self.assertEqual(len([r for r in records if "__ddp_graphs" in r.name]), 4)
# check that logging to a child log of a registered logger
# does not register it and result in duplicated records
@make_settings_test("torch._dynamo.output_graph")
def test_open_registration_with_registered_parent(self, records):
logger = logging.getLogger("torch._dynamo.output_graph")
logger.info("hi")
self.assertEqual(len(records), 1)
# check logging to a random log that is not a child log of a registered
# logger registers it and sets handlers properly
@make_settings_test("torch.utils")
def test_open_registration(self, records):
logger = logging.getLogger("torch.utils")
logger.info("hi")
self.assertEqual(len(records), 1)
# check logging to a random log that is not a child log of a registered
# logger registers it and sets handlers properly
@make_logging_test(modules={"torch.utils": logging.INFO})
def test_open_registration_python_api(self, records):
logger = logging.getLogger("torch.utils")
logger.info("hi")
self.assertEqual(len(records), 1)
@make_logging_test(all=logging.DEBUG, dynamo=logging.INFO)
def test_all(self, _):
registry = torch._logging._internal.log_registry
dynamo_qnames = registry.log_alias_to_log_qnames["dynamo"]
for logger_qname in torch._logging._internal.log_registry.get_log_qnames():
logger = logging.getLogger(logger_qname)
# if logger_qname is a.b.c and dynamo_qnames contains a.b, it still matches dynamo's INFO setting
if any(logger_qname.find(d) == 0 for d in dynamo_qnames):
self.assertEqual(
logger.getEffectiveLevel(),
logging.INFO,
msg=f"expected {logger_qname} is INFO, got {logging.getLevelName(logger.getEffectiveLevel())}",
)
else:
self.assertEqual(
logger.getEffectiveLevel(),
logging.DEBUG,
msg=f"expected {logger_qname} is DEBUG, got {logging.getLevelName(logger.getEffectiveLevel())}",
)
@make_logging_test(graph_breaks=True)
def test_graph_breaks(self, records):
@torch.compile(backend="inductor")
def fn(x):
torch._dynamo.graph_break()
return x + 1
fn(torch.ones(1))
self.assertEqual(len(records), 1)
@make_settings_test("torch._dynamo.utils")
def test_dump_compile_times(self, records):
fn_opt = torch.compile(example_fn, backend="inductor")
fn_opt(torch.ones(1000, 1000))
# This function runs during exit via atexit.register.
# We're not actually going to run atexit._run_exit_funcs() here,
# because it'll destroy state necessary for other tests.
torch._dynamo.utils.dump_compile_times()
self.assertEqual(
len(
[r for r in records if "TorchDynamo compilation metrics" in str(r.msg)]
),
1,
)
@make_logging_test(dynamo=logging.INFO)
def test_custom_format_exc(self, records):
dynamo_log = logging.getLogger(torch._dynamo.__name__)
try:
raise RuntimeError("foo")
except RuntimeError:
dynamo_log.exception("test dynamo")
dynamo_log.info("with exc", exc_info=True)
dynamo_log.info("with stack", stack_info=True)
self.assertEqual(len(records), 3)
# unfortunately there's no easy way to test the final formatted log other than
# to ask the dynamo logger's handler to format it.
for handler in dynamo_log.handlers:
if torch._logging._internal._is_torch_handler(handler):
break
self.assertIsNotNone(handler)
self.assertIn("Traceback", handler.format(records[0]))
self.assertIn("Traceback", handler.format(records[1]))
self.assertIn("Stack", handler.format(records[2]))
@make_logging_test(dynamo=logging.INFO)
def test_custom_format(self, records):
dynamo_log = logging.getLogger(torch._dynamo.__name__)
test_log = torch._logging.getArtifactLogger(
torch._dynamo.__name__, "custom_format_test_artifact"
)
dynamo_log.info("test dynamo")
test_log.info("custom format")
self.assertEqual(len(records), 2)
# unfortunately there's no easy way to test the final formatted log other than
# to ask the dynamo logger's handler to format it.
for handler in dynamo_log.handlers:
if torch._logging._internal._is_torch_handler(handler):
break
self.assertIsNotNone(handler)
self.assertIn("I", handler.format(records[0]))
self.assertEqual("custom format", handler.format(records[1]))
@make_logging_test(dynamo=logging.INFO)
def test_multiline_format(self, records):
dynamo_log = logging.getLogger(torch._dynamo.__name__)
dynamo_log.info("test\ndynamo")
dynamo_log.info("%s", "test\ndynamo")
dynamo_log.info("test\n%s", "test\ndynamo")
self.assertEqual(len(records), 3)
# unfortunately there's no easy way to test the final formatted log other than
# to ask the dynamo logger's handler to format it.
for handler in dynamo_log.handlers:
if torch._logging._internal._is_torch_handler(handler):
break
self.assertIsNotNone(handler)
for record in records:
r = handler.format(record)
for l in r.splitlines():
self.assertIn("I", l)
test_trace_source_simple = within_range_record_test(1, 100, trace_source=True)
@make_logging_test(trace_source=True)
def test_trace_source_if_stmt(self, records):
def fn(x):
if x.sum() > 0:
return x * 2
return x * 3
fn_opt = torch.compile(fn, backend="eager")
fn_opt(torch.ones(3, 3))
found_x2 = False
found_x3 = False
for record in records:
msg = record.getMessage()
if "return x * 2" in msg:
found_x2 = True
if "return x * 3" in msg:
found_x3 = True
self.assertTrue(found_x2)
self.assertFalse(found_x3)
@make_logging_test(trace_source=True)
def test_trace_source_nested(self, records):
def fn1(x):
x = fn2(x)
return x * 2
def fn2(x):
x = fn3(x)
return x * 3
def fn3(x):
return x * 4
fn_opt = torch.compile(fn1, backend="eager")
fn_opt(torch.ones(3, 3))
found_x2 = False
found_x3 = False
found_x4 = False
for record in records:
msg = record.getMessage()
if "return x * 2" in msg:
found_x2 = True
self.assertNotIn("inline depth", msg)
elif "return x * 3" in msg:
found_x3 = True
self.assertIn("inline depth: 1", msg)
elif "return x * 4" in msg:
found_x4 = True
self.assertIn("inline depth: 2", msg)
self.assertTrue(found_x2)
self.assertTrue(found_x3)
self.assertTrue(found_x4)
@make_logging_test(trace_source=True)
def test_trace_source_cond(self, records):
from functorch.experimental.control_flow import cond
def true_fn(x):
return x * 2
def false_fn(x):
return x * 3
def inner(pred, x):
return cond(pred, true_fn, false_fn, [x])
def outer(pred, x):
return inner(pred, x)
fn_opt = torch.compile(outer, backend="eager")
fn_opt(torch.tensor(True), torch.ones(3, 3))
found_x2 = False
found_x3 = False
for record in records:
msg = record.getMessage()
if "return x * 2" in msg:
found_x2 = True
self.assertIn("inline depth: 3", msg)
if "return x * 3" in msg:
found_x3 = True
self.assertIn("inline depth: 3", msg)
self.assertTrue(found_x2)
self.assertTrue(found_x3)
@make_logging_test(trace_source=True)
def test_trace_source_funcname(self, records):
# NOTE: list comprehensions are inlined in 3.12, so test with tuples
def fn1():
def fn2():
if True:
return tuple(torch.ones(3, 3) for _ in range(5))
return None
return fn2()
fn_opt = torch.compile(fn1, backend="eager")
fn_opt()
found_funcname = False
for record in records:
msg = record.getMessage()
if "<genexpr>" in msg and "fn1.fn2" in msg:
found_funcname = True
self.assertTrue(found_funcname)
def test_invalid_artifact_flag(self):
with self.assertRaises(ValueError):
torch._logging.set_logs(aot_graphs=5)
def test_invalid_artifact_flag_error_msg(self):
env = dict(os.environ)
env["TORCH_LOGS"] = "not_an_existing_log_artifact_should_error"
_, stderr = self.run_process_no_exception(
"import torch",
env=env,
)
lines = stderr.decode().split("\r\n" if IS_WINDOWS else "\n")
# This is a sanity assert that our error is not spammy.
# As of this test creation this was 18.
# See this issue for the purpose o this test:
# https://github.com/pytorch/pytorch/issues/151055
self.assertTrue(len(lines) < 50)
# The other sanity assert - check that the last few lines
# map to the actual error message we want to raise
# (I could use an expecttest here, although it would break
# whenever someone adds a new logging artifact)
self.assertEqual(
lines[-5], 'For more info on various settings, try TORCH_LOGS="help"'
)
self.assertEqual(lines[-4], "Valid settings:")
@requires_distributed()
@skipIfWindows(msg="TODO: (xuhancn), Can't reproduce locally")
def test_distributed_rank_logging(self):
env = dict(os.environ)
env["TORCH_LOGS"] = "dynamo"
_, stderr = self.run_process_no_exception(
"""\
import torch.distributed as dist
import logging
from torch.testing._internal.distributed.fake_pg import FakeStore
store = FakeStore()
dist.init_process_group("fake", rank=0, world_size=2, store=store)
dynamo_log = logging.getLogger("torch._dynamo")
dynamo_log.info("woof")
print("arf")
""",
env=env,
)
self.assertIn("[rank0]:", stderr.decode("utf-8"))
@skipIfNotPy311
@make_logging_test(trace_call=True)
def test_trace_call(self, records):
def fn(x, y):
return (x * 2) @ (y * 3)
fn_opt = torch.compile(fn, backend="eager")
fn_opt(torch.randn(10, 20), torch.randn(20, 30))
self.assertEqual(len(records), 3)
# only get last 2 lines
messages = [
"\n".join(record.getMessage().split("\n")[-2:]) for record in records
]
self.assertExpectedInline(
messages[0],
"""\
return (x * 2) @ (y * 3)
~~^~~""",
)
self.assertExpectedInline(
messages[1],
"""\
return (x * 2) @ (y * 3)
~~^~~""",
)
self.assertExpectedInline(
messages[2],
"""\
return (x * 2) @ (y * 3)
~~~~~~~~^~~~~~~~~""",
)
@skipIfNotPy311
@make_logging_test(trace_call=True)
def test_trace_call_prefix(self, records):
def fn(x, y):
return (x * 2) @ (y * 3)
fn_opt = torch.compile(fn, backend="eager")
fn_opt(torch.randn(10, 20), torch.randn(20, 30))
msg0 = munge_exc(records[0].getMessage())
self.assertExpectedInline(
msg0,
"""\
TRACE FX call mul from test_logging.py:N in fn (LoggingTests.test_trace_call_prefix.fn)
return (x * 2) @ (y * 3)
~~^~~""",
)
@skipIfNotPy311
@make_logging_test(trace_call=True)
def test_trace_call_inline_call(self, records):
def g(x):
return x * 2
def f(x):
return g(g(x))
fn_opt = torch.compile(f, backend="eager")
fn_opt(torch.randn(3, 3))
self.assertEqual(len(records), 3)
messages = [
"\n".join(record.getMessage().split("\n")[-2:]) for record in records
]
self.assertExpectedInline(
messages[0],
"""\
return g(g(x))
~^^^""",
)
self.assertExpectedInline(
messages[1],
"""\
return x * 2
~~^~~""",
)
# skip this check since 3.13 removed carets for this case
# see https://github.com/python/cpython/issues/99180
# self.assertExpectedInline(
# messages[2],
# """\
# return g(g(x))
# ~^^^^^^""",
# )
@skipIfNotPy311
@make_logging_test(trace_call=True)
def test_trace_call_graph_break(self, records):
def fn(x):
x = x * 2
torch._dynamo.graph_break()
return x * 3
fn_opt = torch.compile(fn, backend="eager")
fn_opt(torch.randn(3, 3))
self.assertEqual(len(records), 3)
messages = [
"\n".join(record.getMessage().split("\n")[-2:]) for record in records
]
self.assertExpectedInline(
messages[0],
"""\
x = x * 2
~~^~~""",
)
self.assertExpectedInline(
messages[-1],
"""\
return x * 3
~~^~~""",
)
@make_logging_test(guards=True, recompiles=True)
def test_guards_recompiles(self, records):
def fn(x, ys, zs):
return inner(x, ys, zs)
def inner(x, ys, zs):
for y, z in zip(ys, zs):
x += y * z
return x
ys = [1.0, 2.0]
zs = [3.0]
x = torch.tensor([1.0])
fn_opt = torch.compile(fn, backend="eager")
fn_opt(x, ys, zs)
fn_opt(x, ys[:1], zs)
record_str = "\n".join(r.getMessage() for r in records)
self.assertIn(
"""L['zs'][0] == 3.0""",
record_str,
)
self.assertIn(
"len(L['ys']) == 2",
record_str,
)
@make_logging_test(guards=True)
def test_guards_sloc(self, records):
@torch.compile(dynamic=True, backend="eager")
def f(x, y, z):
x = x * 3
if x.size(0) % 3 == 0:
return x + torch.cat([y, z])
else:
return x * 2
f(torch.randn(6), torch.randn(3), torch.randn(3))
record = self.getRecord(records, "TREE_GUARD_MANAGER")
self.assertExpectedInline(
munge_shape_guards(record.getMessage()),
"""\
+- __SHAPE_GUARD__: L['x'].size()[0] == 2*L['y'].size()[0] # return x + torch.cat([y, z]) # #:# in # #:# in #
+- __SHAPE_GUARD__: L['z'].size()[0] == L['y'].size()[0] # duck sizing added this equality because these variables had the same size 3 (to avoid this specialization, set torch.fx.experimental._config.use_duck_shape = False)
+- __SHAPE_GUARD__: ((2*L['y'].size()[0]) % 3) == 0 # if x.size(0) % 3 == 0: # #:# in # #:# in #
+- __SHAPE_GUARD__: 2 <= L['y'].size()[0] # return x + torch.cat([y, z]) # #:# in # (user code shown is first use of this value--the guard itself is not due user code but due to 0/1 specialization in the framework; to avoid specialization try torch._dynamo.decorators.mark_unbacked(tensor, dim))""", # noqa: B950
)
@make_logging_test(guards=True)
def test_guards_polyfill_sloc(self, records):
@torch.compile(dynamic=True, backend="eager")
def f(x, y):
return any([x.size(0) == y.size(0) * 2])
f(torch.randn(6), torch.randn(3))
record = self.getRecord(records, "TREE_GUARD_MANAGER")
self.assertExpectedInline(
munge_shape_guards(record.getMessage()),
"""\
+- __SHAPE_GUARD__: L['x'].size()[0] == 2*L['y'].size()[0] # return any([x.size(0) == y.size(0) * 2]) # #:# in # #:# in #
+- __SHAPE_GUARD__: 2 <= L['y'].size()[0] # return any([x.size(0) == y.size(0) * 2]) # #:# in # (user code shown is first use of this value--the guard itself is not due user code but due to 0/1 specialization in the framework; to avoid specialization try torch._dynamo.decorators.mark_unbacked(tensor, dim))""", # noqa: B950
)
@make_logging_test(guards=True)
def test_guards_sloc_vr(self, records):
@torch.compile(dynamic=True, backend="eager")
def f(x, y):
torch._check(x.size(0) > 5)
torch._check(x.size(0) < 30)
torch._check(x.size(0) == y.size(0) * 2)
return torch.tensor(True)
f(torch.randn(6), torch.randn(3))
record = self.getRecord(records, "TREE_GUARD_MANAGER")
self.assertExpectedInline(
munge_shape_guards(record.getMessage()),
"""\
+- __SHAPE_GUARD__: L['x'].size()[0] == 2*L['y'].size()[0] # torch._check(x.size(0) == y.size(0) * 2) # #:# in # #:# in #
+- __SHAPE_GUARD__: 3 <= L['y'].size()[0] <= 14 # torch._check(x.size(0) > 5) # #:# in # #:# in # and torch._check(x.size(0) < 30) # #:# in # #:# in #""", # noqa: B950
)
@make_logging_test(cudagraph_static_inputs=True)
def test_cudagraph_static_inputs(self, records):
@torch.compile(mode="reduce-overhead")
def fn(x):
return x + 1
x = torch.ones(2, 2)
torch._dynamo.mark_static_address(x)
fn(x)
self.assertGreater(len(records), 0)
self.assertLess(len(records), 4)
@xfailIf(TEST_XPU) # https://github.com/pytorch/pytorch/issues/157778
@make_logging_test(perf_hints=True)
@requires_gpu
def test_optimizer_non_static_param(self, records):
params = [torch.randn(10, 10, device=device_type) for _ in range(2)]
for param in params:
param.grad = torch.zeros_like(param)
opt = torch.optim.Adam(params)
compiled_opt_step = torch.compile(opt.step, mode="reduce-overhead")
compiled_opt_step()
self.assertGreater(len(records), 0)
self.assertLess(len(records), 3)
@make_logging_test(autotuning=True)
@requires_gpu
@unittest.skipIf(not SM90OrLater, "requires H100+ GPU")
def test_autotuning(self, records):
with torch._inductor.utils.fresh_cache():
def f(a, b):
return torch.mm(a, b)
f = torch.compile(f, mode="max-autotune-no-cudagraphs")
f(
torch.randn(10, 10, device=device_type),
torch.randn(10, 10, device=device_type),
)
self.assertGreater(len(records), 0)
self.assertLess(len(records), 40)
@make_logging_test(graph_region_expansion=True)
def test_graph_region_expansion(self, records):
with torch._dynamo.config.patch("track_nodes_for_deduplication", True):
def inner_fn(x, y):
x0 = x + 1
y0 = y + 2
z = x0.sum() + y0.sum()
return z
def fn(x, y):
o0 = inner_fn(x, y)
o1 = torch.sin(o0)
o2 = inner_fn(x, o1)
o3 = inner_fn(x, y)
return o2 * o3 * o3
graph, tracker = extract_graph_and_tracker(
fn, torch.randn(10, 10), torch.randn(10, 10)
)
tracker.get_identical_regions(graph)
self.assertGreater(len(records), 0)
@skipIfTorchDynamo("too slow")
@make_logging_test(**torch._logging.DEFAULT_LOGGING)
def test_default_logging(self, records):
def fn(a):
if a.sum() < 0:
a = torch.sin(a)
else:
a = torch.cos(a)
print("hello")
return a + 1
fn_opt = torch.compile(fn, backend="eager")
fn_opt(torch.ones(10, 10))
fn_opt(-torch.ones(10, 5))
self.assertGreater(len([r for r in records if ".__graph_breaks" in r.name]), 0)
self.assertGreater(len([r for r in records if ".__recompiles" in r.name]), 0)
self.assertGreater(len([r for r in records if ".symbolic_shapes" in r.name]), 0)
self.assertGreater(len([r for r in records if ".__guards" in r.name]), 0)
self.assertGreater(
len([r for r in records if "return a + 1" in r.getMessage()]), 0
)
def test_logs_out(self):
import tempfile
with tempfile.NamedTemporaryFile(delete=True) as tmp:
file_path = _as_posix_path(tmp.name)
"""
NamedTemporaryFile will include a file open operation.
On Windowsm the file is opened by NamedTemporaryFile, the
following run_process_no_exception can't access a opened file.
And then, raise a PermissionError: [Errno 13] Permission denied: [file_path]
"""
tmp.close()
env = dict(os.environ)
env["TORCH_LOGS"] = "dynamo"
env["TORCH_LOGS_OUT"] = file_path
_, stderr = self.run_process_no_exception(
"""\
import torch
@torch.compile(backend="eager")
def fn(a):
return a.sum()
fn(torch.randn(5))
""",
env=env,
)
with open(
file_path, encoding="utf-8"
) as fd: # encoding file to UTF-8 for Windows.
lines = fd.read()
orig_maxDiff = unittest.TestCase.maxDiff
unittest.TestCase.maxDiff = None
try:
self.assertEqual( # process wrap difference: /r/n on Windows, /n on posix.
empty_line_normalizer(lines),
empty_line_normalizer(stderr.decode("utf-8")),
)
except Exception:
unittest.TestCase.maxDiff = orig_maxDiff
raise
@make_settings_test("torch._dynamo.eval_frame")
def test_log_traced_frames(self, records):
torch._dynamo.eval_frame.clear_dynamo_tls()
# Test program
@torch.compile()
def foo():
x = torch.ones([10])
def bar():
y = x + x
torch._dynamo.graph_break()
z = y * x
return z
return bar(), bar
foo()
# `_log_traced_frames` is registered as an atexit callback, so we invoke
# it explicitly for testing.
torch._dynamo.eval_frame._log_traced_frames()
# Get the relevant log.
record = self.getRecord(records, "TorchDynamo attempted to trace")
# Check
self.assertExpectedInline(
munge_exc(record.getMessage()),
"""\
TorchDynamo attempted to trace the following frames: [
* foo test_logging.py:N
* bar test_logging.py:N
]""",
)
# non single record tests
exclusions = {
"bytecode",
"cudagraphs",
"output_code",
"schedule",
"fusion",
"overlap",
"aot_graphs",
"aot_graphs_effects",
"pre_grad_graphs",
"joint_graph_passes",
"post_grad_graphs",
"inductor_metrics",
"ir_pre_fusion",
"ir_post_fusion",
"compiled_autograd",
"compiled_autograd_verbose",
"recompiles",
"recompiles_verbose",
"graph_breaks",
"graph",
"graph_code",
"graph_code_verbose",
"graph_sizes",
"ddp_graphs",
"perf_hints",
"not_implemented",
"trace_source",
"trace_call",
"trace_bytecode",
"custom_format_test_artifact",
"onnx",
"onnx_diagnostics",
"guards",
"verbose_guards",
"sym_node",
"export",
"trace_shape_events",
"cudagraph_static_inputs",
"benchmarking",
"loop_ordering",
"loop_tiling",
"autotuning",
"graph_region_expansion",
"hierarchical_compile",
"compute_dependencies",
"annotation",
"node_runtime_estimation",
}
for name in torch._logging._internal.log_registry.artifact_names:
if name not in exclusions:
setattr(LoggingTests, f"test_{name}", single_record_test(**{name: True}))
if __name__ == "__main__":
from torch._dynamo.test_case import run_tests
run_tests()
| LoggingTests |
python | pennersr__django-allauth | allauth/headless/internal/restkit/response.py | {
"start": 262,
"end": 1267
} | class ____(JsonResponse):
def __init__(
self,
request,
errors=None,
data=None,
meta: Optional[Dict] = None,
status: int = HTTPStatus.OK,
):
d: Dict[str, Any] = {"status": status}
if data is not None:
d["data"] = data
meta = self._add_session_meta(request, meta)
if meta is not None:
d["meta"] = meta
if errors:
d["errors"] = errors
super().__init__(d, status=status)
add_never_cache_headers(self)
def _add_session_meta(self, request, meta: Optional[Dict]) -> Optional[Dict]:
session_token = sessionkit.expose_session_token(request)
access_token_payload = authkit.expose_access_token(request)
if session_token:
meta = meta or {}
meta["session_token"] = session_token
if access_token_payload:
meta = meta or {}
meta.update(access_token_payload)
return meta
| APIResponse |
python | getsentry__sentry | tests/sentry/seer/autofix/test_issue_summary.py | {
"start": 36379,
"end": 38491
} | class ____:
@patch("sentry.seer.autofix.issue_summary.sign_with_seer_secret", return_value={})
@patch("sentry.seer.autofix.issue_summary.requests.post")
def test_fetch_user_preference_success(self, mock_post, mock_sign):
mock_response = Mock()
mock_response.json.return_value = {
"preference": {"automated_run_stopping_point": "solution"}
}
mock_response.raise_for_status = Mock()
mock_post.return_value = mock_response
result = _fetch_user_preference(project_id=123)
assert result == "solution"
mock_post.assert_called_once()
mock_response.raise_for_status.assert_called_once()
@patch("sentry.seer.autofix.issue_summary.sign_with_seer_secret", return_value={})
@patch("sentry.seer.autofix.issue_summary.requests.post")
def test_fetch_user_preference_no_preference(self, mock_post, mock_sign):
mock_response = Mock()
mock_response.json.return_value = {"preference": None}
mock_response.raise_for_status = Mock()
mock_post.return_value = mock_response
result = _fetch_user_preference(project_id=123)
assert result is None
@patch("sentry.seer.autofix.issue_summary.sign_with_seer_secret", return_value={})
@patch("sentry.seer.autofix.issue_summary.requests.post")
def test_fetch_user_preference_empty_preference(self, mock_post, mock_sign):
mock_response = Mock()
mock_response.json.return_value = {"preference": {"automated_run_stopping_point": None}}
mock_response.raise_for_status = Mock()
mock_post.return_value = mock_response
result = _fetch_user_preference(project_id=123)
assert result is None
@patch("sentry.seer.autofix.issue_summary.sign_with_seer_secret", return_value={})
@patch("sentry.seer.autofix.issue_summary.requests.post")
def test_fetch_user_preference_api_error(self, mock_post, mock_sign):
mock_post.side_effect = Exception("API error")
result = _fetch_user_preference(project_id=123)
assert result is None
| TestFetchUserPreference |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 230696,
"end": 241334
} | class ____(Request):
"""
Save frames into a draft version. Frame IDs, if sent, will be ignored, and every frame will be assigned a new ID.
:param version: Draft version ID
:type version: str
:param frames: Frames to save
:type frames: Sequence[Frame]
"""
_service = "datasets"
_action = "save_frames"
_version = "2.23"
_schema = {
"definitions": {
"frame": {
"properties": {
"blob": {
"description": "Raw data (blob) for the frame",
"type": ["string", "null"],
},
"context_id": {
"description": (
"Context ID. Used for the default frames sorting. If not set then it is filled from the uri"
" of the first source."
),
"type": ["string", "null"],
},
"id": {
"description": (
"Frame id. Must be unique within the dataset's version. If already exists, will cause"
" existing frame to be updated"
),
"type": ["string", "null"],
},
"meta": {
"additionalProperties": True,
"description": (
"Additional metadata dictionary for the frame. Please note that using this field"
" effectively defines a schema (dictionary structure and types used as values) - frames"
" within the same dataset cannot use conflicting schemas for this field (see documentation"
" for more details)."
),
"type": ["object", "null"],
},
"meta_blob": {
"additionalProperties": True,
"description": (
"Non searchable metadata dictionary for the frame. The fields in this object cannot be"
" searched by and are not added to the frame schema"
),
"type": ["object", "null"],
},
"rois": {
"description": "Frame regions of interest",
"items": {"$ref": "#/definitions/roi"},
"type": ["array", "null"],
},
"sources": {
"description": "Sources of this frame",
"items": {"$ref": "#/definitions/source"},
"type": "array",
},
"timestamp": {
"description": (
"Frame's offset in milliseconds, used primarily for video content. Used for the default"
" frames sorting as the secondary key (with the primary key being 'context_id'). For"
" images, this value should typically be 0. If not set, value is filled from the timestamp"
" of the first source. We recommend using this field only in cases concerning the default"
" sorting behavior."
),
"type": ["integer", "null"],
},
},
"required": ["sources"],
"type": "object",
},
"mask": {
"properties": {
"content_type": {
"description": "Content type (e.g. 'image/jpeg', 'image/png')",
"type": "string",
},
"height": {"description": "Height in pixels", "type": "integer"},
"id": {
"description": "unique ID (in this frame)",
"type": "string",
},
"timestamp": {
"default": 0,
"description": (
"Timestamp in the source data (for video content. for images, this value should be 0)"
),
"type": "integer",
},
"uri": {"description": "Data URI", "type": "string"},
"width": {"description": "Width in pixels", "type": "integer"},
},
"required": ["id", "uri"],
"type": "object",
},
"preview": {
"properties": {
"content_type": {
"description": "Content type (e.g. 'image/jpeg', 'image/png')",
"type": "string",
},
"height": {
"description": "Height in pixels",
"type": "integer",
},
"timestamp": {
"default": 0,
"description": (
"Timestamp in the source data (for video content. for images, this value should be 0)"
),
"type": "integer",
},
"uri": {"description": "Data URI", "type": "string"},
"width": {"description": "Width in pixels", "type": "integer"},
},
"required": ["uri"],
"type": "object",
},
"roi": {
"properties": {
"confidence": {
"description": "ROI confidence",
"type": "number",
},
"id": {"description": "ROI id", "type": ["string", "null"]},
"label": {
"description": "ROI labels",
"items": {"type": "string"},
"type": "array",
},
"mask": {
"$ref": "#/definitions/roi_mask",
"description": "Mask info for this ROI",
},
"meta": {
"additionalProperties": True,
"description": "Additional metadata dictionary for the roi",
"type": "object",
},
"poly": {
"description": "ROI polygon (x0, y0, ..., xn, yn)",
"items": {"type": "number"},
"type": "array",
},
"sources": {
"description": "Source ID",
"items": {"type": "string"},
"type": "array",
},
},
"required": ["label"],
"type": "object",
},
"roi_mask": {
"properties": {
"id": {"description": "Mask ID", "type": "string"},
"value": {
"description": "Mask value",
"items": {"type": "integer"},
"type": "array",
},
},
"required": ["id", "value"],
"type": "object",
},
"source": {
"properties": {
"content_type": {
"description": "Content type (e.g. 'image/jpeg', 'image/png')",
"type": "string",
},
"height": {
"description": "Height in pixels",
"type": "integer",
},
"id": {
"description": "Source unique ID within this DatasetVersion",
"type": "string",
},
"masks": {"items": {"$ref": "#/definitions/mask"}, "type": "array"},
"meta": {
"additionalProperties": True,
"description": "Additional metadata dictionary for the source",
"type": "object",
},
"preview": {"$ref": "#/definitions/preview"},
"timestamp": {
"default": 0,
"description": (
"Timestamp in the source data (for video content. for images, this value should be 0)"
),
"type": "integer",
},
"uri": {"description": "Source data URI", "type": "string"},
"width": {"description": "Width in pixels", "type": "integer"},
},
"required": ["id", "uri"],
"type": "object",
},
},
"properties": {
"frames": {
"description": "Frames to save",
"items": {"$ref": "#/definitions/frame"},
"type": "array",
},
"version": {"description": "Draft version ID", "type": "string"},
},
"required": ["version", "frames"],
"type": "object",
}
def __init__(self, version, frames, **kwargs):
super(SaveFramesRequest, self).__init__(**kwargs)
self.version = version
self.frames = frames
@schema_property("version")
def version(self):
return self._property_version
@version.setter
def version(self, value):
if value is None:
self._property_version = None
return
self.assert_isinstance(value, "version", six.string_types)
self._property_version = value
@schema_property("frames")
def frames(self):
return self._property_frames
@frames.setter
def frames(self, value):
if value is None:
self._property_frames = None
return
self.assert_isinstance(value, "frames", (list, tuple))
if any(isinstance(v, dict) for v in value):
value = [Frame.from_dict(v) if isinstance(v, dict) else v for v in value]
else:
self.assert_isinstance(value, "frames", Frame, is_array=True)
self._property_frames = value
| SaveFramesRequest |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/test_utils.py | {
"start": 13271,
"end": 14139
} | class ____(RunCoordinator, ConfigurableClass):
def __init__(self, inst_data: Optional[ConfigurableClassData] = None):
self._inst_data = inst_data
self._queue = []
super().__init__()
def submit_run(self, context: SubmitRunContext):
dagster_run = context.dagster_run
check.not_none(dagster_run.remote_job_origin)
self._queue.append(dagster_run)
return dagster_run
def queue(self):
return self._queue
@classmethod
def config_type(cls):
return Shape({})
@classmethod
def from_config_value(cls, inst_data, config_value):
return cls(
inst_data=inst_data,
)
@property
def inst_data(self):
return self._inst_data
def cancel_run(self, run_id):
check.not_implemented("Cancellation not supported")
| MockedRunCoordinator |
python | walkccc__LeetCode | solutions/3162. Find the Number of Good Pairs I/3162.py | {
"start": 0,
"end": 199
} | class ____:
def numberOfPairs(self, nums1: list[int], nums2: list[int], k: int) -> int:
return sum(num1 % (num2 * k) == 0
for num1 in nums1
for num2 in nums2)
| Solution |
python | walkccc__LeetCode | solutions/258. Add Digits/258.py | {
"start": 0,
"end": 104
} | class ____:
def addDigits(self, num: int) -> int:
return 0 if num == 0 else 1 + (num - 1) % 9
| Solution |
python | joke2k__faker | faker/providers/automotive/tl_PH/__init__.py | {
"start": 57,
"end": 237
} | class ____(EnPhAutomotiveProvider):
"""Implement automotive provider for ``tl_PH`` locale.
There is no difference from the ``en_PH`` implementation.
"""
pass
| Provider |
python | walkccc__LeetCode | solutions/701. Insert into a Binary Search Tree/701.py | {
"start": 0,
"end": 296
} | class ____:
def insertIntoBST(self, root: TreeNode | None, val: int) -> TreeNode | None:
if not root:
return TreeNode(val)
if root.val > val:
root.left = self.insertIntoBST(root.left, val)
else:
root.right = self.insertIntoBST(root.right, val)
return root
| Solution |
python | getsentry__sentry | src/sentry/preprod/api/models/project_preprod_build_details_models.py | {
"start": 1371,
"end": 1541
} | class ____(BaseModel):
metrics_artifact_type: PreprodArtifactSizeMetrics.MetricsArtifactType
install_size_bytes: int
download_size_bytes: int
| SizeInfoSizeMetric |
python | pydantic__pydantic | pydantic/mypy.py | {
"start": 14985,
"end": 15625
} | class ____:
"""Based on mypy.plugins.dataclasses.DataclassAttribute.
ClassVars are ignored by subclasses.
Attributes:
name: the ClassVar name
"""
def __init__(self, name):
self.name = name
@classmethod
def deserialize(cls, data: JsonDict) -> PydanticModelClassVar:
"""Based on mypy.plugins.dataclasses.DataclassAttribute.deserialize."""
data = data.copy()
return cls(**data)
def serialize(self) -> JsonDict:
"""Based on mypy.plugins.dataclasses.DataclassAttribute.serialize."""
return {
'name': self.name,
}
| PydanticModelClassVar |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_contextlib.py | {
"start": 22458,
"end": 39929
} | class ____:
exit_stack = None
@support.requires_docstrings
def test_instance_docs(self):
# Issue 19330: ensure context manager instances have good docstrings
cm_docstring = self.exit_stack.__doc__
obj = self.exit_stack()
self.assertEqual(obj.__doc__, cm_docstring)
def test_no_resources(self):
with self.exit_stack():
pass
def test_callback(self):
expected = [
((), {}),
((1,), {}),
((1,2), {}),
((), dict(example=1)),
((1,), dict(example=1)),
((1,2), dict(example=1)),
((1,2), dict(self=3, callback=4)),
]
result = []
def _exit(*args, **kwds):
"""Test metadata propagation"""
result.append((args, kwds))
with self.exit_stack() as stack:
for args, kwds in reversed(expected):
if args and kwds:
f = stack.callback(_exit, *args, **kwds)
elif args:
f = stack.callback(_exit, *args)
elif kwds:
f = stack.callback(_exit, **kwds)
else:
f = stack.callback(_exit)
self.assertIs(f, _exit)
for wrapper in stack._exit_callbacks:
self.assertIs(wrapper[1].__wrapped__, _exit)
self.assertNotEqual(wrapper[1].__name__, _exit.__name__)
self.assertIsNone(wrapper[1].__doc__, _exit.__doc__)
self.assertEqual(result, expected)
result = []
with self.exit_stack() as stack:
with self.assertRaises(TypeError):
stack.callback(arg=1)
with self.assertRaises(TypeError):
self.exit_stack.callback(arg=2)
with self.assertRaises(TypeError):
stack.callback(callback=_exit, arg=3)
self.assertEqual(result, [])
def test_push(self):
exc_raised = ZeroDivisionError
def _expect_exc(exc_type, exc, exc_tb):
self.assertIs(exc_type, exc_raised)
def _suppress_exc(*exc_details):
return True
def _expect_ok(exc_type, exc, exc_tb):
self.assertIsNone(exc_type)
self.assertIsNone(exc)
self.assertIsNone(exc_tb)
with torch._dynamo.error_on_graph_break(False):
class ExitCM(object):
def __init__(self, check_exc):
self.check_exc = check_exc
def __enter__(self):
self.fail("Should not be called!")
def __exit__(self, *exc_details):
self.check_exc(*exc_details)
with self.exit_stack() as stack:
stack.push(_expect_ok)
self.assertIs(stack._exit_callbacks[-1][1], _expect_ok)
cm = ExitCM(_expect_ok)
stack.push(cm)
self.assertIs(stack._exit_callbacks[-1][1].__self__, cm)
stack.push(_suppress_exc)
self.assertIs(stack._exit_callbacks[-1][1], _suppress_exc)
cm = ExitCM(_expect_exc)
stack.push(cm)
self.assertIs(stack._exit_callbacks[-1][1].__self__, cm)
stack.push(_expect_exc)
self.assertIs(stack._exit_callbacks[-1][1], _expect_exc)
stack.push(_expect_exc)
self.assertIs(stack._exit_callbacks[-1][1], _expect_exc)
1/0
def test_enter_context(self):
with torch._dynamo.error_on_graph_break(False):
class TestCM(object):
def __enter__(self):
result.append(1)
def __exit__(self, *exc_details):
result.append(3)
result = []
cm = TestCM()
with self.exit_stack() as stack:
@stack.callback # Registered first => cleaned up last
def _exit():
result.append(4)
self.assertIsNotNone(_exit)
stack.enter_context(cm)
self.assertIs(stack._exit_callbacks[-1][1].__self__, cm)
result.append(2)
self.assertEqual(result, [1, 2, 3, 4])
def test_enter_context_errors(self):
with torch._dynamo.error_on_graph_break(False):
class LacksEnterAndExit:
pass
class LacksEnter:
def __exit__(self, *exc_info):
pass
class LacksExit:
def __enter__(self):
pass
with self.exit_stack() as stack:
with self.assertRaisesRegex(TypeError, 'the context manager'):
stack.enter_context(LacksEnterAndExit())
with self.assertRaisesRegex(TypeError, 'the context manager'):
stack.enter_context(LacksEnter())
with self.assertRaisesRegex(TypeError, 'the context manager'):
stack.enter_context(LacksExit())
self.assertFalse(stack._exit_callbacks)
def test_close(self):
result = []
with self.exit_stack() as stack:
@stack.callback
def _exit():
result.append(1)
self.assertIsNotNone(_exit)
stack.close()
result.append(2)
self.assertEqual(result, [1, 2])
def test_pop_all(self):
result = []
with self.exit_stack() as stack:
@stack.callback
def _exit():
result.append(3)
self.assertIsNotNone(_exit)
new_stack = stack.pop_all()
result.append(1)
result.append(2)
new_stack.close()
self.assertEqual(result, [1, 2, 3])
def test_exit_raise(self):
with self.assertRaises(ZeroDivisionError):
with self.exit_stack() as stack:
stack.push(lambda *exc: False)
1/0
def test_exit_suppress(self):
with self.exit_stack() as stack:
stack.push(lambda *exc: True)
1/0
def test_exit_exception_traceback(self):
# This test captures the current behavior of ExitStack so that we know
# if we ever unintendedly change it. It is not a statement of what the
# desired behavior is (for instance, we may want to remove some of the
# internal contextlib frames).
def raise_exc(exc):
raise exc
try:
with self.exit_stack() as stack:
stack.callback(raise_exc, ValueError)
1/0
except ValueError as e:
exc = e
self.assertIsInstance(exc, ValueError)
ve_frames = traceback.extract_tb(exc.__traceback__)
expected = \
[('test_exit_exception_traceback', 'with self.exit_stack() as stack:')] + \
self.callback_error_internal_frames + \
[('_exit_wrapper', 'callback(*args, **kwds)'),
('raise_exc', 'raise exc')]
self.assertEqual(
[(f.name, f.line) for f in ve_frames], expected)
self.assertIsInstance(exc.__context__, ZeroDivisionError)
zde_frames = traceback.extract_tb(exc.__context__.__traceback__)
self.assertEqual([(f.name, f.line) for f in zde_frames],
[('test_exit_exception_traceback', '1/0')])
def test_exit_exception_chaining_reference(self):
# Sanity check to make sure that ExitStack chaining matches
# actual nested with statements
with torch._dynamo.error_on_graph_break(False):
class RaiseExc:
def __init__(self, exc):
self.exc = exc
def __enter__(self):
return self
def __exit__(self, *exc_details):
raise self.exc
class RaiseExcWithContext:
def __init__(self, outer, inner):
self.outer = outer
self.inner = inner
def __enter__(self):
return self
def __exit__(self, *exc_details):
try:
raise self.inner
except:
raise self.outer
class SuppressExc:
def __enter__(self):
return self
def __exit__(self, *exc_details):
type(self).saved_details = exc_details
return True
try:
with RaiseExc(IndexError):
with RaiseExcWithContext(KeyError, AttributeError):
with SuppressExc():
with RaiseExc(ValueError):
1 / 0
except IndexError as exc:
self.assertIsInstance(exc.__context__, KeyError)
self.assertIsInstance(exc.__context__.__context__, AttributeError)
# Inner exceptions were suppressed
self.assertIsNone(exc.__context__.__context__.__context__)
else:
self.fail("Expected IndexError, but no exception was raised")
# Check the inner exceptions
inner_exc = SuppressExc.saved_details[1]
self.assertIsInstance(inner_exc, ValueError)
self.assertIsInstance(inner_exc.__context__, ZeroDivisionError)
def test_exit_exception_chaining(self):
# Ensure exception chaining matches the reference behaviour
def raise_exc(exc):
raise exc
saved_details = None
def suppress_exc(*exc_details):
nonlocal saved_details
saved_details = exc_details
return True
try:
with self.exit_stack() as stack:
stack.callback(raise_exc, IndexError)
stack.callback(raise_exc, KeyError)
stack.callback(raise_exc, AttributeError)
stack.push(suppress_exc)
stack.callback(raise_exc, ValueError)
1 / 0
except IndexError as exc:
self.assertIsInstance(exc.__context__, KeyError)
self.assertIsInstance(exc.__context__.__context__, AttributeError)
# Inner exceptions were suppressed
self.assertIsNone(exc.__context__.__context__.__context__)
else:
self.fail("Expected IndexError, but no exception was raised")
# Check the inner exceptions
inner_exc = saved_details[1]
self.assertIsInstance(inner_exc, ValueError)
self.assertIsInstance(inner_exc.__context__, ZeroDivisionError)
def test_exit_exception_explicit_none_context(self):
# Ensure ExitStack chaining matches actual nested `with` statements
# regarding explicit __context__ = None.
with torch._dynamo.error_on_graph_break(False):
class MyException(Exception):
pass
@contextmanager
def my_cm():
try:
yield
except BaseException:
exc = MyException()
try:
raise exc
finally:
exc.__context__ = None
@contextmanager
def my_cm_with_exit_stack():
with self.exit_stack() as stack:
stack.enter_context(my_cm())
yield stack
for cm in (my_cm, my_cm_with_exit_stack):
with self.subTest():
try:
with cm():
raise IndexError()
except MyException as exc:
self.assertIsNone(exc.__context__)
else:
self.fail("Expected IndexError, but no exception was raised")
def test_exit_exception_non_suppressing(self):
# http://bugs.python.org/issue19092
def raise_exc(exc):
raise exc
def suppress_exc(*exc_details):
return True
try:
with self.exit_stack() as stack:
stack.callback(lambda: None)
stack.callback(raise_exc, IndexError)
except Exception as exc:
self.assertIsInstance(exc, IndexError)
else:
self.fail("Expected IndexError, but no exception was raised")
try:
with self.exit_stack() as stack:
stack.callback(raise_exc, KeyError)
stack.push(suppress_exc)
stack.callback(raise_exc, IndexError)
except Exception as exc:
self.assertIsInstance(exc, KeyError)
else:
self.fail("Expected KeyError, but no exception was raised")
def test_exit_exception_with_correct_context(self):
# http://bugs.python.org/issue20317
@contextmanager
def gets_the_context_right(exc):
try:
yield
finally:
raise exc
exc1 = Exception(1)
exc2 = Exception(2)
exc3 = Exception(3)
exc4 = Exception(4)
# The contextmanager already fixes the context, so prior to the
# fix, ExitStack would try to fix it *again* and get into an
# infinite self-referential loop
try:
with self.exit_stack() as stack:
stack.enter_context(gets_the_context_right(exc4))
stack.enter_context(gets_the_context_right(exc3))
stack.enter_context(gets_the_context_right(exc2))
raise exc1
except Exception as exc:
self.assertIs(exc, exc4)
self.assertIs(exc.__context__, exc3)
self.assertIs(exc.__context__.__context__, exc2)
self.assertIs(exc.__context__.__context__.__context__, exc1)
self.assertIsNone(
exc.__context__.__context__.__context__.__context__)
def test_exit_exception_with_existing_context(self):
# Addresses a lack of test coverage discovered after checking in a
# fix for issue 20317 that still contained debugging code.
def raise_nested(inner_exc, outer_exc):
try:
raise inner_exc
finally:
raise outer_exc
exc1 = Exception(1)
exc2 = Exception(2)
exc3 = Exception(3)
exc4 = Exception(4)
exc5 = Exception(5)
try:
with self.exit_stack() as stack:
stack.callback(raise_nested, exc4, exc5)
stack.callback(raise_nested, exc2, exc3)
raise exc1
except Exception as exc:
self.assertIs(exc, exc5)
self.assertIs(exc.__context__, exc4)
self.assertIs(exc.__context__.__context__, exc3)
self.assertIs(exc.__context__.__context__.__context__, exc2)
self.assertIs(
exc.__context__.__context__.__context__.__context__, exc1)
self.assertIsNone(
exc.__context__.__context__.__context__.__context__.__context__)
def test_body_exception_suppress(self):
def suppress_exc(*exc_details):
return True
try:
with self.exit_stack() as stack:
stack.push(suppress_exc)
1/0
except IndexError as exc:
self.fail("Expected no exception, got IndexError")
def test_exit_exception_chaining_suppress(self):
with self.exit_stack() as stack:
stack.push(lambda *exc: True)
stack.push(lambda *exc: 1/0)
stack.push(lambda *exc: {}[1])
def test_excessive_nesting(self):
# The original implementation would die with RecursionError here
with self.exit_stack() as stack:
for i in range(10000):
stack.callback(int)
def test_instance_bypass(self):
with torch._dynamo.error_on_graph_break(False):
class Example(object): pass
cm = Example()
cm.__enter__ = object()
cm.__exit__ = object()
stack = self.exit_stack()
with self.assertRaisesRegex(TypeError, 'the context manager'):
stack.enter_context(cm)
stack.push(cm)
self.assertIs(stack._exit_callbacks[-1][1], cm)
def test_dont_reraise_RuntimeError(self):
# https://bugs.python.org/issue27122
with torch._dynamo.error_on_graph_break(False):
class UniqueException(Exception): pass
class UniqueRuntimeError(RuntimeError): pass
@contextmanager
def second():
try:
yield 1
except Exception as exc:
raise UniqueException("new exception") from exc
@contextmanager
def first():
try:
yield 1
except Exception as exc:
raise exc
# The UniqueRuntimeError should be caught by second()'s exception
# handler which chain raised a new UniqueException.
with self.assertRaises(UniqueException) as err_ctx:
with self.exit_stack() as es_ctx:
es_ctx.enter_context(second())
es_ctx.enter_context(first())
raise UniqueRuntimeError("please no infinite loop.")
exc = err_ctx.exception
self.assertIsInstance(exc, UniqueException)
self.assertIsInstance(exc.__context__, UniqueRuntimeError)
self.assertIsNone(exc.__context__.__context__)
self.assertIsNone(exc.__context__.__cause__)
self.assertIs(exc.__cause__, exc.__context__)
| _TestBaseExitStack |
python | realpython__materials | python-pydantic/settings_management.py | {
"start": 101,
"end": 453
} | class ____(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=True,
extra="forbid",
)
database_host: HttpUrl
database_user: str = Field(min_length=5)
database_password: str = Field(min_length=10)
api_key: str = Field(min_length=20)
| AppConfig |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/tests/test_rl_trainer.py | {
"start": 865,
"end": 8459
} | class ____(RLTrainer):
def set_is_policy_updating(self, is_updating):
self.update_policy = is_updating
def get_policy(self, name_behavior_id):
return mock.Mock()
def _is_ready_update(self):
return True
def _update_policy(self):
return self.update_policy
def add_policy(self, mock_behavior_id, mock_policy):
def checkpoint_path(brain_name, step):
onnx_file_path = os.path.join(
self.model_saver.model_path, f"{brain_name}-{step}.onnx"
)
other_file_paths = [
os.path.join(self.model_saver.model_path, f"{brain_name}-{step}.pt")
]
return onnx_file_path, other_file_paths
self.policies[mock_behavior_id] = mock_policy
mock_model_saver = mock.Mock()
mock_model_saver.model_path = self.artifact_path
mock_model_saver.save_checkpoint.side_effect = checkpoint_path
self.model_saver = mock_model_saver
def create_optimizer(self) -> TorchOptimizer:
return mock.Mock()
def create_policy(
self,
parsed_behavior_id: BehaviorIdentifiers,
behavior_spec: BehaviorSpec,
) -> Policy:
return mock.Mock()
def _process_trajectory(self, trajectory):
super()._process_trajectory(trajectory)
def create_rl_trainer():
trainer = FakeTrainer(
"test_trainer",
TrainerSettings(max_steps=100, checkpoint_interval=10, summary_freq=20),
True,
False,
"mock_model_path",
0,
)
trainer.set_is_policy_updating(True)
return trainer
def test_rl_trainer():
trainer = create_rl_trainer()
agent_id = "0"
trainer.collected_rewards["extrinsic"] = {agent_id: 3}
# Test end episode
trainer.end_episode()
for rewards in trainer.collected_rewards.values():
for agent_id in rewards:
assert rewards[agent_id] == 0
def test_clear_update_buffer():
trainer = create_rl_trainer()
trainer.update_buffer = construct_fake_buffer(0)
trainer._clear_update_buffer()
for _, arr in trainer.update_buffer.items():
assert len(arr) == 0
@mock.patch("mlagents.trainers.trainer.trainer.Trainer.save_model")
def test_advance(mocked_save_model):
trainer = create_rl_trainer()
mock_policy = mock.Mock()
trainer.add_policy("TestBrain", mock_policy)
trajectory_queue = AgentManagerQueue("testbrain")
policy_queue = AgentManagerQueue("testbrain")
trainer.subscribe_trajectory_queue(trajectory_queue)
trainer.publish_policy_queue(policy_queue)
time_horizon = 10
trajectory = mb.make_fake_trajectory(
length=time_horizon,
observation_specs=create_observation_specs_with_shapes([(1,)]),
max_step_complete=True,
action_spec=ActionSpec.create_discrete((2,)),
)
trajectory_queue.put(trajectory)
trainer.advance()
policy_queue.get_nowait()
# Check that get_step is correct
assert trainer.get_step == time_horizon
# Check that we can turn off the trainer and that the buffer is cleared
for _ in range(0, 5):
trajectory_queue.put(trajectory)
trainer.advance()
# Check that there is stuff in the policy queue
policy_queue.get_nowait()
# Check that if the policy doesn't update, we don't push it to the queue
trainer.set_is_policy_updating(False)
for _ in range(0, 10):
trajectory_queue.put(trajectory)
trainer.advance()
# Check that there nothing in the policy queue
with pytest.raises(AgentManagerQueue.Empty):
policy_queue.get_nowait()
# Check that no model has been saved
assert not trainer.should_still_train
assert mocked_save_model.call_count == 0
@mock.patch("mlagents.trainers.trainer.trainer.StatsReporter.write_stats")
@mock.patch(
"mlagents.trainers.trainer.rl_trainer.ModelCheckpointManager.add_checkpoint"
)
def test_summary_checkpoint(mock_add_checkpoint, mock_write_summary):
trainer = create_rl_trainer()
mock_policy = mock.Mock()
trainer.add_policy("TestBrain", mock_policy)
trajectory_queue = AgentManagerQueue("testbrain")
policy_queue = AgentManagerQueue("testbrain")
trainer.subscribe_trajectory_queue(trajectory_queue)
trainer.publish_policy_queue(policy_queue)
time_horizon = 10
summary_freq = trainer.trainer_settings.summary_freq
checkpoint_interval = trainer.trainer_settings.checkpoint_interval
trajectory = mb.make_fake_trajectory(
length=time_horizon,
observation_specs=create_observation_specs_with_shapes([(1,)]),
max_step_complete=True,
action_spec=ActionSpec.create_discrete((2,)),
)
# Check that we can turn off the trainer and that the buffer is cleared
num_trajectories = 5
for _ in range(0, num_trajectories):
trajectory_queue.put(trajectory)
trainer.advance()
# Check that there is stuff in the policy queue
policy_queue.get_nowait()
# Check that we have called write_summary the appropriate number of times
calls = [
mock.call(step)
for step in range(summary_freq, num_trajectories * time_horizon, summary_freq)
]
mock_write_summary.assert_has_calls(calls, any_order=True)
checkpoint_range = range(
checkpoint_interval, num_trajectories * time_horizon, checkpoint_interval
)
calls = [mock.call(trainer.brain_name, step) for step in checkpoint_range]
trainer.model_saver.save_checkpoint.assert_has_calls(calls, any_order=True)
export_ext = "onnx"
add_checkpoint_calls = [
mock.call(
trainer.brain_name,
ModelCheckpoint(
step,
f"{trainer.model_saver.model_path}{os.path.sep}{trainer.brain_name}-{step}.{export_ext}",
None,
mock.ANY,
[
f"{trainer.model_saver.model_path}{os.path.sep}{trainer.brain_name}-{step}.pt"
],
),
trainer.trainer_settings.keep_checkpoints,
)
for step in checkpoint_range
]
mock_add_checkpoint.assert_has_calls(add_checkpoint_calls)
def test_update_buffer_append():
trainer = create_rl_trainer()
mock_policy = mock.Mock()
trainer.add_policy("TestBrain", mock_policy)
trajectory_queue = AgentManagerQueue("testbrain")
policy_queue = AgentManagerQueue("testbrain")
trainer.subscribe_trajectory_queue(trajectory_queue)
trainer.publish_policy_queue(policy_queue)
time_horizon = 10
trajectory = mb.make_fake_trajectory(
length=time_horizon,
observation_specs=create_observation_specs_with_shapes([(1,)]),
max_step_complete=True,
action_spec=ActionSpec.create_discrete((2,)),
)
agentbuffer_trajectory = trajectory.to_agentbuffer()
assert trainer.update_buffer.num_experiences == 0
# Check that if we append, our update buffer gets longer.
# max_steps = 100
for i in range(10):
trainer._process_trajectory(trajectory)
trainer._append_to_update_buffer(agentbuffer_trajectory)
assert trainer.update_buffer.num_experiences == (i + 1) * time_horizon
# Check that if we append after stopping training, nothing happens.
# We process enough trajectories to hit max steps
trainer.set_is_policy_updating(False)
trainer._process_trajectory(trajectory)
trainer._append_to_update_buffer(agentbuffer_trajectory)
assert trainer.update_buffer.num_experiences == (i + 1) * time_horizon
| FakeTrainer |
python | eth-brownie__brownie | brownie/network/contract.py | {
"start": 5046,
"end": 18720
} | class ____(_ContractBase):
"""List-like container class that holds all Contract instances of the same
type, and is used to deploy new instances of that contract.
Attributes:
abi: Complete contract ABI.
bytecode: Bytecode used to deploy the contract.
signatures: Dictionary of {'function name': "bytes4 signature"}
topics: Dictionary of {'event name': "bytes32 topic"}"""
def __init__(self, project: Any, build: ContractBuildJson) -> None:
self.tx = None
self.bytecode: Final = build["bytecode"]
self._contracts: Final[List["ProjectContract"]] = []
super().__init__(project, build, project._sources)
self.deploy: Final = ContractConstructor(self, self._name)
_revert_register(self)
# messes with tests if it is created on init
# instead we create when it's requested, but still define it here
self._flattener: Flattener = None
def __iter__(self) -> Iterator["ProjectContract"]:
return iter(self._contracts)
def __getitem__(self, i: Any) -> "ProjectContract":
return self._contracts[i]
def __delitem__(self, key: Any) -> None:
item = self._contracts[key]
self.remove(item)
def __len__(self) -> int:
return len(self._contracts)
def __repr__(self) -> str:
if CONFIG.argv["cli"] == "console":
return str(self._contracts)
return super().__repr__()
def _reset(self) -> None:
for contract in self._contracts:
_remove_contract(contract)
contract._reverted = True
self._contracts.clear()
def _revert(self, height: int) -> None:
reverted = [
i
for i in self._contracts
if (i.tx and i.tx.block_number is not None and i.tx.block_number > height)
# removeprefix is used for compatibility with both hexbytes<1 and >=1
or len(web3.eth.get_code(i.address).hex().removeprefix("0x")) <= 2
]
for contract in reverted:
self.remove(contract)
contract._reverted = True
def remove(self, contract: "ProjectContract") -> None:
"""Removes a contract from the container.
Args:
contract: Contract instance of address string of the contract."""
if contract not in self._contracts:
raise TypeError("Object is not in container.")
self._contracts.remove(contract)
contract._delete_deployment()
_remove_contract(contract)
def at(
self,
address: HexAddress,
owner: Optional[AccountsType] = None,
tx: Optional[TransactionReceiptType] = None,
persist: bool = True,
) -> "ProjectContract":
"""Returns a contract address.
Raises ValueError if no bytecode exists at the address.
Args:
address: Address string of the contract.
owner: Default Account instance to send contract transactions from.
tx: Transaction ID of the contract creation."""
address = _resolve_address(address)
contract = _find_contract(address)
if isinstance(contract, ProjectContract):
if contract._name == self._name and contract._project == self._project:
return contract
raise ContractExists(
f"'{contract._name}' declared at {address} in project '{contract._project._name}'"
)
build = self._build
contract = ProjectContract(self._project, build, address, owner, tx)
if not _verify_deployed_code(address, build["deployedBytecode"], build["language"]):
# prevent trace attempts when the bytecode doesn't match
del contract._build["pcMap"]
contract._save_deployment()
_add_contract(contract)
self._contracts.append(contract)
if CONFIG.network_type == "live" and persist:
_add_deployment(contract)
return contract
def _add_from_tx(self, tx: TransactionReceiptType) -> None:
tx._confirmed.wait()
if tx.status and tx.contract_address is not None:
try:
self.at(tx.contract_address, tx.sender, tx)
except ContractNotFound:
# if the contract self-destructed during deployment
pass
def get_verification_info(self) -> Dict:
"""
Return a dict with flattened source code for this contract
and further information needed for verification
"""
language = self._build["language"]
if language == "Vyper":
raise TypeError(
"Etherscan does not support API verification of source code "
"for vyper contracts. You need to verify the source manually"
)
elif language == "Solidity":
if self._flattener is None:
source_fp = (
Path(self._project._path)
.joinpath(self._build["sourcePath"])
.resolve()
.as_posix()
)
config = self._project._compiler_config
remaps = dict(
map(
lambda s: s.split("=", 1),
compiler._get_solc_remappings(config["solc"]["remappings"]),
)
)
libs = {lib.strip("_") for lib in regex_findall("_{1,}[^_]*_{1,}", self.bytecode)}
compiler_settings = {
"evmVersion": self._build["compiler"]["evm_version"],
"optimizer": config["solc"]["optimizer"],
"libraries": {
Path(source_fp).name: {lib: self._project[lib][-1].address for lib in libs}
},
}
self._flattener = Flattener(source_fp, self._name, remaps, compiler_settings)
build_json = self._build
return {
"standard_json_input": self._flattener.standard_input_json,
"contract_name": build_json["contractName"],
"compiler_version": build_json["compiler"]["version"],
"optimizer_enabled": build_json["compiler"]["optimizer"]["enabled"],
"optimizer_runs": build_json["compiler"]["optimizer"]["runs"],
"license_identifier": self._flattener.license,
"bytecode_len": len(build_json["bytecode"]),
}
else:
raise TypeError(f"Unsupported language for source verification: {language}")
def publish_source(self, contract: "Contract", silent: bool = False) -> bool:
"""Flatten contract and publish source on the selected explorer"""
api_key = os.getenv("ETHERSCAN_TOKEN")
if api_key is None:
raise ValueError(
"An API token is required to verify contract source code. "
"Visit https://etherscan.io/register to obtain a token, and "
"then store it as the environment variable $ETHERSCAN_TOKEN"
)
address = _resolve_address(contract.address)
# Get source code and contract/compiler information
contract_info = self.get_verification_info()
# Select matching license code (https://etherscan.io/contract-license-types)
license_code = 1
identifier = contract_info["license_identifier"].lower()
if "unlicensed" in identifier:
license_code = 2
elif "mit" in identifier:
license_code = 3
elif "agpl" in identifier and "3.0" in identifier:
license_code = 13
elif "lgpl" in identifier:
if "2.1" in identifier:
license_code = 6
elif "3.0" in identifier:
license_code = 7
elif "gpl" in identifier:
if "2.0" in identifier:
license_code = 4
elif "3.0" in identifier:
license_code = 5
elif "bsd-2-clause" in identifier:
license_code = 8
elif "bsd-3-clause" in identifier:
license_code = 9
elif "mpl" in identifier and "2.0" in identifier:
license_code = 10
elif identifier.startswith("osl") and "3.0" in identifier:
license_code = 11
elif "apache" in identifier and "2.0" in identifier:
license_code = 12
# get constructor arguments
url = "https://api.etherscan.io/v2/api"
params_tx: Dict = {
"chainid": web3.chain_id,
"apikey": api_key,
"module": "account",
"action": "txlist",
"address": address,
"page": 1,
"sort": "asc",
"offset": 1,
}
i = 0
while True:
response = requests.get(url, params=params_tx, headers=REQUEST_HEADERS)
if response.status_code != 200:
raise ConnectionError(
f"Status {response.status_code} when querying {url}: {response.text}"
)
data = response.json()
if int(data["status"]) == 1:
# Constructor arguments received
break
# Wait for contract to be recognized by etherscan
# This takes a few seconds after the contract is deployed
# After 10 loops we throw with the API result message (includes address)
if i >= 10:
raise ValueError(f"API request failed with: {data['result']}")
elif i == 0 and not silent:
print(f"Waiting for {url} to process contract...")
i += 1
time.sleep(10)
if data["message"] == "OK":
constructor_arguments = data["result"][0]["input"][contract_info["bytecode_len"] + 2 :]
else:
constructor_arguments = ""
# Submit verification
payload_verification: Dict = {
"apikey": api_key,
"module": "contract",
"action": "verifysourcecode",
"contractaddress": address,
"sourceCode": io.StringIO(ujson_dumps(self._flattener.standard_input_json)),
"codeformat": "solidity-standard-json-input",
"contractname": f"{self._flattener.contract_file}:{self._flattener.contract_name}",
"compilerversion": f"v{contract_info['compiler_version']}",
"optimizationUsed": 1 if contract_info["optimizer_enabled"] else 0,
"runs": contract_info["optimizer_runs"],
# NOTE: This typo is intentional.
# https://docs.etherscan.io/etherscan-v2/common-verification-errors
# "There is an easter egg 🐣 on the constructorArguements field spelling,
# using it as the "correct" spelling may miss your submission!"
"constructorArguements": constructor_arguments,
"licenseType": license_code,
}
response = requests.post(
f"{url}?chainid={web3.chain_id}", data=payload_verification, headers=REQUEST_HEADERS
)
if response.status_code != 200:
raise ConnectionError(
f"Status {response.status_code} when querying {url}: {response.text}"
)
data = response.json()
if int(data["status"]) != 1:
raise ValueError(f"Failed to submit verification request: {data['result']}")
# Status of request
guid = data["result"]
if not silent:
print("Verification submitted successfully. Waiting for result...")
time.sleep(10)
params_status: Dict = {
"chainid": web3.chain_id,
"apikey": api_key,
"module": "contract",
"action": "checkverifystatus",
"guid": guid,
}
while True:
response = requests.get(url, params=params_status, headers=REQUEST_HEADERS)
if response.status_code != 200:
raise ConnectionError(
f"Status {response.status_code} when querying {url}: {response.text}"
)
data = response.json()
if data["result"] == "Pending in queue":
if not silent:
print("Verification pending...")
else:
if not silent:
color = bright_green if data["message"] == "OK" else bright_red
print(f"Verification complete. Result: {color}{data['result']}{color}")
return data["message"] == "OK"
time.sleep(10)
def _slice_source(self, source: str, offset: list) -> str:
"""Slice the source of the contract, preserving any comments above the first line."""
offset_start = offset[0]
top_source = source[:offset_start]
top_lines = top_source.split("\n")[::-1]
comment_open = False
for line in top_lines:
stripped = line.strip()
if (
not stripped
or stripped.startswith(("//", "/*", "*"))
or stripped.endswith("*/")
or comment_open
):
offset_start = offset_start - len(line) - 1
if stripped.endswith("*/"):
comment_open = True
elif stripped.startswith("/*"):
comment_open = False
else:
# Stop on the first non-empty, non-comment line
break
offset_start = max(0, offset_start)
return source[offset_start : offset[1]].strip()
| ContractContainer |
python | django-import-export__django-import-export | tests/core/tests/admin_integration/test_export.py | {
"start": 20541,
"end": 22980
} | class ____(AdminTestMixin, TestCase):
"""Test export ok when column name is defined in fields list (issue 1828)."""
def setUp(self):
super().setUp()
self.author = Author.objects.create(id=11, name="Ian Fleming")
self.book = Book.objects.create(
name="Moonraker", author=self.author, published=date(1955, 4, 5)
)
self.orig_fields = EBookResource._meta.fields
EBookResource._meta.fields = (
"id",
"author_email",
"name",
"published_date",
"auteur_name",
)
def tearDown(self):
super().tearDown()
EBookResource._meta.fields = self.orig_fields
def test_export_with_custom_field(self):
data = {
"format": "0",
"author": self.author.id,
"resource": "",
"ebookresource_id": True,
"ebookresource_author_email": True,
"ebookresource_name": True,
"ebookresource_published_date": True,
}
self._prepend_form_prefix(data)
date_str = datetime.now().strftime("%Y-%m-%d")
response = self._post_url_response(self.ebook_export_url, data)
self.assertTrue(response.has_header("Content-Disposition"))
self.assertEqual(response["Content-Type"], "text/csv")
self.assertEqual(
response["Content-Disposition"],
f'attachment; filename="EBook-{date_str}.csv"',
)
s = (
"id,Email of the author,name,published_date\r\n"
f"{self.book.id},,Moonraker,1955-04-05\r\n"
)
self.assertEqual(s, response.content.decode())
def test_export_with_custom_name(self):
# issue 1893
data = {
"format": "0",
"author": self.author.id,
"resource": "",
"ebookresource_id": True,
"ebookresource_author_email": True,
"ebookresource_name": True,
"ebookresource_published_date": True,
"ebookresource_auteur_name": True,
}
self._prepend_form_prefix(data)
response = self._post_url_response(self.ebook_export_url, data)
s = (
"id,Email of the author,name,published_date,Author Name\r\n"
f"{self.book.id},,Moonraker,1955-04-05,Ian Fleming\r\n"
)
self.assertEqual(s, response.content.decode())
| CustomColumnNameExportTest |
python | graphql-python__graphene | graphene/types/definitions.py | {
"start": 817,
"end": 894
} | class ____(GrapheneGraphQLType, GraphQLObjectType):
pass
| GrapheneObjectType |
python | getsentry__sentry | src/sentry/notifications/notification_action/types.py | {
"start": 2011,
"end": 2111
} | class ____(TypedDict):
actions: list[dict[str, Any]]
legacy_rule_id: NotRequired[int]
| RuleData |
python | apache__airflow | providers/google/tests/unit/google/cloud/sensors/test_dataflow.py | {
"start": 20993,
"end": 28039
} | class ____:
@pytest.mark.parametrize(
("job_current_state", "fail_on_terminal_state"),
[
(DataflowJobStatus.JOB_STATE_RUNNING, True),
(DataflowJobStatus.JOB_STATE_RUNNING, False),
(DataflowJobStatus.JOB_STATE_DONE, False),
],
)
@mock.patch("airflow.providers.google.cloud.sensors.dataflow.DataflowHook")
def test_poke(self, mock_hook, job_current_state, fail_on_terminal_state):
mock_get_job = mock_hook.return_value.get_job
mock_fetch_job_autoscaling_events_by_id = mock_hook.return_value.fetch_job_autoscaling_events_by_id
callback = mock.MagicMock()
task = DataflowJobAutoScalingEventsSensor(
task_id=TEST_TASK_ID,
job_id=TEST_JOB_ID,
callback=callback,
fail_on_terminal_state=fail_on_terminal_state,
location=TEST_LOCATION,
project_id=TEST_PROJECT_ID,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_get_job.return_value = {"id": TEST_JOB_ID, "currentState": job_current_state}
results = task.poke(mock.MagicMock())
assert callback.return_value == results.xcom_value
mock_hook.assert_called_once_with(
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_fetch_job_autoscaling_events_by_id.assert_called_once_with(
job_id=TEST_JOB_ID, project_id=TEST_PROJECT_ID, location=TEST_LOCATION
)
callback.assert_called_once_with(mock_fetch_job_autoscaling_events_by_id.return_value)
@mock.patch("airflow.providers.google.cloud.sensors.dataflow.DataflowHook")
def test_poke_raise_exception_on_terminal_state(self, mock_hook):
mock_get_job = mock_hook.return_value.get_job
mock_fetch_job_autoscaling_events_by_id = mock_hook.return_value.fetch_job_autoscaling_events_by_id
callback = mock.MagicMock()
task = DataflowJobAutoScalingEventsSensor(
task_id=TEST_TASK_ID,
job_id=TEST_JOB_ID,
callback=callback,
fail_on_terminal_state=True,
location=TEST_LOCATION,
project_id=TEST_PROJECT_ID,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_get_job.return_value = {"id": TEST_JOB_ID, "currentState": DataflowJobStatus.JOB_STATE_DONE}
with pytest.raises(
AirflowException,
match=f"Job with id '{TEST_JOB_ID}' is already in terminal state: "
f"{DataflowJobStatus.JOB_STATE_DONE}",
):
task.poke(mock.MagicMock())
mock_hook.assert_called_once_with(
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_fetch_job_autoscaling_events_by_id.assert_not_called()
callback.assert_not_called()
@mock.patch("airflow.providers.google.cloud.hooks.dataflow.AsyncDataflowHook")
def test_execute_enters_deferred_state(self, mock_hook):
"""
Tests that AutoScalingEventTrigger will be fired when the DataflowJobAutoScalingEventSensor
is executed and deferrable is set to True.
"""
task = DataflowJobAutoScalingEventsSensor(
task_id=TEST_TASK_ID,
job_id=TEST_JOB_ID,
fail_on_terminal_state=False,
location=TEST_LOCATION,
project_id=TEST_PROJECT_ID,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
deferrable=True,
callback=None,
)
mock_hook.return_value.exists.return_value = False
with pytest.raises(TaskDeferred) as exc:
task.execute(None)
assert isinstance(exc.value.trigger, DataflowJobAutoScalingEventTrigger), (
"Trigger is not a DataflowJobAutoScalingEventTrigger"
)
def test_execute_complete_success_without_callback_function(self):
"""Tests that the trigger event contains expected values if no callback function is provided."""
expected_result = []
task = DataflowJobAutoScalingEventsSensor(
task_id=TEST_TASK_ID,
job_id=TEST_JOB_ID,
fail_on_terminal_state=False,
location=TEST_LOCATION,
project_id=TEST_PROJECT_ID,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
deferrable=True,
callback=None,
)
actual_message = task.execute_complete(
context=None,
event={
"status": "success",
"message": f"Detected 2 autoscaling events for job '{TEST_JOB_ID}'",
"result": [],
},
)
assert actual_message == expected_result
def test_execute_complete_success_with_callback_function(self):
"""Tests that the trigger event contains expected values if the callback function is provided."""
expected_result = [
{
"event_type": 2,
"description": {},
"time": "2024-02-05T13:43:31.066611771Z",
},
{
"event_type": 1,
"description": {},
"time": "2024-02-05T13:43:31.066611771Z",
},
]
task = DataflowJobAutoScalingEventsSensor(
task_id=TEST_TASK_ID,
job_id=TEST_JOB_ID,
callback=lambda res: res,
fail_on_terminal_state=False,
location=TEST_LOCATION,
project_id=TEST_PROJECT_ID,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
deferrable=True,
)
actual_result = task.execute_complete(
context=None,
event={
"status": "success",
"message": f"Detected 2 autoscaling events for job '{TEST_JOB_ID}'",
"result": expected_result,
},
)
assert actual_result == expected_result
def test_execute_complete_not_success_status_raises_exception(self):
"""Tests that AirflowException or AirflowSkipException is raised if the trigger event contains an error."""
task = DataflowJobAutoScalingEventsSensor(
task_id=TEST_TASK_ID,
job_id=TEST_JOB_ID,
callback=None,
fail_on_terminal_state=False,
location=TEST_LOCATION,
project_id=TEST_PROJECT_ID,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
deferrable=True,
)
with pytest.raises(AirflowException):
task.execute_complete(
context=None,
event={"status": "error", "message": "test error message", "result": None},
)
| TestDataflowJobAutoScalingEventsSensor |
python | huggingface__transformers | src/transformers/models/roberta_prelayernorm/modeling_roberta_prelayernorm.py | {
"start": 50790,
"end": 53943
} | class ____(RobertaPreLayerNormPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.roberta_prelayernorm = RobertaPreLayerNormModel(config, add_pooling_layer=False)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@can_return_tuple
@auto_docstring
# Copied from transformers.models.roberta.modeling_roberta.RobertaForTokenClassification.forward with roberta->roberta_prelayernorm
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,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple[torch.Tensor], TokenClassifierOutput]:
r"""
token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
- 0 corresponds to a *sentence A* token,
- 1 corresponds to a *sentence B* token.
This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
>= 2. All the value in this tensor should be always < type_vocab_size.
[What are token type IDs?](../glossary#token-type-ids)
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
"""
outputs = self.roberta_prelayernorm(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
return_dict=True,
**kwargs,
)
sequence_output = outputs[0]
sequence_output = self.dropout(sequence_output)
logits = self.classifier(sequence_output)
loss = None
if labels is not None:
# move labels to correct device
labels = labels.to(logits.device)
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
return TokenClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
# Copied from transformers.models.roberta.modeling_roberta.RobertaClassificationHead with Roberta->RobertaPreLayerNorm
| RobertaPreLayerNormForTokenClassification |
python | tensorflow__tensorflow | tensorflow/python/ops/tensor_array_ops.py | {
"start": 2231,
"end": 15973
} | class ____:
"""Graph-mode implementation of TensorArray."""
def __init__(self,
dtype,
size=None,
dynamic_size=None,
clear_after_read=None,
tensor_array_name=None,
handle=None,
flow=None,
infer_shape=True,
element_shape=None,
colocate_with_first_write_call=True,
name=None):
"""Constructs a graph mode TensorArray.
Args:
dtype: (required) data type of the TensorArray.
size: (optional) int32 scalar `Tensor`: the size of the TensorArray.
Required if handle is not provided.
dynamic_size: (optional) Python bool: If true, writes to the TensorArray
can grow the TensorArray past its initial size. Default: False.
clear_after_read: Boolean (optional, default: True). If True, clear
TensorArray values after reading them. This disables read-many
semantics, but allows early release of memory.
tensor_array_name: (optional) Python string: the name of the TensorArray.
This is used when creating the TensorArray handle. If this value is
set, handle should be None.
handle: (optional) A `Tensor` handle to an existing TensorArray. If this
is set, tensor_array_name should be None. Only supported in graph mode.
flow: (optional) A float `Tensor` scalar coming from an existing
`TensorArray.flow`. Only supported in graph mode.
infer_shape: (optional, default: True) If True, shape inference is
enabled. In this case, all elements must have the same shape.
element_shape: (optional, default: None) A `TensorShape` object specifying
the shape constraints of each of the elements of the TensorArray. Need
not be fully defined.
colocate_with_first_write_call: If `True`, the TensorArray will be
colocated on the same device as the Tensor used on its first write
(write operations include `write`, `unstack`, and `split`). If `False`,
the TensorArray will be placed on the device determined by the device
context available during its initialization.
name: A name for the operation (optional).
Raises:
ValueError: if both handle and tensor_array_name are provided.
TypeError: if handle is provided but is not a Tensor.
"""
if handle is not None and tensor_array_name:
raise ValueError(
"Cannot provide both `handle` and `tensor_array_name` arguments at "
"the same time.")
if handle is not None and not isinstance(handle, tensor_lib.Tensor):
raise TypeError(
f"Expected `handle` to be a Tensor, but got `{handle}` of type "
f"`{type(handle)}` instead.")
if handle is None and size is None:
raise ValueError(
"Argument `size` must be provided if handle is not provided.")
if handle is not None and size is not None:
raise ValueError("Cannot provide both a `handle` and `size` arguments "
"at the same time.")
if handle is not None and element_shape is not None:
raise ValueError(
"Cannot provide both `handle` and `element_shape` arguments "
"at the same time.")
if handle is not None and dynamic_size is not None:
raise ValueError(
"Cannot provide both `handle` and `dynamic_size` arguments "
"at the same time.")
if handle is not None and clear_after_read is not None:
raise ValueError(
"Cannot provide both `handle` and `clear_after_read` arguments "
"at the same time.")
if clear_after_read is None:
clear_after_read = True
self._dynamic_size = dynamic_size or False
self._dtype = dtypes.as_dtype(dtype).base_dtype
# Used to keep track of what tensors the TensorArray should be
# colocated with. We choose to colocate the TensorArray with the
# first tensor written to it.
self._colocate_with_first_write_call = colocate_with_first_write_call
if colocate_with_first_write_call:
self._colocate_with = []
else:
self._colocate_with = None
# Record the current static shape for the array elements. The element
# shape is defined either by `element_shape` or the shape of the tensor
# of the first write. If `infer_shape` is true, all writes checks for
# shape equality.
self._element_shape = [tensor_shape.as_shape(element_shape)]
self._infer_shape = infer_shape
self._size = size
with ops.name_scope(name, "TensorArray", [handle, size, flow]) as scope:
if handle is not None:
self._handle = handle
if flow is None:
raise ValueError("flow must not be None if handle is not None.")
self._flow = flow
else:
# Construct the TensorArray with an empty device. The first
# write into the TensorArray from a Tensor with a set device
# will retroactively set the device value of this op.
def create():
"""Create the TensorArray op."""
return gen_data_flow_ops.tensor_array_v3(
dtype=dtype,
size=size,
element_shape=element_shape,
identical_element_shapes=infer_shape,
dynamic_size=self._dynamic_size,
clear_after_read=clear_after_read,
tensor_array_name=tensor_array_name,
name=scope)
if colocate_with_first_write_call:
with ops.device(None), ops.colocate_with(None, ignore_existing=True):
self._handle, self._flow = create()
else:
self._handle, self._flow = create()
@property
def flow(self):
return self._flow
@property
def dtype(self):
return self._dtype
@property
def handle(self):
return self._handle
@property
def element_shape(self):
return self._element_shape[0]
def _check_element_shape(self, shape):
"""Changes the element shape of the array given a shape to merge with.
Args:
shape: A `TensorShape` object to merge with.
Raises:
ValueError: if the provided shape is incompatible with the current
element shape of the `TensorArray`.
"""
if not shape.is_compatible_with(self.element_shape):
raise ValueError("Inconsistent shapes: saw %s but expected %s " %
(shape, self.element_shape))
if self._infer_shape:
self._element_shape[0] = self.element_shape.merge_with(shape)
@contextlib.contextmanager
def _maybe_colocate_with(self, value):
"""Colocate operations with an internal colocation group or `value`.
Args:
value: `Tensor`, the tensor to try to colocate with.
Yields:
Does not yield anything, but the new context is a colocation context.
If no internal colocation group is set, colocate with `value` and set
the internal colocation group to be value.
"""
if not self._colocate_with_first_write_call:
yield
else:
if not self._colocate_with:
self._colocate_with.append(value)
with ops.colocate_with(self._colocate_with[0]):
yield
def identity(self):
"""See TensorArray."""
flow = array_ops.identity(self._flow)
return build_ta_with_new_flow(self, flow)
def grad(self, source, flow=None, name=None):
"""See TensorArray."""
# tensor_array_grad requires a flow input when forward
# TensorArrays are dynamically sized. This forces the creation
# of the grad TensorArray only once the final forward array's size
# is fixed.
if flow is None:
flow = self.flow
with ops.name_scope(name, "TensorArrayGrad", [self._handle]):
with ops.colocate_with(self._handle):
g_handle, unused_flow = gen_data_flow_ops.tensor_array_grad_v3(
handle=self._handle, source=source, flow_in=flow, name=name)
with ops.control_dependencies([g_handle]):
flow = array_ops.identity(flow, name="gradient_flow")
g = TensorArray(
dtype=self._dtype,
handle=g_handle,
flow=flow,
infer_shape=self._infer_shape,
colocate_with_first_write_call=False)
# pylint: disable=protected-access
g._implementation._element_shape = self._element_shape
# pylint: enable=protected-access
return g
def read(self, index, name=None):
"""See TensorArray."""
value = gen_data_flow_ops.tensor_array_read_v3(
handle=self._handle,
index=index,
flow_in=self._flow,
dtype=self._dtype,
name=name)
if self._element_shape:
value.set_shape(self._element_shape[0].dims)
return value
def write(self, index, value, name=None):
"""See TensorArray."""
with ops.name_scope(name, "TensorArrayWrite", [self._handle, index, value]):
# TODO(b/129870929): Fix after all callers provide proper init dtype.
value = ops.convert_to_tensor(
value, preferred_dtype=self._dtype, name="value")
_check_dtypes(value, self._dtype)
self._check_element_shape(value.shape)
with self._maybe_colocate_with(value):
flow_out = gen_data_flow_ops.tensor_array_write_v3(
handle=self._handle,
index=index,
value=value,
flow_in=self._flow,
name=name)
return build_ta_with_new_flow(self, flow_out)
def stack(self, name=None):
"""See TensorArray."""
with ops.colocate_with(self._handle):
with ops.name_scope(name, "TensorArrayStack", [self._handle]):
value = self.gather(math_ops.range(0, self.size()), name=name)
if (self.element_shape and not self._dynamic_size and
self._size is not None):
value.set_shape([tensor_util.constant_value(self._size)] +
self.element_shape.dims)
return value
def gather(self, indices, name=None):
"""See TensorArray."""
if self._element_shape:
element_shape = self._element_shape[0]
else:
element_shape = tensor_shape.unknown_shape(None)
value = gen_data_flow_ops.tensor_array_gather_v3(
handle=self._handle,
indices=indices,
flow_in=self._flow,
dtype=self._dtype,
name=name,
element_shape=element_shape)
if self.element_shape:
value.set_shape([None] + self.element_shape.dims)
return value
def concat(self, name=None):
"""See TensorArray."""
value, _ = gen_data_flow_ops.tensor_array_concat_v3(
handle=self._handle,
flow_in=self._flow,
dtype=self._dtype,
name=name,
element_shape_except0=self.element_shape[1:])
if self.element_shape:
dim0 = None
if self._infer_shape:
size = tensor_util.constant_value(self.size())
if size is not None and self.element_shape[0] is not None:
dim0 = size * self.element_shape[0]
value.set_shape([dim0] + self.element_shape.dims[1:])
return value
@tf_should_use.should_use_result
def unstack(self, value, name=None):
"""See TensorArray."""
with ops.name_scope(name, "TensorArrayUnstack", [self._handle, value]):
num_elements = array_ops.shape(value)[0]
return self.scatter(
indices=math_ops.range(0, num_elements), value=value, name=name)
@tf_should_use.should_use_result
def scatter(self, indices, value, name=None):
"""See TensorArray."""
with ops.name_scope(name, "TensorArrayScatter",
[self._handle, value, indices]):
# TODO(b/129870929): Fix after all callers provide proper init dtype.
value = ops.convert_to_tensor(
value, preferred_dtype=self._dtype, name="value")
_check_dtypes(value, self._dtype)
if not context.executing_eagerly():
self._check_element_shape(value.shape[1:])
with self._maybe_colocate_with(value):
flow_out = gen_data_flow_ops.tensor_array_scatter_v3(
handle=self._handle,
indices=indices,
value=value,
flow_in=self._flow,
name=name)
return build_ta_with_new_flow(self, flow_out)
@tf_should_use.should_use_result
def split(self, value, lengths, name=None):
"""See TensorArray."""
with ops.name_scope(name, "TensorArraySplit",
[self._handle, value, lengths]):
value = ops.convert_to_tensor(value, dtype=self._dtype, name="value")
with self._maybe_colocate_with(value):
lengths_64 = math_ops.cast(lengths, dtypes.int64)
if not context.executing_eagerly():
clengths = tensor_util.constant_value(lengths_64)
if value.shape.dims is not None and clengths is not None:
if clengths.shape and clengths.max() == clengths.min():
self._check_element_shape(
tensor_shape.TensorShape([clengths[0]
]).concatenate(value.shape[1:]))
flow_out = gen_data_flow_ops.tensor_array_split_v3(
handle=self._handle,
value=value,
lengths=lengths_64,
flow_in=self._flow,
name=name)
return build_ta_with_new_flow(self, flow_out)
def size(self, name=None):
"""See TensorArray."""
if not self._dynamic_size and self._size is not None:
return ops.convert_to_tensor(self._size, dtype=dtypes.int32)
else:
return gen_data_flow_ops.tensor_array_size_v3(
handle=self._handle, flow_in=self.flow, name=name)
@tf_should_use.should_use_result
def close(self, name=None):
"""See TensorArray."""
return gen_data_flow_ops.tensor_array_close_v3(
handle=self._handle, name=name)
| _GraphTensorArray |
python | tensorflow__tensorflow | tensorflow/python/distribute/mirrored_run.py | {
"start": 18424,
"end": 23268
} | class ____(distribute_lib.ReplicaContext):
"""ReplicaContext for synchronized replica."""
def _merge_call(self, fn, args, kwargs):
"""`merge_call()` implementation for synchronized replica.
This pauses the current replica thread and passes `fn` and its arguments to
the main thread. The main thread will wait until all replicas pause, then
invoke `fn` with grouped arguments. The current replica thread will continue
after `fn` completes.
See `_call_for_each_replica` for the logic in the main thread.
Args:
fn: a function that is called in cross replica context with grouped
arguments from each replica. `fn` should returns grouped values.
args: positional arguments to `fn`.
kwargs: keyword arguments to `fn`.
Returns:
Return value of `fn` for the current replica.
Raises:
RuntimeError: when merge_call happens in a different graph, e.g. in a
different tf.function, which is not supported now.
_RequestedStop: when stop is requested.
"""
t = threading.current_thread()
assert isinstance(t, _MirroredReplicaThread)
t.merge_fn = fn
t.merge_args = args
t.merge_kwargs = kwargs
t.captured_name_scope = t.graph.get_name_scope()
# Adding a "/" at end lets us re-enter this scope later.
if t.captured_name_scope:
t.captured_name_scope += "/"
t.captured_var_scope = variable_scope.get_variable_scope()
t.captured_control_deps = t.graph._current_control_dependencies() # pylint: disable=protected-access
t.merge_call_entered_in_eager = context.context().executing_eagerly()
# It is problematic if `merge_call` is called under a different graph other
# than the one that `_call_for_each_replica` is called under, there are
# 3 cases this can happen:
#
# 1. The `fn` passed to `_call_for_each_replica` is decorated with
# `tf.function` and there is a `merge_call` in `fn`. Since
# MirroredStrategy traces a separate function per thread (per device),
# and each trace takes a shared lock, the lock is never released by the
# first thread and subsequent replica threads cannot proceed to trace
# their own functions. This issue is addressed by always converting
# `_call_for_each_replica(tf.function(f))` to
# ``tf.function(_call_for_each_replica(f))`.` in
# `MirroredStrategy._call_for_each_replica`.
#
# 2. The `fn` passed to `_call_for_each_replica` contains a nested
# `tf.function`, and there is a `merge_call` in the nested `tf.function`.
# In this case each thread can successfully trace its own function, but
# since the `merge_fn` passed to `merge_call` is executed in the main
# thread (where `_call_for_each_replica` is executed), it can't access
# the tensors that come from different graphs.
#
# 3. The `fn` passed to `_call_for_each_replica` contains a control-flow
# statement, and there is a `merge_call` inside the control-flow body,
# `fn` or `_call_for_each_replica` is decorated with `tf.function`.
# Control flow statement creates a separate graph for its body, similar
# to #2, `merge_fn` executed in the main thread can't access the
# tensors that come from different graphs.
#
# We raise an error for #2 and #3.
if ops.get_default_graph() != t.graph:
raise RuntimeError(
"`merge_call` called while defining a new graph or a tf.function."
" This can often happen if the function `fn` passed to"
" `strategy.run()` contains a nested `@tf.function`, and the nested "
"`@tf.function` contains a synchronization point, such as aggregating"
" gradients (e.g, optimizer.apply_gradients), or if the function `fn`"
" uses a control flow statement which contains a synchronization"
" point in the body. Such behaviors are not yet supported. Instead,"
" please avoid nested `tf.function`s or control flow statements that"
" may potentially cross a synchronization boundary, for example,"
" wrap the `fn` passed to `strategy.run` or the entire `strategy.run`"
" inside a `tf.function` or move the control flow out of `fn`. If"
" you are subclassing a `tf.keras.Model`, please avoid decorating"
" overridden methods `test_step` and `train_step` in `tf.function`.")
t.has_paused.set()
t.should_run.wait()
t.should_run.clear()
if t.coord.should_stop():
raise _RequestedStop()
t.merge_call_entered_in_eager = None
return t.merge_result
@property
def devices(self):
distribute_lib.require_replica_context(self)
return [
self._strategy.extended.worker_devices_by_replica[
self._replica_id_in_sync_group]
]
| _MirroredReplicaContext |
python | MongoEngine__mongoengine | tests/document/test_timeseries_collection.py | {
"start": 285,
"end": 6679
} | class ____(unittest.TestCase):
def setUp(self):
connect(db="mongoenginetest")
self.db = get_db()
class SensorData(Document):
timestamp = DateTimeField(required=True)
temperature = FloatField()
meta = {
"timeseries": {
"timeField": "timestamp",
"metaField": "temperature",
"granularity": "seconds",
"expireAfterSeconds": 5,
},
"collection": "sensor_data",
}
self.SensorData = SensorData
def test_get_db(self):
"""Ensure that get_db returns the expected db."""
db = self.SensorData._get_db()
assert self.db == db
def tearDown(self):
for collection_name in self.db.list_collection_names():
if not collection_name.startswith("system."):
self.db.drop_collection(collection_name)
disconnect()
def test_definition(self):
"""Ensure that document may be defined using fields."""
assert ["id", "temperature", "timestamp"] == sorted(
self.SensorData._fields.keys()
)
assert ["DateTimeField", "FloatField", "ObjectIdField"] == sorted(
x.__class__.__name__ for x in self.SensorData._fields.values()
)
@requires_mongodb_gte_50
def test_get_collection(self):
"""Ensure that get_collection returns the expected collection."""
collection_name = "sensor_data"
collection = self.SensorData._get_collection()
assert self.db[collection_name] == collection
@requires_mongodb_gte_50
def test_create_timeseries_collection(self):
"""Ensure that a time-series collection can be created."""
collection_name = self.SensorData._get_collection_name()
collection = self.SensorData._get_collection()
assert collection_name in self.db.list_collection_names()
options = collection.options()
assert options.get("timeseries") is not None
assert options["timeseries"]["timeField"] == "timestamp"
assert options["timeseries"]["granularity"] == "seconds"
@requires_mongodb_gte_50
def test_insert_document_into_timeseries_collection(self):
"""Ensure that a document can be inserted into a time-series collection."""
collection_name = self.SensorData._get_collection_name()
collection = self.SensorData._get_collection()
assert collection_name in self.db.list_collection_names()
# Insert a document and ensure it was inserted
self.SensorData(timestamp=datetime.utcnow(), temperature=23.4).save()
assert collection.count_documents({}) == 1
@requires_mongodb_gte_50
def test_timeseries_expiration(self):
"""Ensure that documents in a time-series collection expire after the specified time."""
self.SensorData._meta["timeseries"]["expireAfterSeconds"] = 1
self.SensorData._get_collection_name()
collection = self.SensorData._get_collection()
options = collection.options()
assert options.get("timeseries", {}) is not None
assert options["expireAfterSeconds"] == 1
self.SensorData(timestamp=datetime.utcnow(), temperature=23.4).save()
assert collection.count_documents({}) == 1
# Wait for more than the expiration time
time.sleep(2)
assert collection.count_documents({}) > 0
@requires_mongodb_gte_50
def test_index_creation(self):
"""Test if the index defined in the meta dictionary is created properly."""
# Define the Document with indexes
class SensorDataWithIndex(Document):
timestamp = DateTimeField(required=True)
temperature = FloatField()
location = StringField() # Field to be indexed
meta = {
"timeseries": {
"timeField": "timestamp",
"metaField": "temperature",
"granularity": "seconds",
"expireAfterSeconds": 5,
},
"collection": "sensor_data",
"indexes": [
{"fields": ["timestamp"], "name": "timestamp_index"},
{"fields": ["temperature"], "name": "temperature_index"},
],
}
collection = SensorDataWithIndex._get_collection()
indexes = collection.index_information()
assert "timestamp_index" in indexes
assert "temperature_index" in indexes
@requires_mongodb_gte_50
def test_timeseries_data_insertion_order(self):
"""Ensure that data in the time-series collection is inserted and queried in the correct time order."""
self.SensorData._get_collection_name()
self.SensorData._get_collection()
# Insert documents out of order
now = datetime.utcnow()
self.SensorData(timestamp=now, temperature=23.4).save()
self.SensorData(timestamp=now - timedelta(seconds=5), temperature=22.0).save()
self.SensorData(timestamp=now + timedelta(seconds=5), temperature=24.0).save()
documents = list(self.SensorData.objects.order_by("timestamp"))
# Check the insertion order
assert len(documents) == 3
assert documents[0].temperature == 22.0
assert documents[1].temperature == 23.4
assert documents[2].temperature == 24.0
@requires_mongodb_gte_50
def test_timeseries_query_by_time_range(self):
"""Ensure that data can be queried by a specific time range in the time-series collection."""
self.SensorData._get_collection_name()
self.SensorData._get_collection()
now = datetime.utcnow()
self.SensorData(timestamp=now - timedelta(seconds=10), temperature=22.0).save()
self.SensorData(timestamp=now - timedelta(seconds=5), temperature=23.0).save()
self.SensorData(timestamp=now, temperature=24.0).save()
# Query documents within the last 6 seconds
start_time = now - timedelta(seconds=6)
documents = self.SensorData.objects(timestamp__gte=start_time)
assert len(documents) == 2
assert documents[0].temperature == 23.0
assert documents[1].temperature == 24.0
if __name__ == "__main__":
unittest.main()
| TestTimeSeriesCollections |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/external.py | {
"start": 6434,
"end": 6634
} | class ____(graphene.ObjectType):
entries = non_null_list(GrapheneWorkspaceLocationStatusEntry)
class Meta:
name = "WorkspaceLocationStatusEntries"
| GrapheneWorkspaceLocationStatusEntries |
python | palantir__python-language-server | pyls/python_ls.py | {
"start": 3190,
"end": 18671
} | class ____(MethodDispatcher):
""" Implementation of the Microsoft VSCode Language Server Protocol
https://github.com/Microsoft/language-server-protocol/blob/master/versions/protocol-1-x.md
"""
# pylint: disable=too-many-public-methods,redefined-builtin
def __init__(self, rx, tx, check_parent_process=False):
self.workspace = None
self.config = None
self.root_uri = None
self.watching_thread = None
self.workspaces = {}
self.uri_workspace_mapper = {}
self._jsonrpc_stream_reader = JsonRpcStreamReader(rx)
self._jsonrpc_stream_writer = JsonRpcStreamWriter(tx)
self._check_parent_process = check_parent_process
self._endpoint = Endpoint(self, self._jsonrpc_stream_writer.write, max_workers=MAX_WORKERS)
self._dispatchers = []
self._shutdown = False
def start(self):
"""Entry point for the server."""
self._jsonrpc_stream_reader.listen(self._endpoint.consume)
def __getitem__(self, item):
"""Override getitem to fallback through multiple dispatchers."""
if self._shutdown and item != 'exit':
# exit is the only allowed method during shutdown
log.debug("Ignoring non-exit method during shutdown: %s", item)
raise KeyError
try:
return super(PythonLanguageServer, self).__getitem__(item)
except KeyError:
# Fallback through extra dispatchers
for dispatcher in self._dispatchers:
try:
return dispatcher[item]
except KeyError:
continue
raise KeyError()
def m_shutdown(self, **_kwargs):
self._shutdown = True
return None
def m_exit(self, **_kwargs):
self._endpoint.shutdown()
self._jsonrpc_stream_reader.close()
self._jsonrpc_stream_writer.close()
def _match_uri_to_workspace(self, uri):
workspace_uri = _utils.match_uri_to_workspace(uri, self.workspaces)
return self.workspaces.get(workspace_uri, self.workspace)
def _hook(self, hook_name, doc_uri=None, **kwargs):
"""Calls hook_name and returns a list of results from all registered handlers"""
workspace = self._match_uri_to_workspace(doc_uri)
doc = workspace.get_document(doc_uri) if doc_uri else None
hook_handlers = self.config.plugin_manager.subset_hook_caller(hook_name, self.config.disabled_plugins)
return hook_handlers(config=self.config, workspace=workspace, document=doc, **kwargs)
def capabilities(self):
server_capabilities = {
'codeActionProvider': True,
'codeLensProvider': {
'resolveProvider': False, # We may need to make this configurable
},
'completionProvider': {
'resolveProvider': False, # We know everything ahead of time
'triggerCharacters': ['.']
},
'documentFormattingProvider': True,
'documentHighlightProvider': True,
'documentRangeFormattingProvider': True,
'documentSymbolProvider': True,
'definitionProvider': True,
'executeCommandProvider': {
'commands': flatten(self._hook('pyls_commands'))
},
'hoverProvider': True,
'referencesProvider': True,
'renameProvider': True,
'foldingRangeProvider': True,
'signatureHelpProvider': {
'triggerCharacters': ['(', ',', '=']
},
'textDocumentSync': {
'change': lsp.TextDocumentSyncKind.INCREMENTAL,
'save': {
'includeText': True,
},
'openClose': True,
},
'workspace': {
'workspaceFolders': {
'supported': True,
'changeNotifications': True
}
},
'experimental': merge(self._hook('pyls_experimental_capabilities'))
}
log.info('Server capabilities: %s', server_capabilities)
return server_capabilities
def m_initialize(self, processId=None, rootUri=None, rootPath=None, initializationOptions=None, **_kwargs):
log.debug('Language server initialized with %s %s %s %s', processId, rootUri, rootPath, initializationOptions)
if rootUri is None:
rootUri = uris.from_fs_path(rootPath) if rootPath is not None else ''
self.workspaces.pop(self.root_uri, None)
self.root_uri = rootUri
self.config = config.Config(rootUri, initializationOptions or {},
processId, _kwargs.get('capabilities', {}))
self.workspace = Workspace(rootUri, self._endpoint, self.config)
self.workspaces[rootUri] = self.workspace
self._dispatchers = self._hook('pyls_dispatchers')
self._hook('pyls_initialize')
if self._check_parent_process and processId is not None and self.watching_thread is None:
def watch_parent_process(pid):
# exit when the given pid is not alive
if not _utils.is_process_alive(pid):
log.info("parent process %s is not alive, exiting!", pid)
self.m_exit()
else:
threading.Timer(PARENT_PROCESS_WATCH_INTERVAL, watch_parent_process, args=[pid]).start()
self.watching_thread = threading.Thread(target=watch_parent_process, args=(processId,))
self.watching_thread.daemon = True
self.watching_thread.start()
# Get our capabilities
return {'capabilities': self.capabilities()}
def m_initialized(self, **_kwargs):
self._hook('pyls_initialized')
def code_actions(self, doc_uri, range, context):
return flatten(self._hook('pyls_code_actions', doc_uri, range=range, context=context))
def code_lens(self, doc_uri):
return flatten(self._hook('pyls_code_lens', doc_uri))
def completions(self, doc_uri, position):
completions = self._hook('pyls_completions', doc_uri, position=position)
return {
'isIncomplete': False,
'items': flatten(completions)
}
def definitions(self, doc_uri, position):
return flatten(self._hook('pyls_definitions', doc_uri, position=position))
def document_symbols(self, doc_uri):
return flatten(self._hook('pyls_document_symbols', doc_uri))
def execute_command(self, command, arguments):
return self._hook('pyls_execute_command', command=command, arguments=arguments)
def format_document(self, doc_uri):
return self._hook('pyls_format_document', doc_uri)
def format_range(self, doc_uri, range):
return self._hook('pyls_format_range', doc_uri, range=range)
def highlight(self, doc_uri, position):
return flatten(self._hook('pyls_document_highlight', doc_uri, position=position)) or None
def hover(self, doc_uri, position):
return self._hook('pyls_hover', doc_uri, position=position) or {'contents': ''}
@_utils.debounce(LINT_DEBOUNCE_S, keyed_by='doc_uri')
def lint(self, doc_uri, is_saved):
# Since we're debounced, the document may no longer be open
workspace = self._match_uri_to_workspace(doc_uri)
if doc_uri in workspace.documents:
workspace.publish_diagnostics(
doc_uri,
flatten(self._hook('pyls_lint', doc_uri, is_saved=is_saved))
)
def references(self, doc_uri, position, exclude_declaration):
return flatten(self._hook(
'pyls_references', doc_uri, position=position,
exclude_declaration=exclude_declaration
))
def rename(self, doc_uri, position, new_name):
return self._hook('pyls_rename', doc_uri, position=position, new_name=new_name)
def signature_help(self, doc_uri, position):
return self._hook('pyls_signature_help', doc_uri, position=position)
def folding(self, doc_uri):
return flatten(self._hook('pyls_folding_range', doc_uri))
def m_text_document__did_close(self, textDocument=None, **_kwargs):
workspace = self._match_uri_to_workspace(textDocument['uri'])
workspace.rm_document(textDocument['uri'])
def m_text_document__did_open(self, textDocument=None, **_kwargs):
workspace = self._match_uri_to_workspace(textDocument['uri'])
workspace.put_document(textDocument['uri'], textDocument['text'], version=textDocument.get('version'))
self._hook('pyls_document_did_open', textDocument['uri'])
self.lint(textDocument['uri'], is_saved=True)
def m_text_document__did_change(self, contentChanges=None, textDocument=None, **_kwargs):
workspace = self._match_uri_to_workspace(textDocument['uri'])
for change in contentChanges:
workspace.update_document(
textDocument['uri'],
change,
version=textDocument.get('version')
)
self.lint(textDocument['uri'], is_saved=False)
def m_text_document__did_save(self, textDocument=None, **_kwargs):
self.lint(textDocument['uri'], is_saved=True)
def m_text_document__code_action(self, textDocument=None, range=None, context=None, **_kwargs):
return self.code_actions(textDocument['uri'], range, context)
def m_text_document__code_lens(self, textDocument=None, **_kwargs):
return self.code_lens(textDocument['uri'])
def m_text_document__completion(self, textDocument=None, position=None, **_kwargs):
return self.completions(textDocument['uri'], position)
def m_text_document__definition(self, textDocument=None, position=None, **_kwargs):
return self.definitions(textDocument['uri'], position)
def m_text_document__document_highlight(self, textDocument=None, position=None, **_kwargs):
return self.highlight(textDocument['uri'], position)
def m_text_document__hover(self, textDocument=None, position=None, **_kwargs):
return self.hover(textDocument['uri'], position)
def m_text_document__document_symbol(self, textDocument=None, **_kwargs):
return self.document_symbols(textDocument['uri'])
def m_text_document__formatting(self, textDocument=None, _options=None, **_kwargs):
# For now we're ignoring formatting options.
return self.format_document(textDocument['uri'])
def m_text_document__rename(self, textDocument=None, position=None, newName=None, **_kwargs):
return self.rename(textDocument['uri'], position, newName)
def m_text_document__folding_range(self, textDocument=None, **_kwargs):
return self.folding(textDocument['uri'])
def m_text_document__range_formatting(self, textDocument=None, range=None, _options=None, **_kwargs):
# Again, we'll ignore formatting options for now.
return self.format_range(textDocument['uri'], range)
def m_text_document__references(self, textDocument=None, position=None, context=None, **_kwargs):
exclude_declaration = not context['includeDeclaration']
return self.references(textDocument['uri'], position, exclude_declaration)
def m_text_document__signature_help(self, textDocument=None, position=None, **_kwargs):
return self.signature_help(textDocument['uri'], position)
def m_workspace__did_change_configuration(self, settings=None):
self.config.update((settings or {}).get('pyls', {}))
for workspace_uri in self.workspaces:
workspace = self.workspaces[workspace_uri]
workspace.update_config(settings)
for doc_uri in workspace.documents:
self.lint(doc_uri, is_saved=False)
def m_workspace__did_change_workspace_folders(self, event=None, **_kwargs): # pylint: disable=too-many-locals
if event is None:
return
added = event.get('added', [])
removed = event.get('removed', [])
for removed_info in removed:
if 'uri' in removed_info:
removed_uri = removed_info['uri']
self.workspaces.pop(removed_uri, None)
for added_info in added:
if 'uri' in added_info:
added_uri = added_info['uri']
workspace_config = config.Config(
added_uri, self.config._init_opts,
self.config._process_id, self.config._capabilities)
workspace_config.update(self.config._settings)
self.workspaces[added_uri] = Workspace(
added_uri, self._endpoint, workspace_config)
root_workspace_removed = any(removed_info['uri'] == self.root_uri for removed_info in removed)
workspace_added = len(added) > 0 and 'uri' in added[0]
if root_workspace_removed and workspace_added:
added_uri = added[0]['uri']
self.root_uri = added_uri
new_root_workspace = self.workspaces[added_uri]
self.config = new_root_workspace._config
self.workspace = new_root_workspace
elif root_workspace_removed:
# NOTE: Removing the root workspace can only happen when the server
# is closed, thus the else condition of this if can never happen.
if self.workspaces:
log.debug('Root workspace deleted!')
available_workspaces = sorted(self.workspaces)
first_workspace = available_workspaces[0]
new_root_workspace = self.workspaces[first_workspace]
self.root_uri = first_workspace
self.config = new_root_workspace._config
self.workspace = new_root_workspace
# Migrate documents that are on the root workspace and have a better
# match now
doc_uris = list(self.workspace._docs.keys())
for uri in doc_uris:
doc = self.workspace._docs.pop(uri)
new_workspace = self._match_uri_to_workspace(uri)
new_workspace._docs[uri] = doc
def m_workspace__did_change_watched_files(self, changes=None, **_kwargs):
changed_py_files = set()
config_changed = False
for d in (changes or []):
if d['uri'].endswith(PYTHON_FILE_EXTENSIONS):
changed_py_files.add(d['uri'])
elif d['uri'].endswith(CONFIG_FILEs):
config_changed = True
if config_changed:
self.config.settings.cache_clear()
elif not changed_py_files:
# Only externally changed python files and lint configs may result in changed diagnostics.
return
for workspace_uri in self.workspaces:
workspace = self.workspaces[workspace_uri]
for doc_uri in workspace.documents:
# Changes in doc_uri are already handled by m_text_document__did_save
if doc_uri not in changed_py_files:
self.lint(doc_uri, is_saved=False)
def m_workspace__execute_command(self, command=None, arguments=None):
return self.execute_command(command, arguments)
def flatten(list_of_lists):
return [item for lst in list_of_lists for item in lst]
def merge(list_of_dicts):
return {k: v for dictionary in list_of_dicts for k, v in dictionary.items()}
| PythonLanguageServer |
python | Pylons__pyramid | tests/test_config/test_assets.py | {
"start": 142,
"end": 11831
} | class ____(unittest.TestCase):
def _makeOne(self, *arg, **kw):
from pyramid.config import Configurator
config = Configurator(*arg, **kw)
return config
def test_override_asset_samename(self):
from pyramid.exceptions import ConfigurationError
config = self._makeOne()
self.assertRaises(ConfigurationError, config.override_asset, 'a', 'a')
def test_override_asset_directory_with_file(self):
from pyramid.exceptions import ConfigurationError
config = self._makeOne()
self.assertRaises(
ConfigurationError,
config.override_asset,
'a:foo/',
'tests.test_config.pkgs.asset:foo.pt',
)
def test_override_asset_file_with_directory(self):
from pyramid.exceptions import ConfigurationError
config = self._makeOne()
self.assertRaises(
ConfigurationError,
config.override_asset,
'a:foo.pt',
'tests.test_config.pkgs.asset:templates/',
)
def test_override_asset_file_with_package(self):
from pyramid.exceptions import ConfigurationError
config = self._makeOne()
self.assertRaises(
ConfigurationError,
config.override_asset,
'a:foo.pt',
'tests.test_config.pkgs.asset',
)
def test_override_asset_file_with_file(self):
from pyramid.config.assets import PackageAssetSource
config = self._makeOne(autocommit=True)
override = DummyUnderOverride()
config.override_asset(
'tests.test_config.pkgs.asset:templates/foo.pt',
'tests.test_config.pkgs.asset.subpackage:templates/bar.pt',
_override=override,
)
from tests.test_config.pkgs import asset
from tests.test_config.pkgs.asset import subpackage
self.assertEqual(override.package, asset)
self.assertEqual(override.path, 'templates/foo.pt')
source = override.source
self.assertTrue(isinstance(source, PackageAssetSource))
self.assertEqual(source.package, subpackage)
self.assertEqual(source.prefix, 'templates/bar.pt')
resource_name = ''
expected = os.path.join(
here, 'pkgs', 'asset', 'subpackage', 'templates', 'bar.pt'
)
self.assertEqual(override.source.get_filename(resource_name), expected)
def test_override_asset_package_with_package(self):
from pyramid.config.assets import PackageAssetSource
config = self._makeOne(autocommit=True)
override = DummyUnderOverride()
config.override_asset(
'tests.test_config.pkgs.asset',
'tests.test_config.pkgs.asset.subpackage',
_override=override,
)
from tests.test_config.pkgs import asset
from tests.test_config.pkgs.asset import subpackage
self.assertEqual(override.package, asset)
self.assertEqual(override.path, '')
source = override.source
self.assertTrue(isinstance(source, PackageAssetSource))
self.assertEqual(source.package, subpackage)
self.assertEqual(source.prefix, '')
resource_name = 'templates/bar.pt'
expected = os.path.join(
here, 'pkgs', 'asset', 'subpackage', 'templates', 'bar.pt'
)
self.assertEqual(override.source.get_filename(resource_name), expected)
def test_override_asset_directory_with_directory(self):
from pyramid.config.assets import PackageAssetSource
config = self._makeOne(autocommit=True)
override = DummyUnderOverride()
config.override_asset(
'tests.test_config.pkgs.asset:templates/',
'tests.test_config.pkgs.asset.subpackage:templates/',
_override=override,
)
from tests.test_config.pkgs import asset
from tests.test_config.pkgs.asset import subpackage
self.assertEqual(override.package, asset)
self.assertEqual(override.path, 'templates/')
source = override.source
self.assertTrue(isinstance(source, PackageAssetSource))
self.assertEqual(source.package, subpackage)
self.assertEqual(source.prefix, 'templates/')
resource_name = 'bar.pt'
expected = os.path.join(
here, 'pkgs', 'asset', 'subpackage', 'templates', 'bar.pt'
)
self.assertEqual(override.source.get_filename(resource_name), expected)
def test_override_asset_directory_with_package(self):
from pyramid.config.assets import PackageAssetSource
config = self._makeOne(autocommit=True)
override = DummyUnderOverride()
config.override_asset(
'tests.test_config.pkgs.asset:templates/',
'tests.test_config.pkgs.asset.subpackage',
_override=override,
)
from tests.test_config.pkgs import asset
from tests.test_config.pkgs.asset import subpackage
self.assertEqual(override.package, asset)
self.assertEqual(override.path, 'templates/')
source = override.source
self.assertTrue(isinstance(source, PackageAssetSource))
self.assertEqual(source.package, subpackage)
self.assertEqual(source.prefix, '')
resource_name = 'templates/bar.pt'
expected = os.path.join(
here, 'pkgs', 'asset', 'subpackage', 'templates', 'bar.pt'
)
self.assertEqual(override.source.get_filename(resource_name), expected)
def test_override_asset_package_with_directory(self):
from pyramid.config.assets import PackageAssetSource
config = self._makeOne(autocommit=True)
override = DummyUnderOverride()
config.override_asset(
'tests.test_config.pkgs.asset',
'tests.test_config.pkgs.asset.subpackage:templates/',
_override=override,
)
from tests.test_config.pkgs import asset
from tests.test_config.pkgs.asset import subpackage
self.assertEqual(override.package, asset)
self.assertEqual(override.path, '')
source = override.source
self.assertTrue(isinstance(source, PackageAssetSource))
self.assertEqual(source.package, subpackage)
self.assertEqual(source.prefix, 'templates/')
resource_name = 'bar.pt'
expected = os.path.join(
here, 'pkgs', 'asset', 'subpackage', 'templates', 'bar.pt'
)
self.assertEqual(override.source.get_filename(resource_name), expected)
def test_override_asset_directory_with_absfile(self):
from pyramid.exceptions import ConfigurationError
config = self._makeOne()
self.assertRaises(
ConfigurationError,
config.override_asset,
'a:foo/',
os.path.join(here, 'pkgs', 'asset', 'foo.pt'),
)
def test_override_asset_file_with_absdirectory(self):
from pyramid.exceptions import ConfigurationError
config = self._makeOne()
abspath = os.path.join(
here, 'pkgs', 'asset', 'subpackage', 'templates'
)
self.assertRaises(
ConfigurationError, config.override_asset, 'a:foo.pt', abspath
)
def test_override_asset_file_with_missing_abspath(self):
from pyramid.exceptions import ConfigurationError
config = self._makeOne()
self.assertRaises(
ConfigurationError,
config.override_asset,
'a:foo.pt',
os.path.join(here, 'wont_exist'),
)
def test_override_asset_file_with_absfile(self):
from pyramid.config.assets import FSAssetSource
config = self._makeOne(autocommit=True)
override = DummyUnderOverride()
abspath = os.path.join(
here, 'pkgs', 'asset', 'subpackage', 'templates', 'bar.pt'
)
config.override_asset(
'tests.test_config.pkgs.asset:templates/foo.pt',
abspath,
_override=override,
)
from tests.test_config.pkgs import asset
self.assertEqual(override.package, asset)
self.assertEqual(override.path, 'templates/foo.pt')
source = override.source
self.assertTrue(isinstance(source, FSAssetSource))
self.assertEqual(source.prefix, abspath)
resource_name = ''
expected = os.path.join(
here, 'pkgs', 'asset', 'subpackage', 'templates', 'bar.pt'
)
self.assertEqual(override.source.get_filename(resource_name), expected)
def test_override_asset_directory_with_absdirectory(self):
from pyramid.config.assets import FSAssetSource
config = self._makeOne(autocommit=True)
override = DummyUnderOverride()
abspath = os.path.join(
here, 'pkgs', 'asset', 'subpackage', 'templates'
)
config.override_asset(
'tests.test_config.pkgs.asset:templates/',
abspath,
_override=override,
)
from tests.test_config.pkgs import asset
self.assertEqual(override.package, asset)
self.assertEqual(override.path, 'templates/')
source = override.source
self.assertTrue(isinstance(source, FSAssetSource))
self.assertEqual(source.prefix, abspath)
resource_name = 'bar.pt'
expected = os.path.join(
here, 'pkgs', 'asset', 'subpackage', 'templates', 'bar.pt'
)
self.assertEqual(override.source.get_filename(resource_name), expected)
def test_override_asset_package_with_absdirectory(self):
from pyramid.config.assets import FSAssetSource
config = self._makeOne(autocommit=True)
override = DummyUnderOverride()
abspath = os.path.join(
here, 'pkgs', 'asset', 'subpackage', 'templates'
)
config.override_asset(
'tests.test_config.pkgs.asset', abspath, _override=override
)
from tests.test_config.pkgs import asset
self.assertEqual(override.package, asset)
self.assertEqual(override.path, '')
source = override.source
self.assertTrue(isinstance(source, FSAssetSource))
self.assertEqual(source.prefix, abspath)
resource_name = 'bar.pt'
expected = os.path.join(
here, 'pkgs', 'asset', 'subpackage', 'templates', 'bar.pt'
)
self.assertEqual(override.source.get_filename(resource_name), expected)
def test__override_not_yet_registered(self):
from pyramid.interfaces import IPackageOverrides
package = DummyPackage('package')
source = DummyAssetSource()
config = self._makeOne()
config._override(
package, 'path', source, PackageOverrides=DummyPackageOverrides
)
overrides = config.registry.queryUtility(
IPackageOverrides, name='package'
)
self.assertEqual(overrides.inserted, [('path', source)])
self.assertEqual(overrides.package, package)
def test__override_already_registered(self):
from pyramid.interfaces import IPackageOverrides
package = DummyPackage('package')
source = DummyAssetSource()
overrides = DummyPackageOverrides(package)
config = self._makeOne()
config.registry.registerUtility(
overrides, IPackageOverrides, name='package'
)
config._override(
package, 'path', source, PackageOverrides=DummyPackageOverrides
)
self.assertEqual(overrides.inserted, [('path', source)])
self.assertEqual(overrides.package, package)
| TestAssetsConfiguratorMixin |
python | coleifer__peewee | tests/libs/mock.py | {
"start": 8859,
"end": 9053
} | class ____(object):
"A unique, named, sentinel object."
def __init__(self, name):
self.name = name
def __repr__(self):
return 'sentinel.%s' % self.name
| _SentinelObject |
python | huggingface__transformers | src/transformers/models/mimi/modeling_mimi.py | {
"start": 20625,
"end": 21253
} | class ____(nn.Module):
"""Layer scale from [Touvron et al 2021] (https://huggingface.co/papers/2103.17239).
This rescales diagonally the residual outputs close to 0, with a learnt scale.
"""
def __init__(self, config):
super().__init__()
channels = config.hidden_size
initial_scale = config.layer_scale_initial_scale
self.scale = nn.Parameter(torch.full((channels,), initial_scale, requires_grad=True))
def forward(self, x: torch.Tensor):
return self.scale * x
# Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Mimi
| MimiLayerScale |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/partitions/mapping/last.py | {
"start": 674,
"end": 3115
} | class ____(PartitionMapping, NamedTuple("_LastPartitionMapping", [])):
"""Maps all dependencies to the last partition in the upstream asset.
Commonly used in the case when the downstream asset is not partitioned, in which the entire
downstream asset depends on the last partition of the upstream asset.
"""
def validate_partition_mapping(
self,
upstream_partitions_def: PartitionsDefinition,
downstream_partitions_def: Optional[PartitionsDefinition],
):
pass
def get_upstream_mapped_partitions_result_for_partitions(
self,
downstream_partitions_subset: Optional[PartitionsSubset],
downstream_partitions_def: Optional[PartitionsDefinition],
upstream_partitions_def: PartitionsDefinition,
current_time: Optional[datetime] = None,
dynamic_partitions_store: Optional["DynamicPartitionsStore"] = None,
) -> UpstreamPartitionsResult:
with partition_loading_context(current_time, dynamic_partitions_store):
last = upstream_partitions_def.get_last_partition_key()
upstream_subset = upstream_partitions_def.empty_subset()
if last is not None:
upstream_subset = upstream_subset.with_partition_keys([last])
return UpstreamPartitionsResult(
partitions_subset=upstream_subset,
required_but_nonexistent_subset=upstream_partitions_def.empty_subset(),
)
def get_downstream_partitions_for_partitions(
self,
upstream_partitions_subset: PartitionsSubset,
upstream_partitions_def: PartitionsDefinition,
downstream_partitions_def: PartitionsDefinition,
current_time: Optional[datetime] = None,
dynamic_partitions_store: Optional["DynamicPartitionsStore"] = None,
) -> PartitionsSubset:
with partition_loading_context(current_time, dynamic_partitions_store):
last_upstream_partition = upstream_partitions_def.get_last_partition_key()
if last_upstream_partition and last_upstream_partition in upstream_partitions_subset:
return downstream_partitions_def.subset_with_all_partitions()
else:
return downstream_partitions_def.empty_subset()
@property
def description(self) -> str:
return "Each downstream partition depends on the last partition of the upstream asset."
| LastPartitionMapping |
python | PyCQA__pylint | doc/data/messages/s/single-string-used-for-slots/bad.py | {
"start": 0,
"end": 126
} | class ____: # [single-string-used-for-slots]
__slots__ = "name"
def __init__(self, name):
self.name = name
| Fruit |
python | celery__celery | celery/backends/gcs.py | {
"start": 5266,
"end": 12563
} | class ____(GCSBackendBase):
"""Google Cloud Storage task result backend.
Uses Firestore for chord ref count.
"""
implements_incr = True
supports_native_join = True
# Firestore parameters
_collection_name = 'celery'
_field_count = 'chord_count'
_field_expires = 'expires_at'
def __init__(self, **kwargs):
if not (firestore and firestore_admin_v1):
raise ImproperlyConfigured(
'You must install google-cloud-firestore to use gcs backend'
)
super().__init__(**kwargs)
self._firestore_lock = RLock()
self._firestore_client = None
self.firestore_project = self.app.conf.get(
'firestore_project', self.project
)
if not self._is_firestore_ttl_policy_enabled():
raise ImproperlyConfigured(
f'Missing TTL policy to use gcs backend with ttl on '
f'Firestore collection: {self._collection_name} '
f'project: {self.firestore_project}'
)
@property
def firestore_client(self):
"""Returns a firestore client."""
# make sure it's thread-safe, as creating a new client is expensive
with self._firestore_lock:
if self._firestore_client and self._pid == getpid():
return self._firestore_client
# make sure each process gets its own connection after a fork
self._firestore_client = firestore.Client(
project=self.firestore_project
)
self._pid = getpid()
return self._firestore_client
def _is_firestore_ttl_policy_enabled(self):
client = firestore_admin_v1.FirestoreAdminClient()
name = (
f"projects/{self.firestore_project}"
f"/databases/(default)/collectionGroups/{self._collection_name}"
f"/fields/{self._field_expires}"
)
request = firestore_admin_v1.GetFieldRequest(name=name)
field = client.get_field(request=request)
ttl_config = field.ttl_config
return ttl_config and ttl_config.state in {
firestore_admin_v1.Field.TtlConfig.State.ACTIVE,
firestore_admin_v1.Field.TtlConfig.State.CREATING,
}
def _apply_chord_incr(self, header_result_args, body, **kwargs):
key = self.get_key_for_chord(header_result_args[0]).decode()
self._expire_chord_key(key, 86400)
return super()._apply_chord_incr(header_result_args, body, **kwargs)
def incr(self, key: bytes) -> int:
doc = self._firestore_document(key)
resp = doc.set(
{self._field_count: firestore.Increment(1)},
merge=True,
retry=retry.Retry(
predicate=if_exception_type(Conflict),
initial=1.0,
maximum=180.0,
multiplier=2.0,
timeout=180.0,
),
)
return resp.transform_results[0].integer_value
def on_chord_part_return(self, request, state, result, **kwargs):
"""Chord part return callback.
Called for each task in the chord.
Increments the counter stored in Firestore.
If the counter reaches the number of tasks in the chord, the callback
is called.
If the callback raises an exception, the chord is marked as errored.
If the callback returns a value, the chord is marked as successful.
"""
app = self.app
gid = request.group
if not gid:
return
key = self.get_key_for_chord(gid)
val = self.incr(key)
size = request.chord.get("chord_size")
if size is None:
deps = self._restore_deps(gid, request)
if deps is None:
return
size = len(deps)
if val > size: # pragma: no cover
logger.warning(
'Chord counter incremented too many times for %r', gid
)
elif val == size:
# Read the deps once, to reduce the number of reads from GCS ($$)
deps = self._restore_deps(gid, request)
if deps is None:
return
callback = maybe_signature(request.chord, app=app)
j = deps.join_native
try:
with allow_join_result():
ret = j(
timeout=app.conf.result_chord_join_timeout,
propagate=True,
)
except Exception as exc: # pylint: disable=broad-except
try:
culprit = next(deps._failed_join_report())
reason = 'Dependency {0.id} raised {1!r}'.format(
culprit,
exc,
)
except StopIteration:
reason = repr(exc)
logger.exception('Chord %r raised: %r', gid, reason)
chord_error = _create_chord_error_with_cause(message=reason, original_exc=exc)
self.chord_error_from_stack(callback, chord_error)
else:
try:
callback.delay(ret)
except Exception as exc: # pylint: disable=broad-except
logger.exception('Chord %r raised: %r', gid, exc)
self.chord_error_from_stack(
callback,
ChordError(f'Callback error: {exc!r}'),
)
finally:
deps.delete()
# Firestore doesn't have an exact ttl policy, so delete the key.
self._delete_chord_key(key)
def _restore_deps(self, gid, request):
app = self.app
try:
deps = GroupResult.restore(gid, backend=self)
except Exception as exc: # pylint: disable=broad-except
callback = maybe_signature(request.chord, app=app)
logger.exception('Chord %r raised: %r', gid, exc)
self.chord_error_from_stack(
callback,
ChordError(f'Cannot restore group: {exc!r}'),
)
return
if deps is None:
try:
raise ValueError(gid)
except ValueError as exc:
callback = maybe_signature(request.chord, app=app)
logger.exception('Chord callback %r raised: %r', gid, exc)
self.chord_error_from_stack(
callback,
ChordError(f'GroupResult {gid} no longer exists'),
)
return deps
def _delete_chord_key(self, key):
doc = self._firestore_document(key)
doc.delete()
def _expire_chord_key(self, key, expires):
"""Set TTL policy for a Firestore document.
Firestore ttl data is typically deleted within 24 hours after its
expiration date.
"""
val_expires = datetime.utcnow() + timedelta(seconds=expires)
doc = self._firestore_document(key)
doc.set({self._field_expires: val_expires}, merge=True)
def _firestore_document(self, key):
return self.firestore_client.collection(
self._collection_name
).document(bytes_to_str(key))
| GCSBackend |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/utils/kubernetes.py | {
"start": 3808,
"end": 4018
} | class ____(BaseModel):
model_config = {
"extra": "allow",
"json_schema_extra": {
"$ref": create_definition_ref("io.k8s.api.core.v1.LocalObjectReference")
},
}
| SecretRef |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 126634,
"end": 136915
} | class ____(ScopedExprNode):
# Used as part of for statement implementation.
#
# Implements result = iter(sequence)
#
# sequence ExprNode
type = py_object_type
iter_func_ptr = None
counter_cname = None
reversed = False # currently only used for list/tuple types (see Optimize.py)
is_async = False
has_local_scope = False
subexprs = ['sequence']
def analyse_types(self, env):
if self.expr_scope:
env = self.expr_scope # actually evaluate sequence in this scope instead
self.sequence = self.sequence.analyse_types(env)
if (self.sequence.type.is_array or self.sequence.type.is_ptr) and \
not self.sequence.type.is_string:
# C array iteration will be transformed later on
self.type = self.sequence.type
elif self.sequence.type.is_cpp_class:
return CppIteratorNode(self.pos, sequence=self.sequence).analyse_types(env)
elif self.is_reversed_cpp_iteration():
sequence = self.sequence.arg_tuple.args[0].arg
return CppIteratorNode(self.pos, sequence=sequence, reversed=True).analyse_types(env)
else:
self.sequence = self.sequence.coerce_to_pyobject(env)
if self.sequence.type in (list_type, tuple_type):
self.sequence = self.sequence.as_none_safe_node("'NoneType' object is not iterable")
self.is_temp = 1
return self
gil_message = "Iterating over Python object"
_func_iternext_type = PyrexTypes.CPtrType(PyrexTypes.CFuncType(
PyrexTypes.py_object_type, [
PyrexTypes.CFuncTypeArg("it", PyrexTypes.py_object_type, None),
]))
def is_reversed_cpp_iteration(self):
"""
Returns True if the 'reversed' function is applied to a C++ iterable.
This supports C++ classes with reverse_iterator implemented.
"""
if not (isinstance(self.sequence, SimpleCallNode) and
self.sequence.arg_tuple and len(self.sequence.arg_tuple.args) == 1):
return False
func = self.sequence.function
if func.is_name and func.name == "reversed":
if not func.entry.is_builtin:
return False
arg = self.sequence.arg_tuple.args[0]
if isinstance(arg, CoercionNode) and arg.arg.is_name:
arg = arg.arg.entry
return arg.type.is_cpp_class
return False
def type_dependencies(self, env):
return self.sequence.type_dependencies(self.expr_scope or env)
def infer_type(self, env):
sequence_type = self.sequence.infer_type(env)
if sequence_type.is_array or sequence_type.is_ptr:
return sequence_type
elif sequence_type.is_cpp_class:
begin = sequence_type.scope.lookup("begin")
if begin is not None:
return begin.type.return_type
elif sequence_type.is_pyobject:
return sequence_type
return py_object_type
def generate_result_code(self, code):
sequence_type = self.sequence.type
if sequence_type.is_cpp_class:
assert False, "Should have been changed to CppIteratorNode"
if sequence_type.is_array or sequence_type.is_ptr:
raise InternalError("for in carray slice not transformed")
is_builtin_sequence = sequence_type in (list_type, tuple_type)
if not is_builtin_sequence:
# reversed() not currently optimised (see Optimize.py)
assert not self.reversed, "internal error: reversed() only implemented for list/tuple objects"
self.may_be_a_sequence = not sequence_type.is_builtin_type
if self.may_be_a_sequence:
code.putln(
"if (likely(PyList_CheckExact(%s)) || PyTuple_CheckExact(%s)) {" % (
self.sequence.py_result(),
self.sequence.py_result()))
if is_builtin_sequence or self.may_be_a_sequence:
code.putln("%s = %s; __Pyx_INCREF(%s);" % (
self.result(),
self.sequence.py_result(),
self.result(),
))
self.counter_cname = code.funcstate.allocate_temp(
PyrexTypes.c_py_ssize_t_type, manage_ref=False)
if self.reversed:
if sequence_type is list_type:
len_func = '__Pyx_PyList_GET_SIZE'
else:
len_func = '__Pyx_PyTuple_GET_SIZE'
code.putln("%s = %s(%s);" % (self.counter_cname, len_func, self.result()))
code.putln("#if !CYTHON_ASSUME_SAFE_SIZE")
code.putln(code.error_goto_if_neg(self.counter_cname, self.pos))
code.putln("#endif")
code.putln("--%s;" % self.counter_cname) # len -> last item
else:
code.putln("%s = 0;" % self.counter_cname)
if not is_builtin_sequence:
self.iter_func_ptr = code.funcstate.allocate_temp(self._func_iternext_type, manage_ref=False)
if self.may_be_a_sequence:
code.putln("%s = NULL;" % self.iter_func_ptr)
code.putln("} else {")
code.put("%s = -1; " % self.counter_cname)
code.putln("%s = PyObject_GetIter(%s); %s" % (
self.result(),
self.sequence.py_result(),
code.error_goto_if_null(self.result(), self.pos)))
self.generate_gotref(code)
# PyObject_GetIter() fails if "tp_iternext" is not set, but the check below
# makes it visible to the C compiler that the pointer really isn't NULL, so that
# it can distinguish between the special cases and the generic case.
code.put(
f"{self.iter_func_ptr} = (CYTHON_COMPILING_IN_LIMITED_API) ? "
f"PyIter_Next : __Pyx_PyObject_GetIterNextFunc({self.py_result()}); "
)
code.putln(code.error_goto_if_null(self.iter_func_ptr, self.pos))
if self.may_be_a_sequence:
code.putln("}")
def generate_for_loop_header(self, code):
code.put(";;")
def generate_next_sequence_item(self, test_name, result_name, code):
assert self.counter_cname, "internal error: counter_cname temp not prepared"
assert test_name in ('List', 'Tuple')
final_size = f'__Pyx_Py{test_name}_GET_SIZE({self.py_result()})'
size_is_safe = False
if self.sequence.is_sequence_constructor:
item_count = len(self.sequence.args)
if self.sequence.mult_factor is None:
final_size = item_count
size_is_safe = True
elif isinstance(self.sequence.mult_factor.constant_result, int):
final_size = item_count * self.sequence.mult_factor.constant_result
size_is_safe = True
if size_is_safe:
code.putln("if (%s >= %s) break;" % (self.counter_cname, final_size))
else:
code.putln("{")
code.putln("Py_ssize_t %s = %s;" % (Naming.quick_temp_cname, final_size))
code.putln("#if !CYTHON_ASSUME_SAFE_SIZE")
code.putln(code.error_goto_if_neg(Naming.quick_temp_cname, self.pos))
code.putln("#endif")
code.putln("if (%s >= %s) break;" % (self.counter_cname, Naming.quick_temp_cname))
code.putln("}")
inc_dec = '--' if self.reversed else '++'
if test_name == 'List':
code.putln(
f"{result_name} = __Pyx_PyList_GetItemRefFast("
f"{self.py_result()}, {self.counter_cname}, {self.may_be_unsafe_shared()});")
else: # Tuple
code.putln("#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS")
code.putln(f"{result_name} = __Pyx_NewRef(PyTuple_GET_ITEM({self.py_result()}, {self.counter_cname}));")
code.putln("#else")
code.putln(f"{result_name} = __Pyx_PySequence_ITEM({self.py_result()}, {self.counter_cname});")
code.putln("#endif")
code.putln(f"{inc_dec}{self.counter_cname};")
def generate_iter_next_result_code(self, result_name, code):
sequence_type = self.sequence.type
if self.reversed:
code.putln(f"if ({self.counter_cname} < 0) break;")
if sequence_type is list_type:
self.generate_next_sequence_item('List', result_name, code)
code.putln(code.error_goto_if_null(result_name, self.pos))
code.put_gotref(result_name, py_object_type)
return
elif sequence_type is tuple_type:
self.generate_next_sequence_item('Tuple', result_name, code)
code.putln(code.error_goto_if_null(result_name, self.pos))
code.put_gotref(result_name, py_object_type)
return
if self.may_be_a_sequence:
code.putln("if (likely(!%s)) {" % self.iter_func_ptr)
code.putln("if (likely(PyList_CheckExact(%s))) {" % self.py_result())
self.generate_next_sequence_item('List', result_name, code)
code.putln("} else {")
self.generate_next_sequence_item('Tuple', result_name, code)
code.putln("}")
code.putln(code.error_goto_if_null(result_name, self.pos))
code.put("} else ")
code.putln("{")
code.putln(f"{result_name} = {self.iter_func_ptr}({self.py_result()});")
code.putln("if (unlikely(!%s)) {" % result_name)
code.putln("PyObject* exc_type = PyErr_Occurred();")
code.putln("if (exc_type) {")
code.putln(code.error_goto_if("!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)", self.pos))
code.putln("PyErr_Clear();")
code.putln("}")
code.putln("break;")
code.putln("}")
code.putln("}")
code.put_gotref(result_name, py_object_type)
def free_temps(self, code):
if self.counter_cname:
code.funcstate.release_temp(self.counter_cname)
if self.iter_func_ptr:
code.funcstate.release_temp(self.iter_func_ptr)
self.iter_func_ptr = None
ExprNode.free_temps(self, code)
| IteratorNode |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.