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
getsentry__sentry
src/sentry/utils/snuba.py
{ "start": 16253, "end": 17203 }
class ____(Exception): pass SnubaTSResult = namedtuple("SnubaTSResult", ("data", "start", "end", "rollup")) @contextmanager def timer(name, prefix="snuba.client"): t = time.time() try: yield finally: metrics.timing(f"{prefix}.{name}", time.time() - t) @contextmanager def options_override(overrides): """\ NOT THREAD SAFE! Adds to OVERRIDE_OPTIONS, restoring previous values and removing keys that didn't previously exist on exit, so that calls to this can be nested. """ previous = {} delete = [] for k, v in overrides.items(): try: previous[k] = OVERRIDE_OPTIONS[k] except KeyError: delete.append(k) OVERRIDE_OPTIONS[k] = v try: yield finally: for k, v in previous.items(): OVERRIDE_OPTIONS[k] = v for k in delete: OVERRIDE_OPTIONS.pop(k)
QueryOutsideGroupActivityError
python
kamyu104__LeetCode-Solutions
Python/maximum-score-of-non-overlapping-intervals.py
{ "start": 85, "end": 1083 }
class ____(object): def maximumWeight(self, intervals): """ :type intervals: List[List[int]] :rtype: List[int] """ K = 4 lookup = {} for i, (l, r, w) in enumerate(intervals): if (r, l, w) not in lookup: lookup[r, l, w] = i sorted_intervals = sorted(lookup.iterkeys(), key=lambda x: x[0]) dp = [[[0, []] for _ in xrange(K+1)] for _ in xrange(len(sorted_intervals)+1)] for i in xrange(len(dp)-1): j = bisect.bisect_right(sorted_intervals, (sorted_intervals[i][1], 0, 0))-1 idx = lookup[sorted_intervals[i]] for k in xrange(1, len(dp[i])): new_dp = [dp[j+1][k-1][0]-sorted_intervals[i][2], dp[j+1][k-1][1][:]] insort(new_dp[1], idx) dp[i+1][k] = min(dp[i][k], new_dp) return dp[len(sorted_intervals)][K][1] # Time: O(nlogn + n * k^2) # Space: O(n * k^2) import bisect # dp, binary search
Solution
python
apache__airflow
dev/breeze/src/airflow_breeze/utils/provider_dependencies.py
{ "start": 7605, "end": 7708 }
class ____(NamedTuple): python_version: str packages: dict[str, PackageInfo]
ConstraintsForPython
python
PrefectHQ__prefect
tests/events/client/test_flow_run_subscriber.py
{ "start": 494, "end": 1050 }
class ____: """Mock event subscriber for testing""" def __init__(self, events: list[Event]): self.events = events self._index = 0 async def __aenter__(self) -> Self: return self async def __aexit__(self, *args) -> None: pass def __aiter__(self) -> Self: return self async def __anext__(self) -> Event: if self._index >= len(self.events): raise StopAsyncIteration event = self.events[self._index] self._index += 1 return event
MockEventSubscriber
python
spack__spack
lib/spack/spack/util/spack_json.py
{ "start": 899, "end": 1112 }
class ____(spack.error.SpackError): """Raised when there are issues with JSON parsing.""" def __init__(self, msg: str, json_error: BaseException): super().__init__(msg, str(json_error))
SpackJSONError
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py
{ "start": 5207, "end": 5406 }
class ____(ParentI): def b(self): x = __class__ if False: super def f(self): self.b() builtins.super(ChildI2, self).f() # no __class__ in the local scope
ChildI2
python
getsentry__sentry
tests/sentry/ratelimits/utils/test_get_ratelimit_key.py
{ "start": 9028, "end": 9098 }
class ____(Endpoint): permission_classes = (AllowAny,)
DummyEndpoint
python
allegroai__clearml
clearml/backend_api/services/v2_23/frames.py
{ "start": 381346, "end": 403493 }
class ____(Request): """ Return first frame per unique URI for the given dataview specification. Note: 'count_range' option for label rules is not supported and does not affect the returned snippets :param dataview: Dataview specification :type dataview: Dataview :param size: The amount of snippets to return. :type size: int :param search_after: For getting the next portion of snippets should be set to the value returned from the previous call. To get snippets from the beginning should be set to null or empty string :type search_after: str :param projection: Used to select which parts of the frame will be returned. Each string represents a field or sub-field (using dot-separated notation). In order to specify a specific array element, use array index as a field name. To specify all array elements, use '*'. :type projection: Sequence[str] :param aggregation: Specifies whether the returned frames should be aggregated. If not passed then 'aggregate_on_context_id' setting is consulted :type aggregation: dict :param order_by: The list of fields to sort on. :type order_by: Sequence[dict] """ _service = "frames" _action = "get_snippets_for_dataview2" _version = "2.23" _schema = { "definitions": { "dataview": { "properties": { "augmentation": { "description": "Augmentation parameters. Only for training and testing tasks.", "oneOf": [ {"$ref": "#/definitions/dv_augmentation"}, {"type": "null"}, ], }, "filters": { "description": "List of FilterRule ('OR' relationship)", "items": {"$ref": "#/definitions/filter_rule"}, "type": ["array", "null"], }, "iteration": { "description": "Iteration parameters. Not applicable for register (import) tasks.", "oneOf": [ {"$ref": "#/definitions/iteration"}, {"type": "null"}, ], }, "labels_enumeration": { "additionalProperties": {"type": "integer"}, "description": ( "Labels enumerations, specifies numbers to be assigned to ROI labels when getting frames" ), "type": ["object", "null"], }, "mapping": { "description": "Mapping parameters", "oneOf": [{"$ref": "#/definitions/mapping"}, {"type": "null"}], }, "output_rois": { "description": ( "'all_in_frame' - all rois for a frame are returned\n\n'only_filtered' - only rois which" " led this frame to be selected\n\n'frame_per_roi' - single roi per frame. Frame can be" " returned multiple times with a different roi each time.\n\nNote: this should be used for" " Training tasks only\n\nNote: frame_per_roi implies that only filtered rois will be" " returned\n " ), "oneOf": [ {"$ref": "#/definitions/output_rois_enum"}, {"type": "null"}, ], }, "versions": { "description": "View dataset versions", "items": {"$ref": "#/definitions/view_entry"}, "type": ["array", "null"], }, }, "type": "object", }, "dv_augmentation": { "properties": { "crop_around_rois": { "description": "Crop image data around all frame ROIs", "type": ["boolean", "null"], }, "sets": { "description": "List of augmentation sets", "items": {"$ref": "#/definitions/dv_augmentation_set"}, "type": ["array", "null"], }, }, "type": "object", }, "dv_augmentation_set": { "properties": { "arguments": { "additionalProperties": { "additionalProperties": True, "type": "object", }, "description": "Arguments dictionary per custom augmentation type.", "type": ["object", "null"], }, "cls": { "description": "Augmentation class", "type": ["string", "null"], }, "strength": { "description": "Augmentation strength. Range [0,).", "minimum": 0, "type": ["number", "null"], }, "types": { "description": "Augmentation type", "items": {"type": "string"}, "type": ["array", "null"], }, }, "type": "object", }, "filter_by_roi_enum": { "default": "label_rules", "enum": ["disabled", "no_rois", "label_rules"], "type": "string", }, "filter_label_rule": { "properties": { "conf_range": { "description": ( "Range of ROI confidence level in the frame (min, max). -1 for not applicable\n " " Both min and max can be either -1 or positive.\n 2nd number (max) must be" " either -1 or larger than or equal to the 1st number (min)" ), "items": {"type": "number"}, "maxItems": 2, "minItems": 1, "type": "array", }, "count_range": { "description": ( "Range of times ROI appears in the frame (min, max). -1 for not applicable.\n " " Both integers must be larger than or equal to -1.\n 2nd integer (max) must be" " either -1 or larger than or equal to the 1st integer (min)" ), "items": {"type": "integer"}, "maxItems": 2, "minItems": 1, "type": "array", }, "label": { "description": ( "Lucene format query (see lucene query syntax).\nDefault search field is label.keyword and" " default operator is AND, so searching for:\n\n'Bus Stop' Blue\n\nis equivalent" " to:\n\nLabel.keyword:'Bus Stop' AND label.keyword:'Blue'" ), "type": "string", }, "must_not": { "default": False, "description": ( "If set then the label must not exist or lucene query must not be true.\n The" " default value is false" ), "type": "boolean", }, }, "required": ["label"], "type": "object", }, "filter_rule": { "properties": { "dataset": { "description": ( "Dataset ID. Must be a dataset which is in the task's view. If set to '*' all datasets in" " View are used." ), "type": "string", }, "filter_by_roi": { "description": "Type of filter. Optional, the default value is 'label_rules'", "oneOf": [ {"$ref": "#/definitions/filter_by_roi_enum"}, {"type": "null"}, ], }, "frame_query": { "description": "Frame filter, in Lucene query syntax", "type": ["string", "null"], }, "label_rules": { "description": ( "List of FilterLabelRule ('AND' connection)\n\ndisabled - No filtering by ROIs. Select all" " frames, even if they don't have ROIs (all frames)\n\nno_rois - Select only frames without" " ROIs (empty frames)\n\nlabel_rules - Select frames according to label rules" ), "items": {"$ref": "#/definitions/filter_label_rule"}, "type": ["array", "null"], }, "sources_query": { "description": "Sources filter, in Lucene query syntax. Filters sources in each frame.", "type": ["string", "null"], }, "version": { "description": ( "Dataset version to apply rule to. Must belong to the dataset and be in the task's view. If" " set to '*' all version of the datasets in View are used." ), "type": "string", }, "weight": { "description": "Rule weight. Default is 1", "type": "number", }, }, "required": ["dataset"], "type": "object", }, "iteration": { "description": "Sequential Iteration API configuration", "properties": { "infinite": { "description": "Infinite iteration", "type": ["boolean", "null"], }, "jump": { "description": "Jump entry", "oneOf": [{"$ref": "#/definitions/jump"}, {"type": "null"}], }, "limit": { "description": ( "Maximum frames per task. If not passed, frames will end when no more matching frames are" " found, unless infinite is True." ), "type": ["integer", "null"], }, "min_sequence": { "description": ( "Length (in ms) of video clips to return. This is used in random order, and in sequential" " order only if jumping is provided and only for video frames" ), "type": ["integer", "null"], }, "order": { "description": ( "\n Input frames order. Values: 'sequential', 'random'\n In" " Sequential mode frames will be returned according to the order in which the frames were" " added to the dataset." ), "oneOf": [ {"$ref": "#/definitions/iteration_order_enum"}, {"type": "null"}, ], }, "random_seed": { "description": "Random seed used when iterating over the dataview", "type": ["integer", "null"], }, }, "type": "object", }, "iteration_order_enum": { "enum": ["sequential", "random"], "type": "string", }, "jump": { "properties": { "time": { "description": "Max time in milliseconds between frames", "type": ["integer", "null"], } }, "type": "object", }, "label_source": { "properties": { "dataset": { "description": "Source dataset id. '*' for all datasets in view", "type": ["string", "null"], }, "labels": { "description": ( "List of source labels (AND connection). '*' indicates any label. Labels must exist in at" " least one of the dataset versions in the task's view" ), "items": {"type": "string"}, "type": ["array", "null"], }, "version": { "description": ( "Source dataset version id. Default is '*' (for all versions in dataset in the view)" " Version must belong to the selected dataset, and must be in the task's view[i]" ), "type": ["string", "null"], }, }, "type": "object", }, "mapping": { "properties": { "rules": { "description": "Rules list", "items": {"$ref": "#/definitions/mapping_rule"}, "type": ["array", "null"], } }, "type": "object", }, "mapping_rule": { "properties": { "source": { "description": "Source label info", "oneOf": [ {"$ref": "#/definitions/label_source"}, {"type": "null"}, ], }, "target": { "description": "Target label name", "type": ["string", "null"], }, }, "type": "object", }, "output_rois_enum": { "enum": ["all_in_frame", "only_filtered", "frame_per_roi"], "type": "string", }, "view_entry": { "properties": { "dataset": { "description": "Existing Dataset id", "type": ["string", "null"], }, "merge_with": { "description": "Version ID to merge with", "type": ["string", "null"], }, "version": { "description": "Version id of a version belonging to the dataset", "type": ["string", "null"], }, }, "type": "object", }, }, "properties": { "aggregation": { "description": ( "Specifies whether the returned frames should be aggregated. If not passed then" " 'aggregate_on_context_id' setting is consulted" ), "properties": { "aggregate": { "description": "If set to Truethen the returned frames are aggregated on the provided fields", "type": "boolean", }, "fields": { "description": ( "The list of the fields to aggragate on. Only if the aggregate parameter is set to True" ), "items": {"type": "string"}, "type": "array", }, }, "required": ["aggregate"], "type": "object", }, "dataview": { "$ref": "#/definitions/dataview", "description": "Dataview specification", }, "order_by": { "description": "The list of fields to sort on.", "items": { "properties": { "field": { "description": "The name of the field", "type": "string", }, "order": { "default": "asc", "description": "The order of the sorting", "enum": ["asc", "desc"], "type": "string", }, }, "type": "object", }, "type": "array", }, "projection": { "description": ( "Used to select which parts of the frame will be returned. Each string represents a\n " " field or sub-field (using dot-separated notation). In order to specify a specific array" " element,\n use array index as a field name. To specify all array elements, use" " '*'." ), "items": {"type": "string"}, "type": "array", }, "search_after": { "description": ( "For getting the next portion of snippets should be set to the value returned from the previous" " call. To get snippets from the beginning should be set to null or empty string" ), "type": "string", }, "size": { "default": 50, "description": "The amount of snippets to return.", "type": "integer", }, }, "required": ["dataview"], "type": "object", } def __init__( self, dataview, size=50, search_after=None, projection=None, aggregation=None, order_by=None, **kwargs ): super(GetSnippetsForDataview2Request, self).__init__(**kwargs) self.dataview = dataview self.size = size self.search_after = search_after self.projection = projection self.aggregation = aggregation self.order_by = order_by @schema_property("dataview") def dataview(self): return self._property_dataview @dataview.setter def dataview(self, value): if value is None: self._property_dataview = None return if isinstance(value, dict): value = Dataview.from_dict(value) else: self.assert_isinstance(value, "dataview", Dataview) self._property_dataview = value @schema_property("size") def size(self): return self._property_size @size.setter def size(self, value): if value is None: self._property_size = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "size", six.integer_types) self._property_size = value @schema_property("search_after") def search_after(self): return self._property_search_after @search_after.setter def search_after(self, value): if value is None: self._property_search_after = None return self.assert_isinstance(value, "search_after", six.string_types) self._property_search_after = value @schema_property("projection") def projection(self): return self._property_projection @projection.setter def projection(self, value): if value is None: self._property_projection = None return self.assert_isinstance(value, "projection", (list, tuple)) self.assert_isinstance(value, "projection", six.string_types, is_array=True) self._property_projection = value @schema_property("aggregation") def aggregation(self): return self._property_aggregation @aggregation.setter def aggregation(self, value): if value is None: self._property_aggregation = None return self.assert_isinstance(value, "aggregation", (dict,)) self._property_aggregation = value @schema_property("order_by") def order_by(self): return self._property_order_by @order_by.setter def order_by(self, value): if value is None: self._property_order_by = None return self.assert_isinstance(value, "order_by", (list, tuple)) self.assert_isinstance(value, "order_by", (dict,), is_array=True) self._property_order_by = value
GetSnippetsForDataview2Request
python
milvus-io__pymilvus
pymilvus/exceptions.py
{ "start": 819, "end": 1548 }
class ____(Exception): def __init__( self, code: int = ErrorCode.UNEXPECTED_ERROR, message: str = "", compatible_code: int = common_pb2.UnexpectedError, ) -> None: super().__init__() self._code = code self._message = message # for compatibility, remove it after 2.4.0 self._compatible_code = compatible_code @property def code(self): return self._code @property def message(self): return self._message @property def compatible_code(self): return self._compatible_code def __str__(self) -> str: return f"<{type(self).__name__}: (code={self.code}, message={self.message})>"
MilvusException
python
instagram__MonkeyType
monkeytype/stubs.py
{ "start": 19451, "end": 20555 }
class ____(Stub): def __init__( self, name: str, function_stubs: Optional[Iterable[FunctionStub]] = None, attribute_stubs: Optional[Iterable[AttributeStub]] = None, ) -> None: self.name = name self.function_stubs: Dict[str, FunctionStub] = {} self.attribute_stubs = attribute_stubs or [] if function_stubs is not None: self.function_stubs = {stub.name: stub for stub in function_stubs} def render(self) -> str: parts = [ f"class {self.name}:", *[ stub.render(prefix=" ") for stub in sorted(self.attribute_stubs, key=lambda stub: stub.name) ], *[ stub.render(prefix=" ") for _, stub in sorted(self.function_stubs.items()) ], ] return "\n".join(parts) def __repr__(self) -> str: return "ClassStub(%s, %s, %s)" % ( repr(self.name), tuple(self.function_stubs.values()), tuple(self.attribute_stubs), )
ClassStub
python
pytorch__pytorch
test/fx/test_partitioner_order.py
{ "start": 461, "end": 787 }
class ____(CapabilityBasedPartitioner): def __init__(self, graph_module: torch.fx.GraphModule): super().__init__( graph_module, DummyDevOperatorSupport(), allows_single_node_partition=True, ) # original graph node order is: ['x', 'add', 'add_1', 'output']
DummyPartitioner
python
django__django
django/contrib/contenttypes/apps.py
{ "start": 382, "end": 846 }
class ____(AppConfig): default_auto_field = "django.db.models.AutoField" name = "django.contrib.contenttypes" verbose_name = _("Content Types") def ready(self): pre_migrate.connect(inject_rename_contenttypes_operations, sender=self) post_migrate.connect(create_contenttypes) checks.register(check_generic_foreign_keys, checks.Tags.models) checks.register(check_model_name_lengths, checks.Tags.models)
ContentTypesConfig
python
kamyu104__LeetCode-Solutions
Python/number-of-substrings-containing-all-three-characters.py
{ "start": 793, "end": 1273 }
class ____(object): def numberOfSubstrings(self, s): """ :type s: str :rtype: int """ result, right, count = 0, 0, [0]*3 for left, c in enumerate(s): while right < len(s) and not all(count): count[ord(s[right])-ord('a')] += 1 right += 1 if all(count): result += (len(s)-1) - (right-1) + 1 count[ord(c)-ord('a')] -= 1 return result
Solution3
python
huggingface__transformers
src/transformers/models/qwen3_next/modeling_qwen3_next.py
{ "start": 40237, "end": 43005 }
class ____(GradientCheckpointingLayer): def __init__(self, config: Qwen3NextConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size # token mixer self.layer_type = config.layer_types[layer_idx] if self.layer_type == "linear_attention": self.linear_attn = Qwen3NextGatedDeltaNet(config, layer_idx) elif self.layer_type == "full_attention": self.self_attn = Qwen3NextAttention(config, layer_idx) if (layer_idx not in config.mlp_only_layers) and ( config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0 ): self.mlp = Qwen3NextSparseMoeBlock(config) else: self.mlp = Qwen3NextMLP(config, intermediate_size=config.intermediate_size) self.input_layernorm = Qwen3NextRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = Qwen3NextRMSNorm(config.hidden_size, eps=config.rms_norm_eps) def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> torch.FloatTensor: residual = hidden_states hidden_states = self.input_layernorm(hidden_states) # Token Mixer if self.layer_type == "linear_attention": hidden_states = self.linear_attn( hidden_states=hidden_states, cache_params=past_key_values, cache_position=cache_position, attention_mask=attention_mask, ) elif self.layer_type == "full_attention": # Self Attention hidden_states, _ = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) hidden_states = residual + hidden_states # Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) # For the MoE layers, we need to unpack if isinstance(hidden_states, tuple): hidden_states, _ = hidden_states hidden_states = residual + hidden_states return hidden_states
Qwen3NextDecoderLayer
python
mitmproxy__pdoc
pdoc/doc.py
{ "start": 2384, "end": 6618 }
class ____(Generic[T]): """ A base class for all documentation objects. """ modulename: str """ The module that this object is in, for example `pdoc.doc`. """ qualname: str """ The qualified identifier name for this object. For example, if we have the following code: ```python class Foo: def bar(self): pass ``` The qualname of `Foo`'s `bar` method is `Foo.bar`. The qualname of the `Foo` class is just `Foo`. See <https://www.python.org/dev/peps/pep-3155/> for details. """ obj: T """ The underlying Python object. """ taken_from: tuple[str, str] """ `(modulename, qualname)` of this doc object's original location. In the context of a module, this points to the location it was imported from, in the context of classes, this points to the class an attribute is inherited from. """ kind: ClassVar[str] """ The type of the doc object, either `"module"`, `"class"`, `"function"`, or `"variable"`. """ @property def type(self) -> str: # pragma: no cover warnings.warn( "pdoc.doc.Doc.type is deprecated. Use pdoc.doc.Doc.kind instead.", DeprecationWarning, ) return self.kind def __init__( self, modulename: str, qualname: str, obj: T, taken_from: tuple[str, str] ): """ Initializes a documentation object, where `modulename` is the name this module is defined in, `qualname` contains a dotted path leading to the object from the module top-level, and `obj` is the object to document. """ self.modulename = modulename self.qualname = qualname self.obj = obj self.taken_from = taken_from @cached_property def fullname(self) -> str: """The full qualified name of this doc object, for example `pdoc.doc.Doc`.""" # qualname is empty for modules return f"{self.modulename}.{self.qualname}".rstrip(".") @cached_property def name(self) -> str: """The name of this object. For top-level functions and classes, this is equal to the qualname attribute.""" return self.fullname.split(".")[-1] @cached_property def docstring(self) -> str: """ The docstring for this object. It has already been cleaned by `inspect.cleandoc`. If no docstring can be found, an empty string is returned. """ return _safe_getdoc(self.obj) @cached_property def source(self) -> str: """ The source code of the Python object as a `str`. If the source cannot be obtained (for example, because we are dealing with a native C object), an empty string is returned. """ return doc_ast.get_source(self.obj) @cached_property def source_file(self) -> Path | None: """The name of the Python source file in which this object was defined. `None` for built-in objects.""" try: return Path(inspect.getsourcefile(self.obj) or inspect.getfile(self.obj)) # type: ignore except TypeError: return None @cached_property def source_lines(self) -> tuple[int, int] | None: """ Return a `(start, end)` line number tuple for this object. If no source file can be found, `None` is returned. """ try: lines, start = inspect.getsourcelines(self.obj) # type: ignore return start, start + len(lines) - 1 except Exception: return None @cached_property def is_inherited(self) -> bool: """ If True, the doc object is inherited from another location. This most commonly refers to methods inherited by a subclass, but can also apply to variables that are assigned a class defined in a different module. """ return (self.modulename, self.qualname) != self.taken_from def __lt__(self, other): assert isinstance(other, Doc) return self.fullname.replace("__init__", "").__lt__( other.fullname.replace("__init__", "") ) U = TypeVar("U", bound=types.ModuleType | type)
Doc
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/conjecture/dfa/lstar.py
{ "start": 4648, "end": 15675 }
class ____: """This class holds the state for learning a DFA. The current DFA can be accessed as the ``dfa`` member of this class. Such a DFA becomes invalid as soon as ``learn`` has been called, and should only be used until the next call to ``learn``. Note that many of the DFA methods are on this class, but it is not itself a DFA. The reason for this is that it stores mutable state which can cause the structure of the learned DFA to change in potentially arbitrary ways, making all cached properties become nonsense. """ def __init__(self, member): self.experiments = [] self.__experiment_set = set() self.normalizer = IntegerNormalizer() self.__member_cache = {} self.__member = member self.__generation = 0 # A list of all state objects that correspond to strings we have # seen and can demonstrate map to unique states. self.__states = [ DistinguishedState( index=0, label=b"", accepting=self.member(b""), experiments={b"": self.member(b"")}, ) ] # When we're trying to figure out what state a string leads to we will # end up searching to find a suitable candidate. By putting states in # a self-organising list we ideally minimise the number of lookups. self.__self_organising_states = SelfOrganisingList(self.__states) self.start = 0 self.__dfa_changed() def __dfa_changed(self): """Note that something has changed, updating the generation and resetting any cached state.""" self.__generation += 1 self.dfa = LearnedDFA(self) def is_accepting(self, i): """Equivalent to ``self.dfa.is_accepting(i)``""" return self.__states[i].accepting def label(self, i): """Returns the string label for state ``i``.""" return self.__states[i].label def transition(self, i, c): """Equivalent to ``self.dfa.transition(i, c)```""" c = self.normalizer.normalize(c) state = self.__states[i] try: return state.transitions[c] except KeyError: pass # The state that we transition to when reading ``c`` is reached by # this string, because this state is reached by state.label. We thus # want our candidate for the transition to be some state with a label # equivalent to this string. # # We find such a state by looking for one such that all of its listed # experiments agree on the result for its state label and this string. string = state.label + bytes([c]) # We keep track of some useful experiments for distinguishing this # string from other states, as this both allows us to more accurately # select the state to map to and, if necessary, create the new state # that this string corresponds to with a decent set of starting # experiments. accumulated = {} counts = Counter() def equivalent(t): """Checks if ``string`` could possibly lead to state ``t``.""" for e, expected in accumulated.items(): if self.member(t.label + e) != expected: counts[e] += 1 return False for e, expected in t.experiments.items(): result = self.member(string + e) if result != expected: # We expect most experiments to return False so if we add # only True ones to our collection of essential experiments # we keep the size way down and select only ones that are # likely to provide useful information in future. if result: accumulated[e] = result return False return True try: destination = self.__self_organising_states.find(equivalent) except NotFound: i = len(self.__states) destination = DistinguishedState( index=i, label=string, experiments=accumulated, accepting=self.member(string), ) self.__states.append(destination) self.__self_organising_states.add(destination) state.transitions[c] = destination.index return destination.index def member(self, s): """Check whether this string is a member of the language to be learned.""" try: return self.__member_cache[s] except KeyError: result = self.__member(s) self.__member_cache[s] = result return result @property def generation(self): """Return an integer value that will be incremented every time the DFA we predict changes.""" return self.__generation def learn(self, string): """Learn to give the correct answer on this string. That is, after this method completes we will have ``self.dfa.matches(s) == self.member(s)``. Note that we do not guarantee that this will remain true in the event that learn is called again with a different string. It is in principle possible that future learning will cause us to make a mistake on this string. However, repeatedly calling learn on each of a set of strings until the generation stops changing is guaranteed to terminate. """ string = bytes(string) correct_outcome = self.member(string) # We don't want to check this inside the loop because it potentially # causes us to evaluate more of the states than we actually need to, # but if our model is mostly correct then this will be faster because # we only need to evaluate strings that are of the form # ``state + experiment``, which will generally be cached and/or needed # later. if self.dfa.matches(string) == correct_outcome: return # In the papers they assume that we only run this process # once, but this is silly - often when you've got a messy # string it will be wrong for many different reasons. # # Thus we iterate this to a fixed point where we repair # the DFA by repeatedly adding experiments until the DFA # agrees with the membership function on this string. # First we make sure that normalization is not the source of the # failure to match. while True: normalized = bytes(self.normalizer.normalize(c) for c in string) # We can correctly replace the string with its normalized version # so normalization is not the problem here. if self.member(normalized) == correct_outcome: string = normalized break alphabet = sorted(set(string), reverse=True) target = string for a in alphabet: def replace(b): if a == b: return target return bytes(b if c == a else c for c in target) self.normalizer.distinguish(a, lambda x: self.member(replace(x))) target = replace(self.normalizer.normalize(a)) assert self.member(target) == correct_outcome assert target != normalized self.__dfa_changed() if self.dfa.matches(string) == correct_outcome: return # Now we know normalization is correct we can attempt to determine if # any of our transitions are wrong. while True: dfa = self.dfa states = [dfa.start] def seems_right(n): """After reading n characters from s, do we seem to be in the right state? We determine this by replacing the first n characters of s with the label of the state we expect to be in. If we are in the right state, that will replace a substring with an equivalent one so must produce the same answer. """ if n > len(string): return False # Populate enough of the states list to know where we are. while n >= len(states): states.append(dfa.transition(states[-1], string[len(states) - 1])) return self.member(dfa.label(states[n]) + string[n:]) == correct_outcome assert seems_right(0) n = find_integer(seems_right) # We got to the end without ever finding ourself in a bad # state, so we must correctly match this string. if n == len(string): assert dfa.matches(string) == correct_outcome break # Reading n characters does not put us in a bad state but # reading n + 1 does. This means that the remainder of # the string that we have not read yet is an experiment # that allows us to distinguish the state that we ended # up in from the state that we should have ended up in. source = states[n] character = string[n] wrong_destination = states[n + 1] # We've made an error in transitioning from ``source`` to # ``wrong_destination`` via ``character``. We now need to update # the DFA so that this transition no longer occurs. Note that we # do not guarantee that the transition is *correct* after this, # only that we don't make this particular error. assert self.transition(source, character) == wrong_destination labels_wrong_destination = self.dfa.label(wrong_destination) labels_correct_destination = self.dfa.label(source) + bytes([character]) ex = string[n + 1 :] assert self.member(labels_wrong_destination + ex) != self.member( labels_correct_destination + ex ) # Adding this experiment causes us to distinguish the wrong # destination from the correct one. self.__states[wrong_destination].experiments[ex] = self.member( labels_wrong_destination + ex ) # We now clear the cached details that caused us to make this error # so that when we recalculate this transition we get to a # (hopefully now correct) different state. del self.__states[source].transitions[character] self.__dfa_changed() # We immediately recalculate the transition so that we can check # that it has changed as we expect it to have. new_destination = self.transition(source, string[n]) assert new_destination != wrong_destination
LStar
python
walkccc__LeetCode
solutions/861. Score After Flipping Matrix/861.py
{ "start": 0, "end": 764 }
class ____: def matrixScore(self, grid: list[list[int]]) -> int: # Flip the rows with a leading 0. for row in grid: if row[0] == 0: self._flip(row) # Flip the columns with 1s < 0s. for j, col in enumerate(list(zip(*grid))): if sum(col) * 2 < len(grid): self._flipCol(grid, j) # Add a binary number for each row. return sum(self._binary(row) for row in grid) def _flip(self, row: list[int]) -> None: for i in range(len(row)): row[i] ^= 1 def _flipCol(self, grid: list[list[int]], j: int) -> None: for i in range(len(grid)): grid[i][j] ^= 1 def _binary(self, row: list[int]) -> int: res = row[0] for j in range(1, len(row)): res = res * 2 + row[j] return res
Solution
python
rapidsai__cudf
python/cudf/cudf/pandas/fast_slow_proxy.py
{ "start": 32238, "end": 33326 }
class ____(_FunctionProxy): def __init__(self, fast, slow, _fsproxy_transfer_block=None): super().__init__( fast, slow, updated=functools.WRAPPER_UPDATES, assigned=( tuple(filter(lambda x: x != "__name__", _WRAPPER_ASSIGNMENTS)) ), _fsproxy_transfer_block=_fsproxy_transfer_block, ) def __dir__(self): return self._fsproxy_slow.__dir__() @property def __doc__(self): return self._fsproxy_slow.__doc__ @property def __name__(self): return self._fsproxy_slow.__name__ @__name__.setter def __name__(self, value): try: setattr(self._fsproxy_fast, "__name__", value) except AttributeError: pass setattr(self._fsproxy_slow, "__name__", value) @property def _customqualname(self): return self._fsproxy_slow.__qualname__ def _assert_fast_slow_eq(left, right): if _is_final_type(type(left)) or type(left) in NUMPY_TYPES: assert_eq(left, right)
_MethodProxy
python
numpy__numpy
numpy/_core/tests/test_simd.py
{ "start": 3710, "end": 8045 }
class ____(_Test_Utility): """ To test all boolean vector types at once """ def _nlanes(self): return getattr(self.npyv, "nlanes_u" + self.sfx[1:]) def _data(self, start=None, count=None, reverse=False): true_mask = self._true_mask() rng = range(self._nlanes()) if reverse: rng = reversed(rng) return [true_mask if x % 2 else 0 for x in rng] def _load_b(self, data): len_str = self.sfx[1:] load = getattr(self.npyv, "load_u" + len_str) cvt = getattr(self.npyv, f"cvt_b{len_str}_u{len_str}") return cvt(load(data)) def test_operators_logical(self): """ Logical operations for boolean types. Test intrinsics: npyv_xor_##SFX, npyv_and_##SFX, npyv_or_##SFX, npyv_not_##SFX, npyv_andc_b8, npvy_orc_b8, nvpy_xnor_b8 """ data_a = self._data() data_b = self._data(reverse=True) vdata_a = self._load_b(data_a) vdata_b = self._load_b(data_b) data_and = [a & b for a, b in zip(data_a, data_b)] vand = getattr(self, "and")(vdata_a, vdata_b) assert vand == data_and data_or = [a | b for a, b in zip(data_a, data_b)] vor = getattr(self, "or")(vdata_a, vdata_b) assert vor == data_or data_xor = [a ^ b for a, b in zip(data_a, data_b)] vxor = self.xor(vdata_a, vdata_b) assert vxor == data_xor vnot = getattr(self, "not")(vdata_a) assert vnot == data_b # among the boolean types, andc, orc and xnor only support b8 if self.sfx not in ("b8"): return data_andc = [(a & ~b) & 0xFF for a, b in zip(data_a, data_b)] vandc = self.andc(vdata_a, vdata_b) assert data_andc == vandc data_orc = [(a | ~b) & 0xFF for a, b in zip(data_a, data_b)] vorc = self.orc(vdata_a, vdata_b) assert data_orc == vorc data_xnor = [~(a ^ b) & 0xFF for a, b in zip(data_a, data_b)] vxnor = self.xnor(vdata_a, vdata_b) assert data_xnor == vxnor def test_tobits(self): data2bits = lambda data: sum(int(x != 0) << i for i, x in enumerate(data, 0)) for data in (self._data(), self._data(reverse=True)): vdata = self._load_b(data) data_bits = data2bits(data) tobits = self.tobits(vdata) bin_tobits = bin(tobits) assert bin_tobits == bin(data_bits) def test_pack(self): """ Pack multiple vectors into one Test intrinsics: npyv_pack_b8_b16 npyv_pack_b8_b32 npyv_pack_b8_b64 """ if self.sfx not in ("b16", "b32", "b64"): return # create the vectors data = self._data() rdata = self._data(reverse=True) vdata = self._load_b(data) vrdata = self._load_b(rdata) pack_simd = getattr(self.npyv, f"pack_b8_{self.sfx}") # for scalar execution, concatenate the elements of the multiple lists # into a single list (spack) and then iterate over the elements of # the created list applying a mask to capture the first byte of them. if self.sfx == "b16": spack = [(i & 0xFF) for i in (list(rdata) + list(data))] vpack = pack_simd(vrdata, vdata) elif self.sfx == "b32": spack = [(i & 0xFF) for i in (2 * list(rdata) + 2 * list(data))] vpack = pack_simd(vrdata, vrdata, vdata, vdata) elif self.sfx == "b64": spack = [(i & 0xFF) for i in (4 * list(rdata) + 4 * list(data))] vpack = pack_simd(vrdata, vrdata, vrdata, vrdata, vdata, vdata, vdata, vdata) assert vpack == spack @pytest.mark.parametrize("intrin", ["any", "all"]) @pytest.mark.parametrize("data", ( [-1, 0], [0, -1], [-1], [0] )) def test_operators_crosstest(self, intrin, data): """ Test intrinsics: npyv_any_##SFX npyv_all_##SFX """ data_a = self._load_b(data * self._nlanes()) func = eval(intrin) intrin = getattr(self, intrin) desired = func(data_a) simd = intrin(data_a) assert not not simd == desired
_SIMD_BOOL
python
getsentry__sentry
tests/sentry/web/frontend/test_group_event_json.py
{ "start": 172, "end": 898 }
class ____(TestCase): @cached_property def path(self) -> str: return f"/organizations/{self.organization.slug}/issues/{self.event.group_id}/events/{self.event.event_id}/json/" def test_does_render(self) -> None: self.login_as(self.user) min_ago = before_now(minutes=1).isoformat() self.event = self.store_event( data={"fingerprint": ["group1"], "timestamp": min_ago}, project_id=self.project.id ) resp = self.client.get(self.path) assert resp.status_code == 200 assert resp["Content-Type"] == "application/json" data = json.loads(resp.content.decode("utf-8")) assert data["event_id"] == self.event.event_id
GroupEventJsonTest
python
ansible__ansible
lib/ansible/_internal/_templating/_jinja_bits.py
{ "start": 12718, "end": 13840 }
class ____(Template): """ A helper class, which prevents Jinja2 from running lazy containers through dict(). """ _python_source_temp_path: pathlib.Path | None = None def __del__(self): # DTFIX-FUTURE: this still isn't working reliably; something else must be keeping the template object alive if self._python_source_temp_path: self._python_source_temp_path.unlink(missing_ok=True) def __call__(self, jinja_vars: c.Mapping[str, t.Any]) -> t.Any: return self.render(ArgSmuggler.package_jinja_vars(jinja_vars)) # noinspection PyShadowingBuiltins def new_context( self, vars: c.Mapping[str, t.Any] | None = None, shared: bool = False, locals: c.Mapping[str, t.Any] | None = None, ) -> Context: return _new_context( environment=self.environment, template_name=self.name, blocks=self.blocks, shared=shared, jinja_locals=locals, jinja_vars=ArgSmuggler.extract_jinja_vars(vars), jinja_globals=self.globals, )
AnsibleTemplate
python
django__django
tests/admin_views/admin.py
{ "start": 12400, "end": 12542 }
class ____(admin.ModelAdmin): def get_queryset(self, request): return super().get_queryset(request).filter(pk__gt=1)
EmptyModelAdmin
python
getsentry__sentry
src/sentry/migrations/0988_data_forwarding.py
{ "start": 269, "end": 4329 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # of a table. # Here are some things that make sense to mark as post deployment: # - Large data migrations. Typically we want these to be run manually so that they can be # monitored and not block the deploy for a long period of time while they run. # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to # run this outside deployments so that we don't block them. Note that while adding an index # is a schema change, it's completely safe to run the operation after the code has deployed. # Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment is_post_deployment = False dependencies = [ ("sentry", "0987_authidentity_json_field"), ] operations = [ migrations.CreateModel( name="DataForwarder", fields=[ ( "id", sentry.db.models.fields.bounded.BoundedBigAutoField( primary_key=True, serialize=False ), ), ("date_updated", models.DateTimeField(auto_now=True)), ("date_added", models.DateTimeField(auto_now_add=True)), ("is_enabled", models.BooleanField(default=True)), ("enroll_new_projects", models.BooleanField(default=False)), ("provider", models.CharField(max_length=64)), ("config", models.JSONField(default=dict)), ( "organization", sentry.db.models.fields.foreignkey.FlexibleForeignKey( on_delete=django.db.models.deletion.CASCADE, to="sentry.organization" ), ), ], options={ "db_table": "sentry_dataforwarder", }, ), migrations.CreateModel( name="DataForwarderProject", fields=[ ( "id", sentry.db.models.fields.bounded.BoundedBigAutoField( primary_key=True, serialize=False ), ), ("date_updated", models.DateTimeField(auto_now=True)), ("date_added", models.DateTimeField(auto_now_add=True)), ("is_enabled", models.BooleanField(default=True)), ("overrides", models.JSONField(default=dict)), ( "data_forwarder", sentry.db.models.fields.foreignkey.FlexibleForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="projects", to="sentry.dataforwarder", ), ), ( "project", sentry.db.models.fields.foreignkey.FlexibleForeignKey( on_delete=django.db.models.deletion.CASCADE, to="sentry.project" ), ), ], options={ "db_table": "sentry_dataforwarderproject", "unique_together": {("data_forwarder", "project")}, }, ), migrations.AddField( model_name="dataforwarder", name="enrolled_projects", field=models.ManyToManyField( related_name="data_forwarders", through="sentry.DataForwarderProject", to="sentry.project", ), ), migrations.AlterUniqueTogether( name="dataforwarder", unique_together={("organization", "provider")}, ), ]
Migration
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/lib/metadata_service/gcs_upload.py
{ "start": 1772, "end": 26077 }
class ____: zip_file_path: Path | None sha256_file_path: Path | None sha256: str | None manifest_file_path: Path # 🛣️ FILES AND PATHS def get_doc_local_file_path(docs_path: Path, inapp: bool) -> Optional[Path]: extension = ".inapp.md" if inapp else ".md" return docs_path.with_suffix(extension) def get_manifest_only_file_paths(working_directory: Path) -> ManifestOnlyFilePaths: """Create a zip file for components if they exist and return its SHA256 hash.""" yaml_manifest_file_path = working_directory / MANIFEST_FILE_NAME components_py_file_path = working_directory / COMPONENTS_PY_FILE_NAME if not components_py_file_path.exists(): return ManifestOnlyFilePaths( zip_file_path=None, sha256_file_path=None, sha256=None, manifest_file_path=yaml_manifest_file_path, ) with ( tempfile.NamedTemporaryFile(mode="wb", suffix=".zip", delete=False) as zip_tmp_file, tempfile.NamedTemporaryFile(mode="w", suffix=".sha256", delete=False) as sha256_tmp_file, ): python_components_zip_file_path = Path(zip_tmp_file.name) python_components_zip_sha256_file_path = Path(sha256_tmp_file.name) files_to_zip: List[Path] = [components_py_file_path, yaml_manifest_file_path] components_zip_sha256 = create_zip_and_get_sha256(files_to_zip, python_components_zip_file_path) sha256_tmp_file.write(components_zip_sha256) return ManifestOnlyFilePaths( zip_file_path=python_components_zip_file_path, sha256_file_path=python_components_zip_sha256_file_path, sha256=components_zip_sha256, manifest_file_path=yaml_manifest_file_path, ) def _write_metadata_to_tmp_file(metadata_dict: dict) -> Path: """Write the metadata to a temporary file.""" with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as tmp_file: yaml.dump(metadata_dict, tmp_file) return Path(tmp_file.name) # 🛠️ HELPERS def _safe_load_metadata_file(metadata_file_path: Path) -> dict: try: metadata = yaml.safe_load(metadata_file_path.read_text()) if metadata is None or not isinstance(metadata, dict): raise ValueError(f"Validation error: Metadata file {metadata_file_path} is invalid yaml.") return metadata except Exception as e: raise ValueError(f"Validation error: Metadata file {metadata_file_path} is invalid yaml: {e}") def _any_uploaded(uploaded_files: List[UploadedFile], keys: List[str]) -> bool: """Check if the list of uploaded files contains any of the provided keys.""" for uploaded_file in uploaded_files: if uploaded_file.id in keys: return True return False def _commit_to_git_info(commit: git.Commit) -> GitInfo: return GitInfo( commit_sha=commit.hexsha, commit_timestamp=commit.authored_datetime, commit_author=commit.author.name, commit_author_email=commit.author.email, ) def _get_git_info_for_file(original_metadata_file_path: Path) -> Optional[GitInfo]: """ Add additional information to the metadata file before uploading it to GCS. e.g. The git commit hash, the date of the commit, the author of the commit, etc. """ try: repo = git.Repo(search_parent_directories=True) # get the commit hash for the last commit that modified the metadata file commit_sha = repo.git.log("-1", "--format=%H", str(original_metadata_file_path)) commit = repo.commit(commit_sha) return _commit_to_git_info(commit) except git.exc.InvalidGitRepositoryError: logging.warning(f"Metadata file {original_metadata_file_path} is not in a git repository, skipping author info attachment.") return None except git.exc.GitCommandError as e: if "unknown revision or path not in the working tree" in str(e): logging.warning(f"Metadata file {original_metadata_file_path} is not tracked by git, skipping author info attachment.") return None else: raise e # 🚀 UPLOAD def _save_blob_to_gcs(blob_to_save: storage.blob.Blob, file_path: Path, disable_cache: bool = False) -> bool: """Uploads a file to the bucket.""" print(f"Uploading {file_path} to {blob_to_save.name}...") # Set Cache-Control header to no-cache to avoid caching issues # This is IMPORTANT because if we don't set this header, the metadata file will be cached by GCS # and the next time we try to download it, we will get the stale version if disable_cache: blob_to_save.cache_control = "no-cache" blob_to_save.upload_from_filename(file_path) return True def upload_file_if_changed( local_file_path: Path, bucket: storage.bucket.Bucket, blob_path: str, disable_cache: bool = False ) -> MaybeUpload: """Upload a file to GCS if it has changed.""" local_file_md5_hash = compute_gcs_md5(local_file_path) remote_blob = bucket.blob(blob_path) # reload the blob to get the md5_hash if remote_blob.exists(): remote_blob.reload() remote_blob_md5_hash = remote_blob.md5_hash if remote_blob.exists() else None print(f"Local {local_file_path} md5_hash: {local_file_md5_hash}") print(f"Remote {blob_path} md5_hash: {remote_blob_md5_hash}") if local_file_md5_hash != remote_blob_md5_hash: uploaded = _save_blob_to_gcs(remote_blob, local_file_path, disable_cache=disable_cache) return MaybeUpload(uploaded, remote_blob.id) return MaybeUpload(False, remote_blob.id) def _file_upload( local_path: Path | None, gcp_connector_dir: str, bucket: storage.bucket.Bucket, file_key: str, *, upload_as_version: bool, upload_as_latest: bool, skip_if_not_exists: bool = True, disable_cache: bool = False, version_folder: Optional[str] = None, override_destination_file_name: str | None = None, ) -> tuple[UploadedFile, UploadedFile]: """Upload a file to GCS. Optionally upload it as a versioned file and/or as the latest version. Args: local_path: Path to the file to upload. gcp_connector_dir: Path to the connector folder in GCS. This is the parent folder, containing the versioned and "latest" folders as its subdirectories. bucket: GCS bucket to upload the file to. upload_as_version: The version to upload the file as or 'False' to skip uploading the versioned copy. upload_as_latest: Whether to upload the file as the latest version. skip_if_not_exists: Whether to skip the upload if the file does not exist. Otherwise, an exception will be raised if the file does not exist. Returns: Tuple of two UploadInfo objects, each containing a boolean indicating whether the file was uploaded, the blob id, and the description. The first tuple is for the versioned file, the second for the latest file. """ if upload_as_version and not version_folder: raise ValueError("version_folder must be provided if upload_as_version is True") latest_file_key = f"latest_{file_key}" versioned_file_key = f"versioned_{file_key}" versioned_file_info = UploadedFile(id=versioned_file_key, uploaded=False, blob_id=None) latest_file_info = UploadedFile(id=latest_file_key, uploaded=False, blob_id=None) if not local_path or not local_path.exists(): msg = f"Expected to find file at {local_path}, but none was found." if skip_if_not_exists: logging.warning(msg) return versioned_file_info, latest_file_info raise FileNotFoundError(msg) file_name = local_path.name if override_destination_file_name is None else override_destination_file_name if upload_as_version: remote_upload_path = f"{gcp_connector_dir}/{version_folder}" versioned_uploaded, versioned_blob_id = upload_file_if_changed( local_file_path=local_path, bucket=bucket, blob_path=f"{remote_upload_path}/{file_name}", disable_cache=disable_cache, ) versioned_file_info = UploadedFile(id=versioned_file_key, uploaded=versioned_uploaded, blob_id=versioned_blob_id) if upload_as_latest: remote_upload_path = f"{gcp_connector_dir}/{LATEST_GCS_FOLDER_NAME}" latest_uploaded, latest_blob_id = upload_file_if_changed( local_file_path=local_path, bucket=bucket, blob_path=f"{remote_upload_path}/{file_name}", disable_cache=disable_cache, ) latest_file_info = UploadedFile(id=latest_file_key, uploaded=latest_uploaded, blob_id=latest_blob_id) return versioned_file_info, latest_file_info # 🔧 METADATA MODIFICATIONS def _apply_prerelease_overrides(metadata_dict: dict, validator_opts: ValidatorOptions) -> dict: """Apply any prerelease overrides to the metadata file before uploading it to GCS.""" if validator_opts.prerelease_tag is None: return metadata_dict # replace any dockerImageTag references with the actual tag # this includes metadata.data.dockerImageTag, metadata.data.registryOverrides[].dockerImageTag # where registries is a dictionary of registry name to registry object metadata_dict["data"]["dockerImageTag"] = validator_opts.prerelease_tag for registry in get(metadata_dict, "data.registryOverrides", {}).values(): if "dockerImageTag" in registry: registry["dockerImageTag"] = validator_opts.prerelease_tag return metadata_dict def _apply_author_info_to_metadata_file(metadata_dict: dict, original_metadata_file_path: Path) -> dict: """Apply author info to the metadata file before uploading it to GCS.""" git_info = _get_git_info_for_file(original_metadata_file_path) if git_info: # Apply to the nested / optional field at metadata.data.generated.git git_info_dict = to_json_sanitized_dict(git_info, exclude_none=True) metadata_dict = set_(metadata_dict, "data.generated.git", git_info_dict) return metadata_dict def _apply_python_components_sha_to_metadata_file( metadata_dict: dict, python_components_sha256: Optional[str] = None, ) -> dict: """If a `components.py` file is required, store the necessary information in the metadata. This adds a `required=True` flag and the sha256 hash of the `python_components.zip` file. This is a no-op if `python_components_sha256` is not provided. """ if python_components_sha256: metadata_dict = set_(metadata_dict, "data.generated.pythonComponents.required", True) metadata_dict = set_( metadata_dict, "data.generated.pythonComponents.sha256", python_components_sha256, ) return metadata_dict def _apply_sbom_url_to_metadata_file(metadata_dict: dict) -> dict: """Apply sbom url to the metadata file before uploading it to GCS.""" try: sbom_url = f"https://connectors.airbyte.com/files/sbom/{metadata_dict['data']['dockerRepository']}/{metadata_dict['data']['dockerImageTag']}.spdx.json" except KeyError: return metadata_dict response = requests.head(sbom_url) if response.ok: metadata_dict = set_(metadata_dict, "data.generated.sbomUrl", sbom_url) return metadata_dict def _apply_modifications_to_metadata_file( original_metadata_file_path: Path, validator_opts: ValidatorOptions, components_zip_sha256: str | None = None, ) -> Path: """Apply modifications to the metadata file before uploading it to GCS. e.g. The git commit hash, the date of the commit, the author of the commit, etc. Args: original_metadata_file_path (Path): Path to the original metadata file. validator_opts (ValidatorOptions): Options to use when validating the metadata file. components_zip_sha256 (str): The sha256 hash of the `python_components.zip` file. This is required if the `python_components.zip` file is present. """ metadata = _safe_load_metadata_file(original_metadata_file_path) metadata = _apply_prerelease_overrides(metadata, validator_opts) metadata = _apply_author_info_to_metadata_file(metadata, original_metadata_file_path) metadata = _apply_python_components_sha_to_metadata_file(metadata, components_zip_sha256) metadata = _apply_sbom_url_to_metadata_file(metadata) return _write_metadata_to_tmp_file(metadata) # 💎 Main Logic def upload_metadata_to_gcs(bucket_name: str, metadata_file_path: Path, validator_opts: ValidatorOptions) -> MetadataUploadInfo: """Upload a metadata file to a GCS bucket. If the per 'version' key already exists it won't be overwritten. Also updates the 'latest' key on each new version. Args: bucket_name (str): Name of the GCS bucket to which the metadata file will be uploade. metadata_file_path (Path): Path to the metadata file. service_account_file_path (Path): Path to the JSON file with the service account allowed to read and write on the bucket. prerelease_tag (Optional[str]): Whether the connector is a prerelease_tag or not. Returns: Tuple[bool, str]: Whether the metadata file was uploaded and its blob id. """ # Get our working directory working_directory = metadata_file_path.parent manifest_only_file_info = get_manifest_only_file_paths(working_directory) metadata_file_path = _apply_modifications_to_metadata_file( original_metadata_file_path=metadata_file_path, validator_opts=validator_opts, components_zip_sha256=manifest_only_file_info.sha256, ) metadata, error = validate_and_load(metadata_file_path, POST_UPLOAD_VALIDATORS, validator_opts) if metadata is None: raise ValueError(f"Metadata file {metadata_file_path} is invalid for uploading: {error}") is_pre_release = validator_opts.prerelease_tag is not None is_release_candidate = "-rc" in metadata.data.dockerImageTag should_upload_release_candidate = is_release_candidate and not is_pre_release should_upload_latest = not is_release_candidate and not is_pre_release storage_client = get_gcs_storage_client() bucket = storage_client.bucket(bucket_name) docs_path = Path(validator_opts.docs_path) gcp_connector_dir = f"{METADATA_FOLDER}/{metadata.data.dockerRepository}" # Upload version metadata and doc # If the connector is a pre-release, we use the pre-release tag as the version # Otherwise, we use the dockerImageTag from the metadata version_folder = metadata.data.dockerImageTag if not is_pre_release else validator_opts.prerelease_tag # Start uploading files uploaded_files = [] # Metadata upload metadata_files_uploaded = _file_upload( file_key="metadata", local_path=metadata_file_path, gcp_connector_dir=gcp_connector_dir, bucket=bucket, version_folder=version_folder, upload_as_version=True, upload_as_latest=should_upload_latest, disable_cache=True, override_destination_file_name=METADATA_FILE_NAME, ) uploaded_files.extend(metadata_files_uploaded) # Release candidate upload # We just upload the current metadata to the "release_candidate" path # The doc and inapp doc are not uploaded, which means that the release candidate will still point to the latest doc if should_upload_release_candidate: release_candidate_files_uploaded = _file_upload( file_key="release_candidate", local_path=metadata_file_path, gcp_connector_dir=gcp_connector_dir, bucket=bucket, version_folder=RELEASE_CANDIDATE_GCS_FOLDER_NAME, upload_as_version=True, upload_as_latest=False, disable_cache=True, override_destination_file_name=METADATA_FILE_NAME, ) uploaded_files.extend(release_candidate_files_uploaded) # Icon upload icon_files_uploaded = _file_upload( file_key="icon", local_path=working_directory / ICON_FILE_NAME, gcp_connector_dir=gcp_connector_dir, bucket=bucket, upload_as_version=False, upload_as_latest=should_upload_latest, ) uploaded_files.extend(icon_files_uploaded) # Doc upload local_doc_path = get_doc_local_file_path(docs_path, inapp=False) doc_files_uploaded = _file_upload( file_key="doc", local_path=local_doc_path, gcp_connector_dir=gcp_connector_dir, bucket=bucket, upload_as_version=True, version_folder=version_folder, upload_as_latest=should_upload_latest, override_destination_file_name=DOC_FILE_NAME, ) uploaded_files.extend(doc_files_uploaded) local_inapp_doc_path = get_doc_local_file_path(docs_path, inapp=True) inapp_doc_files_uploaded = _file_upload( file_key="inapp_doc", local_path=local_inapp_doc_path, gcp_connector_dir=gcp_connector_dir, bucket=bucket, upload_as_version=True, version_folder=version_folder, upload_as_latest=should_upload_latest, override_destination_file_name=DOC_INAPP_FILE_NAME, ) uploaded_files.extend(inapp_doc_files_uploaded) # Manifest and components upload manifest_files_uploaded = _file_upload( file_key="manifest", local_path=manifest_only_file_info.manifest_file_path, gcp_connector_dir=gcp_connector_dir, bucket=bucket, upload_as_version=True, version_folder=version_folder, upload_as_latest=should_upload_latest, override_destination_file_name=MANIFEST_FILE_NAME, ) uploaded_files.extend(manifest_files_uploaded) components_zip_sha256_files_uploaded = _file_upload( file_key="components_zip_sha256", local_path=manifest_only_file_info.sha256_file_path, gcp_connector_dir=gcp_connector_dir, bucket=bucket, upload_as_version=True, version_folder=version_folder, upload_as_latest=should_upload_latest, override_destination_file_name=COMPONENTS_ZIP_SHA256_FILE_NAME, ) uploaded_files.extend(components_zip_sha256_files_uploaded) components_zip_files_uploaded = _file_upload( file_key="components_zip", local_path=manifest_only_file_info.zip_file_path, gcp_connector_dir=gcp_connector_dir, bucket=bucket, upload_as_version=True, version_folder=version_folder, upload_as_latest=should_upload_latest, override_destination_file_name=COMPONENTS_ZIP_FILE_NAME, ) uploaded_files.extend(components_zip_files_uploaded) return MetadataUploadInfo( uploaded_files=uploaded_files, metadata_file_path=str(metadata_file_path), metadata_uploaded=_any_uploaded( uploaded_files, [ "latest_metadata", "version_metadata", "version_release_candidate", ], ), ) def delete_release_candidate_from_gcs(bucket_name: str, docker_repository: str, connector_version: str) -> MetadataDeleteInfo: """ Delete a release candidate from a GCS bucket. The release candidate and version metadata file will be deleted. We first check that the release candidate metadata file hash matches the version metadata file hash. Args: bucket_name (str): Name of the GCS bucket from which the release candidate will be deleted. docker_repository (str): Name of the connector docker image. connector_version (str): Version of the connector. Returns: MetadataDeleteInfo: Information about the files that were deleted. """ storage_client = get_gcs_storage_client() bucket = storage_client.bucket(bucket_name) gcp_connector_dir = f"{METADATA_FOLDER}/{docker_repository}" version_path = f"{gcp_connector_dir}/{connector_version}/{METADATA_FILE_NAME}" rc_path = f"{gcp_connector_dir}/{RELEASE_CANDIDATE_GCS_FOLDER_NAME}/{METADATA_FILE_NAME}" version_blob = bucket.blob(version_path) rc_blob = bucket.blob(rc_path) if not version_blob.exists(): raise FileNotFoundError(f"Version metadata file {version_path} does not exist in the bucket. ") if not rc_blob.exists(): raise FileNotFoundError(f"Release candidate metadata file {rc_path} does not exist in the bucket. ") if rc_blob.md5_hash != version_blob.md5_hash: raise ValueError( f"Release candidate metadata file {rc_path} hash does not match the version metadata file {version_path} hash. Unsafe to delete. Please check the Remote Release Candidate to confirm its the version you would like to remove and rerun with --force" ) deleted_files = [] rc_blob.delete() deleted_files.append( DeletedFile( id="release_candidate_metadata", deleted=True, description="release candidate metadata", blob_id=rc_blob.id, ) ) version_blob.delete() deleted_files.append( DeletedFile( id="version_metadata", deleted=True, description="versioned metadata", blob_id=version_blob.id, ) ) return MetadataDeleteInfo( metadata_deleted=True, deleted_files=deleted_files, ) def promote_release_candidate_in_gcs( bucket_name: str, docker_repository: str, connector_version: str ) -> Tuple[MetadataUploadInfo, MetadataDeleteInfo]: """Promote a release candidate to the latest version in a GCS bucket. The release candidate metadata file will be copied to the latest metadata file and then deleted. We first check that the release candidate metadata file hash matches the version metadata file hash. Args: bucket_name (str): Name of the GCS bucket from which the release candidate will be deleted. docker_repository (str): Name of the connector docker image. connector_version (str): Version of the connector. Returns: Tuple[MetadataUploadInfo, MetadataDeleteInfo]: Information about the files that were uploaded (new latest version) and deleted (release candidate). """ storage_client = get_gcs_storage_client() bucket = storage_client.bucket(bucket_name) gcp_connector_dir = f"{METADATA_FOLDER}/{docker_repository}" version_path = f"{gcp_connector_dir}/{connector_version}/{METADATA_FILE_NAME}" rc_path = f"{gcp_connector_dir}/{RELEASE_CANDIDATE_GCS_FOLDER_NAME}/{METADATA_FILE_NAME}" latest_path = f"{gcp_connector_dir}/{LATEST_GCS_FOLDER_NAME}/{METADATA_FILE_NAME}" version_blob = bucket.blob(version_path) latest_blob = bucket.blob(latest_path) rc_blob = bucket.blob(rc_path) if not version_blob.exists(): raise FileNotFoundError(f"Version metadata file {version_path} does not exist in the bucket.") if not rc_blob.exists(): raise FileNotFoundError(f"Release candidate metadata file {rc_path} does not exist in the bucket.") if rc_blob.md5_hash != version_blob.md5_hash: raise ValueError( f"""Release candidate metadata file {rc_path} hash does not match the version metadata file {version_path} hash. Unsafe to promote. It's likely that something changed the release candidate hash but have not changed the metadata for the lastest matching version.""" ) uploaded_files = [] deleted_files = [] bucket.copy_blob(rc_blob, bucket, latest_blob) uploaded_files.append( UploadedFile( id="latest_metadata", uploaded=True, blob_id=latest_blob.id, ) ) rc_blob.delete() deleted_files.append( DeletedFile( id="release_candidate_metadata", deleted=True, description="release candidate metadata", blob_id=rc_blob.id, ) ) return MetadataUploadInfo( metadata_uploaded=True, metadata_file_path=str(version_path), uploaded_files=uploaded_files, ), MetadataDeleteInfo( metadata_deleted=True, deleted_files=deleted_files, )
ManifestOnlyFilePaths
python
django-crispy-forms__django-crispy-forms
crispy_forms/layout.py
{ "start": 13301, "end": 15174 }
class ____(BaseInput): """ Used to create a Hidden input descriptor for the {% crispy %} template tag. Attributes ---------- template: str The default template which this Layout Object will be rendered with. field_classes: str CSS classes to be applied to the ``<input>``. input_type: str The ``type`` attribute of the ``<input>``. Parameters ---------- name : str The name attribute of the button. value : str The value attribute of the button. css_id : str, optional A custom DOM id for the layout object. If not provided the name argument is slugified and turned into the id for the submit button. By default None. css_class : str, optional Additional CSS classes to be applied to the ``<input>``. By default None. template : str, optional Overrides the default template, if provided. By default None. **kwargs : dict, optional Additional attributes are passed to `flatatt` and converted into key="value", pairs. These attributes are added to the ``<input>``. Examples -------- Note: ``form`` arg to ``render()`` is not required for ``BaseInput`` inherited objects. >>> hidden = Hidden("hidden", "hide-me") >>> hidden.render("", "", Context()) '<input type="hidden" name="hidden" value="hide-me"/>' Usually you will not call the render method on the object directly. Instead add it to your ``Layout`` manually or use the `add_input` method:: class ExampleForm(forms.Form): [...] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.add_input(Hidden("hidden", "hide-me")) """ input_type = "hidden" field_classes = "hidden"
Hidden
python
pytorch__pytorch
torch/_inductor/codegen/subgraph.py
{ "start": 6029, "end": 14655 }
class ____(KernelTemplate): """ A template for subgraph evaluation to be used in autotuning. This class allows creating customized subgraphs that can be appended as choices during the autotuning process, enabling the selection of optimal implementations for complex operations. """ index_counter = itertools.count() def __init__( self, name: str, ): """ Initialize a subgraph template. Args: name: The name of this template graph: The FX graph """ super().__init__(name=name) def generate( # type: ignore[override] self, name: str, input_nodes: list[Buffer], layout: Layout, make_fx_graph: Callable[..., Any], description: str = "", **kwargs: Any, ) -> SubgraphChoiceCaller: """ Generate a SubgraphChoiceCaller instance for autotuning. Args: name: The name for this subgraph choice input_nodes: List of input nodes to the subgraph layout: Memory layout information for the output make_fx_graph: Callable that creates the FX graph for this subgraph description: Optional description of this choice **kwargs: Additional keyword arguments Returns: SubgraphChoiceCaller: A callable object that can be used for autotuning """ return SubgraphChoiceCaller( name=f"{name}_{next(SubgraphTemplate.index_counter)}", input_nodes=input_nodes, layout=layout, description=description, make_fx_graph=make_fx_graph, ) def generate_custom_op_choices( self, name: str, decompositions: list[Callable[..., Any]], input_nodes: list[Buffer], non_tensor_args: list[dict[str, Any]], default_impl: Callable[..., Any] | None = None, ) -> list[SubgraphChoiceCaller]: """ Generate multiple SubgraphChoiceCaller instances for custom op autotuning. This method extends SubgraphTemplate to support custom op decompositions, allowing multiple implementations to compete in autotuning. Args: name: Base name for the choices decompositions: List of decomposition functions to compete in autotuning input_nodes: List of tensor inputs. All tensor arguments must be passed here. non_tensor_args: List of non-tensor kwargs only, one dict per corresponding decomposition. default_impl: Default implementation for layout inference Returns: List of SubgraphChoiceCaller instances for autotuning """ if not decompositions: return [] assert len(decompositions) == len(non_tensor_args), ( f"decompositions and non_tensor_args must have same length, " f"got {len(decompositions)} decompositions and {len(non_tensor_args)} kwargs" ) # Infer layouts and ensure layout consistency for fair autotuning comparison layouts = [ self._infer_custom_op_layout(input_nodes, decomp, kwargs, default_impl) for decomp, kwargs in zip(decompositions, non_tensor_args) ] # Validate all decompositions produce equivalent layouts for fair comparison self._validate_layout_equivalence(name, decompositions, layouts) layout = layouts[0] # All layouts are now validated to be equivalent choices: list[SubgraphChoiceCaller] = [] for decomp, decomp_kwargs in zip(decompositions, non_tensor_args): # Create make_fx_graph function for this decomposition import functools def make_fx_graph( *args: Any, decomp: Callable[..., Any] = decomp, decomp_kwargs: dict[str, Any] = decomp_kwargs, ) -> Any: # decomp_kwargs contains all merged parameters: CustomOpConfig params + runtime kwargs from torch.fx.experimental.proxy_tensor import make_fx from ..decomposition import select_decomp_table decomposition_table = select_decomp_table() return make_fx( functools.partial(decomp, **decomp_kwargs), decomposition_table=decomposition_table, )(*args) # Generate descriptive name for this variant variant_name = self._generate_variant_name(decomp, decomp_kwargs) choice = self.generate( name=f"{name}_{variant_name}", input_nodes=input_nodes, layout=layout, make_fx_graph=make_fx_graph, description=f"CustomOp {decomp.__name__}", ) choices.append(choice) return choices def _generate_variant_name( self, decomp: Callable[..., Any], kwargs: dict[str, Any] ) -> str: """Generate a descriptive name for a decomposition variant with its parameters.""" base_name = decomp.__name__ if not kwargs: return base_name param_suffix = "_".join(f"{k}_{v}" for k, v in sorted(kwargs.items())) return f"{base_name}_{param_suffix}" def _validate_non_tensor_kwargs(self, kwargs: dict[str, Any]) -> None: """Validate that kwargs contains only non-tensor arguments.""" for key, value in kwargs.items(): assert not isinstance(value, (torch.Tensor, Buffer)), ( f"kwargs['{key}'] contains tensor {type(value)}. " f"Tensor arguments should be in input_nodes, not kwargs. " f"Only scalar/non-tensor parameters should be in kwargs." ) def _validate_layout_equivalence( self, op_name: str, decompositions: list[Callable[..., Any]], layouts: list[Layout], ) -> None: """Ensure all layouts have consistent stride, device, dtype, and sizes for fair autotuning.""" if not layouts: return reference = layouts[0] for i, layout in enumerate(layouts[1:], start=1): if (layout.device, layout.dtype, layout.size, layout.stride) != ( reference.device, reference.dtype, reference.size, reference.stride, ): raise AssertionError( f"Layout mismatch in custom op '{op_name}': " f"decomposition '{decompositions[i].__name__}' produces " f"({layout.device}, {layout.dtype}, {layout.size}, {layout.stride}) " f"but '{decompositions[0].__name__}' produces " f"({reference.device}, {reference.dtype}, {reference.size}, {reference.stride})" ) def _infer_custom_op_layout( self, input_nodes: list[Buffer], function_decomposition: Callable[..., Any], kwargs: dict[str, Any], default_impl: Callable[..., Any] | None = None, ) -> Layout: """Infer output layout for custom ops using the default implementation when available. Note that the Subgraph assumes custom ops return exactly one tensor output. TODO: Add support for multiple output custom ops. """ import functools from torch._inductor.virtualized import V # Assert kwargs contain only non-tensor arguments self._validate_non_tensor_kwargs(kwargs) with V.fake_mode: example_inputs = [] for inp in input_nodes: raw_shape = inp.get_size() concrete_shape = V.graph.sizevars.size_hints( raw_shape, fallback=config.unbacked_symint_fallback ) fake_tensor = torch.empty( concrete_shape, dtype=inp.get_dtype(), device=inp.get_device() ) example_inputs.append(fake_tensor) fn = functools.partial(function_decomposition, **kwargs) output = fn(*example_inputs) # Assert single output assert isinstance(output, torch.Tensor), ( f"Expected single tensor output, got {type(output)}. " f"Multi-output custom ops not yet supported in autotuning." ) return FixedLayout( device=output.device, dtype=output.dtype, size=output.shape, stride=output.stride(), )
SubgraphTemplate
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 47296, "end": 47690 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("poll_option_id", "client_mutation_id") poll_option_id = sgqlc.types.Field( sgqlc.types.non_null(ID), graphql_name="pollOptionId" ) client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
AddDiscussionPollVoteInput
python
pallets__quart
src/quart/asgi.py
{ "start": 1565, "end": 6686 }
class ____: def __init__(self, app: Quart, scope: HTTPScope) -> None: self.app = app self.scope = scope async def __call__( self, receive: ASGIReceiveCallable, send: ASGISendCallable ) -> None: request = self._create_request_from_scope(send) receiver_task = asyncio.ensure_future(self.handle_messages(request, receive)) handler_task = asyncio.ensure_future(self.handle_request(request, send)) done, pending = await asyncio.wait( [handler_task, receiver_task], return_when=asyncio.FIRST_COMPLETED ) await cancel_tasks(pending) raise_task_exceptions(done) async def handle_messages( self, request: Request, receive: ASGIReceiveCallable ) -> None: while True: message = await receive() if message["type"] == "http.request": request.body.append(message.get("body", b"")) if not message.get("more_body", False): request.body.set_complete() elif message["type"] == "http.disconnect": return def _create_request_from_scope(self, send: ASGISendCallable) -> Request: headers = Headers() headers["Remote-Addr"] = (self.scope.get("client") or ["<local>"])[0] for name, value in self.scope["headers"]: headers.add(name.decode("latin1").title(), value.decode("latin1")) if self.scope["http_version"] < "1.1": headers.setdefault("Host", self.app.config["SERVER_NAME"] or "") path = self.scope["path"] path = path if path[0] == "/" else urlparse(path).path root_path = self.scope.get("root_path", "") if root_path != "": try: path = path.split(root_path, 1)[1] path = " " if path == "" else path except IndexError: path = " " # Invalid in paths, hence will result in 404 return self.app.request_class( self.scope["method"], self.scope["scheme"], path, self.scope["query_string"], headers, self.scope.get("root_path", ""), self.scope["http_version"], max_content_length=self.app.config["MAX_CONTENT_LENGTH"], body_timeout=self.app.config["BODY_TIMEOUT"], send_push_promise=partial(self._send_push_promise, send), scope=self.scope, ) async def handle_request(self, request: Request, send: ASGISendCallable) -> None: try: response = await self.app.handle_request(request) except Exception as error: response = await _handle_exception(self.app, error) if isinstance(response, Response) and response.timeout != Ellipsis: timeout = cast(Optional[float], response.timeout) else: timeout = self.app.config["RESPONSE_TIMEOUT"] try: await asyncio.wait_for(self._send_response(send, response), timeout=timeout) except asyncio.TimeoutError: pass async def _send_response( self, send: ASGISendCallable, response: ResponseTypes ) -> None: await send( cast( HTTPResponseStartEvent, { "type": "http.response.start", "status": response.status_code, "headers": encode_headers(response.headers), }, ) ) if isinstance(response, WerkzeugResponse): for data in response.response: body = data.encode() if isinstance(data, str) else data await send( cast( HTTPResponseBodyEvent, {"type": "http.response.body", "body": body, "more_body": True}, ) ) else: async with response.response as response_body: async for data in response_body: body = data.encode() if isinstance(data, str) else data await send( cast( HTTPResponseBodyEvent, { "type": "http.response.body", "body": body, "more_body": True, }, ) ) await send( cast( HTTPResponseBodyEvent, {"type": "http.response.body", "body": b"", "more_body": False}, ) ) async def _send_push_promise( self, send: ASGISendCallable, path: str, headers: Headers ) -> None: extensions = self.scope.get("extensions", {}) or {} if "http.response.push" in extensions: await send( { "type": "http.response.push", "path": path, "headers": encode_headers(headers), } )
ASGIHTTPConnection
python
SmileyChris__easy-thumbnails
easy_thumbnails/migrations/0002_thumbnaildimensions.py
{ "start": 43, "end": 760 }
class ____(migrations.Migration): dependencies = [ ('easy_thumbnails', '0001_initial'), ] operations = [ migrations.CreateModel( name='ThumbnailDimensions', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('thumbnail', models.OneToOneField(on_delete=models.CASCADE, related_name='dimensions', to='easy_thumbnails.Thumbnail')), ('width', models.PositiveIntegerField(null=True)), ('height', models.PositiveIntegerField(null=True)), ], options={ }, bases=(models.Model,), ), ]
Migration
python
kamyu104__LeetCode-Solutions
Python/largest-sum-of-averages.py
{ "start": 36, "end": 824 }
class ____(object): def largestSumOfAverages(self, A, K): """ :type A: List[int] :type K: int :rtype: float """ accum_sum = [A[0]] for i in xrange(1, len(A)): accum_sum.append(A[i]+accum_sum[-1]) dp = [[0]*len(A) for _ in xrange(2)] for k in xrange(1, K+1): for i in xrange(k-1, len(A)): if k == 1: dp[k % 2][i] = float(accum_sum[i])/(i+1) else: for j in xrange(k-2, i): dp[k % 2][i] = \ max(dp[k % 2][i], dp[(k-1) % 2][j] + float(accum_sum[i]-accum_sum[j])/(i-j)) return dp[K % 2][-1]
Solution
python
dagster-io__dagster
examples/docs_projects/project_prompt_eng/src/project_prompt_eng/defs/resources.py
{ "start": 202, "end": 1245 }
class ____(dg.ConfigurableResource): api_key: str = Field(description=("NREL API key. See https://developer.nrel.gov/signup/")) def alt_fuel_stations(self, latitude: float, longitude: float, fuel_type: str = "all"): if fuel_type not in {"BD", "ELEC", "all"}: raise ValueError(f"{fuel_type} is not a valid fuel type") url = "https://developer.nrel.gov/api/alt-fuel-stations/v1/nearest.json" params = { "api_key": self.api_key, "latitude": latitude, "longitude": longitude, "radius": 5.0, "fuel_type": fuel_type, "status": "E", } resp = requests.get(url, params=params) return resp.json()["fuel_stations"] # end_resource @dg.definitions def resources() -> dg.Definitions: return dg.Definitions( resources={ "nrel": NRELResource(api_key=dg.EnvVar("NREL_API_KEY")), "anthropic": AnthropicResource(api_key=dg.EnvVar("ANTHROPIC_API_KEY")), }, )
NRELResource
python
ansible__ansible
test/lib/ansible_test/_internal/data.py
{ "start": 905, "end": 1074 }
class ____: """Configuration required to build a source tree payload for delegation.""" files: list[tuple[str, str]] permissions: dict[str, int]
PayloadConfig
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_lookup.py
{ "start": 9566, "end": 13880 }
class ____(Foo): pass st.register_type_strategy(Bar, st.builds(Bar, st.integers())) st.register_type_strategy(Baz, st.builds(Baz, st.integers())) @pytest.mark.parametrize( "var,expected", [ (typing.TypeVar("V"), object), (typing.TypeVar("V", bound=int), int), (typing.TypeVar("V", bound=Foo), (Bar, Baz)), (typing.TypeVar("V", bound=int | str), (int, str)), (typing.TypeVar("V", int, str), (int, str)), ], ) @settings(suppress_health_check=[HealthCheck.too_slow]) @given(data=st.data()) def test_typevar_type_is_consistent(data, var, expected): strat = st.from_type(var) v1 = data.draw(strat) v2 = data.draw(strat) assume(v1 != v2) # Values may vary, just not types assert type(v1) == type(v2) assert isinstance(v1, expected) def test_distinct_typevars_same_constraint(): A = typing.TypeVar("A", int, str) B = typing.TypeVar("B", int, str) find_any( st.tuples(st.from_type(A), st.from_type(B)), lambda ab: type(ab[0]) != type(ab[1]), ) def test_distinct_typevars_distinct_type(): """Ensures that two different type vars have at least one different type in their strategies.""" A = typing.TypeVar("A") B = typing.TypeVar("B") find_any( st.tuples(st.from_type(A), st.from_type(B)), lambda ab: type(ab[0]) != type(ab[1]), ) A = typing.TypeVar("A") def same_type_args(a: A, b: A): assert type(a) == type(b) @given(st.builds(same_type_args)) def test_same_typevars_same_type(_): """Ensures that single type argument will always have the same type in a single context.""" def test_typevars_can_be_redefined(): """We test that one can register a custom strategy for all type vars.""" A = typing.TypeVar("A") with temp_registered(typing.TypeVar, st.just(1)): assert_all_examples(st.from_type(A), lambda obj: obj == 1) def test_typevars_can_be_redefine_with_factory(): """We test that one can register a custom strategy for all type vars.""" A = typing.TypeVar("A") with temp_registered(typing.TypeVar, lambda thing: st.just(thing.__name__)): assert_all_examples(st.from_type(A), lambda obj: obj == "A") def test_typevars_can_be_resolved_conditionally(): sentinel = object() A = typing.TypeVar("A") B = typing.TypeVar("B") def resolve_type_var(thing): assert thing in (A, B) if thing == A: return st.just(sentinel) return NotImplemented with temp_registered(typing.TypeVar, resolve_type_var): assert_simple_property(st.from_type(A), lambda x: x is sentinel) # We've re-defined the default TypeVar resolver, so there is no fallback. # This causes the lookup to fail. with pytest.raises(InvalidArgument): check_can_generate_examples(st.from_type(B)) def annotated_func(a: int, b: int = 2, *, c: int, d: int = 4): return a + b + c + d def test_issue_946_regression(): # Turned type hints into kwargs even if the required posarg was passed check_can_generate_examples(st.builds(annotated_func, st.integers())) @pytest.mark.parametrize( "thing", [ annotated_func, # Works via typing.get_type_hints typing.NamedTuple("N", [("a", int)]), # Falls back to inspection int, # Fails; returns empty dict ], ) def test_can_get_type_hints(thing): assert isinstance(get_type_hints(thing), dict) def test_force_builds_to_infer_strategies_for_default_args(): # By default, leaves args with defaults and minimises to 2+4=6 assert minimal(st.builds(annotated_func), lambda ex: True) == 6 # Inferring integers() for args makes it minimise to zero assert minimal(st.builds(annotated_func, b=..., d=...), lambda ex: True) == 0 def non_annotated_func(a, b=2, *, c, d=4): pass def test_cannot_pass_infer_as_posarg(): with pytest.raises(InvalidArgument): check_can_generate_examples(st.builds(annotated_func, ...)) def test_cannot_force_inference_for_unannotated_arg(): with pytest.raises(InvalidArgument): check_can_generate_examples(st.builds(non_annotated_func, a=..., c=st.none())) with pytest.raises(InvalidArgument): check_can_generate_examples(st.builds(non_annotated_func, a=st.none(), c=...))
Baz
python
run-llama__llama_index
llama-index-integrations/indices/llama-index-indices-managed-llama-cloud/llama_index/indices/managed/llama_cloud/composite_retriever.py
{ "start": 936, "end": 11748 }
class ____(BaseRetriever): def __init__( self, # retriever identifier name: Optional[str] = None, retriever_id: Optional[str] = None, # project identifier project_name: Optional[str] = DEFAULT_PROJECT_NAME, project_id: Optional[str] = None, organization_id: Optional[str] = None, # creation options create_if_not_exists: bool = False, # connection params api_key: Optional[str] = None, base_url: Optional[str] = None, app_url: Optional[str] = None, timeout: int = 60, httpx_client: Optional[httpx.Client] = None, async_httpx_client: Optional[httpx.AsyncClient] = None, # composite retrieval params mode: Optional[CompositeRetrievalMode] = None, rerank_top_n: Optional[int] = None, rerank_config: Optional[ReRankConfig] = None, persisted: Optional[bool] = True, **kwargs: Any, ) -> None: """Initialize the Composite Retriever.""" # initialize clients self._client = get_client(api_key, base_url, app_url, timeout, httpx_client) self._aclient = get_aclient( api_key, base_url, app_url, timeout, async_httpx_client ) self.project = resolve_project( self._client, project_name, project_id, organization_id ) self.name = name self.project_name = self.project.name self._persisted = persisted self.retriever = resolve_retriever( self._client, self.project, name, retriever_id, persisted ) if self.retriever is None and persisted: if create_if_not_exists: self.retriever = self._client.retrievers.upsert_retriever( project_id=self.project.id, request=RetrieverCreate(name=self.name, pipelines=[]), ) else: raise ValueError( f"Retriever with name '{self.name}' does not exist in project." ) # composite retrieval params self._mode = mode if mode is not None else OMIT self._rerank_top_n = rerank_top_n if rerank_top_n is not None else OMIT self._rerank_config = rerank_config if rerank_config is not None else OMIT super().__init__( callback_manager=kwargs.get("callback_manager"), verbose=kwargs.get("verbose", False), ) @property def retriever_pipelines(self) -> List[RetrieverPipeline]: return self.retriever.pipelines or [] def update_retriever_pipelines( self, pipelines: List[RetrieverPipeline] ) -> Retriever: if self._persisted: self.retriever = self._client.retrievers.update_retriever( self.retriever.id, pipelines=pipelines ) else: # Update in-memory retriever for non-persisted case using copy self.retriever = self.retriever.copy(update={"pipelines": pipelines}) return self.retriever def add_index( self, index: LlamaCloudIndex, name: Optional[str] = None, description: Optional[str] = None, preset_retrieval_parameters: Optional[PresetRetrievalParams] = None, ) -> Retriever: name = name or index.name preset_retrieval_parameters = ( preset_retrieval_parameters or index.pipeline.preset_retrieval_parameters ) retriever_pipeline = RetrieverPipeline( pipeline_id=index.id, name=name, description=description, preset_retrieval_parameters=preset_retrieval_parameters, ) current_retriever_pipelines_by_name = { pipeline.name: pipeline for pipeline in (self.retriever_pipelines or []) } current_retriever_pipelines_by_name[retriever_pipeline.name] = ( retriever_pipeline ) return self.update_retriever_pipelines( list(current_retriever_pipelines_by_name.values()) ) def remove_index(self, name: str) -> bool: current_retriever_pipeline_names = self.retriever.pipelines or [] new_retriever_pipelines = [ pipeline for pipeline in current_retriever_pipeline_names if pipeline.name != name ] if len(new_retriever_pipelines) == len(current_retriever_pipeline_names): return False self.update_retriever_pipelines(new_retriever_pipelines) return True async def aupdate_retriever_pipelines( self, pipelines: List[RetrieverPipeline] ) -> Retriever: if self._persisted: self.retriever = await self._aclient.retrievers.update_retriever( self.retriever.id, pipelines=pipelines ) else: # Update in-memory retriever for non-persisted case using copy self.retriever = self.retriever.copy(update={"pipelines": pipelines}) return self.retriever async def async_add_index( self, index: LlamaCloudIndex, name: Optional[str] = None, description: Optional[str] = None, preset_retrieval_parameters: Optional[PresetRetrievalParams] = None, ) -> Retriever: name = name or index.name preset_retrieval_parameters = ( preset_retrieval_parameters or index.pipeline.preset_retrieval_parameters ) retriever_pipeline = RetrieverPipeline( pipeline_id=index.id, name=name, description=description, preset_retrieval_parameters=preset_retrieval_parameters, ) current_retriever_pipelines_by_name = { pipeline.name: pipeline for pipeline in (self.retriever_pipelines or []) } current_retriever_pipelines_by_name[retriever_pipeline.name] = ( retriever_pipeline ) return await self.aupdate_retriever_pipelines( list(current_retriever_pipelines_by_name.values()) ) async def aremove_index(self, name: str) -> bool: current_retriever_pipeline_names = self.retriever.pipelines or [] new_retriever_pipelines = [ pipeline for pipeline in current_retriever_pipeline_names if pipeline.name != name ] if len(new_retriever_pipelines) == len(current_retriever_pipeline_names): return False await self.aupdate_retriever_pipelines(new_retriever_pipelines) return True def _result_nodes_to_node_with_score( self, composite_retrieval_node: CompositeRetrievedTextNodeWithScore ) -> NodeWithScore: return NodeWithScore( node=TextNode( id=composite_retrieval_node.node.id, text=composite_retrieval_node.node.text, metadata=composite_retrieval_node.node.metadata, ), score=composite_retrieval_node.score, ) def _retrieve( self, query_bundle: QueryBundle, mode: Optional[CompositeRetrievalMode] = None, rerank_top_n: Optional[int] = None, rerank_config: Optional[ReRankConfig] = None, ) -> List[NodeWithScore]: mode = mode if mode is not None else self._mode rerank_top_n = rerank_top_n if rerank_top_n is not None else self._rerank_top_n rerank_config = ( rerank_config if rerank_config is not None else self._rerank_config ) # Inject rerank_top_n into rerank_config if specified if rerank_top_n is not None and rerank_top_n != OMIT: if rerank_config is None or rerank_config == OMIT: rerank_config = ReRankConfig(top_n=rerank_top_n) else: # Update existing rerank_config with top_n rerank_config = rerank_config.copy(update={"top_n": rerank_top_n}) if self._persisted: result = self._client.retrievers.retrieve( self.retriever.id, mode=mode, rerank_config=rerank_config, query=query_bundle.query_str, ) else: result = self._client.retrievers.direct_retrieve( project_id=self.project.id, mode=mode, rerank_config=rerank_config, query=query_bundle.query_str, pipelines=self.retriever.pipelines, ) node_w_scores = [ self._result_nodes_to_node_with_score(node) for node in result.nodes ] image_nodes_w_scores = page_screenshot_nodes_to_node_with_score( self._client, result.image_nodes, self.retriever.project_id ) return sorted( node_w_scores + image_nodes_w_scores, key=lambda x: x.score, reverse=True ) async def _aretrieve( self, query_bundle: QueryBundle, mode: Optional[CompositeRetrievalMode] = None, rerank_top_n: Optional[int] = None, rerank_config: Optional[ReRankConfig] = None, ) -> List[NodeWithScore]: mode = mode if mode is not None else self._mode rerank_top_n = rerank_top_n if rerank_top_n is not None else self._rerank_top_n rerank_config = ( rerank_config if rerank_config is not None else self._rerank_config ) # Inject rerank_top_n into rerank_config if specified if rerank_top_n is not None and rerank_top_n != OMIT: if rerank_config is None or rerank_config == OMIT: rerank_config = ReRankConfig(top_n=rerank_top_n) else: # Update existing rerank_config with top_n rerank_config = rerank_config.copy(update={"top_n": rerank_top_n}) if self._persisted: result = await self._aclient.retrievers.retrieve( self.retriever.id, mode=mode, rerank_config=rerank_config, query=query_bundle.query_str, ) else: result = await self._aclient.retrievers.direct_retrieve( project_id=self.project.id, mode=mode, rerank_config=rerank_config, query=query_bundle.query_str, pipelines=self.retriever.pipelines, ) node_w_scores = [ self._result_nodes_to_node_with_score(node) for node in result.nodes ] image_nodes_w_scores = page_screenshot_nodes_to_node_with_score( self._aclient, result.image_nodes, self.retriever.project_id ) return sorted( node_w_scores + image_nodes_w_scores, key=lambda x: x.score, reverse=True )
LlamaCloudCompositeRetriever
python
django-mptt__django-mptt
tests/myapp/tests.py
{ "start": 77937, "end": 81040 }
class ____(TreeTestCase): def setUp(self): self.user = User.objects.create_superuser("admin", "test@example.com", "p") self.client.login(username=self.user.username, password="p") def test_changelist(self): p1 = Person.objects.create(name="Franz") p2 = Person.objects.create(name="Fritz") p3 = Person.objects.create(name="Hans") self.assertNotEqual(p1._mpttfield("tree_id"), p2._mpttfield("tree_id")) response = self.client.get("/admin/myapp/person/") self.assertContains(response, 'class="drag-handle"', 3) self.assertContains(response, 'style="text-indent:0px"', 3) self.assertContains( response, 'src="/static/mptt/draggable-admin.js" data-context="{&quot;', ) self.assertContains(response, '}" id="draggable-admin-context"></script>') response = self.client.post( "/admin/myapp/person/", { "cmd": "move_node", "cut_item": p1.pk, "pasted_on": p2.pk, "position": "last-child", }, HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) self.assertEqual(response.status_code, 200) p1.refresh_from_db() p2.refresh_from_db() self.assertEqual(p1.parent, p2) self.assertTreeEqual( Person.objects.all(), """ 2 - 2 0 1 4 1 2 2 1 2 3 3 - 3 0 1 2 """, ) response = self.client.get("/admin/myapp/person/") self.assertContains(response, 'style="text-indent:0px"', 2) self.assertContains(response, 'style="text-indent:20px"', 1) response = self.client.post( "/admin/myapp/person/", { "cmd": "move_node", "cut_item": p3.pk, "pasted_on": p1.pk, "position": "left", }, HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) self.assertEqual(response.status_code, 200) self.assertTreeEqual( Person.objects.all(), """ 2 - 2 0 1 6 3 2 2 1 2 3 1 2 2 1 4 5 """, ) response = self.client.post( "/admin/myapp/person/", { "action": "delete_selected", "_selected_action": [1], }, ) if django.VERSION < (5, 2): self.assertContains(response, "Are you sure?") else: self.assertContains(response, "Delete multiple objects") response = self.client.post( "/admin/myapp/person/", { "action": "delete_selected", "_selected_action": [1], "post": "yes", }, ) self.assertRedirects(response, "/admin/myapp/person/") self.assertTreeEqual( Person.objects.all(), """ 2 - 2 0 1 4 3 2 2 1 2 3 """, )
DraggableMPTTAdminTestCase
python
modin-project__modin
modin/config/envvars.py
{ "start": 37824, "end": 38006 }
class ____(EnvironmentVariable, type=bool): """Set to true to test reading from Postgres.""" varname = "MODIN_TEST_READ_FROM_POSTGRES" default = False
TestReadFromPostgres
python
airbytehq__airbyte
airbyte-integrations/connectors/source-appsflyer/source_appsflyer/source.py
{ "start": 12544, "end": 12859 }
class ____(AggregateDataMixin, IncrementalAppsflyerStream): def path( self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None ) -> str: return f"agg-data/export/app/{self.app_id}/partners_by_date_report/v5"
PartnersReport
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 208196, "end": 208857 }
class ____(sgqlc.types.Input): """Autogenerated input type of CreateTeamDiscussionComment""" __schema__ = github_schema __field_names__ = ("discussion_id", "body", "client_mutation_id") discussion_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="discussionId") """The ID of the discussion to which the comment belongs.""" body = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="body") """The content of the comment.""" client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation."""
CreateTeamDiscussionCommentInput
python
doocs__leetcode
solution/0700-0799/0737.Sentence Similarity II/Solution.py
{ "start": 0, "end": 1033 }
class ____: def areSentencesSimilarTwo( self, sentence1: List[str], sentence2: List[str], similarPairs: List[List[str]] ) -> bool: if len(sentence1) != len(sentence2): return False n = len(similarPairs) p = list(range(n << 1)) def find(x): if p[x] != x: p[x] = find(p[x]) return p[x] words = {} idx = 0 for a, b in similarPairs: if a not in words: words[a] = idx idx += 1 if b not in words: words[b] = idx idx += 1 p[find(words[a])] = find(words[b]) for i in range(len(sentence1)): if sentence1[i] == sentence2[i]: continue if ( sentence1[i] not in words or sentence2[i] not in words or find(words[sentence1[i]]) != find(words[sentence2[i]]) ): return False return True
Solution
python
fluentpython__example-code-2e
24-class-metaprog/checked/decorator/checkeddeco_demo.py
{ "start": 66, "end": 727 }
class ____: title: str year: int box_office: float if __name__ == '__main__': # No static type checker can understand this... movie = Movie(title='The Godfather', year=1972, box_office=137) # type: ignore print(movie.title) print(movie) try: # remove the "type: ignore" comment to see Mypy correctly spot the error movie.year = 'MCMLXXII' # type: ignore except TypeError as e: print(e) try: # Again, no static type checker can understand this... blockbuster = Movie(title='Avatar', year=2009, box_office='billions') # type: ignore except TypeError as e: print(e)
Movie
python
getsentry__sentry
tools/flake8_plugin.py
{ "start": 1487, "end": 6285 }
class ____(ast.NodeVisitor): def __init__(self, filename: str) -> None: self.errors: list[tuple[int, int, str]] = [] self.filename = filename self._except_vars: list[str | None] = [] def visit_ImportFrom(self, node: ast.ImportFrom) -> None: if node.module and not node.level: if node.module.split(".")[0] in S003_modules: self.errors.append((node.lineno, node.col_offset, S003_msg)) elif node.module == "sentry.models": self.errors.append((node.lineno, node.col_offset, S005_msg)) elif ( ("tests/" in self.filename or "testutils/" in self.filename) and node.module == "django.utils.encoding" and any(x.name in {"force_bytes", "force_str"} for x in node.names) ): self.errors.append((node.lineno, node.col_offset, S006_msg)) elif ( "tests/" in self.filename or "testutils/" in self.filename ) and node.module == "dateutil.parser": self.errors.append((node.lineno, node.col_offset, S008_msg)) elif ( "tests/" not in self.filename and "fixtures/" not in self.filename and "sentry/testutils/" not in self.filename and "sentry.testutils" in node.module ): self.errors.append((node.lineno, node.col_offset, S007_msg)) elif node.module == "rest_framework.permissions" and any( x.name == "IsAuthenticated" for x in node.names ): self.errors.append((node.lineno, node.col_offset, S012_msg)) elif node.module == "sentry.db.models.fields.array": self.errors.append((node.lineno, node.col_offset, S013_msg)) self.generic_visit(node) def visit_Import(self, node: ast.Import) -> None: for alias in node.names: if alias.name.split(".")[0] in S003_modules: self.errors.append((node.lineno, node.col_offset, S003_msg)) elif ( "tests/" not in self.filename and "fixtures/" not in self.filename and "sentry/testutils/" not in self.filename and "sentry.testutils" in alias.name ): self.errors.append((node.lineno, node.col_offset, S007_msg)) self.generic_visit(node) def visit_Attribute(self, node: ast.Attribute) -> None: if node.attr in S001_methods: self.errors.append((node.lineno, node.col_offset, S001_fmt.format(node.attr))) elif node.attr in S004_methods: self.errors.append((node.lineno, node.col_offset, S004_msg)) self.generic_visit(node) def visit_Name(self, node: ast.Name) -> None: if node.id == "print": self.errors.append((node.lineno, node.col_offset, S002_msg)) self.generic_visit(node) def visit_arg(self, node: ast.arg) -> None: if node.arg == "monkeypatch": self.errors.append((node.lineno, node.col_offset, S014_msg)) self.generic_visit(node) def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None: self._except_vars.append(node.name) try: self.generic_visit(node) finally: self._except_vars.pop() def visit_Raise(self, node: ast.Raise) -> None: if ( self._except_vars and isinstance(node.exc, ast.Name) and node.exc.id == self._except_vars[-1] ): self.errors.append((node.lineno, node.col_offset, S009_msg)) self.generic_visit(node) def visit_Try(self, node: ast.Try) -> None: if ( node.handlers and len(node.handlers[-1].body) == 1 and isinstance(node.handlers[-1].body[0], ast.Raise) and node.handlers[-1].body[0].exc is None ): self.errors.append((node.handlers[-1].lineno, node.handlers[-1].col_offset, S010_msg)) self.generic_visit(node) def visit_Call(self, node: ast.Call) -> None: if ( # override_settings(...) (isinstance(node.func, ast.Name) and node.func.id == "override_settings") or # self.settings(...) ( isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) and node.func.value.id == "self" and node.func.attr == "settings" ) ): for keyword in node.keywords: if keyword.arg == "SENTRY_OPTIONS": self.errors.append((keyword.lineno, keyword.col_offset, S011_msg)) self.generic_visit(node)
SentryVisitor
python
pytorch__pytorch
test/dynamo/test_profiler.py
{ "start": 278, "end": 6910 }
class ____(torch._dynamo.test_case.TestCase): def test_dynamo_timed_profiling_isolated(self): # dynamo_timed functions should appear in profile traces. def inner_fn(x): with dynamo_timed("inner_fn"): return x.sin() def outer_fn(x, y): return inner_fn(x) * y x, y = (torch.rand((2, 2)) for _ in range(2)) with torch.profiler.profile(with_stack=False) as prof: outer_fn(x, y) self.assertTrue( any("inner_fn (dynamo_timed)" in evt.name for evt in prof.events()) ) def test_dynamo_timed_profiling_backend_compile(self): # dynamo_timed functions should appear in profile traces. # this checks whether these actually appear in actual dynamo execution. # "backend_compile" is just chosen as an example; if it gets renamed # this test can be replaced or deleted fn_name = "call_user_compiler" def fn(x, y): return x.sin() * y.cos() x, y = (torch.rand((2, 2)) for _ in range(2)) with torch.profiler.profile(with_stack=False) as prof: torch.compile(fn, backend="aot_eager")(x, y) self.assertTrue( any(f"{fn_name} (dynamo_timed)" in evt.name for evt in prof.events()) ) @patch.object(torch._dynamo.config, "assume_static_by_default", False) def test_profile_dynamic_shapes_runtime(self): def fn(x, y, z): return x @ y + z opt_fn = torch.compile(fn, backend="aot_eager", dynamic=True, fullgraph=True) inputs = [ (torch.rand(a, b), torch.rand(b, c), torch.rand(a, c)) for (a, b, c) in [(15, 16, 17), (15, 15, 16), (16, 16, 16)] ] opt_fn(*inputs[0]) opt_fn(*inputs[1]) with torch.profiler.profile(record_shapes=True): opt_fn(*inputs[2]) @patch.object(torch._dynamo.config, "assume_static_by_default", False) def test_profile_dynamic_shapes_compilation(self): def fn(x, y, z): return x @ y + z opt_fn = torch.compile(fn, backend="aot_eager", dynamic=True, fullgraph=True) inputs = (torch.rand(15, 16), torch.rand(16, 17), torch.rand(15, 17)) with torch.profiler.profile(record_shapes=True): opt_fn(*inputs) @patch.object(torch._dynamo.config, "assume_static_by_default", False) def test_profile_dynamic_shapes_list_compilation(self): def fn(x, y, z): return torch.cat([x, y], dim=0) + z opt_fn = torch.compile(fn, backend="aot_eager", dynamic=True, fullgraph=True) inputs = (torch.rand(4, 16), torch.rand(12, 16), torch.rand(16, 16)) with torch.profiler.profile(record_shapes=True): opt_fn(*inputs) def test_execution_trace_dynamic_shapes(self): def fn(x, y, z): return x @ y + z et = torch.profiler.ExecutionTraceObserver() opt_fn = torch.compile(fn, dynamic=True, backend="aot_eager") inputs = [torch.rand((4, 4)) for _ in range(3)] with TemporaryFileName() as fname: et.register_callback(fname) et.start() opt_fn(*inputs) et.stop() et.unregister_callback() def test_profiler_cache_lookup(self): def fn(x): y = x**2 y = y + 2 z = y**3 return z for profiler, get_events in ( (torch.autograd.profiler.profile, lambda prof: prof.function_events), (torch.profiler.profiler.profile, lambda prof: prof.events()), ): x = torch.randn((2, 2), requires_grad=True) ref = fn(x) opt_fn = torch.compile(fn, backend="aot_eager") # warmup opt_fn(x) with profiler() as prof: res = opt_fn(x) events = list( filter( lambda event: "TorchDynamo Cache Lookup" in event.name, get_events(prof), ) ) self.assertEqual(ref, res) self.assertTrue( len(events) == 1, "Expected one lookup profiler event for one opt_fn run", ) def test_profiler_cache_lookup_profiler_step(self): def fn(x, y, z): return torch.add(torch.sub(x, y), z) opt_fn = torch.compile(fn, backend="aot_eager") ( x, y, z, ) = (torch.rand(4, 4) for _ in range(3)) prof = torch.profiler.profile( schedule=torch.profiler.schedule(wait=2, warmup=2, active=2, repeat=1) ) for _ in range(10): opt_fn(x, y, z) prof.step() self.assertTrue( any(e.name == "TorchDynamo Cache Lookup" for e in prof.events()) ) def test_profiler_enabled_export(self): class Mod(torch.nn.Module): def __init__(self): super().__init__() def forward(self, x): x = torch.sin(x) if torch.autograd._profiler_enabled(): return torch.cos(x) else: return torch.sigmoid(x) mod = Mod() x = torch.randn(4) opt_mod = torch._dynamo.export(mod, (x)) ref = mod(x) res = opt_mod.graph_module(x) self.assertEqual(ref, res) with torch.autograd.profiler.profile(): ref = mod(x) # Reexport because export skips guards opt_mod = torch._dynamo.export(mod, (x)) res = opt_mod.graph_module(x) self.assertEqual(ref, res) def test_profiler_dynamo_compiled_region(self): def fn(x, y): r = y.sum(dim=1) print(r.shape) return x * r with torch.profiler.profile() as prof: fn_c = torch.compile(fn) fn_c( torch.randn(10), torch.randn(10, 10), ) fn_c( torch.randn(10), torch.randn(10, 15), ) annotations = [e.name for e in prof.events() if "Torch-Compiled" in e.name] self.assertEqual( annotations, [ "Torch-Compiled Region: 0/0", "Torch-Compiled Region: 1/0", "Torch-Compiled Region: 0/1", "Torch-Compiled Region: 1/0", ], ) if __name__ == "__main__": from torch._dynamo.test_case import run_tests run_tests()
DynamoProfilerTests
python
pallets__click
src/click/types.py
{ "start": 21650, "end": 23787 }
class ____(ParamType): name = "boolean" bool_states: dict[str, bool] = { "1": True, "0": False, "yes": True, "no": False, "true": True, "false": False, "on": True, "off": False, "t": True, "f": False, "y": True, "n": False, # Absence of value is considered False. "": False, } """A mapping of string values to boolean states. Mapping is inspired by :py:attr:`configparser.ConfigParser.BOOLEAN_STATES` and extends it. .. caution:: String values are lower-cased, as the ``str_to_bool`` comparison function below is case-insensitive. .. warning:: The mapping is not exhaustive, and does not cover all possible boolean strings representations. It will remains as it is to avoid endless bikeshedding. Future work my be considered to make this mapping user-configurable from public API. """ @staticmethod def str_to_bool(value: str | bool) -> bool | None: """Convert a string to a boolean value. If the value is already a boolean, it is returned as-is. If the value is a string, it is stripped of whitespaces and lower-cased, then checked against the known boolean states pre-defined in the `BoolParamType.bool_states` mapping above. Returns `None` if the value does not match any known boolean state. """ if isinstance(value, bool): return value return BoolParamType.bool_states.get(value.strip().lower()) def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> bool: normalized = self.str_to_bool(value) if normalized is None: self.fail( _( "{value!r} is not a valid boolean. Recognized values: {states}" ).format(value=value, states=", ".join(sorted(self.bool_states))), param, ctx, ) return normalized def __repr__(self) -> str: return "BOOL"
BoolParamType
python
Lightning-AI__lightning
src/lightning/pytorch/callbacks/model_checkpoint.py
{ "start": 1538, "end": 51578 }
class ____(Checkpoint): r"""Save the model after every epoch by monitoring a quantity. Every logged metrics are passed to the :class:`~lightning.pytorch.loggers.logger.Logger` for the version it gets saved in the same directory as the checkpoint. After training finishes, use :attr:`best_model_path` to retrieve the path to the best checkpoint file and :attr:`best_model_score` to get its score. .. note:: When using manual optimization with ``every_n_train_steps``, you should save the model state in your ``training_step`` before the optimizer step if you want the checkpoint to reflect the pre-optimization state. Example: .. code-block:: python def training_step(self, batch, batch_idx): # ... forward pass, loss calculation, backward pass ... # Save model state before optimization if not hasattr(self, 'saved_models'): self.saved_models = {} self.saved_models[batch_idx] = { k: v.detach().clone() for k, v in self.layer.state_dict().items() } # Then perform optimization optimizer.zero_grad() self.manual_backward(loss) optimizer.step() # Optional: Clean up old states to save memory if batch_idx > 10: # Keep last 10 states del self.saved_models[batch_idx - 10] Args: dirpath: Directory to save the model file. Example: ``dirpath='my/path/'``. .. warning:: In a distributed environment like DDP, it's recommended to provide a `dirpath` to avoid race conditions. When using manual optimization with ``every_n_train_steps``, make sure to save the model state in your training loop as shown in the example above. Can be remote file paths such as `s3://mybucket/path/` or 'hdfs://path/' (default: ``None``). If dirpath is ``None``, we only keep the ``k`` best checkpoints in memory, and do not save anything to disk. filename: Checkpoint filename. Can contain named formatting options to be auto-filled. If no name is provided, it will be ``None`` and the checkpoint will be saved to ``{epoch}``.and if the Trainer uses a logger, the path will also contain logger name and version. filename: checkpoint filename. Can contain named formatting options to be auto-filled. Example:: # save any arbitrary metrics like `val_loss`, etc. in name # saves a file like: my/path/epoch=2-val_loss=0.02-other_metric=0.03.ckpt >>> checkpoint_callback = ModelCheckpoint( ... dirpath='my/path', ... filename='{epoch}-{val_loss:.2f}-{other_metric:.2f}' ... ) By default, filename is ``None`` and will be set to ``'{epoch}-{step}'``, where "epoch" and "step" match the number of finished epoch and optimizer steps respectively. monitor: quantity to monitor. By default it is ``None`` which saves a checkpoint only for the last epoch. verbose: verbosity mode. Default: ``False``. save_last: When ``True``, saves a `last.ckpt` copy whenever a checkpoint file gets saved. Can be set to ``'link'`` on a local filesystem to create a symbolic link. This allows accessing the latest checkpoint in a deterministic manner. Default: ``None``. save_top_k: if ``save_top_k == k``, the best k models according to the quantity monitored will be saved. If ``save_top_k == 0``, no models are saved. If ``save_top_k == -1``, all models are saved. Please note that the monitors are checked every ``every_n_epochs`` epochs. If ``save_top_k >= 2`` and the callback is called multiple times inside an epoch, and the filename remains unchanged, the name of the saved file will be appended with a version count starting with ``v1`` to avoid collisions unless ``enable_version_counter`` is set to False. The version counter is unrelated to the top-k ranking of the checkpoint, and we recommend formatting the filename to include the monitored metric to avoid collisions. save_on_exception: Whether to save a checkpoint when an exception is raised. Default: ``False``. mode: one of {min, max}. If ``save_top_k != 0``, the decision to overwrite the current save file is made based on either the maximization or the minimization of the monitored quantity. For ``'val_acc'``, this should be ``'max'``, for ``'val_loss'`` this should be ``'min'``, etc. auto_insert_metric_name: When ``True``, the checkpoints filenames will contain the metric name. For example, ``filename='checkpoint_{epoch:02d}-{acc:02.0f}`` with epoch ``1`` and acc ``1.12`` will resolve to ``checkpoint_epoch=01-acc=01.ckpt``. Is useful to set it to ``False`` when metric names contain ``/`` as this will result in extra folders. For example, ``filename='epoch={epoch}-step={step}-val_acc={val/acc:.2f}', auto_insert_metric_name=False`` save_weights_only: if ``True``, then only the model's weights will be saved. Otherwise, the optimizer states, lr-scheduler states, etc are added in the checkpoint too. every_n_train_steps: How many training steps to wait before saving a checkpoint. This does not take into account the steps of the current epoch. If ``every_n_train_steps == None or every_n_train_steps == 0``, no checkpoints will be saved during training. Mutually exclusive with ``train_time_interval`` and ``every_n_epochs``. .. note:: When using with manual optimization, the checkpoint will be saved after the optimizer step by default. To save the model state before the optimizer step, you need to save the model state in your ``training_step`` before calling ``optimizer.step()``. See the class docstring for an example. train_time_interval: Checkpoints are monitored at the specified time interval. For all practical purposes, this cannot be smaller than the amount of time it takes to process a single training batch. This is not guaranteed to execute at the exact time specified, but should be close. This must be mutually exclusive with ``every_n_train_steps`` and ``every_n_epochs``. every_n_epochs: Number of epochs between checkpoints. This value must be ``None`` or non-negative. To disable saving top-k checkpoints, set ``every_n_epochs = 0``. This argument does not impact the saving of ``save_last=True`` checkpoints. If all of ``every_n_epochs``, ``every_n_train_steps`` and ``train_time_interval`` are ``None``, we save a checkpoint at the end of every epoch (equivalent to ``every_n_epochs = 1``). If ``every_n_epochs == None`` and either ``every_n_train_steps != None`` or ``train_time_interval != None``, saving at the end of each epoch is disabled (equivalent to ``every_n_epochs = 0``). This must be mutually exclusive with ``every_n_train_steps`` and ``train_time_interval``. Setting both ``ModelCheckpoint(..., every_n_epochs=V, save_on_train_epoch_end=False)`` and ``Trainer(max_epochs=N, check_val_every_n_epoch=M)`` will only save checkpoints at epochs 0 < E <= N where both values for ``every_n_epochs`` and ``check_val_every_n_epoch`` evenly divide E. save_on_train_epoch_end: Whether to run checkpointing at the end of the training epoch. If ``True``, checkpoints are saved at the end of every training epoch. If ``False``, checkpoints are saved at the end of validation. If ``None`` (default), checkpointing behavior is determined based on training configuration. If ``val_check_interval`` is a str, dict, or `timedelta` (time-based), checkpointing is performed after validation. If ``check_val_every_n_epoch != 1``, checkpointing will not be performed at the end of every training epoch. If there are no validation batches of data, checkpointing will occur at the end of the training epoch. If there is a non-default number of validation runs per training epoch (``val_check_interval != 1``), checkpointing is performed after validation. enable_version_counter: Whether to append a version to the existing file name. If ``False``, then the checkpoint files will be overwritten. Note: For extra customization, ModelCheckpoint includes the following attributes: - ``CHECKPOINT_JOIN_CHAR = "-"`` - ``CHECKPOINT_EQUALS_CHAR = "="`` - ``CHECKPOINT_NAME_LAST = "last"`` - ``FILE_EXTENSION = ".ckpt"`` - ``STARTING_VERSION = 1`` For example, you can change the default last checkpoint name by doing ``checkpoint_callback.CHECKPOINT_NAME_LAST = "{epoch}-last"`` If you want to checkpoint every N hours, every M train batches, and/or every K val epochs, then you should create multiple ``ModelCheckpoint`` callbacks. If the checkpoint's ``dirpath`` changed from what it was before while resuming the training, only ``best_model_path`` will be reloaded and a warning will be issued. If you provide a ``filename`` on a mounted device where changing permissions is not allowed (causing ``chmod`` to raise a ``PermissionError``), install `fsspec>=2025.5.0`. Then the error is caught, the file's permissions remain unchanged, and the checkpoint is still saved. Otherwise, no checkpoint will be saved and training stops. Raises: MisconfigurationException: If ``save_top_k`` is smaller than ``-1``, if ``monitor`` is ``None`` and ``save_top_k`` is none of ``None``, ``-1``, and ``0``, or if ``mode`` is none of ``"min"`` or ``"max"``. ValueError: If ``trainer.save_checkpoint`` is ``None``. Example:: >>> from lightning.pytorch import Trainer >>> from lightning.pytorch.callbacks import ModelCheckpoint # saves checkpoints to 'my/path/' at every epoch >>> checkpoint_callback = ModelCheckpoint(dirpath='my/path/') >>> trainer = Trainer(callbacks=[checkpoint_callback]) # save epoch and val_loss in name # saves a file like: my/path/sample-mnist-epoch=02-val_loss=0.32.ckpt >>> checkpoint_callback = ModelCheckpoint( ... monitor='val_loss', ... dirpath='my/path/', ... filename='sample-mnist-{epoch:02d}-{val_loss:.2f}' ... ) # save epoch and val_loss in name, but specify the formatting yourself (e.g. to avoid problems with Tensorboard # or Neptune, due to the presence of characters like '=' or '/') # saves a file like: my/path/sample-mnist-epoch02-val_loss0.32.ckpt >>> checkpoint_callback = ModelCheckpoint( ... monitor='val/loss', ... dirpath='my/path/', ... filename='sample-mnist-epoch{epoch:02d}-val_loss{val/loss:.2f}', ... auto_insert_metric_name=False ... ) # retrieve the best checkpoint after training >>> checkpoint_callback = ModelCheckpoint(dirpath='my/path/') >>> trainer = Trainer(callbacks=[checkpoint_callback]) >>> model = ... # doctest: +SKIP >>> trainer.fit(model) # doctest: +SKIP >>> print(checkpoint_callback.best_model_path) # doctest: +SKIP .. tip:: Saving and restoring multiple checkpoint callbacks at the same time is supported under variation in the following arguments: *monitor, mode, every_n_train_steps, every_n_epochs, train_time_interval* Read more: :ref:`Persisting Callback State <extensions/callbacks_state:save callback state>` """ CHECKPOINT_JOIN_CHAR = "-" CHECKPOINT_EQUALS_CHAR = "=" CHECKPOINT_NAME_LAST = "last" FILE_EXTENSION = ".ckpt" STARTING_VERSION = 1 def __init__( self, dirpath: Optional[_PATH] = None, filename: Optional[str] = None, monitor: Optional[str] = None, verbose: bool = False, save_last: Optional[Union[bool, Literal["link"]]] = None, save_top_k: int = 1, save_on_exception: bool = False, save_weights_only: bool = False, mode: str = "min", auto_insert_metric_name: bool = True, every_n_train_steps: Optional[int] = None, train_time_interval: Optional[timedelta] = None, every_n_epochs: Optional[int] = None, save_on_train_epoch_end: Optional[bool] = None, enable_version_counter: bool = True, ): super().__init__() self.monitor = monitor self.verbose = verbose self.save_last = save_last self.save_top_k = save_top_k self.save_on_exception = save_on_exception self.save_weights_only = save_weights_only self.auto_insert_metric_name = auto_insert_metric_name self._save_on_train_epoch_end = save_on_train_epoch_end self._enable_version_counter = enable_version_counter self._last_global_step_saved = 0 # no need to save when no steps were taken self._last_time_checked: Optional[float] = None self.current_score: Optional[Tensor] = None self.best_k_models: dict[str, Tensor] = {} self.kth_best_model_path = "" self.best_model_score: Optional[Tensor] = None self.best_model_path = "" self.last_model_path = "" self._last_checkpoint_saved = "" # When using step/time-based checkpointing with a validation-only monitored metric, # defer the save until validation has produced the metric self._defer_save_until_validation: bool = False self.kth_value: Tensor self.dirpath: Optional[_PATH] self.__init_monitor_mode(mode) self.__init_ckpt_dir(dirpath, filename) self.__init_triggers(every_n_train_steps, every_n_epochs, train_time_interval) self.__validate_init_configuration() @property @override def state_key(self) -> str: return self._generate_state_key( monitor=self.monitor, mode=self.mode, every_n_train_steps=self._every_n_train_steps, every_n_epochs=self._every_n_epochs, train_time_interval=self._train_time_interval, ) @override def setup(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule", stage: str) -> None: dirpath = self.__resolve_ckpt_dir(trainer) dirpath = trainer.strategy.broadcast(dirpath) self.dirpath = dirpath self._fs = get_filesystem(self.dirpath or "") if trainer.is_global_zero and stage == "fit": self.__warn_if_dir_not_empty(self.dirpath) if self.save_last == "link" and not _is_local_file_protocol(self.dirpath): raise ValueError( f"`ModelCheckpoint(save_last='link')` is only supported for local file paths, got `dirpath={dirpath}`." ) @override def on_train_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: self._last_time_checked = time.monotonic() @override def on_train_batch_end( self, trainer: "pl.Trainer", pl_module: "pl.LightningModule", outputs: STEP_OUTPUT, batch: Any, batch_idx: int, ) -> None: """Save checkpoint on train batch end if we meet the criteria for `every_n_train_steps`""" # For manual optimization, we need to handle saving differently if not pl_module.automatic_optimization: # Skip if we don't need to save at this step if self._every_n_train_steps < 1 or (trainer.global_step % self._every_n_train_steps != 0): return # Check if we should skip due to trainer/callback state if self._should_skip_saving_checkpoint(trainer): return # Get monitor candidates and check if we have the monitored metric monitor_candidates = self._monitor_candidates(trainer) if self.monitor is not None and self.monitor not in monitor_candidates: self._defer_save_until_validation = True return # For manual optimization, we save the model state that was captured in training_step # before the optimizer step. The test case saves this state in model.saved_models. if ( hasattr(pl_module, "saved_models") and isinstance(pl_module.saved_models, dict) and pl_module.saved_models and hasattr(pl_module, "layer") and isinstance(pl_module.layer, torch.nn.Module) ): # Get the latest saved state saved_models = pl_module.saved_models if not saved_models: # Check if dictionary is not empty return latest_step = max(saved_models.keys()) # Save the checkpoint with the pre-optimization state with torch.no_grad(): # Save the current state original_state = {k: v.detach().clone() for k, v in pl_module.layer.state_dict().items()} try: # Restore the pre-optimization state saved_state = saved_models[latest_step] if not isinstance(saved_state, dict): raise TypeError("Saved model state must be a dictionary") pl_module.layer.load_state_dict(saved_state) # Save the checkpoint self._save_topk_checkpoint(trainer, monitor_candidates) self._save_last_checkpoint(trainer, monitor_candidates) self._last_time_checked = time.monotonic() finally: # Restore the original state pl_module.layer.load_state_dict(original_state) else: # Fallback to default behavior if no saved state is available if not pl_module.automatic_optimization and trainer.is_global_zero: rank_zero_warn( "Using ModelCheckpoint with manual optimization and every_n_train_steps, but no " "pre-optimization state was saved. The checkpoint will contain the model state " "AFTER optimization. To save the pre-optimization state, save the model state in " "training_step before " "optimizer.step(). " "Example:\n" "def training_step(self, batch, batch_idx):\n" " # ... forward pass, loss calculation, backward pass ...\n" " # Save model state before optimization\n" " if not hasattr(self, 'saved_models'):\n" " self.saved_models = {}\n" " self.saved_models[batch_idx] = {\n" " k: v.detach().clone() for k, v in self.layer.state_dict().items()\n" " }\n" " # Then perform optimization\n" " optimizer.zero_grad()\n" " self.manual_backward(loss)\n" " optimizer.step()", category=UserWarning, ) self._save_topk_checkpoint(trainer, monitor_candidates) self._save_last_checkpoint(trainer, monitor_candidates) self._last_time_checked = time.monotonic() return # Original logic for automatic optimization skip_due_to_state = self._should_skip_saving_checkpoint(trainer) skip_batch = self._every_n_train_steps < 1 or (trainer.global_step % self._every_n_train_steps != 0) train_time_interval = self._train_time_interval skip_time = True now = time.monotonic() # Important: allow zero timedelta as a valid interval if train_time_interval is not None: prev_time_check = self._last_time_checked skip_time = prev_time_check is None or (now - prev_time_check) < train_time_interval.total_seconds() # in case we have time differences across ranks # broadcast the decision on whether to checkpoint from rank 0 to avoid possible hangs skip_time = trainer.strategy.broadcast(skip_time) if skip_batch and skip_time: return if not skip_time: self._last_time_checked = now monitor_candidates = self._monitor_candidates(trainer) # If monitoring a metric that is not yet available (e.g., validation-only), # defer saving until validation end so the metric is present. if self.monitor is not None and self.monitor not in monitor_candidates: # Defer both top-k and last to avoid blocking with `_last_global_step_saved` self._defer_save_until_validation = True return # Even if the monitored key exists, it could be stale from a previous validation. # If validation is scheduled to run right after this batch (e.g., last batch of epoch) # and we are not saving at train epoch end, defer to `on_validation_end` to use fresh metrics. if ( self.monitor is not None and not self._should_save_on_train_epoch_end(trainer) and getattr(trainer.fit_loop.epoch_loop.batch_progress, "is_last_batch", False) ): # Only defer if a validation loop is expected to run after this batch. will_run_val = False if getattr(trainer, "enable_validation", False): num_val_batches = ( sum(trainer.num_val_batches) if isinstance(trainer.num_val_batches, list) else trainer.num_val_batches ) if num_val_batches and num_val_batches > 0: cve = trainer.check_val_every_n_epoch if cve is None or ((trainer.current_epoch + 1) % cve == 0): will_run_val = True if will_run_val: self._defer_save_until_validation = True return # Only proceed to save if not skipping due to trainer/callback state if skip_due_to_state: return self._save_topk_checkpoint(trainer, monitor_candidates) self._save_last_checkpoint(trainer, monitor_candidates) @override def on_train_epoch_end(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: """Save a checkpoint at the end of the training epoch.""" if not self._should_skip_saving_checkpoint(trainer) and self._should_save_on_train_epoch_end(trainer): monitor_candidates = self._monitor_candidates(trainer) if self._every_n_epochs >= 1 and (trainer.current_epoch + 1) % self._every_n_epochs == 0: self._save_topk_checkpoint(trainer, monitor_candidates) # Only save last checkpoint if a checkpoint was actually saved in this step or if save_last="link" if self._last_global_step_saved == trainer.global_step or ( self.save_last == "link" and self._last_checkpoint_saved ): self._save_last_checkpoint(trainer, monitor_candidates) @override def on_validation_end(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: """Save a checkpoint at the end of the validation stage.""" if not self._should_skip_saving_checkpoint(trainer) and not self._should_save_on_train_epoch_end(trainer): monitor_candidates = self._monitor_candidates(trainer) # If a step/time-triggered save was deferred due to a missing monitored metric, # perform the save now that validation metrics are available. if self._defer_save_until_validation: self._save_topk_checkpoint(trainer, monitor_candidates) self._save_last_checkpoint(trainer, monitor_candidates) self._defer_save_until_validation = False return if self._every_n_epochs >= 1 and (trainer.current_epoch + 1) % self._every_n_epochs == 0: self._save_topk_checkpoint(trainer, monitor_candidates) # Only save last checkpoint if a checkpoint was actually saved in this step or if save_last="link" if self._last_global_step_saved == trainer.global_step or ( self.save_last == "link" and self._last_checkpoint_saved ): self._save_last_checkpoint(trainer, monitor_candidates) @override def on_exception(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule", exception: BaseException) -> None: """Save a checkpoint when an exception is raised.""" if not self._should_save_on_exception(trainer): return monitor_candidates = self._monitor_candidates(trainer) filepath = self.format_checkpoint_name(metrics=monitor_candidates) self._save_checkpoint(trainer, filepath) self._save_last_checkpoint(trainer, monitor_candidates) rank_zero_info( f"An {type(exception).__name__} was raised with message: \ {str(exception)}, saved checkpoint to {filepath}" ) def on_train_end(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: """Ensure save_last=True is applied when training ends.""" if self.save_last and not self._last_checkpoint_saved: monitor_candidates = self._monitor_candidates(trainer) self._save_last_checkpoint(trainer, monitor_candidates) @override def state_dict(self) -> dict[str, Any]: return { "monitor": self.monitor, "best_model_score": self.best_model_score, "best_model_path": self.best_model_path, "current_score": self.current_score, "dirpath": self.dirpath, "best_k_models": self.best_k_models, "kth_best_model_path": self.kth_best_model_path, "kth_value": self.kth_value, "last_model_path": self.last_model_path, } @override def load_state_dict(self, state_dict: dict[str, Any]) -> None: dirpath_from_ckpt = state_dict.get("dirpath", self.dirpath) if self.dirpath == dirpath_from_ckpt: self.best_model_score = state_dict["best_model_score"] self.kth_best_model_path = state_dict.get("kth_best_model_path", self.kth_best_model_path) self.kth_value = state_dict.get("kth_value", self.kth_value) self.best_k_models = state_dict.get("best_k_models", self.best_k_models) self.last_model_path = state_dict.get("last_model_path", self.last_model_path) else: warnings.warn( f"The dirpath has changed from {dirpath_from_ckpt!r} to {self.dirpath!r}," " therefore `best_model_score`, `kth_best_model_path`, `kth_value`, `last_model_path` and" " `best_k_models` won't be reloaded. Only `best_model_path` will be reloaded." ) self.best_model_path = state_dict["best_model_path"] def _save_topk_checkpoint(self, trainer: "pl.Trainer", monitor_candidates: dict[str, Tensor]) -> None: if self.save_top_k == 0: return # validate metric if self.monitor is not None: if self.monitor not in monitor_candidates: m = ( f"`ModelCheckpoint(monitor={self.monitor!r})` could not find the monitored key in the returned" f" metrics: {list(monitor_candidates)}." f" HINT: Did you call `log({self.monitor!r}, value)` in the `LightningModule`?" ) if trainer.fit_loop.epoch_loop.val_loop._has_run: raise MisconfigurationException(m) warning_cache.warn(m) self._save_monitor_checkpoint(trainer, monitor_candidates) else: self._save_none_monitor_checkpoint(trainer, monitor_candidates) def _save_checkpoint(self, trainer: "pl.Trainer", filepath: str) -> None: """Save the checkpoint to the given filepath. For manual optimization, we rely on the fact that the model's training_step method saves the model state before the optimizer step, so we can use that state directly. """ trainer.save_checkpoint(filepath, self.save_weights_only) self._last_global_step_saved = trainer.global_step self._last_checkpoint_saved = filepath # notify loggers if trainer.is_global_zero: for logger in trainer.loggers: logger.after_save_checkpoint(proxy(self)) @staticmethod def _link_checkpoint(trainer: "pl.Trainer", filepath: str, linkpath: str) -> None: if trainer.is_global_zero and os.path.abspath(filepath) != os.path.abspath(linkpath): if os.path.islink(linkpath) or os.path.isfile(linkpath): os.remove(linkpath) elif os.path.isdir(linkpath): shutil.rmtree(linkpath) try: os.symlink(os.path.relpath(filepath, os.path.dirname(linkpath)), linkpath) except OSError: # on Windows, special permissions are required to create symbolic links as a regular user # fall back to copying the file shutil.copy(filepath, linkpath) trainer.strategy.barrier() def _should_skip_saving_checkpoint(self, trainer: "pl.Trainer") -> bool: from lightning.pytorch.trainer.states import TrainerFn return ( bool(trainer.fast_dev_run) # disable checkpointing with fast_dev_run or trainer.state.fn != TrainerFn.FITTING # don't save anything during non-fit or trainer.sanity_checking # don't save anything during sanity check or self._last_global_step_saved == trainer.global_step # already saved at the last step ) def _should_save_on_exception(self, trainer: "pl.Trainer") -> bool: return ( self.save_on_exception and not bool(trainer.fast_dev_run) # disable checkpointing with fast_dev_run and not trainer.sanity_checking # don't save anything during sanity check and self._last_global_step_saved != trainer.global_step # already saved at the last step ) def _should_save_on_train_epoch_end(self, trainer: "pl.Trainer") -> bool: if self._save_on_train_epoch_end is not None: return self._save_on_train_epoch_end # time-based validation: always defer saving to validation end if getattr(trainer, "_val_check_time_interval", None) is not None: return False # if `check_val_every_n_epoch != 1`, we can't say when the validation dataloader will be loaded # so let's not enforce saving at every training epoch end if trainer.check_val_every_n_epoch != 1: return False # no validation means save on train epoch end num_val_batches = ( sum(trainer.num_val_batches) if isinstance(trainer.num_val_batches, list) else trainer.num_val_batches ) if num_val_batches == 0: return True # if the user runs validation multiple times per training epoch, then we run after validation # instead of on train epoch end return trainer.val_check_interval == 1.0 def __validate_init_configuration(self) -> None: if self.save_top_k < -1: raise MisconfigurationException(f"Invalid value for save_top_k={self.save_top_k}. Must be >= -1") if self._every_n_train_steps < 0: raise MisconfigurationException( f"Invalid value for every_n_train_steps={self._every_n_train_steps}. Must be >= 0" ) if self._every_n_epochs < 0: raise MisconfigurationException(f"Invalid value for every_n_epochs={self._every_n_epochs}. Must be >= 0") every_n_train_steps_triggered = self._every_n_train_steps >= 1 every_n_epochs_triggered = self._every_n_epochs >= 1 train_time_interval_triggered = self._train_time_interval is not None if every_n_train_steps_triggered + every_n_epochs_triggered + train_time_interval_triggered > 1: raise MisconfigurationException( f"Combination of parameters every_n_train_steps={self._every_n_train_steps}, " f"every_n_epochs={self._every_n_epochs} and train_time_interval={self._train_time_interval} " "should be mutually exclusive." ) if self.monitor is None and self.save_top_k not in (-1, 0, 1): # -1: save all epochs, 0: nothing is saved, 1: save last epoch raise MisconfigurationException( f"ModelCheckpoint(save_top_k={self.save_top_k}, monitor=None) is not a valid" " configuration. No quantity for top_k to track." ) def __init_ckpt_dir(self, dirpath: Optional[_PATH], filename: Optional[str]) -> None: self._fs = get_filesystem(dirpath if dirpath else "") if dirpath and _is_local_file_protocol(dirpath if dirpath else ""): dirpath = os.path.realpath(os.path.expanduser(dirpath)) self.dirpath = dirpath self.filename = filename def __init_monitor_mode(self, mode: str) -> None: torch_inf = torch.tensor(torch.inf) mode_dict = {"min": (torch_inf, "min"), "max": (-torch_inf, "max")} if mode not in mode_dict: raise MisconfigurationException(f"`mode` can be {', '.join(mode_dict.keys())} but got {mode}") self.kth_value, self.mode = mode_dict[mode] def __init_triggers( self, every_n_train_steps: Optional[int], every_n_epochs: Optional[int], train_time_interval: Optional[timedelta], ) -> None: # Default to running once after each validation epoch if neither # every_n_train_steps nor every_n_epochs is set if every_n_train_steps is None and every_n_epochs is None and train_time_interval is None: every_n_epochs = 1 every_n_train_steps = 0 log.debug("Both every_n_train_steps and every_n_epochs are not set. Setting every_n_epochs=1") else: every_n_epochs = every_n_epochs or 0 every_n_train_steps = every_n_train_steps or 0 self._train_time_interval: Optional[timedelta] = train_time_interval self._every_n_epochs: int = every_n_epochs self._every_n_train_steps: int = every_n_train_steps @property def every_n_epochs(self) -> Optional[int]: return self._every_n_epochs def check_monitor_top_k(self, trainer: "pl.Trainer", current: Optional[Tensor] = None) -> bool: if current is None: return False if self.save_top_k == -1: return True less_than_k_models = len(self.best_k_models) < self.save_top_k if less_than_k_models: return True monitor_op = {"min": torch.lt, "max": torch.gt}[self.mode] should_update_best_and_save = monitor_op(current, self.best_k_models[self.kth_best_model_path]) # If using multiple devices, make sure all processes are unanimous on the decision. should_update_best_and_save = trainer.strategy.reduce_boolean_decision(bool(should_update_best_and_save)) return should_update_best_and_save def _format_checkpoint_name( self, filename: Optional[str], metrics: dict[str, Tensor], prefix: Optional[str] = None, auto_insert_metric_name: bool = True, ) -> str: if not filename: # filename is not set, use default name filename = "{epoch}" + self.CHECKPOINT_JOIN_CHAR + "{step}" # check and parse user passed keys in the string groups = re.findall(r"(\{.*?)[:\}]", filename) # sort keys from longest to shortest to avoid replacing substring # eg: if keys are "epoch" and "epoch_test", the latter must be replaced first groups = sorted(groups, key=lambda x: len(x), reverse=True) for group in groups: name = group[1:] if auto_insert_metric_name: filename = filename.replace(group, name + self.CHECKPOINT_EQUALS_CHAR + "{" + name) # support for dots: https://stackoverflow.com/a/7934969 filename = filename.replace(group, f"{{0[{name}]") if name not in metrics: metrics[name] = torch.tensor(0) filename = filename.format(metrics) if prefix is not None: filename = self.CHECKPOINT_JOIN_CHAR.join([prefix, filename]) return filename def format_checkpoint_name( self, metrics: dict[str, Tensor], filename: Optional[str] = None, ver: Optional[int] = None, prefix: Optional[str] = None, ) -> str: """Generate a filename according to the defined template. Example:: >>> tmpdir = os.path.dirname(__file__) >>> ckpt = ModelCheckpoint(dirpath=tmpdir, filename='{epoch}') >>> os.path.basename(ckpt.format_checkpoint_name(dict(epoch=0))) 'epoch=0.ckpt' >>> ckpt = ModelCheckpoint(dirpath=tmpdir, filename='{epoch:03d}') >>> os.path.basename(ckpt.format_checkpoint_name(dict(epoch=5))) 'epoch=005.ckpt' >>> ckpt = ModelCheckpoint(dirpath=tmpdir, filename='{epoch}-{val_loss:.2f}') >>> os.path.basename(ckpt.format_checkpoint_name(dict(epoch=2, val_loss=0.123456))) 'epoch=2-val_loss=0.12.ckpt' >>> os.path.basename(ckpt.format_checkpoint_name(dict(epoch=2, val_loss=0.12), filename='{epoch:d}')) 'epoch=2.ckpt' >>> ckpt = ModelCheckpoint(dirpath=tmpdir, ... filename='epoch={epoch}-validation_loss={val_loss:.2f}', ... auto_insert_metric_name=False) >>> os.path.basename(ckpt.format_checkpoint_name(dict(epoch=2, val_loss=0.123456))) 'epoch=2-validation_loss=0.12.ckpt' >>> ckpt = ModelCheckpoint(dirpath=tmpdir, filename='{missing:d}') >>> os.path.basename(ckpt.format_checkpoint_name({})) 'missing=0.ckpt' >>> ckpt = ModelCheckpoint(filename='{step}') >>> os.path.basename(ckpt.format_checkpoint_name(dict(step=0))) 'step=0.ckpt' """ filename = filename or self.filename filename = self._format_checkpoint_name( filename, metrics, prefix=prefix, auto_insert_metric_name=self.auto_insert_metric_name ) if ver is not None: filename = self.CHECKPOINT_JOIN_CHAR.join((filename, f"v{ver}")) ckpt_name = f"{filename}{self.FILE_EXTENSION}" return os.path.join(self.dirpath, ckpt_name) if self.dirpath else ckpt_name def __resolve_ckpt_dir(self, trainer: "pl.Trainer") -> _PATH: """Determines model checkpoint save directory at runtime. Reference attributes from the trainer's logger to determine where to save checkpoints. The path for saving weights is set in this priority: 1. The ``ModelCheckpoint``'s ``dirpath`` if passed in 2. The ``Logger``'s ``log_dir`` if the trainer has loggers 3. The ``Trainer``'s ``default_root_dir`` if the trainer has no loggers The path gets extended with subdirectory "checkpoints". """ if self.dirpath is not None: # short circuit if dirpath was passed to ModelCheckpoint return self.dirpath if len(trainer.loggers) > 0: if trainer.loggers[0].save_dir is not None: save_dir = trainer.loggers[0].save_dir else: save_dir = trainer.default_root_dir name = trainer.loggers[0].name version = trainer.loggers[0].version version = version if isinstance(version, str) else f"version_{version}" ckpt_path = os.path.join(save_dir, str(name), version, "checkpoints") else: # if no loggers, use default_root_dir ckpt_path = os.path.join(trainer.default_root_dir, "checkpoints") return ckpt_path def _find_last_checkpoints(self, trainer: "pl.Trainer") -> set[str]: # find all checkpoints in the folder ckpt_path = self.__resolve_ckpt_dir(trainer) last_pattern = rf"^{self.CHECKPOINT_NAME_LAST}(-(\d+))?" def _is_last(path: Path) -> bool: return path.suffix == self.FILE_EXTENSION and bool(re.match(last_pattern, path.stem)) if self._fs.exists(ckpt_path): return {os.path.normpath(p) for p in self._fs.ls(ckpt_path, detail=False) if _is_last(Path(p))} return set() def __warn_if_dir_not_empty(self, dirpath: _PATH) -> None: if self.save_top_k != 0 and _is_dir(self._fs, dirpath, strict=True) and len(self._fs.ls(dirpath)) > 0: rank_zero_warn(f"Checkpoint directory {dirpath} exists and is not empty.") def _get_metric_interpolated_filepath_name( self, monitor_candidates: dict[str, Tensor], trainer: "pl.Trainer", del_filepath: Optional[str] = None ) -> str: filepath = self.format_checkpoint_name(monitor_candidates) if self._enable_version_counter: version_cnt = self.STARTING_VERSION while self.file_exists(filepath, trainer) and filepath != del_filepath: filepath = self.format_checkpoint_name(monitor_candidates, ver=version_cnt) version_cnt += 1 return filepath def _monitor_candidates(self, trainer: "pl.Trainer") -> dict[str, Tensor]: monitor_candidates = deepcopy(trainer.callback_metrics) # cast to int if necessary because `self.log("epoch", 123)` will convert it to float. if it's not a tensor # or does not exist we overwrite it as it's likely an error epoch = monitor_candidates.get("epoch") monitor_candidates["epoch"] = epoch.int() if isinstance(epoch, Tensor) else torch.tensor(trainer.current_epoch) step = monitor_candidates.get("step") monitor_candidates["step"] = step.int() if isinstance(step, Tensor) else torch.tensor(trainer.global_step) return monitor_candidates def _save_last_checkpoint(self, trainer: "pl.Trainer", monitor_candidates: dict[str, Tensor]) -> None: if not self.save_last: return filepath = self.format_checkpoint_name(monitor_candidates, self.CHECKPOINT_NAME_LAST) if self._enable_version_counter: version_cnt = self.STARTING_VERSION while self.file_exists(filepath, trainer) and filepath != self.last_model_path: filepath = self.format_checkpoint_name(monitor_candidates, self.CHECKPOINT_NAME_LAST, ver=version_cnt) version_cnt += 1 # set the last model path before saving because it will be part of the state. previous, self.last_model_path = self.last_model_path, filepath if self.save_last == "link" and self._last_checkpoint_saved and self.save_top_k != 0: self._link_checkpoint(trainer, self._last_checkpoint_saved, filepath) else: self._save_checkpoint(trainer, filepath) if previous and self._should_remove_checkpoint(trainer, previous, filepath): self._remove_checkpoint(trainer, previous) def _save_monitor_checkpoint(self, trainer: "pl.Trainer", monitor_candidates: dict[str, Tensor]) -> None: assert self.monitor current = monitor_candidates.get(self.monitor) if self.check_monitor_top_k(trainer, current): assert current is not None self._update_best_and_save(current, trainer, monitor_candidates) elif self.verbose: epoch = monitor_candidates["epoch"] step = monitor_candidates["step"] rank_zero_info(f"Epoch {epoch:d}, global step {step:d}: {self.monitor!r} was not in top {self.save_top_k}") def _save_none_monitor_checkpoint(self, trainer: "pl.Trainer", monitor_candidates: dict[str, Tensor]) -> None: filepath = self._get_metric_interpolated_filepath_name(monitor_candidates, trainer, self.best_model_path) # set the best model path before saving because it will be part of the state. previous, self.best_model_path = self.best_model_path, filepath self._save_checkpoint(trainer, filepath) if self.save_top_k == 1 and previous and self._should_remove_checkpoint(trainer, previous, filepath): self._remove_checkpoint(trainer, previous) def _update_best_and_save( self, current: Tensor, trainer: "pl.Trainer", monitor_candidates: dict[str, Tensor] ) -> None: k = len(self.best_k_models) + 1 if self.save_top_k == -1 else self.save_top_k del_filepath = None if len(self.best_k_models) == k and k > 0: del_filepath = self.kth_best_model_path self.best_k_models.pop(del_filepath) # do not save nan, replace with +/- inf if isinstance(current, Tensor) and torch.isnan(current): current = torch.tensor(float("inf" if self.mode == "min" else "-inf"), device=current.device) filepath = self._get_metric_interpolated_filepath_name(monitor_candidates, trainer, del_filepath) # save the current score self.current_score = current self.best_k_models[filepath] = current if len(self.best_k_models) == k: # monitor dict has reached k elements _op = max if self.mode == "min" else min self.kth_best_model_path = _op(self.best_k_models, key=self.best_k_models.get) # type: ignore[arg-type] self.kth_value = self.best_k_models[self.kth_best_model_path] _op = min if self.mode == "min" else max self.best_model_path = _op(self.best_k_models, key=self.best_k_models.get) # type: ignore[arg-type] self.best_model_score = self.best_k_models[self.best_model_path] if self.verbose: epoch = monitor_candidates["epoch"] step = monitor_candidates["step"] rank_zero_info( f"Epoch {epoch:d}, global step {step:d}: {self.monitor!r} reached {current:0.5f}" f" (best {self.best_model_score:0.5f}), saving model to {filepath!r} as top {k}" ) self._save_checkpoint(trainer, filepath) if del_filepath and self._should_remove_checkpoint(trainer, del_filepath, filepath): self._remove_checkpoint(trainer, del_filepath) def to_yaml(self, filepath: Optional[_PATH] = None) -> None: """Saves the `best_k_models` dict containing the checkpoint paths with the corresponding scores to a YAML file.""" best_k = {k: v.item() for k, v in self.best_k_models.items()} if filepath is None: assert self.dirpath filepath = os.path.join(self.dirpath, "best_k_models.yaml") with self._fs.open(filepath, "w") as fp: yaml.dump(best_k, fp) def file_exists(self, filepath: _PATH, trainer: "pl.Trainer") -> bool: """Checks if a file exists on rank 0 and synchronizes the result to all other ranks, preventing the internal state to diverge between ranks.""" # In distributed setups, only global rank 0 touches the filesystem local_decision = self._fs.exists(filepath) if trainer.is_global_zero else False # Reduce the decision across ranks using an "any"-style reduction to decide if the file exists anywhere return trainer.strategy.reduce_boolean_decision(local_decision, all=False) def _should_remove_checkpoint(self, trainer: "pl.Trainer", previous: str, current: str) -> bool: """Checks if the previous checkpoint should be deleted. A checkpoint won't be deleted if any of the cases apply: - The previous checkpoint is the same as the current checkpoint (means the old was already overwritten by new) - The previous checkpoint is not in the current checkpoint directory and the filesystem is local - The previous checkpoint is the checkpoint the Trainer resumed from and the filesystem is local """ if previous == current: return False if not _is_local_file_protocol(previous): return True previous = Path(previous).absolute() resume_path = Path(trainer.ckpt_path).absolute() if trainer.ckpt_path is not None else None if resume_path is not None and previous == resume_path: return False assert self.dirpath is not None dirpath = Path(self.dirpath).absolute() return dirpath in previous.parents def _remove_checkpoint(self, trainer: "pl.Trainer", filepath: str) -> None: """Calls the strategy to remove the checkpoint file.""" trainer.strategy.remove_checkpoint(filepath)
ModelCheckpoint
python
huggingface__transformers
tests/quantization/bnb/test_mixed_int8.py
{ "start": 2808, "end": 4044 }
class ____(unittest.TestCase): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module model_name = "bigscience/bloom-1b7" # Constant values EXPECTED_RELATIVE_DIFFERENCE = ( 1.540025 # This was obtained on a Quadro RTX 8000 so the number might slightly change ) input_text = "Hello my name is" EXPECTED_OUTPUTS = set() EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of the family.\n") # Expected values on a A10 EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n") MAX_NEW_TOKENS = 10 # Expected values with offload EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer based in") # Expected values on Intel XPU and NV A100 EXPECTED_OUTPUTS.add("Hello my name is Alina. I have been working as a professional") def setUp(self): # Models and tokenizer self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) @apply_skip_if_not_implemented
BaseMixedInt8Test
python
django__django
tests/model_fields/test_generatedfield.py
{ "start": 16087, "end": 16505 }
class ____(GeneratedFieldTestMixin, TestCase): base_model = GeneratedModelVirtual nullable_model = GeneratedModelNullVirtual check_constraint_model = GeneratedModelCheckConstraintVirtual unique_constraint_model = GeneratedModelUniqueConstraintVirtual output_field_db_collation_model = GeneratedModelOutputFieldDbCollationVirtual params_model = GeneratedModelParamsVirtual
VirtualGeneratedFieldTests
python
django__django
django/contrib/admin/widgets.py
{ "start": 12946, "end": 13102 }
class ____(forms.TextInput): def __init__(self, attrs=None): super().__init__(attrs={"class": "vTextField", **(attrs or {})})
AdminTextInputWidget
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/oracle/cx_oracle.py
{ "start": 26219, "end": 28969 }
class ____(OracleCompiler): _oracle_cx_sql_compiler = True _oracle_returning = False # Oracle bind names can't start with digits or underscores. # currently we rely upon Oracle-specific quoting of bind names in most # cases. however for expanding params, the escape chars are used. # see #8708 bindname_escape_characters = util.immutabledict( { "%": "P", "(": "A", ")": "Z", ":": "C", ".": "C", "[": "C", "]": "C", " ": "C", "\\": "C", "/": "C", "?": "C", } ) def bindparam_string(self, name, **kw): quote = getattr(name, "quote", None) if ( quote is True or quote is not False and self.preparer._bindparam_requires_quotes(name) # bind param quoting for Oracle doesn't work with post_compile # params. For those, the default bindparam_string will escape # special chars, and the appending of a number "_1" etc. will # take care of reserved words and not kw.get("post_compile", False) ): # interesting to note about expanding parameters - since the # new parameters take the form <paramname>_<int>, at least if # they are originally formed from reserved words, they no longer # need quoting :). names that include illegal characters # won't work however. quoted_name = '"%s"' % name kw["escaped_from"] = name name = quoted_name return OracleCompiler.bindparam_string(self, name, **kw) # TODO: we could likely do away with quoting altogether for # Oracle parameters and use the custom escaping here escaped_from = kw.get("escaped_from", None) if not escaped_from: if self._bind_translate_re.search(name): # not quite the translate use case as we want to # also get a quick boolean if we even found # unusual characters in the name new_name = self._bind_translate_re.sub( lambda m: self._bind_translate_chars[m.group(0)], name, ) if new_name[0].isdigit() or new_name[0] == "_": new_name = "D" + new_name kw["escaped_from"] = name name = new_name elif name[0].isdigit() or name[0] == "_": new_name = "D" + name kw["escaped_from"] = name name = new_name return OracleCompiler.bindparam_string(self, name, **kw)
OracleCompiler_cx_oracle
python
walkccc__LeetCode
solutions/3120. Count the Number of Special Characters I/3120.py
{ "start": 0, "end": 403 }
class ____: def numberOfSpecialChars(self, word: str) -> int: lower = collections.defaultdict(bool) upper = collections.defaultdict(bool) for c in word: if c.islower(): lower[c] = True else: upper[c] = True return sum(lower[a] and upper[b] for a, b in zip(string.ascii_lowercase, string.ascii_uppercase))
Solution
python
joke2k__faker
faker/providers/address/fa_IR/__init__.py
{ "start": 45, "end": 6155 }
class ____(AddressProvider): city_prefixes = ( "شمال", "غرب", "شرق", "جنوب", "بندر", "شهر", "روستای", "دهستان", "شهرستان", "باغات", "استان", ) building_number_formats = ("#####", "####", "###") street_suffixes = ( "کوچه", "خیابان", "پل", "دره", "میدان", "چهار راه", "بن بست", "بلوار", "جنب", "تقاطع", "آزاد راه", "بزرگ راه", "جزیره", "کوه", "جاده", "تونل", ) postcode_formats = ("###", "####", "#####", "######", "##########") states = ( "آذربایجان شرقی", "آذربایجان غربی", "اردبیل", "خراسان", "کردستان", "گیلان", "اصفهان", "البرز", "ایلام", "بوشهر", "تهران", "چهارمحال و بختیاری", "خراسان جنوبی", "خراسان رضوی", "خراسان شمالی", "خوزستان", "زنجان", "سمنان", "سیستان و بلوچستان", "فارس", "قزوین", "قم", "کرمان", "کرمانشاه", "کهگیلویه و بویراحمد", "گلستان", "لرستان", "مازندران", "مرکزی", "هرمزگان", "همدان", "یزد", ) countries = ( "جمهوری آذربایجان", "آرژانتین", "آفریقای جنوبی", "جمهوری آفریقای مرکزی", "آلبانی", "آلمان", "آنتیگوا و باربودا", "آندورا", "آنگولا", "اتریش", "اتیوپی", "اردن", "ارمنستان", "اروگوئه", "اریتره", "ازبکستان", "اسپانیا", "استرالیا", "استونی", "اسرائیل", "اسلواکی", "اسلوونی", "افغانستان", "اکوادور", "الجزایر", "السالوادور", "امارات متحده عربی", "اندونزی", "اوکراین", "اوگاندا", "ایالات متحده آمریکا", "ایتالیا", "ایران", "جمهوری ایرلند", "ایسلند", "باربادوس", "باهاما", "بحرین", "برزیل", "برونئی", "بریتانیا", "بلاروس", "بلژیک", "بلغارستان", "بلیز", "بنگلادش", "بنین", "پادشاهی بوتان", "بوتسوانا", "بورکینافاسو", "بوروندی", "بوسنی و هرزگوین", "بولیوی", "پاپوآ گینه نو", "پاراگوئه", "پاناما", "پاکستان", "پرتغال", "پرو", "پورتوریکو", "تاجیکستان", "تانزانیا", "تایلند", "جمهوری چین", "ترکمنستان", "ترکیه", "ترینیداد و توباگو", "توگو", "تونس", "تونگا", "تووالو", "تیمور شرقی", "جامائیکا", "جزایر سلیمان", "جزایر مارشال", "جمهوری چک", "جمهوری دومینیکن", "جیبوتی", "چاد", "چین", "دانمارک", "دومینیکا", "جمهوری دومینیکن", "رواندا", "روسیه", "رومانی", "زامبیا", "نیوزیلند", "زیمباوه", "جمهوری دموکراتیک کنگو (زئیر)", "ژاپن", "سائوتومه و پرینسیپ", "ساحل عاج", "ساموآی غربی", "سن مارینو", "سری‌لانکا", "سنت کیتس و نویس", "سنت لوسیا", "سنت وینسنت و گرنادین‌ها", "سنگاپور", "سنگال", "سوئد", "سوئیس", "سوازیلند", "سودان", "سودان جنوبی", "سورینام", "سوریه", "سومالی", "سیرالئون", "سیشل", "شیلی", "صربستان", "عراق", "عربستان سعودی", "عمان", "غنا", "فرانسه", "فلسطین", "فنلاند", "فیجی", "فیلیپین", "قبرس", "قرقیزستان", "قزاقستان", "قطر", "کامبوج", "کامرون", "کانادا", "کره جنوبی", "کره شمالی", "کرواسی", "کاستاریکا", "کلمبیا", "جمهوری کنگو", "جمهوری دموکراتیک کنگو", "کنیا", "کوبا", "کوزوو", "مجمع‌الجزایر قمر", "کویت", "کیپ ورد", "کیریباتی", "گابن", "گامبیا", "گرجستان", "گرنادا", "گرینلند(از مستعمرات دانمارک)", "گواتمالا", "گویان", "گینه", "گینه استوایی", "گینه بیسائو", "لائوس", "لبنان", "لتونی", "لسوتو", "لهستان", "لوکزامبورگ", "لیبریا", "لیبی", "لیتوانی", "لیختن‌اشتاین", "ماداگاسکار", "مالاوی", "مالت", "مالدیو", "مالزی", "مالی", "مجارستان", "مراکش", "مصر", "مغولستان", "مقدونیه شمالی", "مکزیک", "موریتانی", "موریس", "موزامبیک", "مولداوی", "موناکو", "مونته‌نگرو", "میانمار", "ایالات فدرال میکرونزی", "نائورو", "نامیبیا", "نپال", "نروژ", "نیجریه", "نیکاراگوئه", "نیوزیلند", "واتیکان", "وانواتو", "ونزوئلا", "ویتنام", "هائیتی", "هلند", "هندوراس", "هند", "یمن", "یونان", ) city_formats = ("{{city_prefix}} {{first_name}}",) street_name_formats = ( "{{first_name}} {{street_suffix}}", "{{last_name}} {{street_suffix}}", ) street_address_formats = ( "{{building_number}} {{street_name}}", "{{building_number}} {{street_name}} {{secondary_address}}", ) address_formats = ("{{street_address}}\n{{city}}, {{state}} {{postcode}}",) secondary_address_formats = ("سوئیت ###", "واحد ###") def city_prefix(self) -> str: return self.random_element(self.city_prefixes) def secondary_address(self) -> str: return self.numerify(self.random_element(self.secondary_address_formats)) def administrative_unit(self) -> str: return self.random_element(self.states) state = administrative_unit
Provider
python
getsentry__sentry
src/sentry/core/endpoints/team_details.py
{ "start": 1300, "end": 2007 }
class ____(CamelSnakeModelSerializer): slug = SentrySerializerSlugField( max_length=DEFAULT_SLUG_MAX_LENGTH, help_text="Uniquely identifies a team. This is must be available.", ) class Meta: model = Team fields = ("name", "slug") def validate_slug(self, value: str) -> str: assert self.instance is not None qs = Team.objects.filter(slug=value, organization=self.instance.organization).exclude( id=self.instance.id ) if qs.exists(): raise serializers.ValidationError(f'The slug "{value}" is already in use.') return value @extend_schema(tags=["Teams"]) @region_silo_endpoint
TeamDetailsSerializer
python
chroma-core__chroma
chromadb/api/types.py
{ "start": 16553, "end": 16699 }
class ____(TypedDict): ids: Optional[IDs] where: Optional[Where] where_document: Optional[WhereDocument] include: Include
GetRequest
python
dagster-io__dagster
python_modules/libraries/dagster-looker/dagster_looker/api/components/looker_component.py
{ "start": 2212, "end": 8627 }
class ____(StateBackedComponent, Resolvable): """Pulls in the contents of a Looker instance into Dagster assets. Example: .. code-block:: yaml # defs.yaml type: dagster_looker.LookerComponent attributes: looker_resource: base_url: https://your-company.looker.com client_id: "{{ env.LOOKER_CLIENT_ID }}" client_secret: "{{ env.LOOKER_CLIENT_SECRET }}" looker_filter: dashboard_folders: - ["Shared"] only_fetch_explores_used_in_dashboards: true """ looker_resource: Annotated[ LookerResource, Resolver.default( model_field_type=LookerInstanceArgs.model(), description="Configuration for connecting to the Looker instance", examples=[ { "base_url": "https://your-company.looker.com", "client_id": "{{ env.LOOKER_CLIENT_ID }}", "client_secret": "{{ env.LOOKER_CLIENT_SECRET }}", } ], ), ] looker_filter: Annotated[ Optional[LookerFilter], Resolver.default( model_field_type=LookerFilterArgs.model(), description="Filters for which Looker content to load", examples=[ { "dashboard_folders": [["Shared", "Team"]], "only_fetch_explores_used_in_dashboards": True, } ], ), ] = None translation: Optional[ResolvedMultilayerTranslationFn] = None defs_state: ResolvedDefsStateConfig = field( default_factory=DefsStateConfigArgs.legacy_code_server_snapshots ) @property def defs_state_config(self) -> DefsStateConfig: default_key = f"{self.__class__.__name__}[{self.looker_resource.base_url}]" return DefsStateConfig.from_args(self.defs_state, default_key=default_key) @cached_property def translator(self) -> DagsterLookerApiTranslator: translator_cls = create_looker_component_translator(LookerComponent) return translator_cls(self) @cached_property def _base_translator(self) -> DagsterLookerApiTranslator: return DagsterLookerApiTranslator() @public def get_asset_spec(self, looker_structure: LookerApiTranslatorStructureData) -> AssetSpec: """Generates an AssetSpec for a given Looker content item. This method can be overridden in a subclass to customize how Looker content (dashboards, looks, explores) are converted to Dagster asset specs. By default, it delegates to the configured DagsterLookerApiTranslator. Args: looker_structure: The LookerApiTranslatorStructureData containing information about the Looker content item and instance Returns: An AssetSpec that represents the Looker content as a Dagster asset Example: Override this method to add custom tags based on content properties: .. code-block:: python from dagster_looker import LookerComponent from dagster import AssetSpec class CustomLookerComponent(LookerComponent): def get_asset_spec(self, looker_structure): base_spec = super().get_asset_spec(looker_structure) return base_spec.replace_attributes( tags={ **base_spec.tags, "looker_type": looker_structure.structure_data.structure_type, "folder": looker_structure.structure_data.data.get("folder", {}).get("name") } ) """ return self._base_translator.get_asset_spec(looker_structure) def _load_asset_specs(self, state: LookerInstanceData) -> list[AssetSpec]: explores = [ self.translator.get_asset_spec( LookerApiTranslatorStructureData( structure_data=LookerStructureData( structure_type=LookerStructureType.EXPLORE, data=lookml_explore, base_url=self.looker_resource.base_url, ), instance_data=state, ) ) for lookml_explore in state.explores_by_id.values() ] dashboards = [ self.translator.get_asset_spec( LookerApiTranslatorStructureData( structure_data=LookerStructureData( structure_type=LookerStructureType.DASHBOARD, data=looker_dashboard, base_url=self.looker_resource.base_url, ), instance_data=state, ) ) for looker_dashboard in state.dashboards_by_id.values() ] return [*explores, *dashboards] def write_state_to_path(self, state_path: Path) -> None: """Fetches Looker instance data and writes it to the state path.""" sdk = self.looker_resource.get_sdk() # Create a loader to fetch the instance data loader = LookerApiDefsLoader( looker_resource=self.looker_resource, translator=self._base_translator, looker_filter=self.looker_filter or LookerFilter(), ) # Fetch the instance data instance_data = loader.fetch_looker_instance_data() # Convert to state format and serialize state = instance_data.to_state(sdk) state_path.write_text(dg.serialize_value(state)) def build_defs_from_state( self, context: ComponentLoadContext, state_path: Optional[Path] ) -> dg.Definitions: """Builds Dagster definitions from the cached Looker instance state.""" if state_path is None: return dg.Definitions() sdk = self.looker_resource.get_sdk() # Deserialize and convert from state format state = deserialize_value(state_path.read_text(), dict) instance_data = LookerInstanceData.from_state(sdk, state) specs = self._load_asset_specs(instance_data) return dg.Definitions(assets=specs)
LookerComponent
python
pyqtgraph__pyqtgraph
pyqtgraph/opengl/GLViewWidget.py
{ "start": 381, "end": 21555 }
class ____: def __init__(self, *args, rotationMethod='euler', **kwargs): """ Mixin class providing functionality for GLViewWidget ================ ============================================================== **Arguments:** rotationMethod (str): Mechanism to drive the rotation method, options are 'euler' and 'quaternion'. Defaults to 'euler'. ================ ============================================================== """ super().__init__(*args, **kwargs) if rotationMethod not in ["euler", "quaternion"]: raise ValueError("Rotation method should be either 'euler' or 'quaternion'") self.opts = { 'rotationMethod': rotationMethod } self.reset() self.items = [] self.noRepeatKeys = [QtCore.Qt.Key.Key_Right, QtCore.Qt.Key.Key_Left, QtCore.Qt.Key.Key_Up, QtCore.Qt.Key.Key_Down, QtCore.Qt.Key.Key_PageUp, QtCore.Qt.Key.Key_PageDown] self.keysPressed = {} self.keyTimer = QtCore.QTimer() self.keyTimer.timeout.connect(self.evalKeyState) self._modelViewStack = [] self._projectionStack = [] self.default_vao = QtOpenGL.QOpenGLVertexArrayObject(self) def deviceWidth(self): dpr = self.devicePixelRatioF() return int(self.width() * dpr) def deviceHeight(self): dpr = self.devicePixelRatioF() return int(self.height() * dpr) def reset(self): """ Initialize the widget state or reset the current state to the original state. """ self.opts['center'] = Vector(0,0,0) ## will always appear at the center of the widget self.opts['distance'] = 10.0 ## distance of camera from center self.opts['fov'] = 60 ## horizontal field of view in degrees if self.opts['rotationMethod'] == 'quaternion': self.opts['rotation'] = QtGui.QQuaternion(1,0,0,0) ## camera rotation (quaternion:wxyz) else: self.opts['elevation'] = 30 ## camera's angle of elevation in degrees self.opts['azimuth'] = 45 ## camera's azimuthal angle in degrees ## (rotation around z-axis 0 points along x-axis) self.setBackgroundColor(getConfigOption('background')) def addItem(self, item): self.items.append(item) if self.isValid(): item.initialize() item._setView(self) self.update() def removeItem(self, item): """ Remove the item from the scene. """ self.items.remove(item) item._setView(None) self.update() def clear(self): """ Remove all items from the scene. """ for item in self.items: item._setView(None) self.items = [] self.update() def initializeGL(self): """ Initialize items that were not initialized during addItem(). """ ctx = self.context() fmt = ctx.format() if ctx.isOpenGLES(): warnings.warn( f"pyqtgraph.opengl is primarily tested against OpenGL Desktop" f" but OpenGL {fmt.version()} ES detected", RuntimeWarning, stacklevel=2 ) elif fmt.version() < (2, 1): verString = GL.glGetString(GL.GL_VERSION) raise RuntimeError( "pyqtgraph.opengl: Requires >= OpenGL 2.1; Found %s" % verString ) # Core profile requires a non-default VAO if fmt.profile() == QtGui.QSurfaceFormat.OpenGLContextProfile.CoreProfile: if not self.default_vao.isCreated(): self.default_vao.create() self.default_vao.bind() for item in self.items: if not item.isInitialized(): item.initialize() def setBackgroundColor(self, *args, **kwds): """ Set the background color of the widget. Accepts the same arguments as :func:`~pyqtgraph.mkColor`. """ self.opts['bgcolor'] = fn.mkColor(*args, **kwds).getRgbF() self.update() def getViewport(self): return (0, 0, self.width(), self.height()) def setProjection(self, region, viewport): m = self.projectionMatrix(region, viewport) self._projectionStack.clear() self._projectionStack.append(m) def projectionMatrix(self, region, viewport): x0, y0, w, h = viewport dist = self.opts['distance'] fov = self.opts['fov'] nearClip = dist * 0.001 farClip = dist * 1000. r = nearClip * tan(0.5 * radians(fov)) t = r * h / w ## Note that X0 and width in these equations must be the values used in viewport left = r * ((region[0]-x0) * (2.0/w) - 1) right = r * ((region[0]+region[2]-x0) * (2.0/w) - 1) bottom = t * ((region[1]-y0) * (2.0/h) - 1) top = t * ((region[1]+region[3]-y0) * (2.0/h) - 1) tr = QtGui.QMatrix4x4() tr.frustum(left, right, bottom, top, nearClip, farClip) return tr def setModelview(self): m = self.viewMatrix() self._modelViewStack.clear() self._modelViewStack.append(m) def viewMatrix(self): tr = QtGui.QMatrix4x4() tr.translate( 0.0, 0.0, -self.opts['distance']) if self.opts['rotationMethod'] == 'quaternion': tr.rotate(self.opts['rotation']) else: # default rotation method tr.rotate(self.opts['elevation']-90, 1, 0, 0) tr.rotate(self.opts['azimuth']+90, 0, 0, -1) center = self.opts['center'] tr.translate(-center.x(), -center.y(), -center.z()) return tr def currentModelView(self): return self._modelViewStack[-1] def currentProjection(self): return self._projectionStack[-1] def itemsAt(self, region=None): """ Return a list of the items displayed in the region (x, y, w, h) relative to the widget. """ region = (region[0], self.height()-(region[1]+region[3]), region[2], region[3]) viewport = self.getViewport() #buf = np.zeros(100000, dtype=np.uint) buf = GL.glSelectBuffer(100000) try: GL.glRenderMode(GL.GL_SELECT) GL.glInitNames() GL.glPushName(0) self._itemNames = {} self.paint(region=region, viewport=viewport, useItemNames=True) finally: hits = GL.glRenderMode(GL.GL_RENDER) items = [(h.near, h.names[0]) for h in hits] items.sort(key=lambda i: i[0]) return [self._itemNames[i[1]] for i in items] def paintGL(self): # when called by Qt, glViewport has already been called # with device pixel ratio taken of region = self.getViewport() self.paint(region=region, viewport=region) def paint(self, *, region, viewport, useItemNames=False): """ It is caller's responsibility to call glViewport prior to calling this method. region specifies the sub-region of viewport that should be rendered. """ self.setProjection(region, viewport) self.setModelview() bgcolor = self.opts['bgcolor'] GL.glClearColor(*bgcolor) GL.glClear( GL.GL_DEPTH_BUFFER_BIT | GL.GL_COLOR_BUFFER_BIT ) self.drawItemTree(useItemNames=useItemNames) def drawItemTree(self, item=None, useItemNames=False): if item is None: items = [x for x in self.items if x.parentItem() is None] else: items = item.childItems() items.append(item) items.sort(key=lambda a: a.depthValue()) for i in items: if not i.visible(): continue if i is item: try: if useItemNames: GL.glLoadName(i._id) self._itemNames[i._id] = i # The GLGraphicsItem(s) making use of QPainter end # up indirectly unbinding the default VAO, so we # rebind it before each GLGraphicsItem. if self.default_vao.isCreated(): self.default_vao.bind() i.paint() except: from .. import debug debug.printExc() print("Error while drawing item %s." % str(item)) else: self._modelViewStack.append(self.currentModelView() * i.transform()) try: self.drawItemTree(i, useItemNames=useItemNames) finally: self._modelViewStack.pop() def setCameraPosition(self, pos=None, distance=None, elevation=None, azimuth=None, rotation=None): if rotation is not None: # Alternatively, we could define that rotation overrides elevation and azimuth if elevation is not None: raise ValueError("cannot set both rotation and elevation") if azimuth is not None: raise ValueError("cannot set both rotation and azimuth") if pos is not None: self.opts['center'] = pos if distance is not None: self.opts['distance'] = distance if self.opts['rotationMethod'] == "quaternion": # note that "quaternion" mode modifies only opts['rotation'] if elevation is not None or azimuth is not None: eu = self.opts['rotation'].toEulerAngles() if azimuth is not None: eu.setZ(-azimuth-90) if elevation is not None: eu.setX(elevation-90) self.opts['rotation'] = QtGui.QQuaternion.fromEulerAngles(eu) if rotation is not None: self.opts['rotation'] = rotation else: # note that "euler" mode modifies only opts['elevation'] and opts['azimuth'] if elevation is not None: self.opts['elevation'] = elevation if azimuth is not None: self.opts['azimuth'] = azimuth if rotation is not None: eu = rotation.toEulerAngles() self.opts['elevation'] = eu.x() + 90 self.opts['azimuth'] = -eu.z() - 90 self.update() def cameraPosition(self): """Return current position of camera based on center, dist, elevation, and azimuth""" center = self.opts['center'] dist = self.opts['distance'] if self.opts['rotationMethod'] == "quaternion": pos = Vector(center - self.opts['rotation'].rotatedVector(Vector(0,0,dist) )) else: # using 'euler' rotation method elev = radians(self.opts['elevation']) azim = radians(self.opts['azimuth']) pos = Vector( center.x() + dist * cos(elev) * cos(azim), center.y() + dist * cos(elev) * sin(azim), center.z() + dist * sin(elev) ) return pos def setCameraParams(self, **kwds): valid_keys = {'center', 'rotation', 'distance', 'fov', 'elevation', 'azimuth'} if not valid_keys.issuperset(kwds): raise ValueError(f'valid keywords are {valid_keys}') self.setCameraPosition(pos=kwds.get('center'), distance=kwds.get('distance'), elevation=kwds.get('elevation'), azimuth=kwds.get('azimuth'), rotation=kwds.get('rotation')) if 'fov' in kwds: self.opts['fov'] = kwds['fov'] def cameraParams(self): valid_keys = ['center', 'distance', 'fov'] if self.opts['rotationMethod'] == 'quaternion': valid_keys.append('rotation') else: valid_keys.extend(['elevation', 'azimuth']) return { k : self.opts[k] for k in valid_keys } def orbit(self, azim, elev): """Orbits the camera around the center position. *azim* and *elev* are given in degrees.""" if self.opts['rotationMethod'] == 'quaternion': q = QtGui.QQuaternion.fromEulerAngles( elev, -azim, 0 ) # rx-ry-rz q *= self.opts['rotation'] self.opts['rotation'] = q else: # default euler rotation method self.opts['azimuth'] += azim self.opts['elevation'] = fn.clip_scalar(self.opts['elevation'] + elev, -90., 90.) self.update() def pan(self, dx, dy, dz, relative='global'): """ Moves the center (look-at) position while holding the camera in place. ============== ======================================================= **Arguments:** *dx* Distance to pan in x direction *dy* Distance to pan in y direction *dz* Distance to pan in z direction *relative* String that determines the direction of dx,dy,dz. If "global", then the global coordinate system is used. If "view", then the z axis is aligned with the view direction, and x and y axes are in the plane of the view: +x points right, +y points up. If "view-upright", then x is in the global xy plane and points to the right side of the view, y is in the global xy plane and orthogonal to x, and z points in the global z direction. ============== ======================================================= Distances are scaled roughly such that a value of 1.0 moves by one pixel on screen. """ if relative == 'global': self.opts['center'] += QtGui.QVector3D(dx, dy, dz) elif relative == 'view-upright': cPos = self.cameraPosition() cVec = self.opts['center'] - cPos dist = cVec.length() ## distance from camera to center xDist = dist * 2. * tan(0.5 * radians(self.opts['fov'])) ## approx. width of view at distance of center point xScale = xDist / self.width() zVec = QtGui.QVector3D(0,0,1) xVec = QtGui.QVector3D.crossProduct(zVec, cVec).normalized() yVec = QtGui.QVector3D.crossProduct(xVec, zVec).normalized() self.opts['center'] = self.opts['center'] + xVec * xScale * dx + yVec * xScale * dy + zVec * xScale * dz elif relative == 'view': # pan in plane of camera if self.opts['rotationMethod'] == 'quaternion': # obtain basis vectors qc = self.opts['rotation'].conjugated() xv = qc.rotatedVector( Vector(1,0,0) ) yv = qc.rotatedVector( Vector(0,1,0) ) zv = qc.rotatedVector( Vector(0,0,1) ) scale_factor = self.pixelSize( self.opts['center'] ) # apply translation self.opts['center'] += scale_factor * (xv*-dx + yv*dy + zv*dz) else: # use default euler rotation method elev = radians(self.opts['elevation']) azim = radians(self.opts['azimuth']) fov = radians(self.opts['fov']) dist = (self.opts['center'] - self.cameraPosition()).length() fov_factor = tan(fov / 2) * 2 scale_factor = dist * fov_factor / self.width() z = scale_factor * cos(elev) * dy x = scale_factor * (sin(azim) * dx - sin(elev) * cos(azim) * dy) y = scale_factor * (cos(azim) * dx + sin(elev) * sin(azim) * dy) self.opts['center'] += QtGui.QVector3D(x, -y, z) else: raise ValueError("relative argument must be global, view, or view-upright") self.update() def pixelSize(self, pos): """ Return the approximate size of a screen pixel at the location pos Pos may be a Vector or an (N,3) array of locations """ cam = self.cameraPosition() if isinstance(pos, np.ndarray): cam = np.array(cam).reshape((1,)*(pos.ndim-1)+(3,)) dist = ((pos-cam)**2).sum(axis=-1)**0.5 else: dist = (pos-cam).length() xDist = dist * 2. * tan(0.5 * radians(self.opts['fov'])) return xDist / self.width() def mousePressEvent(self, ev): lpos = ev.position() if hasattr(ev, 'position') else ev.localPos() self.mousePos = lpos def mouseMoveEvent(self, ev): lpos = ev.position() if hasattr(ev, 'position') else ev.localPos() if not hasattr(self, 'mousePos'): self.mousePos = lpos diff = lpos - self.mousePos self.mousePos = lpos if ev.buttons() == QtCore.Qt.MouseButton.LeftButton: if (ev.modifiers() & QtCore.Qt.KeyboardModifier.ControlModifier): self.pan(diff.x(), diff.y(), 0, relative='view') else: self.orbit(-diff.x(), diff.y()) elif ev.buttons() == QtCore.Qt.MouseButton.MiddleButton: if (ev.modifiers() & QtCore.Qt.KeyboardModifier.ControlModifier): self.pan(diff.x(), 0, diff.y(), relative='view-upright') else: self.pan(diff.x(), diff.y(), 0, relative='view-upright') def mouseReleaseEvent(self, ev): pass def wheelEvent(self, ev): delta = ev.angleDelta().x() if delta == 0: delta = ev.angleDelta().y() if (ev.modifiers() & QtCore.Qt.KeyboardModifier.ControlModifier): self.opts['fov'] *= 0.999**delta else: self.opts['distance'] *= 0.999**delta self.update() def keyPressEvent(self, ev): if ev.key() in self.noRepeatKeys: ev.accept() if ev.isAutoRepeat(): return self.keysPressed[ev.key()] = 1 self.evalKeyState() def keyReleaseEvent(self, ev): if ev.key() in self.noRepeatKeys: ev.accept() if ev.isAutoRepeat(): return try: del self.keysPressed[ev.key()] except KeyError: self.keysPressed = {} self.evalKeyState() def evalKeyState(self): speed = 2.0 if len(self.keysPressed) > 0: for key in self.keysPressed: if key == QtCore.Qt.Key.Key_Right: self.orbit(azim=-speed, elev=0) elif key == QtCore.Qt.Key.Key_Left: self.orbit(azim=speed, elev=0) elif key == QtCore.Qt.Key.Key_Up: self.orbit(azim=0, elev=-speed) elif key == QtCore.Qt.Key.Key_Down: self.orbit(azim=0, elev=speed) elif key == QtCore.Qt.Key.Key_PageUp: pass elif key == QtCore.Qt.Key.Key_PageDown: pass self.keyTimer.start(16) else: self.keyTimer.stop() def readQImage(self): """ Read the current buffer pixels out as a QImage. """ return self.grabFramebuffer() def renderToArray(self, size, format=GL.GL_BGRA, type=GL.GL_UNSIGNED_BYTE, textureSize=1024, padding=256): w,h = map(int, size) self.makeCurrent() texwidth = textureSize fbo = QtOpenGL.QOpenGLFramebufferObject(texwidth, texwidth, QtOpenGL.QOpenGLFramebufferObject.Attachment.CombinedDepthStencil, GL.GL_TEXTURE_2D) output = np.empty((h, w, 4), dtype=np.ubyte) data = np.empty((texwidth, texwidth, 4), dtype=np.ubyte) try: p2 = 2 * padding for x in range(-padding, w-padding, texwidth-p2): for y in range(-padding, h-padding, texwidth-p2): x2 = min(x+texwidth, w+padding) y2 = min(y+texwidth, h+padding) w2 = x2-x h2 = y2-y fbo.bind() GL.glViewport(0, 0, w2, h2) self.paint(region=(x, h-y-h2, w2, h2), viewport=(0, 0, w, h)) # only render sub-region fbo.bind() GL.glReadPixels(0, 0, texwidth, texwidth, format, type, data) data_yflip = data[::-1, ...] output[y+padding:y2-padding, x+padding:x2-padding] = data_yflip[-(h2-padding):-padding, padding:w2-padding] finally: fbo.release() return output
GLViewMixin
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vector_index.py
{ "start": 6894, "end": 7198 }
class ____(_QuantizerConfigCreate): bitCompression: Optional[bool] = Field(default=None) centroids: Optional[int] encoder: _PQEncoderConfigCreate segments: Optional[int] trainingLimit: Optional[int] @staticmethod def quantizer_name() -> str: return "pq"
_PQConfigCreate
python
django__django
django/db/models/manager.py
{ "start": 167, "end": 5834 }
class ____: # To retain order, track each time a Manager instance is created. creation_counter = 0 # Set to True for the 'objects' managers that are automatically created. auto_created = False #: If set to True the manager will be serialized into migrations and will #: thus be available in e.g. RunPython operations. use_in_migrations = False def __new__(cls, *args, **kwargs): # Capture the arguments to make returning them trivial. obj = super().__new__(cls) obj._constructor_args = (args, kwargs) return obj def __init__(self): super().__init__() self._set_creation_counter() self.model = None self.name = None self._db = None self._hints = {} def __str__(self): """Return "app_label.model_label.manager_name".""" return "%s.%s" % (self.model._meta.label, self.name) def __class_getitem__(cls, *args, **kwargs): return cls def deconstruct(self): """ Return a 5-tuple of the form (as_manager (True), manager_class, queryset_class, args, kwargs). Raise a ValueError if the manager is dynamically generated. """ qs_class = self._queryset_class if getattr(self, "_built_with_as_manager", False): # using MyQuerySet.as_manager() return ( True, # as_manager None, # manager_class "%s.%s" % (qs_class.__module__, qs_class.__name__), # qs_class None, # args None, # kwargs ) else: module_name = self.__module__ name = self.__class__.__name__ # Make sure it's actually there and not an inner class module = import_module(module_name) if not hasattr(module, name): raise ValueError( "Could not find manager %s in %s.\n" "Please note that you need to inherit from managers you " "dynamically generated with 'from_queryset()'." % (name, module_name) ) return ( False, # as_manager "%s.%s" % (module_name, name), # manager_class None, # qs_class self._constructor_args[0], # args self._constructor_args[1], # kwargs ) def check(self, **kwargs): return [] @classmethod def _get_queryset_methods(cls, queryset_class): def create_method(name, method): @wraps(method) def manager_method(self, *args, **kwargs): return getattr(self.get_queryset(), name)(*args, **kwargs) return manager_method new_methods = {} for name, method in inspect.getmembers( queryset_class, predicate=inspect.isfunction ): # Only copy missing methods. if hasattr(cls, name): continue # Only copy public methods or methods with the attribute # queryset_only=False. queryset_only = getattr(method, "queryset_only", None) if queryset_only or (queryset_only is None and name.startswith("_")): continue # Copy the method onto the manager. new_methods[name] = create_method(name, method) return new_methods @classmethod def from_queryset(cls, queryset_class, class_name=None): if class_name is None: class_name = "%sFrom%s" % (cls.__name__, queryset_class.__name__) return type( class_name, (cls,), { "_queryset_class": queryset_class, **cls._get_queryset_methods(queryset_class), }, ) def contribute_to_class(self, cls, name): self.name = self.name or name self.model = cls setattr(cls, name, ManagerDescriptor(self)) cls._meta.add_manager(self) def _set_creation_counter(self): """ Set the creation counter value for this instance and increment the class-level copy. """ self.creation_counter = BaseManager.creation_counter BaseManager.creation_counter += 1 def db_manager(self, using=None, hints=None): obj = copy.copy(self) obj._db = using or self._db obj._hints = hints or self._hints return obj @property def db(self): return self._db or router.db_for_read(self.model, **self._hints) ####################### # PROXIES TO QUERYSET # ####################### def get_queryset(self): """ Return a new QuerySet object. Subclasses can override this method to customize the behavior of the Manager. """ return self._queryset_class(model=self.model, using=self._db, hints=self._hints) def all(self): # We can't proxy this method through the `QuerySet` like we do for the # rest of the `QuerySet` methods. This is because `QuerySet.all()` # works by creating a "copy" of the current queryset and in making said # copy, all the cached `prefetch_related` lookups are lost. See the # implementation of `RelatedManager.get_queryset()` for a better # understanding of how this comes into play. return self.get_queryset() def __eq__(self, other): return ( isinstance(other, self.__class__) and self._constructor_args == other._constructor_args ) def __hash__(self): return id(self)
BaseManager
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/refurb/FURB118.py
{ "start": 2232, "end": 2314 }
class ____: y = lambda self, other: self == other from typing import Callable
Bar
python
pydantic__pydantic
tests/mypy/modules/metaclass_args.py
{ "start": 40, "end": 186 }
class ____(BaseModel): i: int = Field(2, alias='j') class Config: validate_by_name = True ConfigClassUsed(i=None)
ConfigClassUsed
python
geekcomputers__Python
LinkedLists all Types/singly_linked_list.py
{ "start": 626, "end": 6669 }
class ____: def __init__(self): self.head = self.tail = None self.length = 0 def insert_front(self, data): node = Node(data, self.head) if self.head == None: self.tail = node self.head = node self.length += 1 def insert_back(self, data): node = Node(data) if self.head == None: self.tail = self.head = node self.length += 1 else: self.tail.next = node self.tail = node self.length += 1 def insert_values(self, data_values: list): self.head = self.tail = None self.length = 0 for data in data_values: self.insert_back(data) def pop_front(self): if not self.head: print("List is Empty!") return temp = self.head self.head = self.head.next temp.next = None self.length -= 1 def pop_back(self): if not self.head: print("List is Empty!") return temp = self.head while temp.next != self.tail: temp = temp.next self.tail = temp temp.next = None self.length -= 1 def print(self): if self.head is None: print("Linked List is Empty!") return temp = self.head while temp: print(f"{temp.data} ->", end=" ") temp = temp.next print("NULL") def len(self): return self.length # O(1) length calculation # if self.head is None: # return 0 # count = 0 # temp = self.head # while temp: # count += 1 # temp = temp.next # return count def remove_at(self, idx): if idx < 0 or self.len() <= idx: raise Exception("Invalid Position") if idx == 0: self.head = self.head.next self.length -= 1 return temp = self.head dist = 0 while dist != idx - 1: dist += 1 temp = temp.next temp.next = temp.next.next self.length -= 1 def insert_at(self, idx: int, data): if idx < 0 or self.len() < idx: raise Exception("Invalid Position") if idx == 0: self.insert_front(data) return temp = self.head dist = 0 while dist != idx - 1: dist += 1 temp = temp.next node = Node(data, temp.next) temp.next = node self.length += 1 def insert_after_value(self, idx_data, data): if not self.head: # For Empty List case print("List is Empty!") return if self.head.data == idx_data: # To insert after the Head Element self.insert_at(1, data) return temp = self.head while temp: if temp.data == idx_data: node = Node(data, temp.next) temp.next = node self.length += 1 return temp = temp.next print("The Element is not in the List!") def remove_by_value(self, idx_data): temp = self.head if temp.data == idx_data: self.head = self.head.next self.length -= 1 temp.next = None return while temp.next != None: if temp.next.data == idx_data: temp.next = temp.next.next self.length -= 1 return temp = temp.next print("Element is not in the List!") def index(self, data): """Returns the index of the Element""" if not self.head: print("List is Empty!") return idx = 0 temp = self.head while temp: if temp.data == data: return idx temp = temp.next idx += 1 print("The Element is not in the List!") def search(self, idx): """Returns the Element at the Given Index""" if self.len() == 0 or idx >= self.len(): raise Exception("Invalid Position") return temp = self.head curr_idx = 0 while temp: if curr_idx == idx: return temp.data temp = temp.next curr_idx += 1 def reverse(self): if not self.head: print("The List is Empty!") return prev = c_next = None curr = self.head while curr != None: c_next = curr.next curr.next = prev prev = curr curr = c_next self.tail = self.head self.head = prev def mid_element(self): if not self.head: print("List is Empty!") return slow = self.head.next fast = self.head.next.next while fast != None and fast.next != None: slow = slow.next fast = fast.next.next return slow.data def __dir__(self): funcs = [ "insert_front", "insert_back", "pop_front", "pop_back", "print", "len", "length", "remove_at", "insert_after_value", "index", "search", "reverse", "mid_element", "__dir__", ] return funcs def main(): ll: Node = LinkedList() # # ll.insert_front(1) # # ll.insert_front(2) # # ll.insert_front(3) # # ll.insert_back(0) # ll.insert_values(['ZeroTwo' , 'Asuna' , 'Tsukasa' , 'Seras' ]) # # ll.remove_at(3) # ll.insert_at(2 , 'Raeliana') # # ll.pop_front() # ll.insert_after_value('Raeliana' , 'MaoMao') # # print(ll.search(5)) # ll.remove_by_value('Tsukasa') # ll.reverse() # ll.print() # print(ll.mid_element()) # print(ll.length) print(ll.__dir__()) if __name__ == "__main__": main()
LinkedList
python
pypa__setuptools
setuptools/extension.py
{ "start": 896, "end": 6720 }
class ____(_Extension): """ Describes a single extension module. This means that all source files will be compiled into a single binary file ``<module path>.<suffix>`` (with ``<module path>`` derived from ``name`` and ``<suffix>`` defined by one of the values in ``importlib.machinery.EXTENSION_SUFFIXES``). In the case ``.pyx`` files are passed as ``sources and`` ``Cython`` is **not** installed in the build environment, ``setuptools`` may also try to look for the equivalent ``.cpp`` or ``.c`` files. :arg str name: the full name of the extension, including any packages -- ie. *not* a filename or pathname, but Python dotted name :arg Iterable[str | os.PathLike[str]] sources: iterable of source filenames, (except strings, which could be misinterpreted as a single filename), relative to the distribution root (where the setup script lives), in Unix form (slash-separated) for portability. Source files may be C, C++, SWIG (.i), platform-specific resource files, or whatever else is recognized by the "build_ext" command as source for a Python extension. :keyword list[str] include_dirs: list of directories to search for C/C++ header files (in Unix form for portability) :keyword list[tuple[str, str|None]] define_macros: list of macros to define; each macro is defined using a 2-tuple: the first item corresponding to the name of the macro and the second item either a string with its value or None to define it without a particular value (equivalent of "#define FOO" in source or -DFOO on Unix C compiler command line) :keyword list[str] undef_macros: list of macros to undefine explicitly :keyword list[str] library_dirs: list of directories to search for C/C++ libraries at link time :keyword list[str] libraries: list of library names (not filenames or paths) to link against :keyword list[str] runtime_library_dirs: list of directories to search for C/C++ libraries at run time (for shared extensions, this is when the extension is loaded). Setting this will cause an exception during build on Windows platforms. :keyword list[str] extra_objects: list of extra files to link with (eg. object files not implied by 'sources', static library that must be explicitly specified, binary resource files, etc.) :keyword list[str] extra_compile_args: any extra platform- and compiler-specific information to use when compiling the source files in 'sources'. For platforms and compilers where "command line" makes sense, this is typically a list of command-line arguments, but for other platforms it could be anything. :keyword list[str] extra_link_args: any extra platform- and compiler-specific information to use when linking object files together to create the extension (or to create a new static Python interpreter). Similar interpretation as for 'extra_compile_args'. :keyword list[str] export_symbols: list of symbols to be exported from a shared extension. Not used on all platforms, and not generally necessary for Python extensions, which typically export exactly one symbol: "init" + extension_name. :keyword list[str] swig_opts: any extra options to pass to SWIG if a source file has the .i extension. :keyword list[str] depends: list of files that the extension depends on :keyword str language: extension language (i.e. "c", "c++", "objc"). Will be detected from the source extensions if not provided. :keyword bool optional: specifies that a build failure in the extension should not abort the build process, but simply not install the failing extension. :keyword bool py_limited_api: opt-in flag for the usage of :doc:`Python's limited API <python:c-api/stable>`. :raises setuptools.errors.PlatformError: if ``runtime_library_dirs`` is specified on Windows. (since v63) """ # These 4 are set and used in setuptools/command/build_ext.py # The lack of a default value and risk of `AttributeError` is purposeful # to avoid people forgetting to call finalize_options if they modify the extension list. # See example/rationale in https://github.com/pypa/setuptools/issues/4529. _full_name: str #: Private API, internal use only. _links_to_dynamic: bool #: Private API, internal use only. _needs_stub: bool #: Private API, internal use only. _file_name: str #: Private API, internal use only. def __init__( self, name: str, sources: Iterable[StrPath], *args, py_limited_api: bool = False, **kw, ) -> None: # The *args is needed for compatibility as calls may use positional # arguments. py_limited_api may be set only via keyword. self.py_limited_api = py_limited_api super().__init__( name, sources, # type: ignore[arg-type] # Vendored version of setuptools supports PathLike *args, **kw, ) def _convert_pyx_sources_to_lang(self): """ Replace sources with .pyx extensions to sources with the target language extension. This mechanism allows language authors to supply pre-converted sources but to prefer the .pyx sources. """ if _have_cython(): # the build has Cython, so allow it to compile the .pyx files return lang = self.language or '' target_ext = '.cpp' if lang.lower() == 'c++' else '.c' sub = functools.partial(re.sub, '.pyx$', target_ext) self.sources = list(map(sub, self.sources))
Extension
python
spyder-ide__spyder
spyder/plugins/run/api.py
{ "start": 16114, "end": 16968 }
class ____: """ Interface used to display run execution results. This API needs to be implemented by any plugin that wants to display an output produced by a :class:`RunResultViewer`. It also needs to be covariant with respect to :class:`spyder.api.plugins.SpyderPluginV2` """ def display_run_result(self, result: RunResult): """ Display the output of a run execution. Arguments --------- result: RunResult A `RunResult` entry that contains the run execution information, including both input and execution metadata, as well as the result representation in a format that the `RunResultViewer` instance supports. """ raise NotImplementedError( f'{type(self)} must implement display_run_result')
RunResultViewer
python
apache__airflow
providers/apache/livy/src/airflow/providers/apache/livy/operators/livy.py
{ "start": 1509, "end": 11268 }
class ____(BaseOperator): """ Wraps the Apache Livy batch REST API, allowing to submit a Spark application to the underlying cluster. :param file: path of the file containing the application to execute (required). (templated) :param class_name: name of the application Java/Spark main class. (templated) :param args: application command line arguments. (templated) :param jars: jars to be used in this sessions. (templated) :param py_files: python files to be used in this session. (templated) :param files: files to be used in this session. (templated) :param driver_memory: amount of memory to use for the driver process. (templated) :param driver_cores: number of cores to use for the driver process. (templated) :param executor_memory: amount of memory to use per executor process. (templated) :param executor_cores: number of cores to use for each executor. (templated) :param num_executors: number of executors to launch for this session. (templated) :param archives: archives to be used in this session. (templated) :param queue: name of the YARN queue to which the application is submitted. (templated) :param name: name of this session. (templated) :param conf: Spark configuration properties. (templated) :param proxy_user: user to impersonate when running the job. (templated) :param livy_conn_id: reference to a pre-defined Livy Connection. :param livy_conn_auth_type: The auth type for the Livy Connection. :param polling_interval: time in seconds between polling for job completion. Don't poll for values <= 0 :param extra_options: A dictionary of options, where key is string and value depends on the option that's being modified. :param extra_headers: A dictionary of headers passed to the HTTP request to livy. :param retry_args: Arguments which define the retry behaviour. See Tenacity documentation at https://github.com/jd/tenacity :param deferrable: Run operator in the deferrable mode """ template_fields: Sequence[str] = ("spark_params",) template_fields_renderers = {"spark_params": "json"} def __init__( self, *, file: str, class_name: str | None = None, args: Sequence[str | int | float] | None = None, conf: dict[Any, Any] | None = None, jars: Sequence[str] | None = None, py_files: Sequence[str] | None = None, files: Sequence[str] | None = None, driver_memory: str | None = None, driver_cores: int | str | None = None, executor_memory: str | None = None, executor_cores: int | str | None = None, num_executors: int | str | None = None, archives: Sequence[str] | None = None, queue: str | None = None, name: str | None = None, proxy_user: str | None = None, livy_conn_id: str = "livy_default", livy_conn_auth_type: Any | None = None, livy_endpoint_prefix: str | None = None, polling_interval: int = 0, extra_options: dict[str, Any] | None = None, extra_headers: dict[str, Any] | None = None, retry_args: dict[str, Any] | None = None, deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False), openlineage_inject_parent_job_info: bool = conf.getboolean( "openlineage", "spark_inject_parent_job_info", fallback=False ), openlineage_inject_transport_info: bool = conf.getboolean( "openlineage", "spark_inject_transport_info", fallback=False ), **kwargs: Any, ) -> None: super().__init__(**kwargs) if conf is None: conf = {} spark_params = { # Prepare spark parameters, it will be templated later. "file": file, "class_name": class_name, "args": args, "jars": jars, "py_files": py_files, "files": files, "driver_memory": driver_memory, "driver_cores": driver_cores, "executor_memory": executor_memory, "executor_cores": executor_cores, "num_executors": num_executors, "archives": archives, "queue": queue, "name": name, "conf": conf, "proxy_user": proxy_user, } self.spark_params = spark_params self._livy_conn_id = livy_conn_id self._livy_conn_auth_type = livy_conn_auth_type self._livy_endpoint_prefix = livy_endpoint_prefix self._polling_interval = polling_interval self._extra_options = extra_options or {} self._extra_headers = extra_headers or {} self._batch_id: int | str | None = None self.retry_args = retry_args self.deferrable = deferrable self.openlineage_inject_parent_job_info = openlineage_inject_parent_job_info self.openlineage_inject_transport_info = openlineage_inject_transport_info @cached_property def hook(self) -> LivyHook: """ Get valid hook. :return: LivyHook """ return LivyHook( livy_conn_id=self._livy_conn_id, extra_headers=self._extra_headers, extra_options=self._extra_options, auth_type=self._livy_conn_auth_type, endpoint_prefix=self._livy_endpoint_prefix, ) def execute(self, context: Context) -> Any: if self.openlineage_inject_parent_job_info: self.log.debug("Injecting parent job information into Spark properties") self.spark_params["conf"] = inject_parent_job_information_into_spark_properties( cast("dict", self.spark_params["conf"]), context ) if self.openlineage_inject_transport_info: self.log.debug("Injecting transport information into Spark properties") self.spark_params["conf"] = inject_transport_information_into_spark_properties( cast("dict", self.spark_params["conf"]), context ) _batch_id: int | str = self.hook.post_batch(**self.spark_params) self._batch_id = _batch_id self.log.info("Generated batch-id is %s", self._batch_id) # Wait for the job to complete if not self.deferrable: if self._polling_interval > 0: self.poll_for_termination(self._batch_id) context["ti"].xcom_push(key="app_id", value=self.hook.get_batch(self._batch_id)["appId"]) return self._batch_id state = self.hook.get_batch_state(self._batch_id, retry_args=self.retry_args) self.log.debug("Batch with id %s is in state: %s", self._batch_id, state.value) if state not in self.hook.TERMINAL_STATES: self.defer( timeout=self.execution_timeout, trigger=LivyTrigger( batch_id=self._batch_id, spark_params=self.spark_params, livy_conn_id=self._livy_conn_id, polling_interval=self._polling_interval, extra_options=self._extra_options, extra_headers=self._extra_headers, execution_timeout=self.execution_timeout, ), method_name="execute_complete", ) else: self.log.info("Batch with id %s terminated with state: %s", self._batch_id, state.value) self.hook.dump_batch_logs(self._batch_id) if state != BatchState.SUCCESS: raise AirflowException(f"Batch {self._batch_id} did not succeed") context["ti"].xcom_push(key="app_id", value=self.hook.get_batch(self._batch_id)["appId"]) return self._batch_id def poll_for_termination(self, batch_id: int | str) -> None: """ Pool Livy for batch termination. :param batch_id: id of the batch session to monitor. """ state = self.hook.get_batch_state(batch_id, retry_args=self.retry_args) while state not in self.hook.TERMINAL_STATES: self.log.debug("Batch with id %s is in state: %s", batch_id, state.value) time.sleep(self._polling_interval) state = self.hook.get_batch_state(batch_id, retry_args=self.retry_args) self.log.info("Batch with id %s terminated with state: %s", batch_id, state.value) self.hook.dump_batch_logs(batch_id) if state != BatchState.SUCCESS: raise AirflowException(f"Batch {batch_id} did not succeed") def on_kill(self) -> None: self.kill() def kill(self) -> None: """Delete the current batch session.""" if self._batch_id is not None: self.hook.delete_batch(self._batch_id) def execute_complete(self, context: Context, event: dict[str, Any]) -> Any: """ Execute when the trigger fires - returns immediately. Relies on trigger to throw an exception, otherwise it assumes execution was successful. """ # dump the logs from livy to worker through triggerer. if event.get("log_lines", None) is not None: for log_line in event["log_lines"]: self.log.info(log_line) if event["status"] == "timeout": self.hook.delete_batch(event["batch_id"]) if event["status"] in ["error", "timeout"]: raise AirflowException(event["response"]) self.log.info( "%s completed with response %s", self.task_id, event["response"], ) context["ti"].xcom_push(key="app_id", value=self.hook.get_batch(event["batch_id"])["appId"]) return event["batch_id"]
LivyOperator
python
apache__airflow
providers/google/tests/unit/google/leveldb/operators/test_leveldb.py
{ "start": 2001, "end": 2546 }
class ____: @mock.patch.dict("os.environ", AIRFLOW_CONN_LEVELDB_DEFAULT="test") @mock.patch.object(LevelDBHook, "run") def test_execute(self, mock_run): operator = LevelDBOperator( task_id="test_task", leveldb_conn_id="leveldb_default", command="put", key=b"key", value=b"value", ) operator.execute(context="TEST_CONTEXT_ID") mock_run.assert_called_once_with(command="put", value=b"value", key=b"key", values=None, keys=None)
TestLevelDBOperator
python
getsentry__sentry
src/sentry/shared_integrations/exceptions/__init__.py
{ "start": 4506, "end": 4558 }
class ____(ApiError): code = 403
ApiForbiddenError
python
python__mypy
mypy/test/testtypes.py
{ "start": 6868, "end": 24309 }
class ____(Suite): def setUp(self) -> None: self.fx = TypeFixture(INVARIANT) self.fx_co = TypeFixture(COVARIANT) self.fx_contra = TypeFixture(CONTRAVARIANT) # expand_type def test_trivial_expand(self) -> None: for t in ( self.fx.a, self.fx.o, self.fx.t, self.fx.nonet, self.tuple(self.fx.a), self.callable([], self.fx.a, self.fx.a), self.fx.anyt, ): self.assert_expand(t, [], t) self.assert_expand(t, [], t) self.assert_expand(t, [], t) def test_trivial_expand_recursive(self) -> None: A, _ = self.fx.def_alias_1(self.fx.a) self.assert_expand(A, [], A) A, _ = self.fx.def_alias_2(self.fx.a) self.assert_expand(A, [], A) def test_expand_naked_type_var(self) -> None: self.assert_expand(self.fx.t, [(self.fx.t.id, self.fx.a)], self.fx.a) self.assert_expand(self.fx.t, [(self.fx.s.id, self.fx.a)], self.fx.t) def test_expand_basic_generic_types(self) -> None: self.assert_expand(self.fx.gt, [(self.fx.t.id, self.fx.a)], self.fx.ga) # IDEA: Add test cases for # tuple types # callable types # multiple arguments def assert_expand( self, orig: Type, map_items: list[tuple[TypeVarId, Type]], result: Type ) -> None: lower_bounds = {} for id, t in map_items: lower_bounds[id] = t exp = mypy.expandtype.expand_type(orig, lower_bounds) # Remove erased tags (asterisks). assert_equal(str(exp).replace("*", ""), str(result)) # erase_type def test_trivial_erase(self) -> None: for t in (self.fx.a, self.fx.o, self.fx.nonet, self.fx.anyt): self.assert_erase(t, t) def test_erase_with_type_variable(self) -> None: self.assert_erase(self.fx.t, self.fx.anyt) def test_erase_with_generic_type(self) -> None: self.assert_erase(self.fx.ga, self.fx.gdyn) self.assert_erase(self.fx.hab, Instance(self.fx.hi, [self.fx.anyt, self.fx.anyt])) def test_erase_with_generic_type_recursive(self) -> None: tuple_any = Instance(self.fx.std_tuplei, [AnyType(TypeOfAny.explicit)]) A, _ = self.fx.def_alias_1(self.fx.a) self.assert_erase(A, tuple_any) A, _ = self.fx.def_alias_2(self.fx.a) self.assert_erase(A, UnionType([self.fx.a, tuple_any])) def test_erase_with_tuple_type(self) -> None: self.assert_erase(self.tuple(self.fx.a), self.fx.std_tuple) def test_erase_with_function_type(self) -> None: self.assert_erase( self.fx.callable(self.fx.a, self.fx.b), CallableType( arg_types=[self.fx.anyt, self.fx.anyt], arg_kinds=[ARG_STAR, ARG_STAR2], arg_names=[None, None], ret_type=self.fx.anyt, fallback=self.fx.function, ), ) def test_erase_with_type_object(self) -> None: self.assert_erase( self.fx.callable_type(self.fx.a, self.fx.b), CallableType( arg_types=[self.fx.anyt, self.fx.anyt], arg_kinds=[ARG_STAR, ARG_STAR2], arg_names=[None, None], ret_type=self.fx.anyt, fallback=self.fx.type_type, ), ) def test_erase_with_type_type(self) -> None: self.assert_erase(self.fx.type_a, self.fx.type_a) self.assert_erase(self.fx.type_t, self.fx.type_any) def assert_erase(self, orig: Type, result: Type) -> None: assert_equal(str(erase_type(orig)), str(result)) # is_more_precise def test_is_more_precise(self) -> None: fx = self.fx assert is_more_precise(fx.b, fx.a) assert is_more_precise(fx.b, fx.b) assert is_more_precise(fx.b, fx.b) assert is_more_precise(fx.b, fx.anyt) assert is_more_precise(self.tuple(fx.b, fx.a), self.tuple(fx.b, fx.a)) assert is_more_precise(self.tuple(fx.b, fx.b), self.tuple(fx.b, fx.a)) assert not is_more_precise(fx.a, fx.b) assert not is_more_precise(fx.anyt, fx.b) # is_proper_subtype def test_is_proper_subtype(self) -> None: fx = self.fx assert is_proper_subtype(fx.a, fx.a) assert is_proper_subtype(fx.b, fx.a) assert is_proper_subtype(fx.b, fx.o) assert is_proper_subtype(fx.b, fx.o) assert not is_proper_subtype(fx.a, fx.b) assert not is_proper_subtype(fx.o, fx.b) assert is_proper_subtype(fx.anyt, fx.anyt) assert not is_proper_subtype(fx.a, fx.anyt) assert not is_proper_subtype(fx.anyt, fx.a) assert is_proper_subtype(fx.ga, fx.ga) assert is_proper_subtype(fx.gdyn, fx.gdyn) assert not is_proper_subtype(fx.ga, fx.gdyn) assert not is_proper_subtype(fx.gdyn, fx.ga) assert is_proper_subtype(fx.t, fx.t) assert not is_proper_subtype(fx.t, fx.s) assert is_proper_subtype(fx.a, UnionType([fx.a, fx.b])) assert is_proper_subtype(UnionType([fx.a, fx.b]), UnionType([fx.a, fx.b, fx.c])) assert not is_proper_subtype(UnionType([fx.a, fx.b]), UnionType([fx.b, fx.c])) def test_is_proper_subtype_covariance(self) -> None: fx_co = self.fx_co assert is_proper_subtype(fx_co.gsab, fx_co.gb) assert is_proper_subtype(fx_co.gsab, fx_co.ga) assert not is_proper_subtype(fx_co.gsaa, fx_co.gb) assert is_proper_subtype(fx_co.gb, fx_co.ga) assert not is_proper_subtype(fx_co.ga, fx_co.gb) def test_is_proper_subtype_contravariance(self) -> None: fx_contra = self.fx_contra assert is_proper_subtype(fx_contra.gsab, fx_contra.gb) assert not is_proper_subtype(fx_contra.gsab, fx_contra.ga) assert is_proper_subtype(fx_contra.gsaa, fx_contra.gb) assert not is_proper_subtype(fx_contra.gb, fx_contra.ga) assert is_proper_subtype(fx_contra.ga, fx_contra.gb) def test_is_proper_subtype_invariance(self) -> None: fx = self.fx assert is_proper_subtype(fx.gsab, fx.gb) assert not is_proper_subtype(fx.gsab, fx.ga) assert not is_proper_subtype(fx.gsaa, fx.gb) assert not is_proper_subtype(fx.gb, fx.ga) assert not is_proper_subtype(fx.ga, fx.gb) def test_is_proper_subtype_and_subtype_literal_types(self) -> None: fx = self.fx lit1 = fx.lit1 lit2 = fx.lit2 lit3 = fx.lit3 assert is_proper_subtype(lit1, fx.a) assert not is_proper_subtype(lit1, fx.d) assert not is_proper_subtype(fx.a, lit1) assert is_proper_subtype(fx.uninhabited, lit1) assert not is_proper_subtype(lit1, fx.uninhabited) assert is_proper_subtype(lit1, lit1) assert not is_proper_subtype(lit1, lit2) assert not is_proper_subtype(lit2, lit3) assert is_subtype(lit1, fx.a) assert not is_subtype(lit1, fx.d) assert not is_subtype(fx.a, lit1) assert is_subtype(fx.uninhabited, lit1) assert not is_subtype(lit1, fx.uninhabited) assert is_subtype(lit1, lit1) assert not is_subtype(lit1, lit2) assert not is_subtype(lit2, lit3) assert not is_proper_subtype(lit1, fx.anyt) assert not is_proper_subtype(fx.anyt, lit1) assert is_subtype(lit1, fx.anyt) assert is_subtype(fx.anyt, lit1) def test_subtype_aliases(self) -> None: A1, _ = self.fx.def_alias_1(self.fx.a) AA1, _ = self.fx.def_alias_1(self.fx.a) assert is_subtype(A1, AA1) assert is_subtype(AA1, A1) A2, _ = self.fx.def_alias_2(self.fx.a) AA2, _ = self.fx.def_alias_2(self.fx.a) assert is_subtype(A2, AA2) assert is_subtype(AA2, A2) B1, _ = self.fx.def_alias_1(self.fx.b) B2, _ = self.fx.def_alias_2(self.fx.b) assert is_subtype(B1, A1) assert is_subtype(B2, A2) assert not is_subtype(A1, B1) assert not is_subtype(A2, B2) assert not is_subtype(A2, A1) assert is_subtype(A1, A2) # can_be_true / can_be_false def test_empty_tuple_always_false(self) -> None: tuple_type = self.tuple() assert tuple_type.can_be_false assert not tuple_type.can_be_true def test_nonempty_tuple_always_true(self) -> None: tuple_type = self.tuple(AnyType(TypeOfAny.special_form), AnyType(TypeOfAny.special_form)) assert tuple_type.can_be_true assert not tuple_type.can_be_false def test_union_can_be_true_if_any_true(self) -> None: union_type = UnionType([self.fx.a, self.tuple()]) assert union_type.can_be_true def test_union_can_not_be_true_if_none_true(self) -> None: union_type = UnionType([self.tuple(), self.tuple()]) assert not union_type.can_be_true def test_union_can_be_false_if_any_false(self) -> None: union_type = UnionType([self.fx.a, self.tuple()]) assert union_type.can_be_false def test_union_can_not_be_false_if_none_false(self) -> None: union_type = UnionType([self.tuple(self.fx.a), self.tuple(self.fx.d)]) assert not union_type.can_be_false # true_only / false_only def test_true_only_of_false_type_is_uninhabited(self) -> None: to = true_only(NoneType()) assert_type(UninhabitedType, to) def test_true_only_of_true_type_is_idempotent(self) -> None: always_true = self.tuple(AnyType(TypeOfAny.special_form)) to = true_only(always_true) assert always_true is to def test_true_only_of_instance(self) -> None: to = true_only(self.fx.a) assert_equal(str(to), "A") assert to.can_be_true assert not to.can_be_false assert_type(Instance, to) # The original class still can be false assert self.fx.a.can_be_false def test_true_only_of_union(self) -> None: tup_type = self.tuple(AnyType(TypeOfAny.special_form)) # Union of something that is unknown, something that is always true, something # that is always false union_type = UnionType([self.fx.a, tup_type, self.tuple()]) to = true_only(union_type) assert isinstance(to, UnionType) assert_equal(len(to.items), 2) assert to.items[0].can_be_true assert not to.items[0].can_be_false assert to.items[1] is tup_type def test_false_only_of_true_type_is_uninhabited(self) -> None: with state.strict_optional_set(True): fo = false_only(self.tuple(AnyType(TypeOfAny.special_form))) assert_type(UninhabitedType, fo) def test_false_only_tuple(self) -> None: with state.strict_optional_set(False): fo = false_only(self.tuple(self.fx.a)) assert_equal(fo, NoneType()) with state.strict_optional_set(True): fo = false_only(self.tuple(self.fx.a)) assert_equal(fo, UninhabitedType()) def test_false_only_of_false_type_is_idempotent(self) -> None: always_false = NoneType() fo = false_only(always_false) assert always_false is fo def test_false_only_of_instance(self) -> None: fo = false_only(self.fx.a) assert_equal(str(fo), "A") assert not fo.can_be_true assert fo.can_be_false assert_type(Instance, fo) # The original class still can be true assert self.fx.a.can_be_true def test_false_only_of_union(self) -> None: with state.strict_optional_set(True): tup_type = self.tuple() # Union of something that is unknown, something that is always true, something # that is always false union_type = UnionType( [self.fx.a, self.tuple(AnyType(TypeOfAny.special_form)), tup_type] ) assert_equal(len(union_type.items), 3) fo = false_only(union_type) assert isinstance(fo, UnionType) assert_equal(len(fo.items), 2) assert not fo.items[0].can_be_true assert fo.items[0].can_be_false assert fo.items[1] is tup_type def test_simplified_union(self) -> None: fx = self.fx self.assert_simplified_union([fx.a, fx.a], fx.a) self.assert_simplified_union([fx.a, fx.b], fx.a) self.assert_simplified_union([fx.a, fx.d], UnionType([fx.a, fx.d])) self.assert_simplified_union([fx.a, fx.uninhabited], fx.a) self.assert_simplified_union([fx.ga, fx.gs2a], fx.ga) self.assert_simplified_union([fx.ga, fx.gsab], UnionType([fx.ga, fx.gsab])) self.assert_simplified_union([fx.ga, fx.gsba], fx.ga) self.assert_simplified_union([fx.a, UnionType([fx.d])], UnionType([fx.a, fx.d])) self.assert_simplified_union([fx.a, UnionType([fx.a])], fx.a) self.assert_simplified_union( [fx.b, UnionType([fx.c, UnionType([fx.d])])], UnionType([fx.b, fx.c, fx.d]) ) def test_simplified_union_with_literals(self) -> None: fx = self.fx self.assert_simplified_union([fx.lit1, fx.a], fx.a) self.assert_simplified_union([fx.lit1, fx.lit2, fx.a], fx.a) self.assert_simplified_union([fx.lit1, fx.lit1], fx.lit1) self.assert_simplified_union([fx.lit1, fx.lit2], UnionType([fx.lit1, fx.lit2])) self.assert_simplified_union([fx.lit1, fx.lit3], UnionType([fx.lit1, fx.lit3])) self.assert_simplified_union([fx.lit1, fx.uninhabited], fx.lit1) self.assert_simplified_union([fx.lit1_inst, fx.a], fx.a) self.assert_simplified_union([fx.lit1_inst, fx.lit1_inst], fx.lit1_inst) self.assert_simplified_union( [fx.lit1_inst, fx.lit2_inst], UnionType([fx.lit1_inst, fx.lit2_inst]) ) self.assert_simplified_union( [fx.lit1_inst, fx.lit3_inst], UnionType([fx.lit1_inst, fx.lit3_inst]) ) self.assert_simplified_union([fx.lit1_inst, fx.uninhabited], fx.lit1_inst) self.assert_simplified_union([fx.lit1, fx.lit1_inst], fx.lit1) self.assert_simplified_union([fx.lit1, fx.lit2_inst], UnionType([fx.lit1, fx.lit2_inst])) self.assert_simplified_union([fx.lit1, fx.lit3_inst], UnionType([fx.lit1, fx.lit3_inst])) def test_simplified_union_with_str_literals(self) -> None: fx = self.fx self.assert_simplified_union([fx.lit_str1, fx.lit_str2, fx.str_type], fx.str_type) self.assert_simplified_union([fx.lit_str1, fx.lit_str1, fx.lit_str1], fx.lit_str1) self.assert_simplified_union( [fx.lit_str1, fx.lit_str2, fx.lit_str3], UnionType([fx.lit_str1, fx.lit_str2, fx.lit_str3]), ) self.assert_simplified_union( [fx.lit_str1, fx.lit_str2, fx.uninhabited], UnionType([fx.lit_str1, fx.lit_str2]) ) def test_simplify_very_large_union(self) -> None: fx = self.fx literals = [] for i in range(5000): literals.append(LiteralType("v%d" % i, fx.str_type)) # This shouldn't be very slow, even if the union is big. self.assert_simplified_union([*literals, fx.str_type], fx.str_type) def test_simplified_union_with_str_instance_literals(self) -> None: fx = self.fx self.assert_simplified_union( [fx.lit_str1_inst, fx.lit_str2_inst, fx.str_type], fx.str_type ) self.assert_simplified_union( [fx.lit_str1_inst, fx.lit_str1_inst, fx.lit_str1_inst], fx.lit_str1_inst ) self.assert_simplified_union( [fx.lit_str1_inst, fx.lit_str2_inst, fx.lit_str3_inst], UnionType([fx.lit_str1_inst, fx.lit_str2_inst, fx.lit_str3_inst]), ) self.assert_simplified_union( [fx.lit_str1_inst, fx.lit_str2_inst, fx.uninhabited], UnionType([fx.lit_str1_inst, fx.lit_str2_inst]), ) def test_simplified_union_with_mixed_str_literals(self) -> None: fx = self.fx self.assert_simplified_union( [fx.lit_str1, fx.lit_str2, fx.lit_str3_inst], UnionType([fx.lit_str1, fx.lit_str2, fx.lit_str3_inst]), ) self.assert_simplified_union([fx.lit_str1, fx.lit_str1, fx.lit_str1_inst], fx.lit_str1) def assert_simplified_union(self, original: list[Type], union: Type) -> None: assert_equal(make_simplified_union(original), union) assert_equal(make_simplified_union(list(reversed(original))), union) # Helpers def tuple(self, *a: Type) -> TupleType: return TupleType(list(a), self.fx.std_tuple) def callable(self, vars: list[str], *a: Type) -> CallableType: """callable(args, a1, ..., an, r) constructs a callable with argument types a1, ... an and return type r and type arguments vars. """ tv: list[TypeVarType] = [] n = -1 for v in vars: tv.append( TypeVarType( v, v, TypeVarId(n), [], self.fx.o, AnyType(TypeOfAny.from_omitted_generics) ) ) n -= 1 return CallableType( list(a[:-1]), [ARG_POS] * (len(a) - 1), [None] * (len(a) - 1), a[-1], self.fx.function, name=None, variables=tv, )
TypeOpsSuite
python
scipy__scipy
scipy/ndimage/tests/test_measurements.py
{ "start": 536, "end": 3975 }
class ____: """ndimage._measurements._stats() is a utility used by other functions. Since internal ndimage/_measurements.py code is NumPy-only, so is this this test class. """ def test_a(self, xp): x = [0, 1, 2, 6] labels = [0, 0, 1, 1] index = [0, 1] for shp in [(4,), (2, 2)]: x = np.array(x).reshape(shp) labels = np.array(labels).reshape(shp) counts, sums = ndimage._measurements._stats( x, labels=labels, index=index) dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {} xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg)) xp_assert_equal(sums, np.asarray([1.0, 8.0])) def test_b(self, xp): # Same data as test_a, but different labels. The label 9 exceeds the # length of 'labels', so this test will follow a different code path. x = [0, 1, 2, 6] labels = [0, 0, 9, 9] index = [0, 9] for shp in [(4,), (2, 2)]: x = np.array(x).reshape(shp) labels = np.array(labels).reshape(shp) counts, sums = ndimage._measurements._stats( x, labels=labels, index=index) dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {} xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg)) xp_assert_equal(sums, np.asarray([1.0, 8.0])) def test_a_centered(self, xp): x = [0, 1, 2, 6] labels = [0, 0, 1, 1] index = [0, 1] for shp in [(4,), (2, 2)]: x = np.array(x).reshape(shp) labels = np.array(labels).reshape(shp) counts, sums, centers = ndimage._measurements._stats( x, labels=labels, index=index, centered=True) dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {} xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg)) xp_assert_equal(sums, np.asarray([1.0, 8.0])) xp_assert_equal(centers, np.asarray([0.5, 8.0])) def test_b_centered(self, xp): x = [0, 1, 2, 6] labels = [0, 0, 9, 9] index = [0, 9] for shp in [(4,), (2, 2)]: x = np.array(x).reshape(shp) labels = np.array(labels).reshape(shp) counts, sums, centers = ndimage._measurements._stats( x, labels=labels, index=index, centered=True) dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {} xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg)) xp_assert_equal(sums, np.asarray([1.0, 8.0])) xp_assert_equal(centers, np.asarray([0.5, 8.0])) def test_nonint_labels(self, xp): x = [0, 1, 2, 6] labels = [0.0, 0.0, 9.0, 9.0] index = [0.0, 9.0] for shp in [(4,), (2, 2)]: x = np.array(x).reshape(shp) labels = np.array(labels).reshape(shp) counts, sums, centers = ndimage._measurements._stats( x, labels=labels, index=index, centered=True) dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {} xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg)) xp_assert_equal(sums, np.asarray([1.0, 8.0])) xp_assert_equal(centers, np.asarray([0.5, 8.0])) @skip_xp_backends(np_only=True, reason='test internal numpy-only helpers')
Test_measurements_stats
python
kubernetes-client__python
kubernetes/client/models/v1beta2_resource_slice_list.py
{ "start": 383, "end": 7109 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'api_version': 'str', 'items': 'list[V1beta2ResourceSlice]', 'kind': 'str', 'metadata': 'V1ListMeta' } attribute_map = { 'api_version': 'apiVersion', 'items': 'items', 'kind': 'kind', 'metadata': 'metadata' } def __init__(self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None): # noqa: E501 """V1beta2ResourceSliceList - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._api_version = None self._items = None self._kind = None self._metadata = None self.discriminator = None if api_version is not None: self.api_version = api_version self.items = items if kind is not None: self.kind = kind if metadata is not None: self.metadata = metadata @property def api_version(self): """Gets the api_version of this V1beta2ResourceSliceList. # noqa: E501 APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :return: The api_version of this V1beta2ResourceSliceList. # noqa: E501 :rtype: str """ return self._api_version @api_version.setter def api_version(self, api_version): """Sets the api_version of this V1beta2ResourceSliceList. APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :param api_version: The api_version of this V1beta2ResourceSliceList. # noqa: E501 :type: str """ self._api_version = api_version @property def items(self): """Gets the items of this V1beta2ResourceSliceList. # noqa: E501 Items is the list of resource ResourceSlices. # noqa: E501 :return: The items of this V1beta2ResourceSliceList. # noqa: E501 :rtype: list[V1beta2ResourceSlice] """ return self._items @items.setter def items(self, items): """Sets the items of this V1beta2ResourceSliceList. Items is the list of resource ResourceSlices. # noqa: E501 :param items: The items of this V1beta2ResourceSliceList. # noqa: E501 :type: list[V1beta2ResourceSlice] """ if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501 raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501 self._items = items @property def kind(self): """Gets the kind of this V1beta2ResourceSliceList. # noqa: E501 Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :return: The kind of this V1beta2ResourceSliceList. # noqa: E501 :rtype: str """ return self._kind @kind.setter def kind(self, kind): """Sets the kind of this V1beta2ResourceSliceList. Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :param kind: The kind of this V1beta2ResourceSliceList. # noqa: E501 :type: str """ self._kind = kind @property def metadata(self): """Gets the metadata of this V1beta2ResourceSliceList. # noqa: E501 :return: The metadata of this V1beta2ResourceSliceList. # noqa: E501 :rtype: V1ListMeta """ return self._metadata @metadata.setter def metadata(self, metadata): """Sets the metadata of this V1beta2ResourceSliceList. :param metadata: The metadata of this V1beta2ResourceSliceList. # noqa: E501 :type: V1ListMeta """ self._metadata = metadata def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1beta2ResourceSliceList): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1beta2ResourceSliceList): return True return self.to_dict() != other.to_dict()
V1beta2ResourceSliceList
python
jd__tenacity
tests/test_tornado.py
{ "start": 1090, "end": 2228 }
class ____(testing.AsyncTestCase): # type: ignore[misc] @testing.gen_test def test_retry(self): assert gen.is_coroutine_function(_retryable_coroutine) thing = NoIOErrorAfterCount(5) yield _retryable_coroutine(thing) assert thing.counter == thing.count @testing.gen_test def test_stop_after_attempt(self): assert gen.is_coroutine_function(_retryable_coroutine) thing = NoIOErrorAfterCount(2) try: yield _retryable_coroutine_with_2_attempts(thing) except RetryError: assert thing.counter == 2 def test_repr(self): repr(tornadoweb.TornadoRetrying()) def test_old_tornado(self): old_attr = gen.is_coroutine_function try: del gen.is_coroutine_function # is_coroutine_function was introduced in tornado 4.5; # verify that we don't *completely* fall over on old versions @retry def retryable(thing): pass finally: gen.is_coroutine_function = old_attr if __name__ == "__main__": unittest.main()
TestTornado
python
google__pytype
pytype/pytd/visitors.py
{ "start": 24809, "end": 30737 }
class ____(_RemoveTypeParametersFromGenericAny, _ToTypeVisitor): """Look up local identifiers. Must be called on a TypeDeclUnit.""" def __init__(self, allow_singletons=False, toplevel=True): super().__init__(allow_singletons) self._toplevel = toplevel self.local_names = set() self.class_names = [] def EnterTypeDeclUnit(self, unit): self.unit = unit def LeaveTypeDeclUnit(self, _): del self.unit def _LookupItemRecursive(self, name: str) -> pytd.Node: return pytd.LookupItemRecursive(self.unit, name) def EnterClass(self, node): self.class_names.append(node.name) def LeaveClass(self, unused_node): self.class_names.pop() def _LookupScopedName(self, name: str) -> pytd.Node | None: """Look up a name in the chain of nested class scopes.""" scopes = [self.unit.name] prefix = f"{self.unit.name}." if self.class_names and not self.class_names[0].startswith(prefix): # For imported modules, the class names are already prefixed with the # module name. But for the inferred type stub for the current module, the # class names are bare, so we add the prefix here. scopes.extend(prefix + name for name in self.class_names) else: scopes.extend(self.class_names) for inner in scopes: lookup_name = f"{inner}.{name}"[len(prefix) :] try: return self._LookupItemRecursive(lookup_name) except KeyError: pass return None def _LookupLocalName(self, node: pytd.Node) -> pytd.Node: assert "." not in node.name self.local_names.add(node.name) item = self._LookupScopedName(node.name) if item is None: # Node names are not prefixed by the unit name when infer calls # load_pytd.resolve_ast() for the final pyi. try: item = self.unit.Lookup(node.name) except KeyError: pass if item is None: if self.allow_singletons and node.name in pytd.SINGLETON_TYPES: # Let the builtins resolver handle it return node msg = f"Couldn't find {node.name} in {self.unit.name}" raise SymbolLookupError(msg) return item def _LookupLocalTypes(self, node): visitor = LookupLocalTypes(self.allow_singletons, toplevel=False) visitor.unit = self.unit return node.Visit(visitor), visitor.local_names def VisitNamedType(self, node): """Do lookup on a pytd.NamedType.""" # TODO(rechen): This method and FillInLocalPointers._Lookup do very similar # things; is there any common code we can extract out? if "." in node.name: resolved_node = None module_name, name = node.name, "" while "." in module_name: module_name, _, prefix = module_name.rpartition(".") name = f"{prefix}.{name}" if name else prefix if module_name == self.unit.name: # Fully qualified reference to a member of the current module. May # contain nested items that need to be recursively resolved. try: resolved_node = self.to_type(self._LookupItemRecursive(name)) except (KeyError, NotImplementedError): if "." in name: # This might be a dotted local reference without a module_name # prefix, so we'll do another lookup attempt below. pass else: raise break if resolved_node is None: # Possibly a reference to a member of the current module that does not # have a module_name prefix. try: resolved_node = self.to_type(self._LookupItemRecursive(node.name)) except KeyError: resolved_node = node # lookup failures are handled later except NotImplementedError as e: # to_type() can raise NotImplementedError, but _LookupItemRecursive # shouldn't return a pytd node that can't be turned into a type in # this specific case. As such, it's impossible to test this case. # But it's irresponsible to just crash on it, so here we are. raise SymbolLookupError(f"{node.name} is not a type") from e else: if isinstance(resolved_node, pytd.ClassType): resolved_node.name = node.name else: # simple reference to a member of the current module item = self._LookupLocalName(node) if self._toplevel: # Check if the definition of this name refers back to itself. while isinstance(item, pytd.Alias): new_item, new_item_names = self._LookupLocalTypes(item) if node.name in new_item_names: # We've found a self-reference. This is a recursive type, so delay # resolution by representing it as a LateType. if item.name.startswith(f"{self.unit.name}."): late_name = f"{self.unit.name}.{node.name}" else: late_name = node.name item = pytd.LateType(late_name, recursive=True) elif new_item == item: break else: item = new_item try: resolved_node = self.to_type(item) except NotImplementedError as e: raise SymbolLookupError(f"{item} is not a type") from e if isinstance(resolved_node, (pytd.Constant, pytd.Function)): visitor = LookupLocalTypes() visitor.unit = self.unit return self._LookupLocalTypes(resolved_node)[0] return resolved_node def VisitClassType(self, t): if not t.cls: if t.name == self.class_names[-1]: full_name = ".".join(self.class_names) lookup_type = pytd.NamedType(full_name) elif "." in t.name and t.name.split(".", 1)[0] in self.unit: lookup_type = t else: lookup_type = None if lookup_type: t.cls = cast(pytd.ClassType, self.VisitNamedType(lookup_type)).cls return t def VisitGenericType(self, node): return _MaybeSubstituteParametersInGenericType(node)
LookupLocalTypes
python
huggingface__transformers
src/transformers/models/rembert/modeling_rembert.py
{ "start": 4420, "end": 9439 }
class ____(nn.Module): def __init__(self, config, layer_idx=None): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " f"heads ({config.num_attention_heads})" ) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) self.is_decoder = config.is_decoder self.layer_idx = layer_idx def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, past_key_values: Optional[Cache] = None, output_attentions: bool = False, cache_position: Optional[torch.Tensor] = None, ) -> tuple: batch_size, seq_length, _ = hidden_states.shape query_layer = ( self.query(hidden_states) .view(batch_size, -1, self.num_attention_heads, self.attention_head_size) .transpose(1, 2) ) is_updated = False is_cross_attention = encoder_hidden_states is not None if past_key_values is not None: if isinstance(past_key_values, EncoderDecoderCache): is_updated = past_key_values.is_updated.get(self.layer_idx) if is_cross_attention: # after the first generated id, we can subsequently re-use all key/value_layer from cache curr_past_key_values = past_key_values.cross_attention_cache else: curr_past_key_values = past_key_values.self_attention_cache else: curr_past_key_values = past_key_values current_states = encoder_hidden_states if is_cross_attention else hidden_states if is_cross_attention and past_key_values is not None and is_updated: # reuse k,v, cross_attentions key_layer = curr_past_key_values.layers[self.layer_idx].keys value_layer = curr_past_key_values.layers[self.layer_idx].values else: key_layer = ( self.key(current_states) .view(batch_size, -1, self.num_attention_heads, self.attention_head_size) .transpose(1, 2) ) value_layer = ( self.value(current_states) .view(batch_size, -1, self.num_attention_heads, self.attention_head_size) .transpose(1, 2) ) if past_key_values is not None: # save all key/value_layer to cache to be re-used for fast auto-regressive generation cache_position = cache_position if not is_cross_attention else None key_layer, value_layer = curr_past_key_values.update( key_layer, value_layer, self.layer_idx, {"cache_position": cache_position} ) # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache): past_key_values.is_updated[self.layer_idx] = True # Take the dot product between "query" and "key" to get the raw attention scores. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) attention_scores = attention_scores / math.sqrt(self.attention_head_size) if attention_mask is not None: # Apply the attention mask is (precomputed for all layers in RemBertModel forward() function) attention_scores = attention_scores + attention_mask # Normalize the attention scores to probabilities. attention_probs = nn.functional.softmax(attention_scores, dim=-1) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.dropout(attention_probs) context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) return context_layer, attention_probs # Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->RemBert
RemBertSelfAttention
python
scipy__scipy
scipy/_lib/_array_api_docs_tables.py
{ "start": 2176, "end": 10959 }
class ____(Enum): YES = auto() NO = auto() OUT_OF_SCOPE = auto() UNKNOWN = auto() def _process_capabilities_table_entry(entry: dict | None) -> dict[str, dict[str, bool]]: """Returns dict showing alternative backend support in easy to consume form. Parameters ---------- entry : Optional[dict] A dict with the structure of the values of the dict scipy._lib._array_api.xp_capabilities_table. If None, it is assumped that no alternative backends are supported. Default: None. Returns ------- dict[str, dict[str, bool]] The output dict currently has keys "cpu", "gpu", "jit" and "lazy". The value associated to each key is itself a dict. The keys of the inner dicts correspond to backends, with bool values stating whether or not the backend is supported with a given device or mode. Inapplicable backends do not appear in the inner dicts (e.g. since cupy is gpu-only, it does not appear in the inner dict keyed on "cpu"). Only alternative backends to NumPy are included since NumPY support should be guaranteed. """ # This is a template for the output format. If more backends and # backend options are added, it will need to be updated manually. # Entries start as boolean, but upon returning, will take values # from the BackendSupportStatus Enum. output = { "cpu": {"torch": False, "jax": False, "dask": False}, "gpu": {"cupy": False, "torch": False, "jax": False}, "jit": {"jax": False}, "lazy": {"dask": False}, } S = BackendSupportStatus if entry is None: # If there is no entry, assume no alternative backends are supported. # If the list of supported backends will grows, this hard-coded dict # will need to be updated. return { outer_key: {inner_key: S.UNKNOWN for inner_key in outer_value} for outer_key, outer_value in output.items() } if entry["out_of_scope"]: # None is used to signify out-of-scope functions. return { outer_key: {inner_key: S.OUT_OF_SCOPE for inner_key in outer_value} for outer_key, outer_value in output.items() } # For now, use _make_sphinx_capabilities because that's where # the relevant logic for determining what is and isn't # supported based on xp_capabilities_table entries lives. # Perhaps this logic should be decoupled from sphinx. for backend, capabilities in _make_sphinx_capabilities(**entry).items(): if backend in {"array_api_strict", "numpy"}: continue backend = BACKEND_NAMES_MAP.get(backend, backend) cpu, gpu = capabilities.cpu, capabilities.gpu if cpu is not None: if backend not in output["cpu"]: raise ValueError( "Input capabilities table entry contains unhandled" f" backend {backend} on cpu." ) output["cpu"][backend] = cpu if gpu is not None: if backend not in output["gpu"]: raise ValueError( "Input capabilities table entry contains unhandled" f" backend {backend} on gpu." ) output["gpu"][backend] = gpu if backend == "jax": output["jit"]["jax"] = entry["jax_jit"] and output["cpu"]["jax"] if backend == "dask.array": support_lazy = not entry["allow_dask_compute"] and output["dask"] output["lazy"]["dask"] = support_lazy return { outer_key: { inner_key: S.YES if inner_value else S.NO for inner_key, inner_value in outer_value.items() } for outer_key, outer_value in output.items() } def is_named_function_like_object(obj): return ( not isinstance(obj, ModuleType | type) and callable(obj) and hasattr(obj, "__name__") ) def make_flat_capabilities_table( modules: str | list[str], backend_type: str, /, *, capabilities_table: list[str] | None = None, ) -> list[dict[str, str]]: """Generate full table of array api capabilities across public functions. Parameters ---------- modules : str | list[str] A string containing single SciPy module, (e.g `scipy.stats`, `scipy.fft`) or a list of such strings. backend_type : {'cpu', 'gpu', 'jit', 'lazy'} capabilities_table : Optional[list[str]] Table in the form of `scipy._lib._array_api.xp_capabilities_table`. If None, uses `scipy._lib._array_api.xp_capabilities_table`. Default: None. Returns ------- output : list[dict[str, str]] `output` is a table in dict format (keys corresponding to column names). The first column is "module". The other columns correspond to supported backends for the given `backend_type`, e.g. jax.numpy, torch, and dask on cpu. numpy is excluded because it should always be supported. See the helper function `_process_capabilities_table_entry` above). """ if backend_type not in {"cpu", "gpu", "jit", "lazy"}: raise ValueError(f"Received unhandled backend type {backend_type}") if isinstance(modules, str): modules = [modules] if capabilities_table is None: capabilities_table = xp_capabilities_table output = [] for module_name in modules: module = import_module(module_name) public_things = module.__all__ for name in public_things: if name in ALIASES.get(module_name, {}): # Skip undocumented aliases that are kept # for backwards compatibility reasons. continue thing = getattr(module, name) if not is_named_function_like_object(thing): continue entry = xp_capabilities_table.get(thing, None) capabilities = _process_capabilities_table_entry(entry)[backend_type] row = {"module": module_name} row.update({"function": name}) row.update(capabilities) output.append(row) return output def calculate_table_statistics( flat_table: list[dict[str, str]] ) -> dict[str, tuple[dict[str, str], bool]]: """Get counts of what is supported per module. Parameters ---------- flat_table : list[dict[str, str]] A table as returned by `make_flat_capabilities_table` Returns ------- dict[str, tuple[dict[str, str], bool]] dict mapping module names to 2-tuples containing an inner dict and a bool. The inner dicts have a key "total" along with keys for each backend column of the supplied flat capabilities table. The value corresponding to total is the total count of functions in the given module, and the value associated to the other keys is the count of functions that support that particular backend. The bool is False if the calculation may be innacurate due to missing xp_capabilities decorators, and True if all functions for that particular module have been decorated with xp_capabilities. """ if not flat_table: return [] counter = defaultdict(lambda: defaultdict(int)) S = BackendSupportStatus # Keep track of which modules have functions with missing xp_capabilities # decorators so this information can be passed back to the caller. missing_xp_capabilities = set() for entry in flat_table: entry = entry.copy() entry.pop("function") module = entry.pop("module") current_counter = counter[module] # By design, all backends and options must be considered out-of-scope # if one is, so just pick an arbitrary entry here to test if function is # in-scope. if next(iter(entry.values())) != S.OUT_OF_SCOPE: current_counter["total"] += 1 for key, value in entry.items(): # Functions missing xp_capabilities will be tabulated as # unsupported, but may actually be supported. There is a # note about this in the documentation and this function is # set up to return information needed to put asterisks next # to percentages impacted by missing xp_capabilities decorators. current_counter[key] += 1 if value == S.YES else 0 if value == S.UNKNOWN: missing_xp_capabilities.add(module) return { key: (dict(value), key not in missing_xp_capabilities) for key, value in counter.items() }
BackendSupportStatus
python
bokeh__bokeh
tests/unit/bokeh/core/property/test_any.py
{ "start": 2021, "end": 3291 }
class ____: def test_valid(self) -> None: prop = bcpa.AnyRef() assert prop.is_valid(None) assert prop.is_valid(False) assert prop.is_valid(True) assert prop.is_valid(0) assert prop.is_valid(1) assert prop.is_valid(0.0) assert prop.is_valid(1.0) assert prop.is_valid(1.0+1.0j) assert prop.is_valid("") assert prop.is_valid(()) assert prop.is_valid([]) assert prop.is_valid({}) assert prop.is_valid(_TestHasProps()) assert prop.is_valid(_TestModel()) def test_invalid(self) -> None: pass def test_has_ref(self) -> None: prop = bcpa.AnyRef() assert prop.has_ref #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- Test___all__ = verify_all(bcpa, ALL)
Test_AnyRef
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_natural_language.py
{ "start": 2587, "end": 3028 }
class ____: @patch("airflow.providers.google.cloud.operators.natural_language.CloudNaturalLanguageHook") def test_minimal_green_path(self, hook_mock): hook_mock.return_value.analyze_sentiment.return_value = ANALYZE_SENTIMENT_RESPONSE op = CloudNaturalLanguageAnalyzeSentimentOperator(task_id="task-id", document=DOCUMENT) resp = op.execute({}) assert resp == {}
TestCloudLanguageAnalyzeSentimentOperator
python
django__django
tests/schema/models.py
{ "start": 832, "end": 1040 }
class ____(models.Model): name = models.CharField(max_length=255) height = models.PositiveIntegerField(null=True, blank=True, default=42) class Meta: apps = new_apps
AuthorWithDefaultHeight
python
sqlalchemy__sqlalchemy
test/orm/declarative/test_basic.py
{ "start": 104141, "end": 110808 }
class ____(fixtures.TestBase): """test for #8705""" @testing.variation( "mapping_style", [ "decl_base_fn", "decl_base_base", "classical_mapping", ], ) def test_ordering_of_attrs_cols_named_or_unnamed(self, mapping_style): seen_names = {"noname"} is_declarative = ( mapping_style.decl_base_fn or mapping_style.decl_base_base ) def make_name(): name = "noname" while name in seen_names: uppercase = random.randint(1, 3) == 1 name = "".join( random.choice("abcdefghijklmnopqrstuvxyz") for i in range(random.randint(4, 10)) ) if uppercase: name = random.choice("ABCDEFGHIJKLMNOP") + name seen_names.add(name) return name def make_column(assign_col_name): use_key = random.randint(1, 3) == 1 use_name = random.randint(1, 3) == 1 args = [] kw = {} name = col_name = make_name() if use_name: use_different_name = random.randint(1, 3) != 3 if use_different_name: col_name = make_name() args.append(col_name) elif assign_col_name: args.append(col_name) if use_key: kw["key"] = name expected_c_name = name else: expected_c_name = col_name args.append(Integer) use_mapped_column = is_declarative and random.randint(1, 2) == 1 if use_mapped_column: col = mapped_column(*args, **kw) else: col = Column(*args, **kw) use_explicit_property = ( not use_mapped_column and random.randint(1, 6) == 1 ) if use_explicit_property: col_prop = column_property(col) else: col_prop = col return name, expected_c_name, col, col_prop assign_col_name = mapping_style.classical_mapping names = [ make_column(assign_col_name) for i in range(random.randint(10, 15)) ] len_names = len(names) pk_col = names[random.randint(0, len_names - 1)][2] if isinstance(pk_col, MappedColumn): pk_col.column.primary_key = True else: pk_col.primary_key = True names_only = [name for name, _, _, _ in names] col_names_only = [col_name for _, col_name, _, _ in names] cols_only = [col for _, _, col, _ in names] if is_declarative: if mapping_style.decl_base_fn: Base = declarative_base() elif mapping_style.decl_base_base: class Base(DeclarativeBase): pass else: assert False clsdict = { "__tablename__": "new_table", } clsdict.update({name: colprop for name, _, _, colprop in names}) new_cls = type("NewCls", (Base,), clsdict) elif mapping_style.classical_mapping: class new_cls: pass reg = registry() t = Table("new_table", reg.metadata, *cols_only) reg.map_imperatively( new_cls, t, properties={ key: colprop for key, col_name, col, colprop in names if col_name != key }, ) else: mapping_style.fail() eq_(new_cls.__table__.c.keys(), col_names_only) eq_(new_cls.__mapper__.attrs.keys(), names_only) eq_(list(new_cls._sa_class_manager.keys()), names_only) eq_([k for k in new_cls.__dict__ if not k.startswith("_")], names_only) stmt = select(new_cls) eq_(stmt.selected_columns.keys(), col_names_only) @testing.variation( "mapping_style", [ "decl_base_fn", "decl_base_base", "decl_base_no_meta", "map_declaratively", "decorator", "mapped_as_dataclass", ], ) def test_no_imperative_with_declarative_table(self, mapping_style): if mapping_style.decl_base_fn: Base = declarative_base() class DecModel(Base): __tablename__ = "foo" id: Mapped[int] = mapped_column(primary_key=True) data: Mapped[str] elif mapping_style.decl_base_base: class Base(DeclarativeBase): pass class DecModel(Base): __tablename__ = "foo" id: Mapped[int] = mapped_column(primary_key=True) data: Mapped[str] elif mapping_style.decl_base_no_meta: class Base(DeclarativeBaseNoMeta): pass class DecModel(Base): __tablename__ = "foo" id: Mapped[int] = mapped_column(primary_key=True) data: Mapped[str] elif mapping_style.decorator: r = registry() @r.mapped class DecModel: __tablename__ = "foo" id: Mapped[int] = mapped_column(primary_key=True) data: Mapped[str] elif mapping_style.map_declaratively: class DecModel: __tablename__ = "foo" id: Mapped[int] = mapped_column(primary_key=True) data: Mapped[str] registry().map_declaratively(DecModel) elif mapping_style.decorator: r = registry() @r.mapped class DecModel: __tablename__ = "foo" id: Mapped[int] = mapped_column(primary_key=True) data: Mapped[str] elif mapping_style.mapped_as_dataclass: r = registry() @r.mapped_as_dataclass class DecModel: __tablename__ = "foo" id: Mapped[int] = mapped_column(primary_key=True) data: Mapped[str] else: assert False class ImpModel: id: int data: str with expect_raises_message( exc.ArgumentError, "FROM expression, such as a Table or alias.. object expected " "for argument 'local_table'; got", ): registry().map_imperatively(ImpModel, DecModel)
NamedAttrOrderingTest
python
ansible__ansible
test/units/playbook/role/test_role.py
{ "start": 4411, "end": 13480 }
class ____(unittest.TestCase): @patch('ansible.playbook.role.definition.unfrackpath', mock_unfrackpath_noop) def test_load_role_with_tasks(self): fake_loader = DictDataLoader({ "/etc/ansible/roles/foo_tasks/tasks/main.yml": """ - shell: echo 'hello world' """, }) mock_play = MagicMock() mock_play.role_cache = {} i = RoleInclude.load('foo_tasks', play=mock_play, loader=fake_loader) r = Role.load(i, play=mock_play) self.assertEqual(str(r), 'foo_tasks') self.assertEqual(len(r._task_blocks), 1) assert isinstance(r._task_blocks[0], Block) @patch('ansible.playbook.role.definition.unfrackpath', mock_unfrackpath_noop) def test_load_role_with_tasks_dir_vs_file(self): fake_loader = DictDataLoader({ "/etc/ansible/roles/foo_tasks/tasks/custom_main/foo.yml": """ - command: bar """, "/etc/ansible/roles/foo_tasks/tasks/custom_main.yml": """ - command: baz """, }) mock_play = MagicMock() mock_play.role_cache = {} i = RoleInclude.load('foo_tasks', play=mock_play, loader=fake_loader) r = Role.load(i, play=mock_play, from_files=dict(tasks='custom_main')) self.assertEqual(r._task_blocks[0]._ds[0]['command'], 'baz') @patch('ansible.playbook.role.definition.unfrackpath', mock_unfrackpath_noop) def test_load_role_with_handlers(self): fake_loader = DictDataLoader({ "/etc/ansible/roles/foo_handlers/handlers/main.yml": """ - name: test handler shell: echo 'hello world' """, }) mock_play = MagicMock() mock_play.role_cache = {} i = RoleInclude.load('foo_handlers', play=mock_play, loader=fake_loader) r = Role.load(i, play=mock_play) self.assertEqual(len(r._handler_blocks), 1) assert isinstance(r._handler_blocks[0], Block) @patch('ansible.playbook.role.definition.unfrackpath', mock_unfrackpath_noop) def test_load_role_with_vars(self): fake_loader = DictDataLoader({ "/etc/ansible/roles/foo_vars/defaults/main.yml": """ foo: bar """, "/etc/ansible/roles/foo_vars/vars/main.yml": """ foo: bam """, }) mock_play = MagicMock() mock_play.role_cache = {} i = RoleInclude.load('foo_vars', play=mock_play, loader=fake_loader) r = Role.load(i, play=mock_play) self.assertEqual(r._default_vars, dict(foo='bar')) self.assertEqual(r._role_vars, dict(foo='bam')) @patch('ansible.playbook.role.definition.unfrackpath', mock_unfrackpath_noop) def test_load_role_with_vars_dirs(self): fake_loader = DictDataLoader({ "/etc/ansible/roles/foo_vars/defaults/main/foo.yml": """ foo: bar """, "/etc/ansible/roles/foo_vars/vars/main/bar.yml": """ foo: bam """, }) mock_play = MagicMock() mock_play.role_cache = {} i = RoleInclude.load('foo_vars', play=mock_play, loader=fake_loader) r = Role.load(i, play=mock_play) self.assertEqual(r._default_vars, dict(foo='bar')) self.assertEqual(r._role_vars, dict(foo='bam')) @patch('ansible.playbook.role.definition.unfrackpath', mock_unfrackpath_noop) def test_load_role_with_vars_nested_dirs(self): fake_loader = DictDataLoader({ "/etc/ansible/roles/foo_vars/defaults/main/foo/bar.yml": """ foo: bar """, "/etc/ansible/roles/foo_vars/vars/main/bar/foo.yml": """ foo: bam """, }) mock_play = MagicMock() mock_play.role_cache = {} i = RoleInclude.load('foo_vars', play=mock_play, loader=fake_loader) r = Role.load(i, play=mock_play) self.assertEqual(r._default_vars, dict(foo='bar')) self.assertEqual(r._role_vars, dict(foo='bam')) @patch('ansible.playbook.role.definition.unfrackpath', mock_unfrackpath_noop) def test_load_role_with_vars_nested_dirs_combined(self): fake_loader = DictDataLoader({ "/etc/ansible/roles/foo_vars/defaults/main/foo/bar.yml": """ foo: bar a: 1 """, "/etc/ansible/roles/foo_vars/defaults/main/bar/foo.yml": """ foo: bam b: 2 """, }) mock_play = MagicMock() mock_play.role_cache = {} i = RoleInclude.load('foo_vars', play=mock_play, loader=fake_loader) r = Role.load(i, play=mock_play) self.assertEqual(r._default_vars, dict(foo='bar', a=1, b=2)) @patch('ansible.playbook.role.definition.unfrackpath', mock_unfrackpath_noop) def test_load_role_with_vars_dir_vs_file(self): fake_loader = DictDataLoader({ "/etc/ansible/roles/foo_vars/vars/main/foo.yml": """ foo: bar """, "/etc/ansible/roles/foo_vars/vars/main.yml": """ foo: bam """, }) mock_play = MagicMock() mock_play.role_cache = {} i = RoleInclude.load('foo_vars', play=mock_play, loader=fake_loader) r = Role.load(i, play=mock_play) self.assertEqual(r._role_vars, dict(foo='bam')) @patch('ansible.playbook.role.definition.unfrackpath', mock_unfrackpath_noop) def test_load_role_with_metadata(self): fake_loader = DictDataLoader({ '/etc/ansible/roles/foo_metadata/meta/main.yml': """ allow_duplicates: true dependencies: - bar_metadata galaxy_info: a: 1 b: 2 c: 3 """, '/etc/ansible/roles/bar_metadata/meta/main.yml': """ dependencies: - baz_metadata """, '/etc/ansible/roles/baz_metadata/meta/main.yml': """ dependencies: - bam_metadata """, '/etc/ansible/roles/bam_metadata/meta/main.yml': """ dependencies: [] """, '/etc/ansible/roles/bad1_metadata/meta/main.yml': """ 1 """, '/etc/ansible/roles/bad2_metadata/meta/main.yml': """ foo: bar """, '/etc/ansible/roles/recursive1_metadata/meta/main.yml': """ dependencies: ['recursive2_metadata'] """, '/etc/ansible/roles/recursive2_metadata/meta/main.yml': """ dependencies: ['recursive1_metadata'] """, }) mock_play = MagicMock() mock_play.collections = None mock_play.role_cache = {} i = RoleInclude.load('foo_metadata', play=mock_play, loader=fake_loader) r = Role.load(i, play=mock_play) role_deps = r.get_direct_dependencies() self.assertEqual(len(role_deps), 1) self.assertEqual(type(role_deps[0]), Role) self.assertEqual(len(role_deps[0].get_parents()), 1) self.assertEqual(role_deps[0].get_parents()[0], r) self.assertEqual(r._metadata.allow_duplicates, True) self.assertEqual(r._metadata.galaxy_info, dict(a=1, b=2, c=3)) all_deps = r.get_all_dependencies() self.assertEqual(len(all_deps), 3) self.assertEqual(all_deps[0].get_name(), 'bam_metadata') self.assertEqual(all_deps[1].get_name(), 'baz_metadata') self.assertEqual(all_deps[2].get_name(), 'bar_metadata') i = RoleInclude.load('bad1_metadata', play=mock_play, loader=fake_loader) self.assertRaises(AnsibleParserError, Role.load, i, play=mock_play) i = RoleInclude.load('bad2_metadata', play=mock_play, loader=fake_loader) self.assertRaises(AnsibleParserError, Role.load, i, play=mock_play) # TODO: re-enable this test once Ansible has proper role dep cycle detection # that doesn't rely on stack overflows being recoverable (as they aren't in Py3.7+) # see https://github.com/ansible/ansible/issues/61527 # i = RoleInclude.load('recursive1_metadata', play=mock_play, loader=fake_loader) # self.assertRaises(AnsibleError, Role.load, i, play=mock_play) @patch('ansible.playbook.role.definition.unfrackpath', mock_unfrackpath_noop) def test_load_role_complex(self): # FIXME: add tests for the more complex uses of # params and tags/when statements fake_loader = DictDataLoader({ "/etc/ansible/roles/foo_complex/tasks/main.yml": """ - shell: echo 'hello world' """, }) mock_play = MagicMock() mock_play.role_cache = {} i = RoleInclude.load(dict(role='foo_complex'), play=mock_play, loader=fake_loader) r = Role.load(i, play=mock_play) self.assertEqual(r.get_name(), "foo_complex")
TestRole
python
falconry__falcon
tests/test_hello.py
{ "start": 2966, "end": 8043 }
class ____: def test_env_headers_list_of_tuples(self): env = testing.create_environ(headers=[('User-Agent', 'Falcon-Test')]) assert env['HTTP_USER_AGENT'] == 'Falcon-Test' def test_root_route(self, client): doc = {'message': 'Hello world!'} resource = testing.SimpleTestResource(json=doc) client.app.add_route('/', resource) result = client.simulate_get() assert result.json == doc def test_no_route(self, client): result = client.simulate_get('/seenoevil') assert result.status_code == 404 @pytest.mark.parametrize( 'path,resource,get_body', [ ('/body', HelloResource('body'), lambda r: r.text.encode('utf-8')), ('/bytes', HelloResource('body, bytes'), lambda r: r.text), ('/data', HelloResource('data'), lambda r: r.data), ], ) def test_body(self, client, path, resource, get_body): client.app.add_route(path, resource) result = client.simulate_get(path) resp = resource.resp content_length = int(result.headers['content-length']) assert content_length == len(resource.sample_utf8) assert result.status == resource.sample_status assert resp.status == resource.sample_status assert get_body(resp) == resource.sample_utf8 assert result.content == resource.sample_utf8 def test_no_body_on_head(self, client): resource = HelloResource('body') client.app.add_route('/body', resource) result = client.simulate_head('/body') assert not result.content assert result.status_code == 200 assert resource.called assert result.headers['content-length'] == str(len(HelloResource.sample_utf8)) def test_stream_chunked(self, client): resource = HelloResource('stream') client.app.add_route('/chunked-stream', resource) result = client.simulate_get('/chunked-stream') assert result.content == resource.sample_utf8 assert 'content-length' not in result.headers def test_stream_known_len(self, client): resource = HelloResource('stream, stream_len') client.app.add_route('/stream', resource) result = client.simulate_get('/stream') assert resource.called expected_len = int(resource.resp.content_length) actual_len = int(result.headers['content-length']) assert actual_len == expected_len assert len(result.content) == expected_len assert result.content == resource.sample_utf8 def test_filelike(self, client): resource = HelloResource('stream, stream_len, filelike') client.app.add_route('/filelike', resource) for file_wrapper in (None, FileWrapper): result = client.simulate_get('/filelike', file_wrapper=file_wrapper) assert resource.called expected_len = int(resource.resp.content_length) actual_len = int(result.headers['content-length']) assert actual_len == expected_len assert len(result.content) == expected_len for file_wrapper in (None, FileWrapper): result = client.simulate_get('/filelike', file_wrapper=file_wrapper) assert resource.called expected_len = int(resource.resp.content_length) actual_len = int(result.headers['content-length']) assert actual_len == expected_len assert len(result.content) == expected_len @pytest.mark.parametrize( 'stream_factory,assert_closed', [ (ClosingBytesIO, True), # Implements close() (NonClosingBytesIO, False), # Has a non-callable "close" attr ], ) def test_filelike_closing(self, client, stream_factory, assert_closed): resource = ClosingFilelikeHelloResource(stream_factory) client.app.add_route('/filelike-closing', resource) result = client.simulate_get('/filelike-closing', file_wrapper=None) assert resource.called expected_len = int(resource.resp.content_length) actual_len = int(result.headers['content-length']) assert actual_len == expected_len assert len(result.content) == expected_len if assert_closed: assert resource.stream.close_called def test_filelike_using_helper(self, client): resource = HelloResource('stream, stream_len, filelike, use_helper') client.app.add_route('/filelike-helper', resource) result = client.simulate_get('/filelike-helper') assert resource.called expected_len = int(resource.resp.content_length) actual_len = int(result.headers['content-length']) assert actual_len == expected_len assert len(result.content) == expected_len def test_status_not_set(self, client): client.app.add_route('/nostatus', NoStatusResource()) result = client.simulate_get('/nostatus') assert not result.content assert result.status_code == 200
TestHelloWorld
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/variant_on_dependency_condition_root/package.py
{ "start": 216, "end": 766 }
class ____(Package): """Test that dependencies that are conditional on the state of other dependencies are added correctly, for instance: depends_on('A') depends_on('B', when='^A+x') """ homepage = "https://www.example.org" url = "https://example.org/files/v3.4/cmake-3.4.3.tar.gz" version("1.0", md5="4cb3ff35b2472aae70f542116d616e63") depends_on("variant-on-dependency-condition-a") depends_on("variant-on-dependency-condition-b", when="^variant-on-dependency-condition-a+x")
VariantOnDependencyConditionRoot
python
spyder-ide__spyder
spyder/plugins/console/widgets/console.py
{ "start": 4481, "end": 11739 }
class ____(TextEditBaseWidget): """Console base widget""" BRACE_MATCHING_SCOPE = ('sol', 'eol') COLOR_PATTERN = re.compile(r'\x01?\x1b\[(.*?)m\x02?') # --- Signals # This signal emits an error text, which corresponds to a Python # traceback. sig_exception_occurred = Signal(dict) userListActivated = Signal(int, str) completion_widget_activated = Signal(str) CONF_SECTION = 'internal_console' def __init__(self, parent=None): TextEditBaseWidget.__init__(self, parent) # To adjust some things for the internal console self.setObjectName('console') self.setMaximumBlockCount(300) # ANSI escape code handler self.ansi_handler = QtANSIEscapeCodeHandler() # Disable undo/redo (nonsense for a console widget...): self.setUndoRedoEnabled(False) self.userListActivated.connect( lambda user_id, text: self.completion_widget_activated.emit(text)) background_color = MAIN_BG_COLOR default_foreground_color = MAIN_DEFAULT_FG_COLOR error_foreground_color = MAIN_ERROR_FG_COLOR traceback_foreground_color = MAIN_TB_FG_COLOR prompt_foreground_color = MAIN_PROMPT_FG_COLOR self.default_style = ConsoleFontStyle( foregroundcolor=default_foreground_color, backgroundcolor=background_color, bold=False, italic=False, underline=False) self.error_style = ConsoleFontStyle( foregroundcolor=error_foreground_color, backgroundcolor=background_color, bold=False, italic=False, underline=False) self.traceback_link_style = ConsoleFontStyle( foregroundcolor=traceback_foreground_color, backgroundcolor=background_color, bold=True, italic=False, underline=True) self.prompt_style = ConsoleFontStyle( foregroundcolor=prompt_foreground_color, backgroundcolor=background_color, bold=True, italic=False, underline=False) self.font_styles = (self.default_style, self.error_style, self.traceback_link_style, self.prompt_style) self.set_color_scheme(default_foreground_color, background_color) self.setMouseTracking(True) def set_color_scheme(self, foreground_color, background_color): """Set color scheme of the console (foreground and background).""" self.ansi_handler.set_color_scheme(foreground_color, background_color) background_color = QColor(background_color) foreground_color = QColor(foreground_color) self.set_palette(background=background_color, foreground=foreground_color) self.set_pythonshell_font() # ----- Python shell def insert_text(self, text): """Reimplement TextEditBaseWidget method""" # Eventually this maybe should wrap to insert_text_to if # backspace-handling is required self.textCursor().insertText(text, self.default_style.format) def paste(self): """Reimplement Qt method""" if self.has_selected_text(): self.remove_selected_text() self.insert_text(QApplication.clipboard().text()) def append_text_to_shell(self, text, error, prompt): """ Append text to Python shell In a way, this method overrides the method 'insert_text' when text is inserted at the end of the text widget for a Python shell Handles error messages and show blue underlined links Handles ANSI color sequences Handles ANSI FF sequence """ cursor = self.textCursor() cursor.movePosition(QTextCursor.End) if '\r' in text: # replace \r\n with \n text = text.replace('\r\n', '\n') text = text.replace('\r', '\n') while True: index = text.find(chr(12)) if index == -1: break text = text[index+1:] self.clear() if error: is_traceback = False is_warning = False for line in text.splitlines(True): if (line.startswith(' File') and not line.startswith(' File "<')): is_traceback = True is_warning = False # Show error links in blue underlined text cursor.insertText(' ', self.default_style.format) cursor.insertText(line[2:], self.traceback_link_style.format) else: # Detect if line is a warning. if (re.findall('[A-Z].*Warning', line) != [] or 'warnings.warn' in line or 'WARNING' in line): is_warning = True # Show error/warning messages in red cursor.insertText(line, self.error_style.format) # Don't report warnings as internal errors if not is_warning: self.sig_exception_occurred.emit( dict(text=line, is_traceback=is_traceback) ) elif prompt: # Show prompt in green insert_text_to(cursor, text, self.prompt_style.format) else: # Show other outputs in black last_end = 0 for match in self.COLOR_PATTERN.finditer(text): insert_text_to(cursor, text[last_end:match.start()], self.default_style.format) last_end = match.end() try: for code in [int(_c) for _c in match.group(1).split(';')]: self.ansi_handler.set_code(code) except ValueError: pass self.default_style.format = self.ansi_handler.get_format() insert_text_to(cursor, text[last_end:], self.default_style.format) # # Slower alternative: # segments = self.COLOR_PATTERN.split(text) # cursor.insertText(segments.pop(0), self.default_style.format) # if segments: # for ansi_tags, text in zip(segments[::2], segments[1::2]): # for ansi_tag in ansi_tags.split(';'): # self.ansi_handler.set_code(int(ansi_tag)) # self.default_style.format = self.ansi_handler.get_format() # cursor.insertText(text, self.default_style.format) self.set_cursor_position('eof') self.setCurrentCharFormat(self.default_style.format) def set_pythonshell_font(self, font=None): """Python Shell only""" if font is None: font = QFont() for style in self.font_styles: style.apply_style(font=font, is_default=style is self.default_style) self.ansi_handler.set_base_format(self.default_style.format)
ConsoleBaseWidget
python
kamyu104__LeetCode-Solutions
Python/move-zeroes.py
{ "start": 587, "end": 978 }
class ____(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ pos = 0 for i in xrange(len(nums)): if nums[i]: nums[pos] = nums[i] pos += 1 for i in xrange(pos, len(nums)): nums[i] = 0
Solution2
python
ray-project__ray
python/ray/experimental/util/types.py
{ "start": 145, "end": 255 }
class ____(Enum): SUM = 0 PRODUCT = 1 MAX = 2 MIN = 3 AVG = 4 @PublicAPI @dataclass
ReduceOp
python
django__django
tests/expressions/tests.py
{ "start": 52339, "end": 54911 }
class ____(SimpleTestCase): def test_deepcopy(self): f = F("foo") g = deepcopy(f) self.assertEqual(f.name, g.name) def test_deconstruct(self): f = F("name") path, args, kwargs = f.deconstruct() self.assertEqual(path, "django.db.models.F") self.assertEqual(args, (f.name,)) self.assertEqual(kwargs, {}) def test_equal(self): f = F("name") same_f = F("name") other_f = F("username") self.assertEqual(f, same_f) self.assertNotEqual(f, other_f) def test_hash(self): d = {F("name"): "Bob"} self.assertIn(F("name"), d) self.assertEqual(d[F("name")], "Bob") def test_not_equal_Value(self): f = F("name") value = Value("name") self.assertNotEqual(f, value) self.assertNotEqual(value, f) def test_contains(self): msg = "argument of type 'F' is not iterable" with self.assertRaisesMessage(TypeError, msg): "" in F("name") def test_replace_expressions_transform(self): replacements = {F("timestamp"): Value(None)} transform_ref = F("timestamp__date") self.assertIs(transform_ref.replace_expressions(replacements), transform_ref) invalid_transform_ref = F("timestamp__invalid") self.assertIs( invalid_transform_ref.replace_expressions(replacements), invalid_transform_ref, ) replacements = {F("timestamp"): Value(datetime.datetime(2025, 3, 1, 14, 10))} self.assertEqual( F("timestamp__date").replace_expressions(replacements), TruncDate(Value(datetime.datetime(2025, 3, 1, 14, 10))), ) self.assertEqual( F("timestamp__date__day").replace_expressions(replacements), ExtractDay(TruncDate(Value(datetime.datetime(2025, 3, 1, 14, 10)))), ) invalid_nested_transform_ref = F("timestamp__date__invalid") self.assertIs( invalid_nested_transform_ref.replace_expressions(replacements), invalid_nested_transform_ref, ) # `replacements` is not unnecessarily looked up a second time for # transform-less field references as it's the case the vast majority of # the time. mock_replacements = mock.Mock() mock_replacements.get.return_value = None field_ref = F("name") self.assertIs(field_ref.replace_expressions(mock_replacements), field_ref) mock_replacements.get.assert_called_once_with(field_ref)
FTests
python
huggingface__transformers
src/transformers/models/bark/modeling_bark.py
{ "start": 22074, "end": 27254 }
class ____(BarkCausalModel): base_model_prefix = "semantic" config: BarkSemanticConfig def generate( self, input_ids: torch.Tensor, semantic_generation_config: Optional[BarkSemanticGenerationConfig] = None, history_prompt: Optional[dict[str, torch.Tensor]] = None, attention_mask: Optional[torch.Tensor] = None, **kwargs, ) -> torch.LongTensor: """ Generates text semantic tokens from an input prompt and an additional optional `Bark` speaker prompt. Args: input_ids (`Optional[torch.Tensor]` of shape (batch_size, seq_len), *optional*): Input ids, i.e tokenized input sentences. Will be truncated up to semantic_generation_config.max_input_semantic_length tokens. Note that the output audios will be as long as the longest generation among the batch. semantic_generation_config (`BarkSemanticGenerationConfig`): Generation config indicating how to generate the semantic tokens. history_prompt (`Optional[dict[str,torch.Tensor]]`, *optional*): Optional `Bark` speaker prompt. attention_mask (`Optional[torch.Tensor]`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) Returns: torch.LongTensor: Output semantic tokens. """ if semantic_generation_config is None: raise ValueError("`semantic_generation_config` has to be provided") batch_size = input_ids.shape[0] max_input_semantic_length = semantic_generation_config.max_input_semantic_length input_ids = input_ids + semantic_generation_config.text_encoding_offset if attention_mask is not None: input_ids = input_ids.masked_fill((1 - attention_mask).bool(), semantic_generation_config.text_pad_token) if history_prompt is not None: semantic_history = history_prompt["semantic_prompt"][-max_input_semantic_length:] semantic_history = nn.functional.pad( semantic_history, (0, max_input_semantic_length - len(semantic_history)), value=semantic_generation_config.semantic_pad_token, mode="constant", ) else: semantic_history = torch.tensor( [semantic_generation_config.semantic_pad_token] * max_input_semantic_length, dtype=torch.int ).to(self.device) semantic_history = torch.repeat_interleave(semantic_history[None], batch_size, dim=0) infer_array = torch.tensor( [[semantic_generation_config.semantic_infer_token]] * batch_size, dtype=torch.int ).to(self.device) input_embeds = torch.cat( [ self.input_embeds_layer(input_ids[:, :max_input_semantic_length]) + self.input_embeds_layer(semantic_history[:, : max_input_semantic_length + 1]), self.input_embeds_layer(infer_array), ], dim=1, ) tokens_to_suppress = list( range(semantic_generation_config.semantic_vocab_size, semantic_generation_config.semantic_pad_token) ) tokens_to_suppress.extend( list(range(semantic_generation_config.semantic_pad_token + 1, self.config.output_vocab_size)) ) suppress_tokens_logits_processor = SuppressTokensLogitsProcessor(tokens_to_suppress, device=input_ids.device) min_eos_p = kwargs.get("min_eos_p", semantic_generation_config.min_eos_p) early_stopping_logits_processor = BarkEosPrioritizerLogitsProcessor( eos_token_id=semantic_generation_config.eos_token_id, min_eos_p=min_eos_p, device=input_ids.device ) # pass input_ids in order to stay consistent with the transformers generate method even though it is not used # (except to get the input seq_len - that's why we keep the first 257 tokens) semantic_output = super().generate( torch.ones((batch_size, max_input_semantic_length + 1), dtype=torch.int, device=self.device), input_embeds=input_embeds, logits_processor=[suppress_tokens_logits_processor, early_stopping_logits_processor], generation_config=semantic_generation_config, **kwargs, ) # size: 10048 # take the generated semantic tokens if kwargs.get("return_dict_in_generate", False): semantic_output = semantic_output.sequences[:, max_input_semantic_length + 1 :] else: semantic_output = semantic_output[:, max_input_semantic_length + 1 :] return semantic_output @auto_docstring( custom_intro=""" Bark coarse acoustics model. It shares the same architecture as the semantic (or text) model. It is a GPT-2 like autoregressive model with a language modeling head on top. """ )
BarkSemanticModel
python
great-expectations__great_expectations
great_expectations/datasource/fluent/data_asset/path/spark/delta_asset.py
{ "start": 1363, "end": 1949 }
class ____(DirectoryDataAsset, DeltaAssetBase): type: Literal["directory_delta"] = "directory_delta" @classmethod @override def _get_reader_method(cls) -> str: return "delta" @override def _get_reader_options_include(self) -> set[str]: """The options below are available as of 2023-05-12 See https://docs.databricks.com/delta/tutorial.html for more info. """ return ( super()._get_reader_options_include() | super(DirectoryDataAsset, self)._get_reader_options_include() )
DirectoryDeltaAsset
python
Netflix__metaflow
metaflow/plugins/cards/component_serializer.py
{ "start": 1034, "end": 1176 }
class ____(ErrorComponent): def __init__(self, warning_message): super().__init__("@card WARNING", warning_message)
WarningComponent
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/named_types.py
{ "start": 6102, "end": 13378 }
class ____(NamedType, type_api.NativeForEmulated, sqltypes.Enum): """PostgreSQL ENUM type. This is a subclass of :class:`_types.Enum` which includes support for PG's ``CREATE TYPE`` and ``DROP TYPE``. When the builtin type :class:`_types.Enum` is used and the :paramref:`.Enum.native_enum` flag is left at its default of True, the PostgreSQL backend will use a :class:`_postgresql.ENUM` type as the implementation, so the special create/drop rules will be used. The create/drop behavior of ENUM tries to follow the PostgreSQL behavior, with an usability improvement indicated below. When using :class:`_types.Enum` or :class:`_postgresql.ENUM` in an "inline" fashion, the ``CREATE TYPE`` is emitted corresponding to when the :meth:`_schema.Table.create` method is called:: table = Table( "sometable", metadata, Column("some_enum", ENUM("a", "b", "c", name="myenum")), ) # will check if enum exists and emit CREATE ENUM then CREATE TABLE table.create(engine) table.drop(engine) # will *not* drop the enum. The enum will not be dropped when the table is dropped, since it's associated with the metadata, not the table itself. Call drop on the :class:`_postgresql.ENUM` directly to drop the type:: metadata.get_schema_object_by_name("enum", "myenum").drop(engine) To use a common enumerated type between multiple tables, the best practice is to declare the :class:`_types.Enum` or :class:`_postgresql.ENUM` independently:: my_enum = ENUM("a", "b", "c", name="myenum", metadata=metadata) t1 = Table("sometable_one", metadata, Column("some_enum", myenum)) t2 = Table("sometable_two", metadata, Column("some_enum", myenum)) Like before, the type will be created if it does not exist:: # will check if enum exists and emit CREATE ENUM then CREATE TABLE t1.create(engine) The type will always be created and dropped if either the metadata-wide create/drop is called:: metadata.create_all(engine) # will emit CREATE TYPE metadata.drop_all(engine) # will emit DROP TYPE The type can also be created and dropped directly:: my_enum.create(engine) my_enum.drop(engine) .. versionchanged:: 2.1 The behavior of :class:`_postgresql.ENUM` and other named types has been changed to better reflect how PostgreSQL handles CREATE TYPE and DROP TYPE operations. Named types are still created when needed during table creation if they do not already exist. However, they are no longer dropped for an individual :meth:`.Table.drop` operation, since the type may be referenced by other tables as well. Instead, :meth:`.Enum.drop` may be used or :meth:`.MetaData.drop_all` will drop all associated types. """ native_enum = True DDLGenerator = EnumGenerator DDLDropper = EnumDropper def __init__( self, *enums, name: Union[str, _NoArg, None] = _NoArg.NO_ARG, create_type: bool = True, **kw, ): """Construct an :class:`_postgresql.ENUM`. Arguments are the same as that of :class:`_types.Enum`, but also including the following parameters. :param create_type: Defaults to True. Indicates that ``CREATE TYPE`` should be emitted, after optionally checking for the presence of the type, when the parent table is being created. When ``False``, no check will be performed and no ``CREATE TYPE`` or ``DROP TYPE`` is emitted, unless :meth:`~.postgresql.ENUM.create` or :meth:`~.postgresql.ENUM.drop` are called directly. Setting to ``False`` is helpful when invoking a creation scheme to a SQL file without access to the actual database - the :meth:`~.postgresql.ENUM.create` and :meth:`~.postgresql.ENUM.drop` methods can be used to emit SQL to a target bind. """ native_enum = kw.pop("native_enum", None) if native_enum is False: util.warn( "the native_enum flag does not apply to the " "sqlalchemy.dialects.postgresql.ENUM datatype; this type " "always refers to ENUM. Use sqlalchemy.types.Enum for " "non-native enum." ) if name is not _NoArg.NO_ARG: kw["name"] = name kw["create_type"] = create_type super().__init__(*enums, **kw) def coerce_compared_value(self, op, value): super_coerced_type = super().coerce_compared_value(op, value) if ( super_coerced_type._type_affinity is type_api.STRINGTYPE._type_affinity ): return self else: return super_coerced_type @classmethod def __test_init__(cls): return cls(name="name") @classmethod def adapt_emulated_to_native(cls, impl, **kw): """Produce a PostgreSQL native :class:`_postgresql.ENUM` from plain :class:`.Enum`. """ kw.setdefault("validate_strings", impl.validate_strings) kw.setdefault("name", impl.name) kw.setdefault("create_type", impl.create_type) kw.setdefault("schema", impl.schema) kw.setdefault("metadata", impl.metadata) kw.setdefault("_create_events", False) kw.setdefault("values_callable", impl.values_callable) kw.setdefault("omit_aliases", impl._omit_aliases) kw.setdefault("_adapted_from", impl) return cls(**kw) def create(self, bind: _CreateDropBind, checkfirst: bool = True) -> None: """Emit ``CREATE TYPE`` for this :class:`_postgresql.ENUM`. If the underlying dialect does not support PostgreSQL CREATE TYPE, no action is taken. :param bind: a connectable :class:`_engine.Engine`, :class:`_engine.Connection`, or similar object to emit SQL. :param checkfirst: if ``True``, a query against the PG catalog will be first performed to see if the type does not exist already before creating. """ if not bind.dialect.supports_native_enum: return super().create(bind, checkfirst=checkfirst) def drop(self, bind: _CreateDropBind, checkfirst: bool = True) -> None: """Emit ``DROP TYPE`` for this :class:`_postgresql.ENUM`. If the underlying dialect does not support PostgreSQL DROP TYPE, no action is taken. :param bind: a connectable :class:`_engine.Engine`, :class:`_engine.Connection`, or similar object to emit SQL. :param checkfirst: if ``True``, a query against the PG catalog will be first performed to see if the type actually exists before dropping. """ if not bind.dialect.supports_native_enum: return super().drop(bind, checkfirst=checkfirst) def get_dbapi_type(self, dbapi: ModuleType) -> None: """dont return dbapi.STRING for ENUM in PostgreSQL, since that's a different type""" return None
ENUM
python
bokeh__bokeh
src/bokeh/models/glyphs.py
{ "start": 35335, "end": 36842 }
class ____(Glyph, LineGlyph, FillGlyph, HatchGlyph): ''' Render several patches. The data for the ``Patches`` glyph is different in that the vector of values is not a vector of scalars. Rather, it is a "list of lists". During box selection only patches entirely contained in the selection box will be included. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) __example__ = "examples/reference/models/Patches.py" _args = ('xs', 'ys') xs = NumberSpec(default=field("xs"), help=""" The x-coordinates for all the patches, given as a "list of lists". .. note:: Individual patches may comprise multiple polygons. In this case the x-coordinates for each polygon should be separated by NaN values in the sublists. """) ys = NumberSpec(default=field("ys"), help=""" The y-coordinates for all the patches, given as a "list of lists". .. note:: Individual patches may comprise multiple polygons. In this case the y-coordinates for each polygon should be separated by NaN values in the sublists. """) line_props = Include(LineProps, help=""" The {prop} values for the patches. """) fill_props = Include(FillProps, help=""" The {prop} values for the patches. """) hatch_props = Include(HatchProps, help=""" The {prop} values for the patches. """)
Patches
python
huggingface__transformers
src/transformers/models/funnel/modeling_funnel.py
{ "start": 1377, "end": 2110 }
class ____(nn.Module): def __init__(self, config: FunnelConfig) -> None: super().__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) self.layer_norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout) def forward( self, input_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None ) -> torch.Tensor: if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids) embeddings = self.layer_norm(inputs_embeds) embeddings = self.dropout(embeddings) return embeddings
FunnelEmbeddings
python
sphinx-doc__sphinx
tests/test_builders/test_build_linkcheck.py
{ "start": 47662, "end": 49886 }
class ____(BaseHTTPRequestHandler): """Test server that uppercases URL paths via redirects.""" protocol_version = 'HTTP/1.1' def do_GET(self) -> None: if self.path.islower(): # Redirect lowercase paths to uppercase versions self.send_response(301, 'Moved Permanently') self.send_header('Location', self.path.upper()) self.send_header('Content-Length', '0') self.end_headers() else: # Serve uppercase paths content = b'ok\n\n' self.send_response(200, 'OK') self.send_header('Content-Length', str(len(content))) self.end_headers() self.wfile.write(content) @pytest.mark.sphinx( 'linkcheck', testroot='linkcheck-case-check', freshenv=True, ) @pytest.mark.parametrize( ('case_insensitive_pattern', 'expected_path1', 'expected_path2', 'expected_path3'), [ ([], 'redirected', 'redirected', 'working'), # default: case-sensitive ( [r'http://localhost:\d+/.*'], 'working', 'working', 'working', ), # all URLs case-insensitive ( [r'http://localhost:\d+/path1'], 'working', 'redirected', 'working', ), # only path1 case-insensitive ], ) def test_linkcheck_case_sensitivity( app: SphinxTestApp, case_insensitive_pattern: list[str], expected_path1: str, expected_path2: str, expected_path3: str, ) -> None: """Test case-sensitive and case-insensitive URL checking.""" app.config.linkcheck_case_insensitive_urls = case_insensitive_pattern with serve_application(app, CapitalisePathHandler) as address: app.build() content = (app.outdir / 'output.json').read_text(encoding='utf8') rows = [json.loads(x) for x in content.splitlines()] rowsby = {row['uri']: row for row in rows} # Verify expected status for each path assert rowsby[f'http://{address}/path1']['status'] == expected_path1 assert rowsby[f'http://{address}/path2']['status'] == expected_path2 assert rowsby[f'http://{address}/PATH3']['status'] == expected_path3
CapitalisePathHandler
python
django-import-export__django-import-export
tests/core/tests/test_resources/test_import_export.py
{ "start": 15878, "end": 16972 }
class ____(TestCase): # issue 1517 @patch("import_export.resources.logger") @patch("import_export.fields.Field.save") def test_import_with_missing_field_in_row(self, mock_field_save, mock_logger): dataset = tablib.Dataset(*[(1, "Some book")], headers=["id", "name"]) self.resource = BookResource() result = self.resource.import_data(dataset) self.assertFalse(result.has_errors()) mock_logger.debug.assert_any_call( "skipping field '<import_export.fields.Field: author_email>' " "- column name 'author_email' is not present in row" ) self.assertEqual(2, mock_field_save.call_count) def test_import_row_with_no_defined_id_field(self): """Ensure a row with no id field can be imported (issue 1812).""" self.assertEqual(0, Author.objects.count()) dataset = tablib.Dataset(*[("J. R. R. Tolkien",)], headers=["name"]) self.resource = AuthorResource() self.resource.import_data(dataset) self.assertEqual(1, Author.objects.count())
ImportWithMissingFields
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 264613, "end": 265225 }
class ____(sgqlc.types.Input): """Represents a single select field option""" __schema__ = github_schema __field_names__ = ("name", "color", "description") name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name") """The name of the option""" color = sgqlc.types.Field(sgqlc.types.non_null(ProjectV2SingleSelectFieldOptionColor), graphql_name="color") """The display color of the option""" description = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="description") """The description text of the option"""
ProjectV2SingleSelectFieldOptionInput
python
doocs__leetcode
solution/0300-0399/0320.Generalized Abbreviation/Solution.py
{ "start": 0, "end": 441 }
class ____: def generateAbbreviations(self, word: str) -> List[str]: def dfs(i: int) -> List[str]: if i >= n: return [""] ans = [word[i] + s for s in dfs(i + 1)] for j in range(i + 1, n + 1): for s in dfs(j + 1): ans.append(str(j - i) + (word[j] if j < n else "") + s) return ans n = len(word) return dfs(0)
Solution
python
cookiecutter__cookiecutter
cookiecutter/exceptions.py
{ "start": 1620, "end": 1773 }
class ____(CookiecutterException): """ Exception for unknown repo types. Raised if a repo's type cannot be determined. """
UnknownRepoType
python
google__jax
jax/experimental/jax2tf/tests/flax_models/seq2seq_lstm.py
{ "start": 5229, "end": 7110 }
class ____(nn.Module): """Sequence-to-sequence class using encoder/decoder architecture. Attributes: teacher_force: whether to use `decoder_inputs` as input to the decoder at every step. If False, only the first input (i.e., the "=" token) is used, followed by samples taken from the previous output logits. hidden_size: int, the number of hidden dimensions in the encoder and decoder LSTMs. vocab_size: the size of the vocabulary. eos_id: EOS id. """ teacher_force: bool hidden_size: int vocab_size: int eos_id: int = 1 @nn.compact def __call__(self, encoder_inputs: Array, decoder_inputs: Array) -> tuple[Array, Array]: """Applies the seq2seq model. Args: encoder_inputs: [batch_size, max_input_length, vocab_size]. padded batch of input sequences to encode. decoder_inputs: [batch_size, max_output_length, vocab_size]. padded batch of expected decoded sequences for teacher forcing. When sampling (i.e., `teacher_force = False`), only the first token is input into the decoder (which is the token "="), and samples are used for the following inputs. The second dimension of this tensor determines how many steps will be decoded, regardless of the value of `teacher_force`. Returns: Pair (logits, predictions), which are two arrays of length `batch_size` containing respectively decoded logits and predictions (in one hot encoding format). """ # Encode inputs. init_decoder_state = Encoder( hidden_size=self.hidden_size, eos_id=self.eos_id)(encoder_inputs) # Decode outputs. logits, predictions = Decoder( init_state=init_decoder_state, teacher_force=self.teacher_force, vocab_size=self.vocab_size)(decoder_inputs[:, :-1]) return logits, predictions
Seq2seq
python
huggingface__transformers
src/transformers/models/deit/modeling_deit.py
{ "start": 19604, "end": 23721 }
class ____(DeiTPreTrainedModel): def __init__(self, config: DeiTConfig) -> None: super().__init__(config) self.deit = DeiTModel(config, add_pooling_layer=False, use_mask_token=True) self.decoder = nn.Sequential( nn.Conv2d( in_channels=config.hidden_size, out_channels=config.encoder_stride**2 * config.num_channels, kernel_size=1, ), nn.PixelShuffle(config.encoder_stride), ) # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring def forward( self, pixel_values: Optional[torch.Tensor] = None, bool_masked_pos: Optional[torch.BoolTensor] = None, interpolate_pos_encoding: bool = False, **kwargs: Unpack[TransformersKwargs], ) -> MaskedImageModelingOutput: r""" bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`): Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Examples: ```python >>> from transformers import AutoImageProcessor, DeiTForMaskedImageModeling >>> import torch >>> from PIL import Image >>> import requests >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> image_processor = AutoImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224") >>> model = DeiTForMaskedImageModeling.from_pretrained("facebook/deit-base-distilled-patch16-224") >>> num_patches = (model.config.image_size // model.config.patch_size) ** 2 >>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values >>> # create random boolean mask of shape (batch_size, num_patches) >>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool() >>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos) >>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction >>> list(reconstructed_pixel_values.shape) [1, 3, 224, 224] ```""" outputs: BaseModelOutputWithPooling = self.deit( pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding, **kwargs, ) sequence_output = outputs.last_hidden_state # Reshape to (batch_size, num_channels, height, width) sequence_output = sequence_output[:, 1:-1] batch_size, sequence_length, num_channels = sequence_output.shape height = width = int(sequence_length**0.5) sequence_output = sequence_output.permute(0, 2, 1).reshape(batch_size, num_channels, height, width) # Reconstruct pixel values reconstructed_pixel_values = self.decoder(sequence_output) masked_im_loss = None if bool_masked_pos is not None: size = self.config.image_size // self.config.patch_size bool_masked_pos = bool_masked_pos.reshape(-1, size, size) mask = ( bool_masked_pos.repeat_interleave(self.config.patch_size, 1) .repeat_interleave(self.config.patch_size, 2) .unsqueeze(1) .contiguous() ) reconstruction_loss = nn.functional.l1_loss(pixel_values, reconstructed_pixel_values, reduction="none") masked_im_loss = (reconstruction_loss * mask).sum() / (mask.sum() + 1e-5) / self.config.num_channels return MaskedImageModelingOutput( loss=masked_im_loss, reconstruction=reconstructed_pixel_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @auto_docstring( custom_intro=""" DeiT Model transformer with an image classification head on top (a linear layer on top of the final hidden state of the [CLS] token) e.g. for ImageNet. """ )
DeiTForMaskedImageModeling
python
palantir__python-language-server
pyls/workspace.py
{ "start": 4300, "end": 10767 }
class ____(object): def __init__(self, uri, workspace, source=None, version=None, local=True, extra_sys_path=None, rope_project_builder=None): self.uri = uri self.version = version self.path = uris.to_fs_path(uri) self.dot_path = _utils.path_to_dot_name(self.path) self.filename = os.path.basename(self.path) self._config = workspace._config self._workspace = workspace self._local = local self._source = source self._extra_sys_path = extra_sys_path or [] self._rope_project_builder = rope_project_builder self._lock = RLock() def __str__(self): return str(self.uri) def _rope_resource(self, rope_config): from rope.base import libutils return libutils.path_to_resource(self._rope_project_builder(rope_config), self.path) @property @lock def lines(self): return self.source.splitlines(True) @property @lock def source(self): if self._source is None: with io.open(self.path, 'r', encoding='utf-8') as f: return f.read() return self._source def update_config(self, settings): self._config.update((settings or {}).get('pyls', {})) @lock def apply_change(self, change): """Apply a change to the document.""" text = change['text'] change_range = change.get('range') if not change_range: # The whole file has changed self._source = text return start_line = change_range['start']['line'] start_col = change_range['start']['character'] end_line = change_range['end']['line'] end_col = change_range['end']['character'] # Check for an edit occuring at the very end of the file if start_line == len(self.lines): self._source = self.source + text return new = io.StringIO() # Iterate over the existing document until we hit the edit range, # at which point we write the new text, then loop until we hit # the end of the range and continue writing. for i, line in enumerate(self.lines): if i < start_line: new.write(line) continue if i > end_line: new.write(line) continue if i == start_line: new.write(line[:start_col]) new.write(text) if i == end_line: new.write(line[end_col:]) self._source = new.getvalue() def offset_at_position(self, position): """Return the byte-offset pointed at by the given position.""" return position['character'] + len(''.join(self.lines[:position['line']])) def word_at_position(self, position): """Get the word under the cursor returning the start and end positions.""" if position['line'] >= len(self.lines): return '' line = self.lines[position['line']] i = position['character'] # Split word in two start = line[:i] end = line[i:] # Take end of start and start of end to find word # These are guaranteed to match, even if they match the empty string m_start = RE_START_WORD.findall(start) m_end = RE_END_WORD.findall(end) return m_start[0] + m_end[-1] @lock def jedi_names(self, use_document_path, all_scopes=False, definitions=True, references=False): script = self.jedi_script(use_document_path=use_document_path) return script.get_names(all_scopes=all_scopes, definitions=definitions, references=references) @lock def jedi_script(self, position=None, use_document_path=False): extra_paths = [] environment_path = None env_vars = None if self._config: jedi_settings = self._config.plugin_settings('jedi', document_path=self.path) environment_path = jedi_settings.get('environment') extra_paths = jedi_settings.get('extra_paths') or [] env_vars = jedi_settings.get('env_vars') # Drop PYTHONPATH from env_vars before creating the environment because that makes # Jedi throw an error. if env_vars is None: env_vars = os.environ.copy() env_vars.pop('PYTHONPATH', None) environment = self.get_enviroment(environment_path, env_vars=env_vars) if environment_path else None sys_path = self.sys_path(environment_path, env_vars=env_vars) + extra_paths project_path = self._workspace.root_path # Extend sys_path with document's path if requested if use_document_path: sys_path += [os.path.normpath(os.path.dirname(self.path))] kwargs = { 'code': self.source, 'path': self.path, 'environment': environment, 'project': jedi.Project(path=project_path, sys_path=sys_path), } if position: # Deprecated by Jedi to use in Script() constructor kwargs += _utils.position_to_jedi_linecolumn(self, position) return jedi.Script(**kwargs) def get_enviroment(self, environment_path=None, env_vars=None): # TODO(gatesn): #339 - make better use of jedi environments, they seem pretty powerful if environment_path is None: environment = jedi.api.environment.get_cached_default_environment() else: if environment_path in self._workspace._environments: environment = self._workspace._environments[environment_path] else: environment = jedi.api.environment.create_environment(path=environment_path, safe=False, env_vars=env_vars) self._workspace._environments[environment_path] = environment return environment def sys_path(self, environment_path=None, env_vars=None): # Copy our extra sys path # TODO: when safe to break API, use env_vars explicitly to pass to create_environment path = list(self._extra_sys_path) environment = self.get_enviroment(environment_path=environment_path, env_vars=env_vars) path.extend(environment.get_sys_path()) return path
Document
python
aimacode__aima-python
learning4e.py
{ "start": 12536, "end": 12970 }
class ____: """ A very dumb algorithm: always pick the result that was most popular in the training data. Makes a baseline for comparison. """ def __init__(self, dataset): self.most_popular = mode([e[dataset.target] for e in dataset.examples]) def predict(self, example): """Always return same result: the most popular from the training set.""" return self.most_popular
PluralityLearner
python
pytorch__pytorch
test/dynamo/test_misc.py
{ "start": 375547, "end": 421911 }
class ____: class DUMMY: class DUMMY2: pass def dummy(self): def dummy2(): pass class BBB: @staticmethod def CCC(): class DDD: if True: @staticmethod def EEE(): x = [torch.ones(3, 3) for _ in range(5)] return x return DDD def fn(): return 3 """ with WritableTempFile(mode="w") as f: f.write(src) f.flush() from torch._dynamo.funcname_cache import get_funcname names = [get_funcname(f.name, i + 1) for i in range(src.count("\n") + 1)] self.assertExpectedInline( "\n".join(names), """\ AAA AAA.DUMMY AAA.DUMMY.DUMMY2 AAA.DUMMY.DUMMY2 AAA.DUMMY.DUMMY2 AAA.dummy AAA.dummy.dummy2 AAA.dummy.dummy2 AAA.BBB AAA.BBB AAA.BBB.CCC AAA.BBB.CCC.DDD AAA.BBB.CCC.DDD AAA.BBB.CCC.DDD AAA.BBB.CCC.DDD.EEE AAA.BBB.CCC.DDD.EEE AAA.BBB.CCC.DDD.EEE AAA.BBB.CCC fn fn """, ) def test_return_dict_with_graph_break_and_update(self): def create(): torch._dynamo.graph_break() return {0: torch.tensor(3)} def fn(): return {**create()} opt_fn = torch.compile(backend="eager")(fn) result = opt_fn() self.assertIn(0, result) self.assertTrue(same(result[0], torch.tensor(3))) def test_dynamo_reset_clears_cache(self): """Test that dynamo bytecode cache is freed when dynamo reset is called """ def fn(x): return torch.sin(x) opt_fn = torch.compile(backend="eager")(fn) opt_fn(torch.randn(3, 3)) c1 = _debug_get_cache_entry_list(fn.__code__) self.assertEqual(len(c1), 1) torch._dynamo.reset() c2 = _debug_get_cache_entry_list(fn.__code__) self.assertEqual(len(c2), 0) @torch._dynamo.config.patch(capture_scalar_outputs=True) def test_check_simplification(self): @torch.compile(backend="eager", fullgraph=True) def fn(x): u0, u1 = x.tolist() torch._check((2 * u0) // (u0 + u1) != 0) if (2 * u0) // (u0 + u1) == 0: return torch.tensor(True) else: return torch.tensor(False) fn(torch.tensor([3, 3])) @torch._dynamo.config.patch(assume_static_by_default=True) def test_mark_unbacked_strict(self): @torch.compile() def fn(x, y): return torch.mul(x, y) x = torch.ones(5, 5) torch._dynamo.decorators.mark_unbacked(x, 0, strict=True) torch._dynamo.decorators.mark_unbacked(x, 1, strict=True) y = torch.randn(5, 5) with self.assertRaisesRegex(RuntimeError, "specialized"): fn(x, y) @torch._dynamo.config.patch(capture_scalar_outputs=True) def test_infer_unbacked_size_gt_zero(self): # This code, in fact, does NOT work in eager @torch.compile(backend="eager", fullgraph=True) def fn(x): y = torch.zeros(x.item()) if y.size(0) < 0: assert False return y self.assertEqual(fn(torch.tensor([0])), torch.zeros(0)) @torch.fx.experimental._config.patch(no_data_dependent_graph_break=True) def test_unbacked_strict_mode(self): @torch.compile() def fn(x, y): if x.shape[0] == 5: return torch.randn(5) return torch.mul(x, y) x = torch.ones(5, 5) torch._dynamo.decorators.mark_unbacked(x, 0) torch._dynamo.decorators.mark_unbacked(x, 1) y = torch.randn(5, 5) with self.assertRaisesRegex( RuntimeError, "Could not guard on data-dependent expression" ): fn(x, y) def test_guard_size_oblivious_backed(self): @torch.compile(backend="eager", fullgraph=True) def f(x): y = x.size(0) # This doesn't actually do anything if guard_size_oblivious(y == 0): return torch.randn(1) else: return torch.randn(2) # Should not fail in either case self.assertEqual(f(torch.randn(0)).shape, (1,)) self.assertEqual(f(torch.randn(2)).shape, (2,)) def _test_compile_model_free(self, model_inp_ctr, weakref_watch): """ Args: model_inp_ctr - constructor that returns a new model and inputs to that model weakref_watch - function that returns a layer of the model for weakref to finalize on, so we can check that the layer is freed after the model goes out of scope """ cleared = False def finalize(): nonlocal cleared cleared = True def run(): mod, inp = model_inp_ctr() weakref.finalize(weakref_watch(mod), finalize) torch.compile(mod, backend="eager")(inp) run() gc.collect() self.assertTrue(cleared) def test_custom_module_free(self): """Test that a model is freed when it goes out of scope""" class Mod(torch.nn.Module): def __init__(self) -> None: super(Mod, self).__init__() self.fc = torch.nn.Linear(100, 100) def forward(self, out): return self.fc(out) self._test_compile_model_free( lambda: (Mod(), torch.randn(100, 100)), lambda mod: mod.fc, ) def test_sequential_module_free(self): self._test_compile_model_free( lambda: ( torch.nn.Sequential( torch.nn.Linear(100, 100), torch.nn.ReLU(), ), torch.randn(100, 100), ), lambda mod: mod[0], ) def test_linear_module_free(self): self._test_compile_model_free( lambda: (torch.nn.Linear(100, 100), torch.randn(100, 100)), lambda mod: mod, ) def test_outside_linear_module_free(self): # Compared to test_linear_module_free, the linear # layer is not the code object that is directly compiled. # This test does not use _test_compile_model_free because of difficulty # in handling variable fc. cleared = False def finalize(): nonlocal cleared cleared = True def run(): fc = torch.nn.Linear(100, 100) class Mod(torch.nn.Module): def __init__(self) -> None: super().__init__() self.fc_ref = fc def forward(self, x): return self.fc_ref(x) mod = Mod() inp = torch.randn(100, 100) weakref.finalize(fc, finalize) torch.compile(mod, backend="eager")(inp) run() # del fc # This should delete all the references gc.collect() self.assertTrue(cleared) def test_parameter_free(self): def model_inp_ctr(): param = torch.nn.Parameter(torch.randn(100, 100)) class Mod(torch.nn.Module): def __init__(self) -> None: super().__init__() self.param = param def forward(self, x): return self.param * x[0] # return param to keep it alive in _test_compile_model_free return Mod(), (torch.randn(100, 100), param) self._test_compile_model_free(model_inp_ctr, lambda mod: mod.param) def test_conditional_list_comp_in_context(self): def fn(inp): try: return [torch.sin(x) for x in inp if x is not None] except Exception: pass inp = [torch.randn(3, 3) for _ in range(3)] + [None] opt_fn = torch.compile(fn, backend="eager") opt_fn(inp) def test_312_binary_slice_with_graph_break1(self): l1 = torch.nn.Linear(5, 5) l2 = torch.nn.Linear(5, 5) def fn(x): # causes a graph break with items in the stack n = torch.nn.Sequential(l1, l2) out = n[1:](x) return out opt_fn = torch.compile(fn, backend="eager") opt_fn(torch.randn(5, 5)) def test_312_binary_slice_with_graph_break2(self): class Foo: def __setitem__(self, key, val): pass def __getitem__(self, key): torch._dynamo.graph_break() return 1 foo = Foo() def fn(x): # graph break in a STORE_SLICE instruction foo[:] = x # graph break in BINARY_SLICE with has_backedge check x = x + foo[:] if x is None: x = x + 1 else: x = x + 1 return x opt_fn = torch.compile(fn, backend="eager") opt_fn(torch.randn(5, 5)) def test_super_after_graph_break(self): class Foo(torch.nn.Sequential): def __init__(self, layers): torch._dynamo.graph_break() super().__init__(*layers) def fn(x): layers = [torch.nn.Linear(3, 3) for _ in range(3)] mod = Foo(layers) return mod(x) opt_fn = torch.compile(fn, backend="eager") opt_fn(torch.randn(3, 3)) def test_load_fast_and_clear_graph_break(self): # Can result in a segfault in 3.12+ if LOAD_FAST_AND_CLEAR # is not handled properly in a graph break def fn(): out = torch.cat([torch.randn(r, 5) for r in range(3)]) torch._dynamo.graph_break() out = torch.cat([torch.randn(r, 5) for r in range(3)]) return out self.assertEqual(torch.compile(fn, backend="eager")().shape, (3, 5)) def test_raises_importerror1(self): @torch.compile(backend="eager") def fn(x): try: import some_module_that_surely_does_not_exist return except ImportError: pass return x.sin() x = torch.randn(8) self.assertEqual(fn(x), x.sin()) def test_raises_importerror2(self): @torch.compile(backend="eager") def fn(x): import some_module_that_surely_does_not_exist return x + 1 x = torch.randn(8) with self.assertRaises(ImportError): fn(x) def test_dynamo_cache_move_to_front(self): def fn(x, const): return x + const # dynamic=False forces Dynamo to recompile opt_fn = torch.compile(fn, backend="eager", dynamic=False) inp = torch.randn(3, 3) # NOTE: assumes that each cache entry is guarded # on unique Mod instance opt_fn(inp, 1) opt_fn(inp, 2) opt_fn(inp, 3) c1 = _debug_get_cache_entry_list(fn.__code__) self.assertEqual(len(c1), 3) # move cache entry to front opt_fn(inp, 2) c2 = _debug_get_cache_entry_list(fn.__code__) self.assertIs(c1[1], c2[0]) @torch._dynamo.config.patch(inline_inbuilt_nn_modules=False) @skipIfWindows(msg="TODO: (xuhancn) conform, AssertionError: False is not true") def test_dynamo_cache_invalidate(self): DeletedGuardManagerWrapper = torch._dynamo.guards.DeletedGuardManagerWrapper class Mod(torch.nn.Module): def __init__(self) -> None: super(Mod, self).__init__() self.fc = torch.nn.Linear(3, 3) def forward(self, out): return self.fc(out) def fn(x, mod): return mod(x) opt_fn = torch.compile(fn, backend="eager") m1 = Mod() m2 = Mod() m3 = Mod() inp = torch.randn(3, 3) # NOTE: assumes that each cache entry is guarded # on unique Mod instance opt_fn(inp, m1) opt_fn(inp, m2) opt_fn(inp, m3) c1 = _debug_get_cache_entry_list(fn.__code__) self.assertEqual(len(c1), 3) # move cache entry to front opt_fn(inp, m2) c2 = _debug_get_cache_entry_list(fn.__code__) self.assertIs(c1[1], c2[0]) # delete center of cache del m3 c3 = _debug_get_cache_entry_list(fn.__code__) self.assertEqual(len(c3), 3) self.assertTrue(isinstance(c3[2].guard_manager, DeletedGuardManagerWrapper)) # delete end of cache del m1 c4 = _debug_get_cache_entry_list(fn.__code__) self.assertEqual(len(c4), 3) self.assertTrue(isinstance(c4[1].guard_manager, DeletedGuardManagerWrapper)) self.assertTrue(isinstance(c4[2].guard_manager, DeletedGuardManagerWrapper)) del m2 c5 = _debug_get_cache_entry_list(fn.__code__) self.assertTrue(isinstance(c5[0].guard_manager, DeletedGuardManagerWrapper)) self.assertTrue(isinstance(c5[1].guard_manager, DeletedGuardManagerWrapper)) self.assertTrue(isinstance(c5[2].guard_manager, DeletedGuardManagerWrapper)) def test_inspect_signature_bind(self): import inspect def inner(a, b, *ar, c=10, d=11, **kw): pass def fn(x, apply_defaults): sig = inspect.signature(inner) bound = sig.bind(1, 2, 3, d=12, e=15) bound.arguments["d"] = 13 if apply_defaults: bound.apply_defaults() return ( sig, bound.signature, bound, bound.arguments, bound.args, bound.kwargs, x + 1, ) opt_fn = torch.compile(fn, backend="eager", fullgraph=True) for apply_defaults in (True, False): _, _, bound0, arguments0, args0, kwargs0, _ = fn( torch.ones(3, 3), apply_defaults ) _, _, bound1, arguments1, args1, kwargs1, _ = opt_fn( torch.ones(3, 3), apply_defaults ) self.assertEqual(bound0, bound1) self.assertEqual(arguments0, arguments1) self.assertEqual(args0, args1) self.assertEqual(kwargs0, kwargs1) self.assertTrue(args1) self.assertTrue(kwargs1) def test_inspect_signature_bind_non_user_function(self): import inspect class Foo: def __init__(self, a, b, *ar, c=10, d=11, **kw): pass def fn(x): sig = inspect.signature(Foo) bound = sig.bind(1, 2, 3, d=12, e=15) return bound, x + 1 opt_fn = torch.compile(fn, backend="eager") bound0, _ = fn(torch.ones(3, 3)) bound1, _ = opt_fn(torch.ones(3, 3)) self.assertEqual(bound0, bound1) import traceback # choose a function that is skipped but has defaults self.assertTrue(hasattr(traceback.print_exc, "__kwdefaults__")) self.assertIs( torch._dynamo.trace_rules.lookup(traceback.print_exc), torch._dynamo.variables.SkipFunctionVariable, ) def gn(x): sig = inspect.signature(traceback.print_exc) bound = sig.bind() return bound, x + 1 opt_gn = torch.compile(gn, backend="eager", fullgraph=True) bound0, _ = gn(torch.ones(3, 3)) bound1, _ = opt_gn(torch.ones(3, 3)) self.assertEqual(bound0, bound1) def test_inspect_signature_parameters(self): import inspect def fn(x, gn): d = inspect.signature(gn).parameters if d["a"].default is inspect.Parameter.empty: return torch.sin(x + 1) else: return torch.cos(x + 1) def gn(a: torch.Tensor, b: int) -> torch.Tensor: return a + b x = torch.randn(2, 3) opt_fn = torch.compile(backend="eager", fullgraph=True)(fn) self.assertEqual(fn(x, gn), opt_fn(x, gn)) def test_grad_none(self): def fn(x, y): x.grad = torch.abs(y) x.grad.add_(y) return torch.abs(y) y = torch.arange(4).reshape(2, 2).to(torch.float) x = torch.randn(2, 2) x.grad = None z = fn(x, y) ref_y = torch.clone(z).detach() ref_x_grad = torch.clone(x.grad).detach() y = torch.arange(4).reshape(2, 2).to(torch.float) x = torch.randn(2, 2) x.grad = None opt_fn = torch.compile(fn, backend="eager") z = opt_fn(x, y) self.assertEqual(z, ref_y) self.assertEqual(x.grad, ref_x_grad) def test_grad_non_none(self): def fn(x, y): x.grad.add_(y) return torch.abs(y) y = torch.ones(2, 2) x = torch.randn(2, 2) x.grad = torch.arange(4).reshape(2, 2).to(torch.float) z = fn(x, y) ref_y = torch.clone(z).detach() ref_x_grad = torch.clone(x.grad).detach() y = torch.ones(2, 2) x = torch.randn(2, 2) x.grad = torch.arange(4).reshape(2, 2).to(torch.float) cnt = torch._dynamo.testing.CompileCounterWithBackend("eager") opt_fn = torch.compile(fn, backend=cnt) z = opt_fn(x, y) # Ensure that the generated graph returns only one output. We want the # add_ on the grad to be part of the graph itself, so that inductor can # theoretically move the add_ and resulting copy_ nodes at the right # place to free memory. self.assertEqual(len(list(cnt.graphs[0].graph.nodes)[-1].all_input_nodes), 1) self.assertEqual(z, ref_y) self.assertEqual(x.grad, ref_x_grad) def test_new_with_int_list(self): # Make sure torch.Tensor.new(int argument list) behaves the same on dynamo. def fn(x): return x.new(*x.size()) + 5 optfn = torch.compile(backend="eager")(fn) x = torch.arange(10).view(2, 5) expected = fn(x) actual = optfn(x) self.assertEqual(expected.dtype, actual.dtype) self.assertEqual(expected.shape, actual.shape) self.assertEqual(expected.stride(), actual.stride()) self.assertEqual(expected.storage_offset(), actual.storage_offset()) def test_dynamic_shapes_as_strided(self): def fn(t, new_size, new_stride): tmp = t.as_strided(new_size, new_stride) tmp = tmp.view(-1) return t * tmp.sum() optfn = torch.compile(backend="eager", dynamic=True)(fn) x = torch.randn(3) new_size = [0, 3] new_stride = [3, 1] expected = fn(x, new_size, new_stride) actual = optfn(x, new_size, new_stride) self.assertEqual(expected.dtype, actual.dtype) self.assertEqual(expected.shape, actual.shape) self.assertEqual(expected.stride(), actual.stride()) self.assertEqual(expected.storage_offset(), actual.storage_offset()) @torch._dynamo.config.patch(guard_nn_modules=True) def test_hasattr_nn_module_guard(self): class M(torch.nn.Module): def __init__(self) -> None: super().__init__() self.a = torch.nn.Linear(3, 3) def forward(self, x): if hasattr(self, "a"): return self.a(x) else: return x m = M() x = torch.randn(3, 3) ref = m(x) opt_m = torch.compile(backend="eager")(m) res = opt_m(x) self.assertEqual(ref, res) def test_ordered_dict_move_to_end(self): d = { "foo": 1, "bar": 2, } d = collections.OrderedDict(d) d.move_to_end("foo") @torch.compile(backend="eager") def fn(x, d): return x * d["foo"] * d["bar"] fn(torch.randn(4), d) with unittest.mock.patch("torch._dynamo.config.error_on_recompile", True): fn(torch.randn(4), d) def test_defaultdict(self): d = collections.defaultdict() d["foo"] = 1 d["bar"] = 2 @torch.compile(backend="eager") def fn(x, d): return x * d["foo"] * d["bar"] fn(torch.randn(4), d) with unittest.mock.patch("torch._dynamo.config.error_on_recompile", True): fn(torch.randn(4), d) def test_custom_dict(self): class MyDict(dict): pass d = { "foo": 1, "bar": 2, } d = MyDict(d) @torch.compile(backend="eager") def fn(x, d): return x * d["foo"] * d["bar"] fn(torch.randn(4), d) with unittest.mock.patch("torch._dynamo.config.error_on_recompile", True): fn(torch.randn(4), d) def test_hash_hop(self): associative_scan = importlib.import_module( "torch._higher_order_ops.associative_scan" ) @torch.compile(fullgraph=True) def fn(y, s): d = dict() d[s] = y return d[s] + 1.0 fn(torch.ones(2, 2, device="cpu"), associative_scan.AssociativeScanOp()) def test_iter_type(self): @torch.compile(fullgraph=True) def fn(y): x = iter([]) if isinstance(x, list): return y + 1 else: return y + 2 res = fn(torch.ones(2)) self.assertEqual(torch.ones(2) + 2, res) def test_descriptor(self): class lazy_property: def __init__(self, wrapped): self.wrapped = wrapped def __get__(self, instance, obj_type=None): value = self.wrapped(instance) setattr(instance, self.wrapped.__name__, value) return value class UserDefined: def __init__(self) -> None: self.a = 3 @lazy_property def length(self): return 3 def run(self, x): return x * self.length obj = UserDefined() def fn(x): return obj.run(x) opt_fn = torch.compile(fn, backend="eager", fullgraph=True) x = torch.randn(4) # Opt_fn is deliberately called first to trigger the __get__ function. # Otherwise, the setattr removes the lazy property. ref = opt_fn(x) res = fn(x) self.assertEqual(ref, res) ref = opt_fn(x) res = fn(x) self.assertEqual(ref, res) def test_descriptor_side_effect(self): # This pattern (readonly descriptor but writable value in `__dict__`) is # from scipy `_make_tuple_bunch`: # https://github.com/scipy/scipy/blob/maintenance/1.9.x/scipy/_lib/_bunch.py#L32-L226 def fget(obj): return obj.__dict__["field"] class MyClass: def __init__(self, n): self.__dict__["field"] = n field = property(fget) def fn(x): obj = MyClass(42) return x + obj.field, obj opt_fn = torch.compile(fn, backend="eager", fullgraph=True) x = torch.randn(4) ref_t, ref_obj = fn(x) res_t, res_obj = opt_fn(x) self.assertEqual(ref_t, res_t) self.assertEqual(ref_obj.field, res_obj.field) def test_assert_size_stride(self): x = torch.randn(2, 3, 4) with self.assertRaisesRegex( AssertionError, "expected size 2==5, stride 12==9 at dim=0; expected size 3==6, stride 4==9 at dim=1; expected size 4==7, stride 1==10 at dim=2", ): torch._C._dynamo.guards.assert_size_stride(x, (5, 6, 7), (9, 9, 10)) def test_frozen_dict(self): # A pattern from StableDiffusion class FrozenDict(collections.OrderedDict): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for key, value in self.items(): setattr(self, key, value) self.__frozen = True def __delitem__(self, *args, **kwargs): raise Exception( f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance." ) def setdefault(self, *args, **kwargs): raise Exception( f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance." ) def pop(self, *args, **kwargs): raise Exception( f"You cannot use ``pop`` on a {self.__class__.__name__} instance." ) def update(self, *args, **kwargs): raise Exception( f"You cannot use ``update`` on a {self.__class__.__name__} instance." ) def __setattr__(self, name, value): if hasattr(self, "__frozen") and self.__frozen: raise Exception( f"You cannot use ``__setattr__`` on a {self.__class__.__name__} instance." ) super().__setattr__(name, value) def __setitem__(self, name, value): if hasattr(self, "__frozen") and self.__frozen: raise Exception( f"You cannot use ``__setattr__`` on a {self.__class__.__name__} instance." ) super().__setitem__(name, value) d = {"a": 1} frozen_d = FrozenDict(d) @torch.compile(backend="eager", fullgraph=True) def fn(x): dict(frozen_d).items() return torch.sin(x) fn(torch.randn(4)) def test_tuple_class(self): cnts = torch._dynamo.testing.CompileCounter() def fn(x): updated_x = [] for v in x: updated_x.append(v + 1) return x.__class__(updated_x) opt_fn = torch.compile(fn, backend=cnts, fullgraph=True) d1 = torch.zeros(2, 2) d2 = torch.ones(2, 2) r = opt_fn((d1, d2)) self.assertEqual(r.__class__, tuple) r1, r2 = r self.assertEqual(r1, torch.ones(2, 2)) self.assertEqual(r2, torch.ones(2, 2) + 1) self.assertEqual(cnts.frame_count, 1) def test_list_class(self): cnts = torch._dynamo.testing.CompileCounter() def fn(x): updated_x = [] for v in x: updated_x.append(v + 1) return x.__class__(updated_x) opt_fn = torch.compile(fn, backend=cnts, fullgraph=True) d1 = torch.zeros(2, 2) d2 = torch.ones(2, 2) r = opt_fn([d1, d2]) self.assertEqual(r.__class__, list) self.assertEqual(len(r), 2) self.assertEqual(r[0], torch.ones(2, 2)) self.assertEqual(r[1], torch.ones(2, 2) + 1) self.assertEqual(cnts.frame_count, 1) def test_namedtuple_class(self): import collections cnts = torch._dynamo.testing.CompileCounter() def fn(x): updated_x = [] for v in x: updated_x.append(v + 1) return x.__class__(*updated_x) opt_fn = torch.compile(fn, backend=cnts, fullgraph=True) d1 = torch.zeros(2, 2) d2 = torch.ones(2, 2) point = collections.namedtuple("Point", ["x", "y"]) p = point(d1, d2) r = opt_fn(p) self.assertEqual(r.__class__, point) self.assertEqual(r.x, torch.ones(2, 2)) self.assertEqual(r.y, torch.ones(2, 2) + 1) self.assertEqual(cnts.frame_count, 1) def test_getattrvariable_as_python_constant(self): from torch._dynamo.variables.misc import GetAttrVariable @torch.compile(backend="eager") def fn(x, rand1): random.Random().setstate(rand1.getstate()) return x + rand1.random() def get_rng(): rand1 = random.Random(1) orig_random = rand1.random rand1.random = lambda: orig_random() return rand1 x = torch.randn(3, 3) expected = fn.__wrapped__(x, get_rng()) with patch.object(GetAttrVariable, "as_python_constant", autospec=True) as po: actual = fn(x, get_rng()) self.assertEqual(expected, actual) self.assertGreater(po.call_count, 0) def test_data_ptr_graph_break_builtin(self): def f(a, b): # builtin + not implemented for DataPtrVariable return a.data_ptr() + b.data_ptr() a = torch.randn(4) b = torch.randn(5) # make sure there is a graph break with self.assertRaises(torch._dynamo.exc.Unsupported): torch.compile(f, backend="eager", fullgraph=True)(a, b) torch._dynamo.reset() expected = f(a, b) actual = torch.compile(f, backend="eager")(a, b) self.assertEqual(expected, actual) def test_data_ptr_graph_break_aten(self): def f(a): # torch.add not implemented for DataPtrVariable return torch.add(a, a.data_ptr()) a = torch.randn(4) counters.clear() expected = f(a) actual = torch.compile(f, backend="eager")(a) self.assertEqual(expected, actual) self.assertTrue(len(counters["graph_break"]) > 0) counters.clear() class AssertNumOutputBackend: """ A backend that checks the number of output for compiled graph, and return the graph as is. """ def __init__(self, test_case, expected_num_output: int): self.test_case = test_case self.expected_num_output = expected_num_output def __call__(self, gm: torch.fx.GraphModule, example_inputs): outputs = gm(*example_inputs) self.test_case.assertEqual(self.expected_num_output, len(outputs)) return gm def test_returning_nested_func_with_captured_tensor(self): @torch.compile(backend=self.AssertNumOutputBackend(self, 2)) def test(): x = torch.rand(1) def func(): return x + x # Returning `func` forces dynamo to output `x` in the compiled # graph, so that we can store it as `func`'s closure. The output of # compiled graph would be `(x, x + x)`. return func, func() test() def test_running_nested_func_with_captured_tensor(self): @torch.compile(backend=self.AssertNumOutputBackend(self, 1)) def test(): x = torch.rand(1) def func(): return x + x # `x` is no longer needed after running the compiled graph, so we # shouldn't return it. The output of compiled graph would be `(x + # x,)`. return func() test() def test_returning_func_with_captured_func_and_tensor(self): @torch.compile(backend=self.AssertNumOutputBackend(self, 2)) def test(): x = torch.rand(1) def nested(): return x + x def func(): return nested() # Returning `func` forces dynamo to output `x` in the compiled # graph, so that we can store it as `func`'s closure. The output of # compiled graph would be `(x, x + x)`. return func, func() test() def test_running_func_with_captured_func_and_tensor(self): @torch.compile(backend=self.AssertNumOutputBackend(self, 1)) def test(): x = torch.rand(1) def nested(): return x + x def func(): return nested() # `x` is no longer needed after running the compiled graph, so we # shouldn't return it. The output of compiled graph would be `(x)`. return func() test() def test_escaping_closure_var_with_backward_hook(self): @torch.compile(backend=self.AssertNumOutputBackend(self, 2)) def fn(x): temp = x * x captured_var = temp + 1 # This is where the lambda escapes the lifetime of `fn`, so # dynamo must generate proper bytecode to update `captured_var`. x.register_hook(lambda _: captured_var) # The output of compiled graph would be `(x * x, x * x + 1)`. return temp ones = torch.ones(4, requires_grad=True) fn(ones).sum().backward() def test_escaping_closure_var_with_nonlocal_var(self): nonlocal_fn = None @torch.compile(backend=self.AssertNumOutputBackend(self, 2)) def fn(x): temp = x * x captured_var = x + 1 def inner(): return captured_var # This is where `inner` escapes the lifetime of `fn`, so dynamo must # generate proper bytecode to update `captured_var`. nonlocal nonlocal_fn nonlocal_fn = inner # The output of compiled graph would be `(x * x, x * x + 1)`. return temp ones = torch.ones(4, requires_grad=True) fn(ones) nonlocal_fn() def test_compare_tensor_with_none(self): @torch.compile() def f(x): return torch.tensor(x == None) res = f(torch.tensor(1)) self.assertEqual(torch.tensor(False), res) def test_dataclass(self): @dataclasses.dataclass(frozen=True) class Foo: x: int @torch.compile(backend="eager", fullgraph=True) def run(x, foo0): if dataclasses.is_dataclass(foo0): foo1 = dataclasses.replace(foo0, **{"x": 1}) return x + 1, foo1 return x + 2, foo0 res, foo = run(torch.zeros(1), Foo(0)) self.assertTrue(res, torch.ones(1)) self.assertEqual(foo.x, 1) def test_frozenset_of_non_literals(self): class Foo: pass foo = Foo() foo.x = 0 s = frozenset([foo]) @torch.compile(backend="eager") def run(x, s, foo0): # Dynamo must have the same representation for `foo0` and `foo1`, # otherwise the update to `foo0.x` won't be reflected in the read of # `foo1.x`. foo1 = list(s)[0] foo0.x += 1 return x + 1, foo1.x res = run(torch.ones(1), s, foo) self.assertTrue(same(res[0], torch.ones(1) + 1)) self.assertEqual(res[1], 1) def test_ne_operator_with_custom_eq(self): class Foo: def __init__(self, x): self.x = x def __eq__(self, other): return self.x == other.x @torch.compile(fullgraph=True, backend="eager") def run(x): f1 = Foo(0) f2 = Foo(0) # `x + 1` prevents Dynamo from skipping this frame. return x + 1, f1 != f2 _, ne = run(torch.ones(1)) self.assertFalse(ne) def test_ne_operator_with_custom_ne(self): class Foo: def __init__(self, x): self.x = x self.ne_called = False def __ne__(self, other): # ne_called attr is later checked to ensure that overridden # `__ne__` is traced self.ne_called = True return not self.__eq__(other) def __eq__(self, other): return self.x == other.x f1 = Foo(0) f2 = Foo(0) @torch.compile(fullgraph=True, backend="eager") def run(x): # `x + 1` prevents Dynamo from skipping this frame. return x + 1, f1 != f2 _, ne = run(torch.ones(1)) self.assertFalse(ne) self.assertTrue(f1.ne_called) def test_ne_operator_with_custom_graphbreak_eq(self): counters.clear() class Foo: def __init__(self, x): self.x = x def __eq__(self, other): # This allows us to check that Dynamo actually traced into the # custom eq method. torch._dynamo.graph_break() return self.x == other.x @torch.compile(backend="eager") def run(x): f1 = Foo(0) f2 = Foo(0) # `x + 1` prevents Dynamo from skipping this frame. return x + 1, f1 != f2 _, ne = run(torch.ones(1)) self.assertFalse(ne) self.assertEqual(len(counters["graph_break"]), 1) @unittest.skipIf(sys.version_info < (3, 11), "Python 3.11+") def test_RAISE_VARARGS_0(self): def foo(): try: raise ValueError except: raise @torch.compile(backend="eager", fullgraph=True) def fn(t): try: foo() except ValueError: return t.sin() except Exception: return t.cos() t = torch.randn(2) y = fn(t) self.assertEqual(y, t.sin()) def test_overridden_getattribute(self): class Bar: def __init__(self, v): self.v = v class Foo: attribute_map = {} def __init__(self): self.attribute_map = { "a_premap": "a", } # `bar` attribute requires propagating sources correctly through # object.__getattribute__ self.bar = Bar(5) def __setattr__(self, key, value): if key in super().__getattribute__("attribute_map"): key = super().__getattribute__("attribute_map")[key] super().__setattr__(key, value) def __getattribute__(self, key): if key == "sentinel": raise AttributeError() if key != "attribute_map" and key in super().__getattribute__( "attribute_map" ): key = super().__getattribute__("attribute_map")[key] return super().__getattribute__(key) def __getattr__(self, key): if key == "sentinel": return 5 raise AttributeError() def get_foo(): f = Foo() f.a_premap = 2 f.b = 3 return f def fn(x, f): return x * f.a_premap * f.a * f.b * f.sentinel * f.bar.v x = torch.randn(4) opt_fn = torch.compile(fn, backend="eager", fullgraph=True) self.assertEqual(fn(x, get_foo()), opt_fn(x, get_foo())) def test_dunder_weakref(self): class Foo: pass def fn(x): foo = Foo() # tests isgetsetdescriptor if foo.__weakref__: return torch.cos(x) return torch.sin(x) opt_fn = torch.compile(fn, backend="eager", fullgraph=True) x = torch.randn(4) self.assertEqual(fn(x), opt_fn(x)) def test_guard_filter_fn_by_id(self): def guard_filter_fn(entries): return [entry.guard_type != "ID_MATCH" for entry in entries] @torch.compile(fullgraph=True, options={"guard_filter_fn": guard_filter_fn}) def fn(x): return id(x) inputs = (torch.randn(3, 2),) fn(*inputs) inputs_1 = (torch.randn(3, 2),) with torch.compiler.set_stance("fail_on_recompile"): self.assertEqual(fn(*inputs_1), id(inputs[0])) def test_guard_filter_fn_by_is_global(self): def guard_filter_fn(entries): return [not entry.is_global for entry in entries] global GLOBAL_INT @torch.compile(fullgraph=True, options={"guard_filter_fn": guard_filter_fn}) def fn(x): return x + GLOBAL_INT GLOBAL_INT = 1 fn(torch.randn(3, 2)) GLOBAL_INT = 2 inputs = (torch.randn(3, 2),) with torch.compiler.set_stance("fail_on_recompile"): self.assertEqual(fn(*inputs), inputs[0] + 1) def test_guard_filter_fn_by_name_and_value(self): def guard_filter_fn(entries): return [ not (entry.name == "y" and entry.value is None) for entry in entries ] @torch.compile(fullgraph=True, options={"guard_filter_fn": guard_filter_fn}) def fn(x, y): if y is not None: x += y return x fn(torch.randn(3, 2), None) inputs = (torch.randn(3, 2), torch.tensor(1)) with torch.compiler.set_stance("fail_on_recompile"): self.assertEqual(fn(*inputs), inputs[0]) def test_guard_filter_inbuilt_nn_modules(self): class Mod(torch.nn.Module): def __init__(self): super().__init__() self.norm = torch.nn.LayerNorm(8) def forward(self, x): return self.norm(x) mod = Mod() opt_mod = torch.compile( mod, options={ "guard_filter_fn": torch.compiler.skip_guard_on_inbuilt_nn_modules_unsafe }, ) x = torch.rand(4, 8) opt_mod(x) mod.norm.eps = 1e-02 # Since the guards are skipped on inbuilt nn modules, we should not recompile with unittest.mock.patch("torch._dynamo.config.error_on_recompile", True): opt_mod(x) def test_guard_filter_nn_modules(self): class Mod(torch.nn.Module): def __init__(self): super().__init__() self.c = 2 self.norm = torch.nn.LayerNorm(8) def forward(self, x): return self.norm(x) + self.c mod = Mod() opt_mod = torch.compile( mod, options={ "guard_filter_fn": torch.compiler.skip_guard_on_all_nn_modules_unsafe }, ) x = torch.rand(4, 8) opt_mod(x) mod.c = 3 # Since the guards are skipped on all nn modules, we should not recompile with unittest.mock.patch("torch._dynamo.config.error_on_recompile", True): opt_mod(x) def test_guard_filter_tensors(self): class Mod(torch.nn.Module): def __init__(self): super().__init__() self.c = 2.0 self.norm = torch.nn.LayerNorm(8) def forward(self, x): return self.norm(x) + self.c mod = Mod() opt_mod = torch.compile( mod, options={ "guard_filter_fn": torch.compiler.keep_tensor_guards_unsafe, }, ) x = torch.rand(4, 8) opt_mod(x) mod.c = 3.0 # Since the guards are skipped on all tensors with unittest.mock.patch("torch._dynamo.config.error_on_recompile", True): opt_mod(x) def test_guard_filter_globals(self): class Mod(torch.nn.Module): def __init__(self): super().__init__() self.c = 2 self.norm = torch.nn.LayerNorm(8) def forward(self, x): return self.norm(x) + self.c + GLOBAL_INT mod = Mod() opt_mod = torch.compile( mod, options={ "guard_filter_fn": torch.compiler.skip_guard_on_globals_unsafe, }, ) global GLOBAL_INT GLOBAL_INT = 1 x = torch.rand(4, 8) opt_mod(x) GLOBAL_INT = 2 # Since the guards are skipped on globals, we should not recompile with unittest.mock.patch("torch._dynamo.config.error_on_recompile", True): opt_mod(x) @torch._dynamo.config.patch(capture_scalar_outputs=True) def test_builtin_bool_on_symint(self): def f(x): return bool(x.item()) opt_f = torch.compile(f, backend="eager", fullgraph=True) x = torch.randint(10, (1,)) ref = f(x) res = opt_f(x) self.assertEqual(ref, res) @torch._dynamo.config.patch(capture_scalar_outputs=True) def test_builtin_bool_on_symfloat(self): def f(x): return bool(x.item()) opt_f = torch.compile(f, backend="eager", fullgraph=True) x = torch.randn(1) ref = f(x) res = opt_f(x) self.assertEqual(ref, res) @torch._dynamo.config.patch(capture_scalar_outputs=True) def test_builtin_bool_on_symbool(self): def f(x): return bool(x.item()) opt_f = torch.compile(f, backend="eager", fullgraph=True) x = torch.randn(1) == 1 ref = f(x) res = opt_f(x) self.assertEqual(ref, res) def test_builtin_complex(self): def f(x): c = ( complex(), complex(1), complex(2, 3), complex(imag=2), complex(real=1), complex(imag=1, real=2), complex("1+2j"), complex(1, 2).conjugate(), ) return [x + z for z in c] x = torch.randn(1) opt_f = torch.compile(f, backend="eager", fullgraph=True) res = opt_f(x) ref = f(x) self.assertEqual(res, ref) def test_builtin_complex_args(self): @torch.compile(backend="eager", fullgraph=True) def f(*args, **kwargs): return torch.tensor(complex(*args, **kwargs)) self.assertRaises(Unsupported, f, 1, 1, 1) self.assertRaises(Unsupported, f, 1, 1, fake_arg=1) self.assertRaises(Unsupported, f, fake_arg=1) self.assertRaises(Unsupported, f, []) self.assertRaises(Unsupported, f, "1 + j") def test_compiled_class_graph_break(self): counter = CompileCounter() @torch.compile(backend=counter, fullgraph=False) def f(x): x += 1 class C: pass return x.sin() x = torch.randn(3) f(x) self.assertEqual(counter.frame_count, 2)
AAA
python
huggingface__transformers
src/transformers/models/yolos/image_processing_yolos_fast.py
{ "start": 10835, "end": 29886 }
class ____(BaseImageProcessorFast): resample = PILImageResampling.BILINEAR image_mean = IMAGENET_DEFAULT_MEAN image_std = IMAGENET_DEFAULT_STD format = AnnotationFormat.COCO_DETECTION do_resize = True do_rescale = True do_normalize = True do_pad = True size = {"shortest_edge": 800, "longest_edge": 1333} default_to_square = False model_input_names = ["pixel_values", "pixel_mask"] valid_kwargs = YolosImageProcessorKwargs def __init__(self, **kwargs: Unpack[YolosImageProcessorKwargs]) -> None: kwargs.setdefault("do_pad", kwargs.pop("pad_and_return_pixel_mask", self.do_pad)) size = kwargs.pop("size", None) max_size = None if size is None else kwargs.pop("max_size", 1333) size = size if size is not None else {"shortest_edge": 800, "longest_edge": 1333} self.size = get_size_dict(size, max_size=max_size, default_to_square=False) # Backwards compatibility do_convert_annotations = kwargs.get("do_convert_annotations") do_normalize = kwargs.get("do_normalize") if do_convert_annotations is None and getattr(self, "do_convert_annotations", None) is None: self.do_convert_annotations = do_normalize if do_normalize is not None else self.do_normalize super().__init__(**kwargs) def prepare_annotation( self, image: torch.Tensor, target: dict, format: Optional[AnnotationFormat] = None, return_segmentation_masks: Optional[bool] = None, masks_path: Optional[Union[str, pathlib.Path]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> dict: """ Prepare an annotation for feeding into YOLOS model. """ format = format if format is not None else self.format if format == AnnotationFormat.COCO_DETECTION: return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks target = prepare_coco_detection_annotation( image, target, return_segmentation_masks, input_data_format=input_data_format ) elif format == AnnotationFormat.COCO_PANOPTIC: return_segmentation_masks = True if return_segmentation_masks is None else return_segmentation_masks target = prepare_coco_panoptic_annotation( image, target, masks_path=masks_path, return_masks=return_segmentation_masks, input_data_format=input_data_format, ) else: raise ValueError(f"Format {format} is not supported.") return target def resize( self, image: torch.Tensor, size: SizeDict, interpolation: Optional["F.InterpolationMode"] = None, **kwargs, ) -> torch.Tensor: """ Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an int, smaller edge of the image will be matched to this number. Args: image (`torch.Tensor`): Image to resize. size (`SizeDict`): Size of the image's `(height, width)` dimensions after resizing. Available options are: - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`. Do NOT keep the aspect ratio. - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge less or equal to `longest_edge`. - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to `max_width`. interpolation (`InterpolationMode`, *optional*, defaults to `InterpolationMode.BILINEAR`): Resampling filter to use if resizing the image. """ interpolation = interpolation if interpolation is not None else F.InterpolationMode.BILINEAR if size.shortest_edge and size.longest_edge: # Resize the image so that the shortest edge or the longest edge is of the given size # while maintaining the aspect ratio of the original image. new_size = get_size_with_aspect_ratio( image.size()[-2:], size["shortest_edge"], size["longest_edge"], ) elif size.max_height and size.max_width: new_size = get_image_size_for_max_height_width(image.size()[-2:], size["max_height"], size["max_width"]) elif size.height and size.width: new_size = (size["height"], size["width"]) else: raise ValueError( "Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got" f" {size.keys()}." ) image = F.resize( image, size=new_size, interpolation=interpolation, **kwargs, ) return image def resize_annotation( self, annotation: dict[str, Any], orig_size: tuple[int, int], target_size: tuple[int, int], threshold: float = 0.5, interpolation: Optional["F.InterpolationMode"] = None, ): """ Resizes an annotation to a target size. Args: annotation (`dict[str, Any]`): The annotation dictionary. orig_size (`tuple[int, int]`): The original size of the input image. target_size (`tuple[int, int]`): The target size of the image, as returned by the preprocessing `resize` step. threshold (`float`, *optional*, defaults to 0.5): The threshold used to binarize the segmentation masks. resample (`InterpolationMode`, defaults to `F.InterpolationMode.NEAREST_EXACT`): The resampling filter to use when resizing the masks. """ interpolation = interpolation if interpolation is not None else F.InterpolationMode.NEAREST_EXACT ratio_height, ratio_width = [target / orig for target, orig in zip(target_size, orig_size)] new_annotation = {} new_annotation["size"] = target_size for key, value in annotation.items(): if key == "boxes": boxes = value scaled_boxes = boxes * torch.as_tensor( [ratio_width, ratio_height, ratio_width, ratio_height], dtype=torch.float32, device=boxes.device ) new_annotation["boxes"] = scaled_boxes elif key == "area": area = value scaled_area = area * (ratio_width * ratio_height) new_annotation["area"] = scaled_area elif key == "masks": masks = value[:, None] masks = [F.resize(mask, target_size, interpolation=interpolation) for mask in masks] masks = torch.stack(masks).to(torch.float32) masks = masks[:, 0] > threshold new_annotation["masks"] = masks elif key == "size": new_annotation["size"] = target_size else: new_annotation[key] = value return new_annotation def normalize_annotation(self, annotation: dict, image_size: tuple[int, int]) -> dict: image_height, image_width = image_size norm_annotation = {} for key, value in annotation.items(): if key == "boxes": boxes = value boxes = corners_to_center_format(boxes) boxes /= torch.as_tensor( [image_width, image_height, image_width, image_height], dtype=torch.float32, device=boxes.device ) norm_annotation[key] = boxes else: norm_annotation[key] = value return norm_annotation def _update_annotation_for_padded_image( self, annotation: dict, input_image_size: tuple[int, int], output_image_size: tuple[int, int], padding, update_bboxes, ) -> dict: """ Update the annotation for a padded image. """ new_annotation = {} new_annotation["size"] = output_image_size ratio_height, ratio_width = (input / output for output, input in zip(output_image_size, input_image_size)) for key, value in annotation.items(): if key == "masks": masks = value masks = F.pad( masks, padding, fill=0, ) masks = safe_squeeze(masks, 1) new_annotation["masks"] = masks elif key == "boxes" and update_bboxes: boxes = value boxes *= torch.as_tensor([ratio_width, ratio_height, ratio_width, ratio_height], device=boxes.device) new_annotation["boxes"] = boxes elif key == "size": new_annotation["size"] = output_image_size else: new_annotation[key] = value return new_annotation def pad( self, image: torch.Tensor, padded_size: tuple[int, int], annotation: Optional[dict[str, Any]] = None, update_bboxes: bool = True, fill: int = 0, ): original_size = image.size()[-2:] padding_bottom = padded_size[0] - original_size[0] padding_right = padded_size[1] - original_size[1] if padding_bottom < 0 or padding_right < 0: raise ValueError( f"Padding dimensions are negative. Please make sure that the padded size is larger than the " f"original size. Got padded size: {padded_size}, original size: {original_size}." ) if original_size != padded_size: padding = [0, 0, padding_right, padding_bottom] image = F.pad(image, padding, fill=fill) if annotation is not None: annotation = self._update_annotation_for_padded_image( annotation, original_size, padded_size, padding, update_bboxes ) # Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding. pixel_mask = torch.zeros(padded_size, dtype=torch.int64, device=image.device) pixel_mask[: original_size[0], : original_size[1]] = 1 return image, pixel_mask, annotation def _preprocess( self, images: list["torch.Tensor"], annotations: Optional[Union[AnnotationType, list[AnnotationType]]], masks_path: Optional[Union[str, pathlib.Path]], return_segmentation_masks: bool, do_resize: bool, size: SizeDict, interpolation: Optional["F.InterpolationMode"], do_rescale: bool, rescale_factor: float, do_normalize: bool, do_convert_annotations: bool, image_mean: Optional[Union[float, list[float]]], image_std: Optional[Union[float, list[float]]], do_pad: bool, pad_size: Optional[SizeDict], format: Optional[Union[str, AnnotationFormat]], return_tensors: Optional[Union[str, TensorType]], **kwargs, ) -> BatchFeature: """ Preprocess an image or a batch of images so that it can be used by the model. """ if annotations is not None and isinstance(annotations, dict): annotations = [annotations] if annotations is not None and len(images) != len(annotations): raise ValueError( f"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match." ) format = AnnotationFormat(format) if annotations is not None: validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations) if ( masks_path is not None and format == AnnotationFormat.COCO_PANOPTIC and not isinstance(masks_path, (pathlib.Path, str)) ): raise ValueError( "The path to the directory containing the mask PNG files should be provided as a" f" `pathlib.Path` or string object, but is {type(masks_path)} instead." ) data = {} processed_images = [] processed_annotations = [] pixel_masks = [] # Initialize pixel_masks here for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)): # prepare (COCO annotations as a list of Dict -> YOLOS target as a single Dict per image) if annotations is not None: annotation = self.prepare_annotation( image, annotation, format, return_segmentation_masks=return_segmentation_masks, masks_path=masks_path, input_data_format=ChannelDimension.FIRST, ) if do_resize: resized_image = self.resize(image, size=size, interpolation=interpolation) if annotations is not None: annotation = self.resize_annotation( annotation, orig_size=image.size()[-2:], target_size=resized_image.size()[-2:], ) image = resized_image # Fused rescale and normalize image = self.rescale_and_normalize(image, do_rescale, rescale_factor, do_normalize, image_mean, image_std) if do_convert_annotations and annotations is not None: annotation = self.normalize_annotation(annotation, get_image_size(image, ChannelDimension.FIRST)) processed_images.append(image) processed_annotations.append(annotation) images = processed_images annotations = processed_annotations if annotations is not None else None if do_pad: # depends on all resized image shapes so we need another loop if pad_size is not None: padded_size = (pad_size.height, pad_size.width) else: padded_size = get_max_height_width(images) padded_images = [] padded_annotations = [] for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)): # Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...} if padded_size == image.size()[-2:]: padded_images.append(image) pixel_masks.append(torch.ones(padded_size, dtype=torch.int64, device=image.device)) padded_annotations.append(annotation) continue image, pixel_mask, annotation = self.pad( image, padded_size, annotation=annotation, update_bboxes=do_convert_annotations ) padded_images.append(image) padded_annotations.append(annotation) pixel_masks.append(pixel_mask) images = padded_images annotations = padded_annotations if annotations is not None else None data.update({"pixel_mask": torch.stack(pixel_masks, dim=0)}) data.update({"pixel_values": torch.stack(images, dim=0)}) encoded_inputs = BatchFeature(data, tensor_type=return_tensors) if annotations is not None: encoded_inputs["labels"] = [ BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations ] return encoded_inputs def post_process_object_detection( self, outputs, threshold: float = 0.5, target_sizes: Union[TensorType, list[tuple]] = None, top_k: int = 100 ): """ Converts the raw output of [`YolosForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch. Args: outputs ([`YolosObjectDetectionOutput`]): Raw outputs of the model. threshold (`float`, *optional*): Score threshold to keep object detection predictions. target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*): Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size (height, width) of each image in the batch. If left to None, predictions will not be resized. top_k (`int`, *optional*, defaults to 100): Keep only top k bounding boxes before filtering by thresholding. Returns: `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image in the batch as predicted by the model. """ out_logits, out_bbox = outputs.logits, outputs.pred_boxes if target_sizes is not None: if len(out_logits) != len(target_sizes): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) prob = out_logits.sigmoid() prob = prob.view(out_logits.shape[0], -1) k_value = min(top_k, prob.size(1)) topk_values, topk_indexes = torch.topk(prob, k_value, dim=1) scores = topk_values topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor") labels = topk_indexes % out_logits.shape[2] boxes = center_to_corners_format(out_bbox) boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4)) # and from relative [0, 1] to absolute [0, height] coordinates if target_sizes is not None: if isinstance(target_sizes, list): img_h = torch.Tensor([i[0] for i in target_sizes]) img_w = torch.Tensor([i[1] for i in target_sizes]) else: img_h, img_w = target_sizes.unbind(1) scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device) boxes = boxes * scale_fct[:, None, :] results = [] for s, l, b in zip(scores, labels, boxes): score = s[s > threshold] label = l[s > threshold] box = b[s > threshold] results.append({"scores": score, "labels": label, "boxes": box}) return results __all__ = ["YolosImageProcessorFast"]
YolosImageProcessorFast
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 336009, "end": 341843 }
class ____(FallbackKernel): def should_allocate(self) -> bool: return False def has_side_effects(self) -> bool: return True # This is identical to FallbackKernel.set_cpp_kernel(), minus the # part that checks against input aliasing and mutation. def set_cpp_kernel_name(self, cpp_kernel_name: Optional[str] = None) -> None: assert type(self.op_overload) is torch._ops.OpOverload, ( "Setting cpp kernel needs a valid op_overload" ) kernel = self.op_overload if cpp_kernel_name is not None: self.cpp_kernel_name = cpp_kernel_name else: self.cpp_kernel_name = kernel._schema.name self.ordered_kwargs_for_cpp_kernel = [ x.name for x in kernel._schema.arguments if x.kwarg_only ] # NOTE: [In-Place Collective Safety] # Between the initiation and completion of an in-place collective, the # input buffers are subject to both volatile reads and volatile writes. # They must not be read, written to or reused by another kernel. To ensure # the constraints, we model collective -> wait_tensor as as two-step # mutation of the input buffers. @classmethod def create_inplace( cls, kernel: _OpOverloads, inputs: Union[IRNode, list[IRNode]], *args: Any, **kwargs: Any, ) -> None: with V.graph.fake_mode: ( _example_output, tensor_args, non_tensor_args, unflatten_args, unbacked_bindings, ) = cls.process_kernel(kernel, inputs, *args, **kwargs) assert not unbacked_bindings, f"{kernel} {unbacked_bindings}" for tensor_arg in tensor_args: tensor_arg.realize() V.graph.mark_buffer_mutated(tensor_arg.get_name()) device = tensor_args[0].get_device() packed = cls( NoneLayout(device=device), kernel, tensor_args, non_tensor_args, unflatten_args, ) inps = pytree.tree_leaves(inputs) packed.mutation_outputs.extend( [MutationOutput(NoneLayout(device=device), buf, packed) for buf in inps] ) # For inplace collective ops, the input is guaranteed to be alias of the returned value of op. packed.alias_names.extend([inp.get_name() for inp in inps]) if "out" in kwargs: packed.mutation_outputs.append( MutationOutput(NoneLayout(device=device), kwargs["out"], packed) ) # For out-variant collective ops, the `out=` arg is guaranteed to be alias of the returned value of op. packed.alias_names.append(kwargs["out"].get_name()) # NOTE: [Out-of-Place Collective Safety] # Between the initiation and completion of an out-of-place collective: # # Input buffers: # - Are subject to volatile reads # - Can be read by another kernel # - Must not be written to or reused by another kernel # # Output buffers: # - Are subject to volatile writes # - Must not be read, written to or reused by another kernel # # To ensure the safety of input buffers without sacrificing read # availability, we add input buffers as read deps of wait_tensor kernels. # # To ensure the safety of output buffers, we model wait_tensor as a # mutation to the output buffer. Note we also assumes the user program being # correct and the output buffer is not consumed by kernels other than # wait_tensor. # # TODO(yifu): add a pre-grad pass to validate the correctness of collective # usage in the user program. @classmethod def create_out_of_place( cls, kernel: _OpOverloads, inputs: Union[TensorBox, list[TensorBox]], *args: Any, **kwargs: Any, ) -> Union[list[MultiOutput], _CollectiveKernel]: with V.graph.fake_mode: ( example_output, tensor_args, non_tensor_args, unflatten_args, unbacked_bindings, ) = cls.process_kernel(kernel, inputs, *args, **kwargs) assert not unbacked_bindings, f"{kernel}, {unbacked_bindings}" for tensor_arg in tensor_args: tensor_arg.realize() if isinstance(example_output, list): device = cls.find_device(tensor_args, example_output) assert device is not None packed = cls( MultiOutputLayout(device=device), kernel, tensor_args, non_tensor_args, unflatten_args, ) packed.outputs = [ MultiOutput( cls.tensor_to_layout(tensor), packed, [(list, i)], ) for i, tensor in enumerate(example_output) ] for buf, tensor in zip(packed.outputs, example_output): if config.assume_unaligned_fallback_output or not tensor_is_aligned( tensor ): V.graph.unaligned_buffers.add(buf.name) # type: ignore[arg-type] return packed.outputs else: packed = cls( cls.tensor_to_layout(example_output), kernel, tensor_args, non_tensor_args, unflatten_args, ) if config.assume_unaligned_fallback_output or not tensor_is_aligned( example_output ): V.graph.unaligned_buffers.add(packed.name) # type: ignore[arg-type] packed.outputs = [packed] return packed
_CollectiveKernel