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/search/eap/columns.py
{ "start": 7666, "end": 8611 }
class ____(ResolvedFunction): """ An aggregate is the most primitive type of function, these are the ones that are availble via the RPC directly and contain no logic Examples of this are `sum()` and `avg()`. """ # The internal rpc alias for this column internal_name: Function.ValueType extrapolation_mode: ExtrapolationMode.ValueType is_aggregate: bool = field(default=True, init=False) # Only for aggregates, we only support functions with 1 argument right now argument: AttributeKey | None = None @property def proto_definition(self) -> AttributeAggregation: """The definition of this function as needed by the RPC""" return AttributeAggregation( aggregate=self.internal_name, key=self.argument, label=self.public_alias, extrapolation_mode=self.extrapolation_mode, ) @dataclass(frozen=True, kw_only=True)
ResolvedAggregate
python
eventlet__eventlet
eventlet/zipkin/client.py
{ "start": 206, "end": 1691 }
class ____: def __init__(self, host='127.0.0.1', port=9410): """ :param host: zipkin collector IP address (default '127.0.0.1') :param port: zipkin collector port (default 9410) """ self.host = host self.port = port self.pile = GreenPile(1) self._connect() def _connect(self): socket = TSocket.TSocket(self.host, self.port) self.transport = TTransport.TFramedTransport(socket) protocol = TBinaryProtocol.TBinaryProtocol(self.transport, False, False) self.scribe_client = scribe.Client(protocol) try: self.transport.open() except TTransport.TTransportException as e: warnings.warn(e.message) def _build_message(self, thrift_obj): trans = TTransport.TMemoryBuffer() protocol = TBinaryProtocol.TBinaryProtocolAccelerated(trans=trans) thrift_obj.write(protocol) return base64.b64encode(trans.getvalue()) def send_to_collector(self, span): self.pile.spawn(self._send, span) def _send(self, span): log_entry = scribe.LogEntry(CATEGORY, self._build_message(span)) try: self.scribe_client.Log([log_entry]) except Exception as e: msg = 'ZipkinClient send error %s' % str(e) warnings.warn(msg) self._connect() def close(self): self.transport.close()
ZipkinClient
python
tensorflow__tensorflow
tensorflow/python/tpu/tpu_embedding_v2_utils_test.py
{ "start": 3546, "end": 5811 }
class ____(parameterized.TestCase, test.TestCase): def get_sum_combiner(self): @def_function.function def sum_combiner(valency, vectors): max_valency = vectors.shape[0] valid_mask = array_ops.range(max_valency) < valency vectors_masked = array_ops.where( array_ops.expand_dims(valid_mask, axis=-1), vectors, array_ops.zeros_like(vectors), ) return math_ops.reduce_sum(vectors_masked, axis=0) return sum_combiner def get_positional_weight_combiner(self): @def_function.function def positional_weight_combiner(valency, vectors, weights): max_valency = vectors.shape[0] valid_mask = array_ops.range(max_valency) < valency vectors_masked = array_ops.where( array_ops.expand_dims(valid_mask, axis=-1), vectors, array_ops.zeros_like(vectors), ) return math_ops.matvec(vectors_masked, weights, transpose_a=True) return positional_weight_combiner def test_zero_num_weights_combiner_has_no_slots(self): combiner = tpu_embedding_v2_utils.CustomCombiner( self.get_sum_combiner(), max_valency=16, num_weights=0, ) self.assertEmpty(combiner._slot_names()) self.assertEmpty(combiner._slot_initializers()) def test_name_starts_with_custom_combiner(self): combiner = tpu_embedding_v2_utils.CustomCombiner( self.get_sum_combiner(), max_valency=16, ) self.assertStartsWith(str(combiner), 'custom_combiner') def test_non_zero_weights_requires_initializer(self): with self.assertRaisesRegex(ValueError, '`initializer` must be set'): tpu_embedding_v2_utils.CustomCombiner( self.get_positional_weight_combiner(), max_valency=16, num_weights=16, ) def test_non_zero_weights_has_one_slot_variable(self): combiner = tpu_embedding_v2_utils.CustomCombiner( self.get_positional_weight_combiner(), max_valency=16, num_weights=16, initializer=init_ops_v2.zeros_initializer, ) self.assertLen(combiner._slot_names(), 1) self.assertLen(combiner._slot_initializers(), 1) self.assertStartsWith(combiner._slot_names()[0], 'custom_combiner')
TPUEmbeddingCustomCombinerTest
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_mixed_precision.py
{ "start": 42534, "end": 42716 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.l = nn.Linear(100, 100) def forward(self, x): return self.l(x)
IgnoredModule
python
conda__conda
conda/exceptions.py
{ "start": 24611, "end": 30486 }
class ____(CondaError): """An exception to report unsatisfiable dependencies. Args: bad_deps: a list of tuples of objects (likely MatchSpecs). chains: (optional) if True, the tuples are interpreted as chains of dependencies, from top level to bottom. If False, the tuples are interpreted as simple lists of conflicting specs. Returns: Raises an exception with a formatted message detailing the unsatisfiable specifications. """ def _format_chain_str(self, bad_deps: Iterable[Iterable[MatchSpec]]): chains = {} for dep in sorted(bad_deps, key=len, reverse=True): dep1 = [s.partition(" ") for s in dep[1:]] key = (dep[0],) + tuple(v[0] for v in dep1) vals = ("",) + tuple(v[2] for v in dep1) found = False for key2, csets in chains.items(): if key2[: len(key)] == key: for cset, val in zip(csets, vals): cset.add(val) found = True if not found: chains[key] = [{val} for val in vals] for key, csets in chains.items(): deps = [] for name, cset in zip(key, csets): if "" not in cset: pass elif len(cset) == 1: cset.clear() else: cset.remove("") cset.add("*") if name[0] == "@": name = "feature:" + name[1:] deps.append( "{} {}".format(name, "|".join(sorted(cset))) if cset else name ) chains[key] = " -> ".join(deps) return [chains[key] for key in sorted(chains.keys())] def __init__( self, bad_deps: Iterable[Iterable[MatchSpec]], chains: bool = True, strict: bool = False, ): from .models.match_spec import MatchSpec messages = { "python": dals( """ The following specifications were found to be incompatible with the existing python installation in your environment: Specifications:\n{specs} Your python: {ref} If python is on the left-most side of the chain, that's the version you've asked for. When python appears to the right, that indicates that the thing on the left is somehow not available for the python version you are constrained to. Note that conda will not change your python version to a different minor version unless you explicitly specify that. """ ), "request_conflict_with_history": dals( """ The following specifications were found to be incompatible with a past explicit spec that is not an explicit spec in this operation ({ref}):\n{specs} """ ), "direct": dals( """ The following specifications were found to be incompatible with each other: """ ), "virtual_package": dals( """ The following specifications were found to be incompatible with your system:\n{specs} Your installed version is: {ref} """ ), } msg = "" self.unsatisfiable = [] if len(bad_deps) == 0: msg += """ Did not find conflicting dependencies. If you would like to know which packages conflict ensure that you have enabled unsatisfiable hints. conda config --set unsatisfiable_hints True """ else: for class_name, dep_class in bad_deps.items(): if dep_class: _chains = [] if class_name == "direct": msg += messages["direct"] last_dep_entry = {d[0][-1].name for d in dep_class} dep_constraint_map = {} for dep in dep_class: if dep[0][-1].name in last_dep_entry: if not dep_constraint_map.get(dep[0][-1].name): dep_constraint_map[dep[0][-1].name] = [] dep_constraint_map[dep[0][-1].name].append(dep[0]) msg += "\nOutput in format: Requested package -> Available versions" for dep, chain in dep_constraint_map.items(): if len(chain) > 1: msg += f"\n\nPackage {dep} conflicts for:\n" msg += "\n".join( [" -> ".join([str(i) for i in c]) for c in chain] ) self.unsatisfiable += [ tuple(entries) for entries in chain ] else: for dep_chain, installed_blocker in dep_class: # Remove any target values from the MatchSpecs, convert to strings dep_chain = [ str(MatchSpec(dep, target=None)) for dep in dep_chain ] _chains.append(dep_chain) if _chains: _chains = self._format_chain_str(_chains) else: _chains = [", ".join(c) for c in _chains] msg += messages[class_name].format( specs=dashlist(_chains), ref=installed_blocker ) if strict: msg += ( "\nNote that strict channel priority may have removed " "packages required for satisfiability." ) super().__init__(msg)
UnsatisfiableError
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_vies_vat.py
{ "start": 1879, "end": 4389 }
class ____(ColumnMapExpectation): """Expect column values to be valid VAT (Value Added Tax) according to VIES (VAT Information Exchange System).""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "all_valid": [ "BE0438390312", "DK54562519", "IE1114174HH", ], "some_other": [ "BE0123456749", "BE0897290877", "GB223462237", ], }, "tests": [ { "title": "basic_positive_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "all_valid"}, "out": { "success": True, }, }, { "title": "basic_negative_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "some_other", "mostly": 1}, "out": { "success": False, }, }, ], } ] # This is the id string of the Metric used by this Expectation. # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above. map_metric = "column_values.valid_vies_vat" # This is a list of parameter names that can affect whether the Expectation evaluates to True or False success_keys = ("mostly",) # This dictionary contains default values for any parameters that should have default values default_kwarg_values = {} # This object contains metadata for display in the public Gallery library_metadata = { "maturity": "experimental", "tags": [ "hackathon-22", "experimental", "typed-entities", ], # Tags for this Expectation in the Gallery "contributors": [ # Github handles for all contributors to this Expectation. "@szecsip", # Don't forget to add your github handle here! ], "requirements": ["pyvat"], } if __name__ == "__main__": ExpectColumnValuesToBeValidViesVat().print_diagnostic_checklist()
ExpectColumnValuesToBeValidViesVat
python
Textualize__rich
rich/markdown.py
{ "start": 8187, "end": 8573 }
class ____(MarkdownElement): """MarkdownElement corresponding to `tr_open` and `tr_close`.""" def __init__(self) -> None: self.cells: list[TableDataElement] = [] def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: assert isinstance(child, TableDataElement) self.cells.append(child) return False
TableRowElement
python
facebook__pyre-check
client/commands/statistics.py
{ "start": 3569, "end": 3723 }
class ____(SuppressionCountCollector): def __init__(self) -> None: super().__init__(r".*# *pyre-ignore(\[(\d* *,? *)*\])?")
IgnoreCountCollector
python
huggingface__transformers
src/transformers/models/granitemoehybrid/modeling_granitemoehybrid.py
{ "start": 52859, "end": 55965 }
class ____(GradientCheckpointingLayer): def __init__(self, config: GraniteMoeHybridConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size # Either attention or mamba will be initialized, depending on the layer type. self.self_attn = None self.input_layernorm = GraniteMoeHybridRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = GraniteMoeHybridRMSNorm(config.hidden_size, eps=config.rms_norm_eps) # Allow non-MoE (dense) self.block_sparse_moe = GraniteMoeHybridMoE(config) if config.num_local_experts > 0 else None self.residual_multiplier = config.residual_multiplier # Only diff with mixtral! self.shared_mlp = GraniteMoeHybridMLP(config) self.mamba = None if config.layers_block_type[layer_idx] == "mamba": self.mamba = GraniteMoeHybridMambaLayer(config, layer_idx) else: self.self_attn = GraniteMoeHybridAttention(config, layer_idx) self.layer_type = config.layers_block_type[layer_idx] # Accept 0 experts: skip MoE if num_local_experts == 0 self.has_experts = getattr(config, "num_local_experts", 0) > 0 @auto_docstring def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, past_key_values: Optional[Cache] = None, use_cache: Optional[bool] = False, cache_position: Optional[torch.LongTensor] = None, position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, **kwargs: Unpack[GraniteFlashAttentionKwargs], ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]: residual = hidden_states hidden_states = self.input_layernorm(hidden_states) if self.mamba is not None: hidden_states = self.mamba( hidden_states=hidden_states, cache_position=cache_position, cache_params=past_key_values, attention_mask=attention_mask, **kwargs, ) else: hidden_states, _ = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, past_key_values=past_key_values, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) hidden_states = residual + hidden_states * self.residual_multiplier residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) if self.has_experts: moe_hidden_states = self.block_sparse_moe(hidden_states) hidden_states = moe_hidden_states + self.shared_mlp(hidden_states) else: hidden_states = self.shared_mlp(hidden_states) hidden_states = residual + hidden_states * self.residual_multiplier return hidden_states @auto_docstring
GraniteMoeHybridDecoderLayer
python
pytest-dev__pytest
testing/test_terminal.py
{ "start": 110958, "end": 112171 }
class ____: def test_nodeid_handling_windows_paths(self, pytester: Pytester, tmp_path) -> None: """Test the correct handling of Windows-style paths with backslashes.""" pytester.makeini("[pytest]") # Change `config.rootpath` test_path = pytester.path / "tests" / "test_foo.py" test_path.parent.mkdir() os.chdir(test_path.parent) # Change `config.invocation_params.dir` test_path.write_text( textwrap.dedent( """ import pytest @pytest.mark.parametrize("a", ["x/y", "C:/path", "\\\\", "C:\\\\path", "a::b/"]) def test_x(a): assert False """ ), encoding="utf-8", ) result = pytester.runpytest("-v") result.stdout.re_match_lines( [ r".*test_foo.py::test_x\[x/y\] .*FAILED.*", r".*test_foo.py::test_x\[C:/path\] .*FAILED.*", r".*test_foo.py::test_x\[\\\\\] .*FAILED.*", r".*test_foo.py::test_x\[C:\\\\path\] .*FAILED.*", r".*test_foo.py::test_x\[a::b/\] .*FAILED.*", ] )
TestNodeIDHandling
python
apache__airflow
task-sdk/src/airflow/sdk/api/datamodels/_generated.py
{ "start": 8735, "end": 8980 }
class ____(BaseModel): """ Schema for updating TaskInstance to a target state, excluding terminal and running states. """ model_config = ConfigDict( extra="forbid", ) state: IntermediateTIState
TITargetStatePayload
python
getsentry__sentry
src/sentry/integrations/api/endpoints/doc_integrations_index.py
{ "start": 774, "end": 2087 }
class ____(DocIntegrationsBaseEndpoint): owner = ApiOwner.INTEGRATIONS publish_status = { "GET": ApiPublishStatus.PRIVATE, "POST": ApiPublishStatus.PRIVATE, } def get(self, request: Request): # TODO(schew2381): Change to is_active_staff once the feature flag is rolled out. if has_elevated_mode(request): queryset = DocIntegration.objects.all() else: queryset = DocIntegration.objects.filter(is_draft=False) return self.paginate( request=request, queryset=queryset, paginator_cls=OffsetPaginator, on_results=lambda x: serialize(x, request.user, access=request.access), ) def post(self, request: Request): # Override any incoming JSON for these fields data = request.data data["is_draft"] = True data["metadata"] = self.generate_incoming_metadata(request) serializer = DocIntegrationSerializer(data=data) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) doc_integration = serializer.save() return Response( serialize(doc_integration, request.user), status=status.HTTP_201_CREATED, )
DocIntegrationsEndpoint
python
fluentpython__example-code-2e
12-seq-hacking/vector_v4.py
{ "start": 3138, "end": 4881 }
class ____: typecode = 'd' def __init__(self, components): self._components = array(self.typecode, components) def __iter__(self): return iter(self._components) def __repr__(self): components = reprlib.repr(self._components) components = components[components.find('['):-1] return f'Vector({components})' def __str__(self): return str(tuple(self)) def __bytes__(self): return (bytes([ord(self.typecode)]) + bytes(self._components)) def __eq__(self, other): return (len(self) == len(other) and all(a == b for a, b in zip(self, other))) def __hash__(self): hashes = (hash(x) for x in self) return functools.reduce(operator.xor, hashes, 0) def __abs__(self): return math.hypot(*self) def __bool__(self): return bool(abs(self)) def __len__(self): return len(self._components) def __getitem__(self, key): if isinstance(key, slice): cls = type(self) return cls(self._components[key]) index = operator.index(key) return self._components[index] __match_args__ = ('x', 'y', 'z', 't') def __getattr__(self, name): cls = type(self) try: pos = cls.__match_args__.index(name) except ValueError: pos = -1 if 0 <= pos < len(self._components): return self._components[pos] msg = f'{cls.__name__!r} object has no attribute {name!r}' raise AttributeError(msg) @classmethod def frombytes(cls, octets): typecode = chr(octets[0]) memv = memoryview(octets[1:]).cast(typecode) return cls(memv)
Vector
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 134837, "end": 135201 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("thread_id", "client_mutation_id") thread_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="threadId") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
ResolveReviewThreadInput
python
explosion__spaCy
spacy/lang/fa/__init__.py
{ "start": 670, "end": 1307 }
class ____(Language): lang = "fa" Defaults = PersianDefaults @Persian.factory( "lemmatizer", assigns=["token.lemma"], default_config={ "model": None, "mode": "rule", "overwrite": False, "scorer": {"@scorers": "spacy.lemmatizer_scorer.v1"}, }, default_score_weights={"lemma_acc": 1.0}, ) def make_lemmatizer( nlp: Language, model: Optional[Model], name: str, mode: str, overwrite: bool, scorer: Optional[Callable], ): return Lemmatizer( nlp.vocab, model, name, mode=mode, overwrite=overwrite, scorer=scorer ) __all__ = ["Persian"]
Persian
python
donnemartin__interactive-coding-challenges
linked_lists/linked_list/linked_list.py
{ "start": 163, "end": 2549 }
class ____(object): def __init__(self, head=None): self.head = head def __len__(self): curr = self.head counter = 0 while curr is not None: counter += 1 curr = curr.next return counter def insert_to_front(self, data): if data is None: return None node = Node(data, self.head) self.head = node return node def append(self, data): if data is None: return None node = Node(data) if self.head is None: self.head = node return node curr_node = self.head while curr_node.next is not None: curr_node = curr_node.next curr_node.next = node return node def find(self, data): if data is None: return None curr_node = self.head while curr_node is not None: if curr_node.data == data: return curr_node curr_node = curr_node.next return None def delete(self, data): if data is None: return if self.head is None: return if self.head.data == data: self.head = self.head.next return prev_node = self.head curr_node = self.head.next while curr_node is not None: if curr_node.data == data: prev_node.next = curr_node.next return prev_node = curr_node curr_node = curr_node.next def delete_alt(self, data): if data is None: return if self.head is None: return curr_node = self.head if curr_node.data == data: curr_node = curr_node.next return while curr_node.next is not None: if curr_node.next.data == data: curr_node.next = curr_node.next.next return curr_node = curr_node.next def print_list(self): curr_node = self.head while curr_node is not None: print(curr_node.data) curr_node = curr_node.next def get_all_data(self): data = [] curr_node = self.head while curr_node is not None: data.append(curr_node.data) curr_node = curr_node.next return data
LinkedList
python
keras-team__keras
keras/src/metrics/confusion_metrics_test.py
{ "start": 41099, "end": 57576 }
class ____(testing.TestCase): def setUp(self): self.num_thresholds = 3 self.y_pred = np.array([0, 0.5, 0.3, 0.9], dtype="float32") self.y_pred_multi_label = np.array( [[0.0, 0.4], [0.5, 0.7], [0.3, 0.2], [0.9, 0.3]], dtype="float32" ) epsilon = 1e-12 self.y_pred_logits = -ops.log(1.0 / (self.y_pred + epsilon) - 1.0) self.y_true = np.array([0, 0, 1, 1]) self.y_true_multi_label = np.array([[0, 0], [1, 1], [1, 1], [1, 0]]) self.sample_weight = [1, 2, 3, 4] # threshold values are [0 - 1e-7, 0.5, 1 + 1e-7] # y_pred when threshold = 0 - 1e-7 : [1, 1, 1, 1] # y_pred when threshold = 0.5 : [0, 0, 0, 1] # y_pred when threshold = 1 + 1e-7 : [0, 0, 0, 0] # without sample_weight: # tp = np.sum([[0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0]], axis=1) # fp = np.sum([[1, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], axis=1) # fn = np.sum([[0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 1, 1]], axis=1) # tn = np.sum([[0, 0, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0]], axis=1) # tp = [2, 1, 0], fp = [2, 0, 0], fn = [0, 1, 2], tn = [0, 2, 2] # with sample_weight: # tp = np.sum([[0, 0, 3, 4], [0, 0, 0, 4], [0, 0, 0, 0]], axis=1) # fp = np.sum([[1, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], axis=1) # fn = np.sum([[0, 0, 0, 0], [0, 0, 3, 0], [0, 0, 3, 4]], axis=1) # tn = np.sum([[0, 0, 0, 0], [1, 2, 0, 0], [1, 2, 0, 0]], axis=1) # tp = [7, 4, 0], fp = [3, 0, 0], fn = [0, 3, 7], tn = [0, 3, 3] def test_config(self): auc_obj = metrics.AUC( num_thresholds=100, curve="PR", summation_method="majoring", name="auc_1", dtype="float64", multi_label=True, num_labels=2, from_logits=True, ) auc_obj.update_state(self.y_true_multi_label, self.y_pred_multi_label) self.assertEqual(auc_obj.name, "auc_1") self.assertEqual(auc_obj._dtype, "float64") self.assertLen(auc_obj.variables, 4) self.assertEqual(auc_obj.num_thresholds, 100) self.assertEqual(auc_obj.curve, metrics_utils.AUCCurve.PR) self.assertEqual( auc_obj.summation_method, metrics_utils.AUCSummationMethod.MAJORING ) self.assertTrue(auc_obj.multi_label) self.assertEqual(auc_obj.num_labels, 2) self.assertTrue(auc_obj._from_logits) old_config = auc_obj.get_config() self.assertNotIn("thresholds", old_config) self.assertDictEqual(old_config, json.loads(json.dumps(old_config))) # Check save and restore config. auc_obj2 = metrics.AUC.from_config(auc_obj.get_config()) auc_obj2.update_state(self.y_true_multi_label, self.y_pred_multi_label) self.assertEqual(auc_obj2.name, "auc_1") self.assertLen(auc_obj2.variables, 4) self.assertEqual(auc_obj2.num_thresholds, 100) self.assertEqual(auc_obj2.curve, metrics_utils.AUCCurve.PR) self.assertEqual( auc_obj2.summation_method, metrics_utils.AUCSummationMethod.MAJORING ) self.assertTrue(auc_obj2.multi_label) self.assertEqual(auc_obj2.num_labels, 2) self.assertTrue(auc_obj2._from_logits) new_config = auc_obj2.get_config() self.assertNotIn("thresholds", new_config) self.assertDictEqual(old_config, new_config) self.assertAllClose(auc_obj.thresholds, auc_obj2.thresholds) def test_config_manual_thresholds(self): auc_obj = metrics.AUC( num_thresholds=None, curve="PR", summation_method="majoring", name="auc_1", thresholds=[0.3, 0.5], ) auc_obj.update_state(self.y_true, self.y_pred) self.assertEqual(auc_obj.name, "auc_1") self.assertLen(auc_obj.variables, 4) self.assertEqual(auc_obj.num_thresholds, 4) self.assertAllClose(auc_obj.thresholds, [0.0, 0.3, 0.5, 1.0]) self.assertEqual(auc_obj.curve, metrics_utils.AUCCurve.PR) self.assertEqual( auc_obj.summation_method, metrics_utils.AUCSummationMethod.MAJORING ) old_config = auc_obj.get_config() self.assertDictEqual(old_config, json.loads(json.dumps(old_config))) # Check save and restore config. auc_obj2 = metrics.AUC.from_config(auc_obj.get_config()) auc_obj2.update_state(self.y_true, self.y_pred) self.assertEqual(auc_obj2.name, "auc_1") self.assertLen(auc_obj2.variables, 4) self.assertEqual(auc_obj2.num_thresholds, 4) self.assertEqual(auc_obj2.curve, metrics_utils.AUCCurve.PR) self.assertEqual( auc_obj2.summation_method, metrics_utils.AUCSummationMethod.MAJORING ) new_config = auc_obj2.get_config() self.assertDictEqual(old_config, new_config) self.assertAllClose(auc_obj.thresholds, auc_obj2.thresholds) def test_unweighted_all_correct(self): auc_obj = metrics.AUC() self.assertEqual(auc_obj(self.y_true, self.y_true), 1) def test_unweighted(self): auc_obj = metrics.AUC(num_thresholds=self.num_thresholds) result = auc_obj(self.y_true, self.y_pred) # tp = [2, 1, 0], fp = [2, 0, 0], fn = [0, 1, 2], tn = [0, 2, 2] # recall = [2/2, 1/(1+1), 0] = [1, 0.5, 0] # fp_rate = [2/2, 0, 0] = [1, 0, 0] # heights = [(1 + 0.5)/2, (0.5 + 0)/2] = [0.75, 0.25] # widths = [(1 - 0), (0 - 0)] = [1, 0] expected_result = 0.75 * 1 + 0.25 * 0 self.assertAllClose(result, expected_result, 1e-3) def test_unweighted_from_logits(self): auc_obj = metrics.AUC( num_thresholds=self.num_thresholds, from_logits=True ) result = auc_obj(self.y_true, self.y_pred_logits) # tp = [2, 1, 0], fp = [2, 0, 0], fn = [0, 1, 2], tn = [0, 2, 2] # recall = [2/2, 1/(1+1), 0] = [1, 0.5, 0] # fp_rate = [2/2, 0, 0] = [1, 0, 0] # heights = [(1 + 0.5)/2, (0.5 + 0)/2] = [0.75, 0.25] # widths = [(1 - 0), (0 - 0)] = [1, 0] expected_result = 0.75 * 1 + 0.25 * 0 self.assertAllClose(result, expected_result, 1e-3) def test_manual_thresholds(self): # Verify that when specified, thresholds are used instead of # num_thresholds. auc_obj = metrics.AUC(num_thresholds=2, thresholds=[0.5]) self.assertEqual(auc_obj.num_thresholds, 3) self.assertAllClose(auc_obj.thresholds, [0.0, 0.5, 1.0]) result = auc_obj(self.y_true, self.y_pred) # tp = [2, 1, 0], fp = [2, 0, 0], fn = [0, 1, 2], tn = [0, 2, 2] # recall = [2/2, 1/(1+1), 0] = [1, 0.5, 0] # fp_rate = [2/2, 0, 0] = [1, 0, 0] # heights = [(1 + 0.5)/2, (0.5 + 0)/2] = [0.75, 0.25] # widths = [(1 - 0), (0 - 0)] = [1, 0] expected_result = 0.75 * 1 + 0.25 * 0 self.assertAllClose(result, expected_result, 1e-3) def test_weighted_roc_interpolation(self): auc_obj = metrics.AUC(num_thresholds=self.num_thresholds) result = auc_obj( self.y_true, self.y_pred, sample_weight=self.sample_weight ) # tp = [7, 4, 0], fp = [3, 0, 0], fn = [0, 3, 7], tn = [0, 3, 3] # recall = [7/7, 4/(4+3), 0] = [1, 0.571, 0] # fp_rate = [3/3, 0, 0] = [1, 0, 0] # heights = [(1 + 0.571)/2, (0.571 + 0)/2] = [0.7855, 0.2855] # widths = [(1 - 0), (0 - 0)] = [1, 0] expected_result = 0.7855 * 1 + 0.2855 * 0 self.assertAllClose(result, expected_result, 1e-3) def test_weighted_roc_majoring(self): auc_obj = metrics.AUC( num_thresholds=self.num_thresholds, summation_method="majoring" ) result = auc_obj( self.y_true, self.y_pred, sample_weight=self.sample_weight ) # tp = [7, 4, 0], fp = [3, 0, 0], fn = [0, 3, 7], tn = [0, 3, 3] # recall = [7/7, 4/(4+3), 0] = [1, 0.571, 0] # fp_rate = [3/3, 0, 0] = [1, 0, 0] # heights = [max(1, 0.571), max(0.571, 0)] = [1, 0.571] # widths = [(1 - 0), (0 - 0)] = [1, 0] expected_result = 1 * 1 + 0.571 * 0 self.assertAllClose(result, expected_result, 1e-3) def test_weighted_roc_minoring(self): auc_obj = metrics.AUC( num_thresholds=self.num_thresholds, summation_method="minoring" ) result = auc_obj( self.y_true, self.y_pred, sample_weight=self.sample_weight ) # tp = [7, 4, 0], fp = [3, 0, 0], fn = [0, 3, 7], tn = [0, 3, 3] # recall = [7/7, 4/(4+3), 0] = [1, 0.571, 0] # fp_rate = [3/3, 0, 0] = [1, 0, 0] # heights = [min(1, 0.571), min(0.571, 0)] = [0.571, 0] # widths = [(1 - 0), (0 - 0)] = [1, 0] expected_result = 0.571 * 1 + 0 * 0 self.assertAllClose(result, expected_result, 1e-3) def test_weighted_pr_majoring(self): auc_obj = metrics.AUC( num_thresholds=self.num_thresholds, curve="PR", summation_method="majoring", ) result = auc_obj( self.y_true, self.y_pred, sample_weight=self.sample_weight ) # tp = [7, 4, 0], fp = [3, 0, 0], fn = [0, 3, 7], tn = [0, 3, 3] # precision = [7/(7+3), 4/4, 0] = [0.7, 1, 0] # recall = [7/7, 4/(4+3), 0] = [1, 0.571, 0] # heights = [max(0.7, 1), max(1, 0)] = [1, 1] # widths = [(1 - 0.571), (0.571 - 0)] = [0.429, 0.571] expected_result = 1 * 0.429 + 1 * 0.571 self.assertAllClose(result, expected_result, 1e-3) def test_weighted_pr_minoring(self): auc_obj = metrics.AUC( num_thresholds=self.num_thresholds, curve="PR", summation_method="minoring", ) result = auc_obj( self.y_true, self.y_pred, sample_weight=self.sample_weight ) # tp = [7, 4, 0], fp = [3, 0, 0], fn = [0, 3, 7], tn = [0, 3, 3] # precision = [7/(7+3), 4/4, 0] = [0.7, 1, 0] # recall = [7/7, 4/(4+3), 0] = [1, 0.571, 0] # heights = [min(0.7, 1), min(1, 0)] = [0.7, 0] # widths = [(1 - 0.571), (0.571 - 0)] = [0.429, 0.571] expected_result = 0.7 * 0.429 + 0 * 0.571 self.assertAllClose(result, expected_result, 1e-3) def test_weighted_pr_interpolation(self): auc_obj = metrics.AUC(num_thresholds=self.num_thresholds, curve="PR") result = auc_obj( self.y_true, self.y_pred, sample_weight=self.sample_weight ) # auc = (slope / Total Pos) * [dTP - intercept * log(Pb/Pa)] # tp = [7, 4, 0], fp = [3, 0, 0], fn = [0, 3, 7], tn = [0, 3, 3] # P = tp + fp = [10, 4, 0] # dTP = [7-4, 4-0] = [3, 4] # dP = [10-4, 4-0] = [6, 4] # slope = dTP/dP = [0.5, 1] # intercept = (TPa+(slope*Pa) = [(4 - 0.5*4), (0 - 1*0)] = [2, 0] # (Pb/Pa) = (Pb/Pa) if Pb > 0 AND Pa > 0 else 1 = [10/4, 4/0] = [2.5, 1] # auc * TotalPos = [(0.5 * (3 + 2 * log(2.5))), (1 * (4 + 0))] # = [2.416, 4] # auc = [2.416, 4]/(tp[1:]+fn[1:]) expected_result = 2.416 / 7 + 4 / 7 self.assertAllClose(result, expected_result, 1e-3) def test_weighted_pr_interpolation_negative_weights(self): auc_obj = metrics.AUC(num_thresholds=self.num_thresholds, curve="PR") sample_weight = [-1, -2, -3, -4] result = auc_obj(self.y_true, self.y_pred, sample_weight=sample_weight) # Divisor in auc formula is max(tp[1:]+fn[1:], 0), which is all zeros # because the all values in tp and fn are negative, divide_no_nan will # produce all zeros. self.assertAllClose(result, 0.0, 1e-3) def test_weighted_prgain_majoring(self): auc_obj = metrics.AUC( num_thresholds=self.num_thresholds, curve="PRGAIN", summation_method="majoring", ) result = auc_obj( self.y_true, self.y_pred, sample_weight=self.sample_weight ) # tp = [7, 4, 0], fp = [3, 0, 0], fn = [0, 3, 7], tn = [0, 3, 3] # scaling_factor (P/N) = 7/3 # recall_gain = 1 - 7/3 [0/7, 3/4, 7/0] = [1, -3/4, -inf] -> [1, 0, 0] # precision_gain = 1 - 7/3 [3/7, 0/4, 0/0] = [0, 1, NaN] -> [0, 1, 1] # heights = [max(0, 1), max(1, 1)] = [1, 1] # widths = [(1 - 0), (0 - 0)] = [1, 0] expected_result = 1 * 1 + 0 * 1 self.assertAllClose(result, expected_result, 1e-3) def test_weighted_prgain_minoring(self): auc_obj = metrics.AUC( num_thresholds=self.num_thresholds, curve="PRGAIN", summation_method="minoring", ) result = auc_obj( self.y_true, self.y_pred, sample_weight=self.sample_weight ) # tp = [7, 4, 0], fp = [3, 0, 0], fn = [0, 3, 7], tn = [0, 3, 3] # scaling_factor (P/N) = 7/3 # recall_gain = 1 - 7/3 [0/7, 3/4, 7/0] = [1, -3/4, -inf] -> [1, 0, 0] # precision_gain = 1 - 7/3 [3/7, 0/4, 0/0] = [0, 1, NaN] -> [0, 1, 1] # heights = [min(0, 1), min(1, 1)] = [0, 1] # widths = [(1 - 0), (0 - 0)] = [1, 0] expected_result = 1 * 0 + 0 * 1 self.assertAllClose(result, expected_result, 1e-3) def test_weighted_prgain_interpolation(self): auc_obj = metrics.AUC( num_thresholds=self.num_thresholds, curve="PRGAIN" ) result = auc_obj( self.y_true, self.y_pred, sample_weight=self.sample_weight ) # tp = [7, 4, 0], fp = [3, 0, 0], fn = [0, 3, 7], tn = [0, 3, 3] # scaling_factor (P/N) = 7/3 # recall_gain = 1 - 7/3 [0/7, 3/4, 7/0] = [1, -3/4, -inf] -> [1, 0, 0] # precision_gain = 1 - 7/3 [3/7, 0/4, 0/0] = [0, 1, NaN] -> [0, 1, 1] # heights = [(0+1)/2, (1+1)/2] = [0.5, 1] # widths = [(1 - 0), (0 - 0)] = [1, 0] expected_result = 1 * 0.5 + 0 * 1 self.assertAllClose(result, expected_result, 1e-3) def test_prgain_interpolation(self): auc_obj = metrics.AUC( num_thresholds=self.num_thresholds, curve="PRGAIN" ) y_true = np.array([0, 0, 0, 1, 0, 1, 0, 1, 1, 1]) y_pred = np.array([0.1, 0.2, 0.3, 0.3, 0.4, 0.4, 0.6, 0.6, 0.8, 0.9]) result = auc_obj(y_true, y_pred) # tp = [5, 3, 0], fp = [5, 1, 0], fn = [0, 2, 5], tn = [0, 4, 4] # scaling_factor (P/N) = 5/5 = 1 # recall_gain = 1 - [0/5, 2/3, 5/0] = [1, 1/3, -inf] -> [1, 1/3, 0] # precision_gain = 1 - [5/5, 1/3, 0/0] = [1, 1/3, NaN] -> [0, 2/3, 1] # heights = [(0+2/3)/2, (2/3+1)/2] = [0.333333, 0.833333] # widths = [(1 - 1/3), (1/3 - 0)] = [0.666666, 0.333333] expected_result = 0.666666 * 0.333333 + 0.333333 * 0.833333 self.assertAllClose(result, expected_result, 1e-3) def test_invalid_num_thresholds(self): with self.assertRaisesRegex( ValueError, "Argument `num_thresholds` must be an integer > 1" ): metrics.AUC(num_thresholds=-1) with self.assertRaisesRegex( ValueError, "Argument `num_thresholds` must be an integer > 1." ): metrics.AUC(num_thresholds=1) def test_invalid_curve(self): with self.assertRaisesRegex( ValueError, 'Invalid AUC curve value: "Invalid".' ): metrics.AUC(curve="Invalid") def test_invalid_summation_method(self): with self.assertRaisesRegex( ValueError, 'Invalid AUC summation method value: "Invalid".' ): metrics.AUC(summation_method="Invalid") def test_extra_dims(self): try: from scipy import special logits = special.expit( -np.array( [ [[-10.0, 10.0, -10.0], [10.0, -10.0, 10.0]], [[-12.0, 12.0, -12.0], [12.0, -12.0, 12.0]], ], dtype=np.float32, ) ) labels = np.array( [[[1, 0, 0], [1, 0, 0]], [[0, 1, 1], [0, 1, 1]]], dtype=np.int64 ) auc_obj = metrics.AUC() result = auc_obj(labels, logits) self.assertEqual(result, 0.5) except ImportError as e: logging.warning(f"Cannot test special functions: {str(e)}")
AUCTest
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 136915, "end": 143463 }
class ____(ExprNode): # Iteration over a C++ container. # Created at the analyse_types stage by IteratorNode cpp_sequence_cname = None cpp_attribute_op = "." extra_dereference = "" is_temp = True reversed = False subexprs = ['sequence'] def get_iterator_func_names(self): return ("begin", "end") if not self.reversed else ("rbegin", "rend") def analyse_types(self, env): sequence_type = self.sequence.type if sequence_type.is_ptr: sequence_type = sequence_type.base_type begin_name, end_name = self.get_iterator_func_names() begin = sequence_type.scope.lookup(begin_name) end = sequence_type.scope.lookup(end_name) if (begin is None or not begin.type.is_cfunction or begin.type.args): error(self.pos, "missing %s() on %s" % (begin_name, self.sequence.type)) self.type = error_type return self if (end is None or not end.type.is_cfunction or end.type.args): error(self.pos, "missing %s() on %s" % (end_name, self.sequence.type)) self.type = error_type return self iter_type = begin.type.return_type if iter_type.is_cpp_class: if env.directives['cpp_locals']: self.extra_dereference = "*" if env.lookup_operator_for_types( self.pos, "!=", [iter_type, end.type.return_type]) is None: error(self.pos, "missing operator!= on result of %s() on %s" % (begin_name, self.sequence.type)) self.type = error_type return self if env.lookup_operator_for_types(self.pos, '++', [iter_type]) is None: error(self.pos, "missing operator++ on result of %s() on %s" % (begin_name, self.sequence.type)) self.type = error_type return self if env.lookup_operator_for_types(self.pos, '*', [iter_type]) is None: error(self.pos, "missing operator* on result of %s() on %s" % (begin_name, self.sequence.type)) self.type = error_type return self self.type = iter_type elif iter_type.is_ptr: if not (iter_type == end.type.return_type): error(self.pos, "incompatible types for %s() and %s()" % (begin_name, end_name)) self.type = iter_type else: error(self.pos, "result type of %s() on %s must be a C++ class or pointer" % (begin_name, self.sequence.type)) self.type = error_type return self def generate_result_code(self, code): sequence_type = self.sequence.type begin_name, _ = self.get_iterator_func_names() # essentially 3 options: if self.sequence.is_simple(): # 1) Sequence can be accessed directly, like a name; # assigning to it may break the container, but that's the responsibility # of the user. code.putln("%s = %s%s%s();" % ( self.result(), self.sequence.result(), self.cpp_attribute_op, begin_name, )) return # (while it'd be nice to limit the scope of the loop temp, it's essentially # impossible to do while supporting generators) temp_type = sequence_type if temp_type.is_reference: # 2) Sequence is a reference (often obtained by dereferencing a pointer); # make the temp a pointer so we are not sensitive to users reassigning # the pointer than it came from temp_type = PyrexTypes.CPtrType(sequence_type.ref_base_type) if temp_type.is_ptr or code.globalstate.directives['cpp_locals']: self.cpp_attribute_op = "->" # 3) (otherwise) sequence comes from a function call or similar, so we must # create a temp to store it in self.cpp_sequence_cname = code.funcstate.allocate_temp(temp_type, manage_ref=False) code.putln("%s = %s%s;" % ( self.cpp_sequence_cname, "&" if temp_type.is_ptr else "", self.sequence.move_result_rhs(), )) code.putln("%s = %s%s%s();" % ( self.result(), self.cpp_sequence_cname, self.cpp_attribute_op, begin_name, )) def generate_for_loop_header(self, code): # end call isn't cached to support containers that allow adding while iterating # (much as this is usually a bad idea) _, end_name = self.get_iterator_func_names() code.put("; %s%s != %s%s%s(); ++%s%s" % ( self.extra_dereference, self.result(), self.cpp_sequence_cname or self.sequence.result(), self.cpp_attribute_op, end_name, self.extra_dereference, self.result())) def generate_iter_next_result_code(self, result_name, code): code.putln("%s = *%s%s;" % ( result_name, self.extra_dereference, self.result())) def generate_subexpr_disposal_code(self, code): if not self.cpp_sequence_cname: # the sequence is accessed directly so any temporary result in its # subexpressions must remain available until the iterator is not needed return ExprNode.generate_subexpr_disposal_code(self, code) def free_subexpr_temps(self, code): if not self.cpp_sequence_cname: # the sequence is accessed directly so any temporary result in its # subexpressions must remain available until the iterator is not needed return ExprNode.free_subexpr_temps(self, code) def generate_disposal_code(self, code): if not self.cpp_sequence_cname: # postponed from CppIteratorNode.generate_subexpr_disposal_code # and CppIteratorNode.free_subexpr_temps ExprNode.generate_subexpr_disposal_code(self, code) ExprNode.free_subexpr_temps(self, code) ExprNode.generate_disposal_code(self, code) def free_temps(self, code): if self.cpp_sequence_cname: code.funcstate.release_temp(self.cpp_sequence_cname) # skip over IteratorNode since we don't use any of the temps it does ExprNode.free_temps(self, code)
CppIteratorNode
python
pytorch__pytorch
torch/_dynamo/variables/lists.py
{ "start": 12635, "end": 21819 }
class ____(BaseListVariable): def __init__(self, items: Sequence[VariableTracker], **kwargs: Any) -> None: items_to_map = items start = variables.ConstantVariable.create(0) stop = None step = variables.ConstantVariable.create(1) if len(items_to_map) == 1: (stop,) = items_to_map elif len(items_to_map) == 2: start, stop = items_to_map elif len(items_to_map) == 3: start, stop, step = items_to_map else: raise AssertionError def maybe_as_int(x: VariableTracker) -> VariableTracker: return ( ConstantVariable(int(x.value)) if isinstance(x, ConstantVariable) else x ) # cast each argument to an integer start = maybe_as_int(start) step = maybe_as_int(step) stop = maybe_as_int(stop) assert stop is not None super().__init__([start, stop, step], **kwargs) def debug_repr(self) -> str: return self.debug_repr_helper("range(", ")") def python_type(self) -> type: return range def start(self) -> Any: return self.items[0].as_python_constant() def stop(self) -> Any: return self.items[1].as_python_constant() def step(self) -> Any: return self.items[2].as_python_constant() def range_length(self) -> int: lo = self.start() hi = self.stop() step = self.step() assert step != 0 if step > 0 and lo < hi: return 1 + (hi - 1 - lo) // step elif step < 0 and lo > hi: return 1 + (lo - 1 - hi) // (0 - step) else: return 0 def _get_slice_indices(self, length: int, slice: slice) -> list[int]: step_is_negative = 0 if slice.step is None: step = 1 step_is_negative = False else: step = slice.step step_is_negative = slice.step < 0 # Find lower and upper bounds for start and stop. if step_is_negative: lower = -1 upper = length + lower else: lower = 0 upper = length # Compute start if slice.start is None: start = upper if step_is_negative else lower else: start = slice.start if start < 0: start += length if start < lower: start = lower else: if start > upper: start = upper # Compute stop. if slice.stop is None: stop = lower if step_is_negative else upper else: stop = slice.stop if stop < 0: stop += length if stop < lower: stop = lower else: if stop > upper: stop = upper return [start, stop, step] def apply_index(self, index: int) -> VariableTracker: length = self.range_length() if index < 0: index = length + index if index < 0 or index >= length: tx = torch._dynamo.symbolic_convert.InstructionTranslator.current_tx() raise_observed_exception( IndexError, tx, args=[ConstantVariable("range object index out of range")], ) return variables.ConstantVariable.create(self.start() + (index * self.step())) def apply_slice(self, slice: slice) -> "RangeVariable": (slice_start, slice_stop, slice_step) = self._get_slice_indices( self.range_length(), slice ) def compute_item(index: int) -> int: return self.start() + (index * self.step()) sub_step = self.step() * slice_step sub_start = compute_item(slice_start) sub_stop = compute_item(slice_stop) result = RangeVariable( [ variables.ConstantVariable.create(x) for x in [sub_start, sub_stop, sub_step] ], mutation_type=ValueMutationNew() if self.mutation_type else None, ) return result def as_python_constant(self) -> range: return range(*[x.as_python_constant() for x in self.items]) def getitem_const( self, tx: "InstructionTranslator", arg: VariableTracker ) -> VariableTracker: # implementations mimics https://github.com/python/cpython/blob/main/Objects/rangeobject.c index = arg.as_python_constant() if isinstance(index, slice): return self.apply_slice(index) elif isinstance(index, int): return self.apply_index(index) else: msg = ConstantVariable("range indices must be integers or slices") raise_observed_exception(TypeError, tx, args=[msg]) def as_proxy(self) -> range: return self.python_type()(*self._as_proxy()) def unpack_var_sequence( self, tx: Optional["InstructionTranslator"] = None ) -> list[VariableTracker]: return [variables.ConstantVariable.create(x) for x in self.as_python_constant()] def reconstruct(self, codegen: "PyCodegen") -> None: assert "range" not in codegen.tx.f_globals codegen.add_push_null( lambda: codegen.append_output(codegen.create_load_python_module(range)) # type: ignore[arg-type] ) codegen.foreach(self.items) codegen.extend_output(create_call_function(3, False)) def call_obj_hasattr( self, tx: "InstructionTranslator", name: str ) -> ConstantVariable: if self.python_type() is range: return variables.ConstantVariable.create(name in range.__dict__) return super().call_obj_hasattr(tx, name) def range_equals(self, other: "RangeVariable") -> bool: r0, r1 = self, other if ( self.range_length() != r1.range_length() or self.range_length() == 0 or r0.start() != r1.start() ): return False if self.range_length() == 1: return True return r0.step() == r1.step() def range_count(self, x: VariableTracker) -> int: # Based on CPython # https://github.com/guilhermeleobas/cpython/blob/baefaa6cba1d69efd2f930cdc56bca682c54b139/Objects/rangeobject.c#L442-L486 x = x.as_python_constant() if type(x) not in (bool, int, float): return 0 start, stop, step = self.start(), self.stop(), self.step() if step == 0: return 0 in_range = (start <= x < stop) if step > 0 else (stop < x <= start) if in_range: re = ((x - start) % step) == 0 return int(re) return 0 def call_method( self, tx: "InstructionTranslator", name: str, args: list[VariableTracker], kwargs: dict[str, VariableTracker], ) -> VariableTracker: if name == "__iter__": if not all(var.is_python_constant() for var in self.items): # Can't represent a `range_iterator` without well defined bounds return variables.misc.DelayGraphBreakVariable( msg="Cannot create range_iterator: bounds (start, stop, step) must be fully defined as concrete constants.", ) return RangeIteratorVariable( self.start(), self.stop(), self.step(), self.range_length() ) elif name == "__len__": length = self.range_length() if length > sys.maxsize: raise_observed_exception(OverflowError, tx) return ConstantVariable.create(self.range_length()) elif name in ("count", "__contains__"): return ConstantVariable(self.range_count(*args)) elif name == "__getitem__": return self.getitem_const(tx, *args) elif name in cmp_name_to_op_mapping: other = args[0] pt = other.python_type() if name not in ("__eq__", "__ne__"): # ranges are only comparable to other ranges msg = f"{name} not supported between instances of 'range' and '{pt}'" raise_observed_exception( TypeError, tx, args=[ConstantVariable.create(msg)], ) if pt is not range: return ConstantVariable.create(NotImplemented) if isinstance(other, RangeVariable): cmp = self.range_equals(other) else: cmp = False # Two ranges are equal if they produce the same sequence of values if name == "__eq__": return ConstantVariable(cmp) else: return ConstantVariable(not cmp) return super().call_method(tx, name, args, kwargs) def var_getattr(self, tx: "InstructionTranslator", name: str) -> VariableTracker: fields = ["start", "stop", "step"] if name in fields: return self.items[fields.index(name)] return super().var_getattr(tx, name)
RangeVariable
python
kamyu104__LeetCode-Solutions
Python/distinct-echo-substrings.py
{ "start": 1979, "end": 2754 }
class ____(object): def distinctEchoSubstrings(self, text): """ :type text: str :rtype: int """ MOD = 10**9+7 D = 27 # a-z and '' result = set() for i in xrange(len(text)-1): left, right, pow_D = 0, 0, 1 for l in xrange(1, min(i+2, len(text)-i)): left = (D*left + (ord(text[i-l+1])-ord('a')+1)) % MOD right = (pow_D*(ord(text[i+l])-ord('a')+1) + right) % MOD if left == right: # assumed no collision result.add(left) pow_D = (pow_D*D) % MOD return len(result) # Time: O(n^3 + d), d is the duplicated of result substrings size # Space: O(r), r is the size of result substrings set
Solution3
python
pytorch__pytorch
test/dynamo/cpython/3_13/typinganndata/ann_module3.py
{ "start": 318, "end": 448 }
class ____: def __init__(self, x: int) -> None: sfel.y: int = 0 def g_bad_ann(): no_such_name.attr: int = 0
D_bad_ann
python
kamyu104__LeetCode-Solutions
Python/maximum-font-to-fit-a-sentence-in-a-screen.py
{ "start": 108, "end": 403 }
class ____(object): def getWidth(self, fontSize, ch): """ :type fontSize: int :type ch: char :rtype int """ pass def getHeight(self, fontSize): """ :type fontSize: int :rtype int """ pass
FontInfo
python
wandb__wandb
wandb/filesync/step_upload.py
{ "start": 1044, "end": 1247 }
class ____(NamedTuple): path: str save_name: LogicalPath artifact_id: Optional[str] md5: Optional[str] copied: bool save_fn: Optional[SaveFn] digest: Optional[str]
RequestUpload
python
oauthlib__oauthlib
oauthlib/oauth2/rfc6749/errors.py
{ "start": 5276, "end": 5377 }
class ____(InvalidRequestFatalError): description = 'Invalid redirect URI.'
InvalidRedirectURIError
python
MongoEngine__mongoengine
docs/code/tumblelog.py
{ "start": 50, "end": 152 }
class ____(EmbeddedDocument): content = StringField() name = StringField(max_length=120)
Comment
python
celery__celery
celery/bin/worker.py
{ "start": 2062, "end": 2242 }
class ____(StringParamType): """Hostname option.""" name = "hostname" def convert(self, value, param, ctx): return host_format(default_nodename(value))
Hostname
python
spyder-ide__spyder
spyder/plugins/projects/widgets/projectdialog.py
{ "start": 12367, "end": 14746 }
class ____(SidebarDialog): """Project creation dialog.""" FIXED_SIZE = True MIN_WIDTH = 740 if MAC else (670 if WIN else 730) MIN_HEIGHT = 470 if MAC else (420 if WIN else 450) PAGES_MINIMUM_WIDTH = 450 PAGE_CLASSES = [NewDirectoryPage, ExistingDirectoryPage] sig_project_creation_requested = Signal(str, str, object) """ This signal is emitted to request the Projects plugin the creation of a project. Parameters ---------- project_path: str Location of project. project_type: str Type of project as defined by project types. project_packages: object Package to install. Currently not in use. """ def __init__(self, parent): """Project creation dialog.""" super().__init__(parent=parent) self.project_data = {} self.setWindowFlags( self.windowFlags() & ~Qt.WindowContextHelpButtonHint ) self.setWindowTitle(_('Create new project')) self.setWindowIcon(ima.icon("project_new")) def create_buttons(self): bbox = SpyderDialogButtonBox( QDialogButtonBox.Cancel, orientation=Qt.Horizontal ) self.button_create = QPushButton(_('Create')) self.button_create.clicked.connect(self.create_project) bbox.addButton(self.button_create, QDialogButtonBox.ActionRole) layout = QHBoxLayout() layout.addWidget(bbox) return bbox, layout def create_project(self): """Create project.""" page = self.get_page() # Validate info if not page.validate_page(): return self.project_data = { "root_path": osp.normpath(page.project_location), "project_type": page.project_type.ID, } self.sig_project_creation_requested.emit( page.project_location, page.project_type.ID, [], ) self.accept() def test(): """Local test.""" from spyder.utils.qthelpers import qapplication from spyder.config.base import running_in_ci app = qapplication() dlg = ProjectDialog(None) if not running_in_ci(): from spyder.utils.stylesheet import APP_STYLESHEET app.setStyleSheet(str(APP_STYLESHEET)) dlg.show() sys.exit(app.exec_()) if __name__ == "__main__": test()
ProjectDialog
python
Textualize__textual
docs/examples/widgets/content_switcher.py
{ "start": 699, "end": 1939 }
class ____(App[None]): CSS_PATH = "content_switcher.tcss" def compose(self) -> ComposeResult: with Horizontal(id="buttons"): # (1)! yield Button("DataTable", id="data-table") # (2)! yield Button("Markdown", id="markdown") # (3)! with ContentSwitcher(initial="data-table"): # (4)! yield DataTable(id="data-table") with VerticalScroll(id="markdown"): yield Markdown(MARKDOWN_EXAMPLE) def on_button_pressed(self, event: Button.Pressed) -> None: self.query_one(ContentSwitcher).current = event.button.id # (5)! def on_mount(self) -> None: table = self.query_one(DataTable) table.add_columns("Book", "Year") table.add_rows( [ (title.ljust(35), year) for title, year in ( ("Dune", 1965), ("Dune Messiah", 1969), ("Children of Dune", 1976), ("God Emperor of Dune", 1981), ("Heretics of Dune", 1984), ("Chapterhouse: Dune", 1985), ) ] ) if __name__ == "__main__": ContentSwitcherApp().run()
ContentSwitcherApp
python
huggingface__transformers
src/transformers/models/lfm2_moe/modular_lfm2_moe.py
{ "start": 5751, "end": 5813 }
class ____(Lfm2HybridConvCache): pass
Lfm2MoeHybridConvCache
python
huggingface__transformers
src/transformers/models/sam2_video/modeling_sam2_video.py
{ "start": 37023, "end": 39160 }
class ____(nn.Module): def __init__(self, config: Sam2VideoConfig): super().__init__() hidden_size = config.memory_attention_hidden_size self.self_attn = Sam2VideoRoPEAttention(config) self.cross_attn_image = Sam2VideoRoPEAttention(config, kv_in_dim=64, rope_k_repeat=True) # Implementation of Feedforward model self.linear1 = nn.Linear(hidden_size, config.memory_attention_feed_forward_hidden_size) self.dropout = nn.Dropout(config.memory_attention_dropout) self.linear2 = nn.Linear(config.memory_attention_feed_forward_hidden_size, hidden_size) self.layer_norm1 = nn.LayerNorm(hidden_size) self.layer_norm2 = nn.LayerNorm(hidden_size) self.layer_norm3 = nn.LayerNorm(hidden_size) self.dropout1 = nn.Dropout(config.memory_attention_dropout) self.dropout2 = nn.Dropout(config.memory_attention_dropout) self.dropout3 = nn.Dropout(config.memory_attention_dropout) self.activation = ACT2FN[config.memory_attention_feed_forward_hidden_act] def forward( self, queries: Tensor, keys: Tensor, key_point_embedding: Tensor, rope_position_embeddings: tuple[Tensor, Tensor], num_k_exclude_rope: int = 0, ) -> torch.Tensor: # Self-Attention query = self.layer_norm1(queries) query, _ = self.self_attn(query=query, key=query, value=query, position_embeddings=rope_position_embeddings) queries = queries + self.dropout1(query) # Cross-Attention query = self.layer_norm2(queries) query, _ = self.cross_attn_image( query=query, key=keys + key_point_embedding, value=keys, position_embeddings=rope_position_embeddings, num_k_exclude_rope=num_k_exclude_rope, ) queries = queries + self.dropout2(query) # MLP query = self.layer_norm3(queries) query = self.linear2(self.dropout(self.activation(self.linear1(query)))) queries = queries + self.dropout3(query) return queries
Sam2VideoMemoryAttentionLayer
python
crytic__slither
slither/core/variables/top_level_variable.py
{ "start": 269, "end": 1426 }
class ____(TopLevel, Variable): def __init__(self, scope: "FileScope") -> None: super().__init__() self._node_initialization: Optional["Node"] = None self.file_scope = scope # endregion ################################################################################### ################################################################################### # region IRs (initialization) ################################################################################### ################################################################################### @property def node_initialization(self) -> Optional["Node"]: """ Node for the state variable initalization :return: """ return self._node_initialization @node_initialization.setter def node_initialization(self, node_initialization): self._node_initialization = node_initialization # endregion ################################################################################### ###################################################################################
TopLevelVariable
python
eth-brownie__brownie
brownie/typing.py
{ "start": 1109, "end": 1189 }
class ____(BytecodeJson): sourceMap: str opcodes: str
DeployedBytecodeJson
python
gabrielfalcao__HTTPretty
tests/functional/test_decorator.py
{ "start": 473, "end": 945 }
class ____(object): def test_fail(self): raise AssertionError('Tests in this class should not ' 'be executed by the test runner.') def test_decorated(self): HTTPretty.register_uri( HTTPretty.GET, "http://localhost/", body="glub glub") fd = urllib2.urlopen('http://localhost/') got1 = fd.read() fd.close() expect(got1).to.equal(b'glub glub')
DecoratedNonUnitTest
python
getsentry__sentry
tests/sentry/search/events/test_filter.py
{ "start": 18069, "end": 47797 }
class ____(unittest.TestCase): def run_test(self, version: str, operator: str, expected: SemverFilter): semver_filter = parse_semver(version, operator) assert semver_filter == expected def test_invalid(self) -> None: with pytest.raises( InvalidSearchQuery, match=INVALID_SEMVER_MESSAGE, ): assert parse_semver("1.hello", ">") is None with pytest.raises( InvalidSearchQuery, match=INVALID_SEMVER_MESSAGE, ): assert parse_semver("hello", ">") is None with pytest.raises( InvalidSearchQuery, match="Invalid operation 'IN' for semantic version filter.", ): assert parse_semver("1.2.3.4", "IN") is None def test_normal(self) -> None: self.run_test("1", ">", SemverFilter("gt", [1, 0, 0, 0, 1, ""])) self.run_test("1.2", ">", SemverFilter("gt", [1, 2, 0, 0, 1, ""])) self.run_test("1.2.3", ">", SemverFilter("gt", [1, 2, 3, 0, 1, ""])) self.run_test("1.2.3.4", ">", SemverFilter("gt", [1, 2, 3, 4, 1, ""])) self.run_test("1.2.3-hi", ">", SemverFilter("gt", [1, 2, 3, 0, 0, "hi"])) self.run_test("1.2.3-hi", "<", SemverFilter("lt", [1, 2, 3, 0, 0, "hi"])) self.run_test("sentry@1.2.3-hi", "<", SemverFilter("lt", [1, 2, 3, 0, 0, "hi"], "sentry")) def test_wildcard(self) -> None: self.run_test("1.*", "=", SemverFilter("exact", [1])) self.run_test("1.2.*", "=", SemverFilter("exact", [1, 2])) self.run_test("1.2.3.*", "=", SemverFilter("exact", [1, 2, 3])) self.run_test("sentry@1.2.3.*", "=", SemverFilter("exact", [1, 2, 3], "sentry")) self.run_test("1.X", "=", SemverFilter("exact", [1])) def _cond(lhs, op, rhs): return Condition(lhs=Column(name=lhs), op=op, rhs=rhs) def _email(x): return _cond("email", Op.EQ, x) def _message(x): return Condition( lhs=Function("positionCaseInsensitive", [Column("message"), x]), op=Op.NEQ, rhs=0 ) def _tag(key, value, op=None): if op is None: op = Op.IN if isinstance(value, list) else Op.EQ return Condition(lhs=Function("ifNull", [Column(f"tags[{key}]"), ""]), op=op, rhs=value) def _ntag(key, value): op = Op.NOT_IN if isinstance(value, list) else Op.NEQ return _tag(key, value, op=op) def _count(op, x): return Condition(lhs=Function("count", [], "count"), op=op, rhs=x) def _project(x): return _cond("project_id", Op.EQ, x) @pytest.mark.django_db @pytest.mark.parametrize( "description,query,expected_where,expected_having", [ ( "simple_OR_with_2_emails", "user.email:foo@example.com OR user.email:bar@example.com", [Or(conditions=[_email("foo@example.com"), _email("bar@example.com")])], [], ), ( "simple_AND_with_2_emails", "user.email:foo@example.com AND user.email:bar@example.com", [And(conditions=[_email("foo@example.com"), _email("bar@example.com")])], [], ), ("message_containing_OR_as_a_substring", "ORder", [_message("ORder")], []), ("message_containing_AND_as_a_substring", "ANDroid", [_message("ANDroid")], []), ("single_email_term", "user.email:foo@example.com", [_email("foo@example.com")], []), ( "OR_with_wildcard_array_fields", "error.value:Deadlock* OR !stack.filename:*.py", [ Or( conditions=[ Condition( lhs=Column("exception_stacks.value"), op=Op.LIKE, rhs="Deadlock%" ), Condition( lhs=Column("exception_frames.filename"), op=Op.NOT_LIKE, rhs="%.py" ), ] ) ], [], ), ( "simple_order_of_operations_with_OR_then_AND", "user.email:foo@example.com OR user.email:bar@example.com AND user.email:foobar@example.com", [ Or( conditions=[ _email("foo@example.com"), And(conditions=[_email("bar@example.com"), _email("foobar@example.com")]), ] ) ], [], ), ( "simple_order_of_operations_with_AND_then_OR", "user.email:foo@example.com AND user.email:bar@example.com OR user.email:foobar@example.com", [ Or( conditions=[ And(conditions=[_email("foo@example.com"), _email("bar@example.com")]), _email("foobar@example.com"), ] ) ], [], ), ( "simple_two_ORs", "user.email:foo@example.com OR user.email:bar@example.com OR user.email:foobar@example.com", [ Or( conditions=[ _email("foo@example.com"), Or(conditions=[_email("bar@example.com"), _email("foobar@example.com")]), ] ) ], [], ), ( "simple_two_ANDs", "user.email:foo@example.com AND user.email:bar@example.com AND user.email:foobar@example.com", [ And( conditions=[ _email("foo@example.com"), And(conditions=[_email("bar@example.com"), _email("foobar@example.com")]), ] ) ], [], ), ( "OR_with_two_ANDs", "user.email:foo@example.com AND user.email:bar@example.com OR user.email:foobar@example.com AND user.email:hello@example.com", [ Or( conditions=[ And(conditions=[_email("foo@example.com"), _email("bar@example.com")]), And(conditions=[_email("foobar@example.com"), _email("hello@example.com")]), ] ) ], [], ), ( "OR_with_nested_ANDs", "user.email:foo@example.com AND user.email:bar@example.com OR user.email:foobar@example.com AND user.email:hello@example.com AND user.email:hi@example.com", [ Or( conditions=[ And(conditions=[_email("foo@example.com"), _email("bar@example.com")]), And( conditions=[ _email("foobar@example.com"), And( conditions=[ _email("hello@example.com"), _email("hi@example.com"), ] ), ] ), ] ) ], [], ), ( "multiple_ORs_with_nested_ANDs", "user.email:foo@example.com AND user.email:bar@example.com OR user.email:foobar@example.com AND user.email:hello@example.com AND user.email:hi@example.com OR user.email:foo@example.com AND user.email:bar@example.com OR user.email:foobar@example.com AND user.email:hello@example.com AND user.email:hi@example.com", [ Or( conditions=[ And(conditions=[_email("foo@example.com"), _email("bar@example.com")]), Or( conditions=[ And( conditions=[ _email("foobar@example.com"), And( conditions=[ _email("hello@example.com"), _email("hi@example.com"), ] ), ] ), Or( conditions=[ And( conditions=[ _email("foo@example.com"), _email("bar@example.com"), ] ), And( conditions=[ _email("foobar@example.com"), And( conditions=[ _email("hello@example.com"), _email("hi@example.com"), ] ), ] ), ] ), ] ), ], ), ], [], ), ( "simple_AND_with_grouped_conditions", "(event.type:error) AND (stack.in_app:true)", [ And( conditions=[ _cond("type", Op.EQ, "error"), _cond("exception_frames.in_app", Op.EQ, 1), ] ) ], [], ), ( "simple_OR_inside_group", "(user.email:foo@example.com OR user.email:bar@example.com)", [Or(conditions=[_email("foo@example.com"), _email("bar@example.com")])], [], ), ( "order_of_operations_with_groups_AND_first_OR_second", "(user.email:foo@example.com OR user.email:bar@example.com) AND user.email:foobar@example.com", [ And( conditions=[ Or(conditions=[_email("foo@example.com"), _email("bar@example.com")]), _email("foobar@example.com"), ] ) ], [], ), ( "order_of_operations_with_groups_AND_first_OR_second", "user.email:foo@example.com AND (user.email:bar@example.com OR user.email:foobar@example.com)", [ And( conditions=[ _email("foo@example.com"), Or(conditions=[_email("bar@example.com"), _email("foobar@example.com")]), ] ) ], [], ), ( "order_of_operations_with_groups_second_OR_first", "(user.email:foo@example.com OR (user.email:bar@example.com OR user.email:foobar@example.com))", [ Or( conditions=[ _email("foo@example.com"), Or(conditions=[_email("bar@example.com"), _email("foobar@example.com")]), ] ) ], [], ), ( "order_of_operations_with_nested_groups", "(user.email:foo@example.com OR (user.email:bar@example.com OR (user.email:foobar@example.com AND user.email:hello@example.com OR user.email:hi@example.com)))", [ Or( conditions=[ _email("foo@example.com"), Or( conditions=[ _email("bar@example.com"), Or( conditions=[ And( conditions=[ _email("foobar@example.com"), _email("hello@example.com"), ] ), _email("hi@example.com"), ] ), ] ), ] ) ], [], ), ( "message_outside_simple_grouped_OR", "test (item1 OR item2)", [ And( conditions=[ _message("test"), Or(conditions=[_message("item1"), _message("item2")]), ] ) ], [], ), ("only_parens", "()", [_message("()")], []), ("grouped_free_text", "(test)", [_message("test")], []), ( "free_text_with_parens", "undefined is not an object (evaluating 'function.name')", [_message("undefined is not an object (evaluating 'function.name')")], [], ), ( "free_text_AND_grouped_message", "combined (free text) AND (grouped)", [And(conditions=[_message("combined (free text)"), _message("grouped")])], [], ), ( "free_text_OR_free_text", "foo bar baz OR fizz buzz bizz", [Or(conditions=[_message("foo bar baz"), _message("fizz buzz bizz")])], [], ), ( "grouped_OR_and_OR", "a:b (c:d OR e:f) g:h i:j OR k:l", [ Or( conditions=[ And( conditions=[ _tag("a", "b"), And( conditions=[ Or(conditions=[_tag("c", "d"), _tag("e", "f")]), And(conditions=[_tag("g", "h"), _tag("i", "j")]), ] ), ] ), _tag("k", "l"), ] ) ], [], ), ( "OR_and_grouped_OR", "a:b OR c:d e:f g:h (i:j OR k:l)", [ Or( conditions=[ _tag("a", "b"), And( conditions=[ _tag("c", "d"), And( conditions=[ _tag("e", "f"), And( conditions=[ _tag("g", "h"), Or(conditions=[_tag("i", "j"), _tag("k", "l")]), ] ), ] ), ] ), ], ) ], [], ), ( "grouped_OR", "(a:b OR c:d) e:f", [And(conditions=[Or(conditions=[_tag("a", "b"), _tag("c", "d")]), _tag("e", "f")])], [], ), ( "ORs_and_no_parens", "a:b OR c:d e:f g:h i:j OR k:l", [ Or( conditions=[ _tag("a", "b"), Or( conditions=[ And( conditions=[ _tag("c", "d"), And( conditions=[ _tag("e", "f"), And(conditions=[_tag("g", "h"), _tag("i", "j")]), ] ), ] ), _tag("k", "l"), ], ), ] ) ], [], ), ( "grouped_OR_and_OR", "(a:b OR c:d) e:f g:h OR i:j k:l", [ Or( conditions=[ And( conditions=[ Or(conditions=[_tag("a", "b"), _tag("c", "d")]), And(conditions=[_tag("e", "f"), _tag("g", "h")]), ] ), And(conditions=[_tag("i", "j"), _tag("k", "l")]), ] ) ], [], ), ( "single_OR_and_no_parens", "a:b c:d e:f OR g:h i:j", [ Or( conditions=[ And( conditions=[ _tag("a", "b"), And(conditions=[_tag("c", "d"), _tag("e", "f")]), ] ), And(conditions=[_tag("g", "h"), _tag("i", "j")]), ] ), ], [], ), ( "single_grouped_OR", "a:b c:d (e:f OR g:h) i:j", [ And( conditions=[ _tag("a", "b"), And( conditions=[ _tag("c", "d"), And( conditions=[ Or(conditions=[_tag("e", "f"), _tag("g", "h")]), _tag("i", "j"), ] ), ] ), ] ) ], [], ), ( "negation_and_grouped_OR", "!a:b c:d (e:f OR g:h) i:j", [ And( conditions=[ _ntag("a", "b"), And( conditions=[ _tag("c", "d"), And( conditions=[ Or(conditions=[_tag("e", "f"), _tag("g", "h")]), _tag("i", "j"), ] ), ] ), ] ) ], [], ), ( "nested_ORs_and_AND", "(a:b OR (c:d AND (e:f OR (g:h AND e:f))))", [ Or( conditions=[ _tag("a", "b"), And( conditions=[ _tag("c", "d"), Or( conditions=[ _tag("e", "f"), And(conditions=[_tag("g", "h"), _tag("e", "f")]), ] ), ] ), ] ) ], [], ), ( "grouped_OR_then_AND_with_implied_AND", "(a:b OR c:d) AND (e:f g:h)", [ And( conditions=[ Or(conditions=[_tag("a", "b"), _tag("c", "d")]), And(conditions=[_tag("e", "f"), _tag("g", "h")]), ] ) ], [], ), ( "aggregate_AND_with_2_counts", "count():>1 AND count():<=3", [], [And(conditions=[_count(Op.GT, 1), _count(Op.LTE, 3)])], ), ( "aggregate_OR_with_2_counts", "count():>1 OR count():<=3", [], [Or(conditions=[_count(Op.GT, 1), _count(Op.LTE, 3)])], ), ( "aggregate_order_of_operations_with_OR_then_AND", "count():>1 OR count():>5 AND count():<=3", [], [ Or( conditions=[ _count(Op.GT, 1), And(conditions=[_count(Op.GT, 5), _count(Op.LTE, 3)]), ] ) ], ), ( "aggregate_order_of_operations_with_AND_then_OR", "count():>1 AND count():<=3 OR count():>5", [], [ Or( conditions=[ And(conditions=[_count(Op.GT, 1), _count(Op.LTE, 3)]), _count(Op.GT, 5), ] ) ], ), ( "grouped_aggregate_OR_then_AND", "(count():>1 OR count():>2) AND count():<=3", [], [ And( conditions=[ Or(conditions=[_count(Op.GT, 1), _count(Op.GT, 2)]), _count(Op.LTE, 3), ] ) ], ), ( "grouped_aggregate_AND_then_OR", "(count():>1 AND count():>5) OR count():<=3", [], [ Or( conditions=[ And(conditions=[_count(Op.GT, 1), _count(Op.GT, 5)]), _count(Op.LTE, 3), ] ) ], ), ("aggregate_AND_tag", "count():>1 AND a:b", [_tag("a", "b")], [_count(Op.GT, 1)]), ( "aggregate_AND_two_tags", "count():>1 AND a:b c:d", [And(conditions=[_tag("a", "b"), _tag("c", "d")])], [_count(Op.GT, 1)], ), ( "ORed_tags_AND_aggregate", "(a:b OR c:d) count():>1", [Or(conditions=[_tag("a", "b"), _tag("c", "d")])], [_count(Op.GT, 1)], ), ( "aggregate_like_message_and_columns", "failure_rate():>0.003&& users:>10 event.type:transaction", [ _message("failure_rate():>0.003&&"), _tag("users", ">10"), _cond("type", Op.EQ, "transaction"), ], [], ), ( "message_with_parens", "TypeError Anonymous function(app/javascript/utils/transform-object-keys)", [_message("TypeError Anonymous function(app/javascript/utils/transform-object-keys)")], [], ), ("tag_containing_OR", "organization.slug:slug", [_tag("organization.slug", "slug")], []), ( "in_search_then_AND", 'url:["a", "b"] AND release:test', [And(conditions=[_tag("url", ["a", "b"]), _cond("release", Op.IN, ["test"])])], [], ), ( "in_search_then_OR", 'url:["a", "b"] OR release:test', [Or(conditions=[_tag("url", ["a", "b"]), _cond("release", Op.IN, ["test"])])], [], ), ( "AND_multiple_in_searches", 'url:["a", "b"] AND url:["c", "d"] OR url:["e", "f"]', [ Or( conditions=[ And(conditions=[_tag("url", ["a", "b"]), _tag("url", ["c", "d"])]), _tag("url", ["e", "f"]), ] ) ], [], ), ( "mixed wildcards and non-wildcards", 'error.mechanism:["abc", "*ABC*"]', [ Or( conditions=[ Condition( lhs=Column(name="exception_stacks.mechanism_type"), op=Op.LIKE, rhs="%ABC%", ), Condition( lhs=Function( function="hasAny", parameters=[ Column(name="exception_stacks.mechanism_type"), [ "abc", ], ], ), op=Op.EQ, rhs=1, ), ] ) ], [], ), ], ) def test_snql_boolean_search(description, query, expected_where, expected_having) -> None: dataset = Dataset.Discover params: ParamsType = {"project_id": [1]} query_filter = UnresolvedQuery( dataset, params, config=QueryBuilderConfig(use_aggregate_conditions=True) ) where, having = query_filter.resolve_conditions(query) assert where == expected_where, description assert having == expected_having, description @pytest.mark.parametrize( "description,query,expected_message", [ ( "missing_close_parens", "(user.email:foo@example.com OR user.email:bar@example.com", "Parse error at '(user.' (column 1). This is commonly caused by unmatched parentheses. Enclose any text in double quotes.", ), ( "missing_second_close_parens", "((user.email:foo@example.com OR user.email:bar@example.com AND user.email:bar@example.com)", "Parse error at '((user' (column 1). This is commonly caused by unmatched parentheses. Enclose any text in double quotes.", ), ( "missing_open_parens", "user.email:foo@example.com OR user.email:bar@example.com)", "Parse error at '.com)' (column 57). This is commonly caused by unmatched parentheses. Enclose any text in double quotes.", ), ( "missing_second_open_parens", "(user.email:foo@example.com OR user.email:bar@example.com AND user.email:bar@example.com))", "Parse error at 'com))' (column 91). This is commonly caused by unmatched parentheses. Enclose any text in double quotes.", ), ( "cannot_OR_aggregate_and_normal_filter", "count():>1 OR a:b", "Having an OR between aggregate filters and normal filters is invalid.", ), ( "cannot_OR_normal_filter_with_an_AND_of_aggregate_and_normal_filters", "(count():>1 AND a:b) OR a:b", "Having an OR between aggregate filters and normal filters is invalid.", ), ( "cannot_OR_an_AND_of_aggregate_and_normal_filters", "(count():>1 AND a:b) OR (a:b AND count():>2)", "Having an OR between aggregate filters and normal filters is invalid.", ), ( "cannot_nest_aggregate_filter_in_AND_condition_then_OR_with_normal_filter", "a:b OR (c:d AND (e:f AND count():>1))", "Having an OR between aggregate filters and normal filters is invalid.", ), ( "missing_left_hand_side_of_OR", "OR a:b", "Condition is missing on the left side of 'OR' operator", ), ( "missing_condition_between_OR_and_AND", "a:b Or And c:d", "Missing condition in between two condition operators: 'OR AND'", ), ( "missing_right_hand_side_of_AND", "a:b AND c:d AND", "Condition is missing on the right side of 'AND' operator", ), ( "missing_left_hand_side_of_OR_inside_parens", "(OR a:b) AND c:d", "Condition is missing on the left side of 'OR' operator", ), ], ) def test_snql_malformed_boolean_search(description: str, query: str, expected_message: str) -> None: dataset = Dataset.Discover params: ParamsType = {} query_filter = UnresolvedQuery( dataset, params, config=QueryBuilderConfig(use_aggregate_conditions=True) ) with pytest.raises(InvalidSearchQuery) as error: where, having = query_filter.resolve_conditions(query) assert str(error.value) == expected_message, description
ParseSemverTest
python
jazzband__tablib
src/tablib/core.py
{ "start": 638, "end": 2263 }
class ____: """Internal Row object. Mainly used for filtering.""" __slots__ = ['_row', 'tags'] def __init__(self, row=(), tags=()): self._row = list(row) self.tags = list(tags) def __iter__(self): return (col for col in self._row) def __len__(self): return len(self._row) def __repr__(self): return repr(self._row) def __getitem__(self, i): return self._row[i] def __setitem__(self, i, value): self._row[i] = value def __delitem__(self, i): del self._row[i] def __getstate__(self): return self._row, self.tags def __setstate__(self, state): self._row, self.tags = state def rpush(self, value): self.insert(len(self._row), value) def lpush(self, value): self.insert(0, value) def append(self, value): self.rpush(value) def insert(self, index, value): self._row.insert(index, value) def copy(self): return Row(self._row.copy(), self.tags.copy()) def __contains__(self, item): return item in self._row @property def tuple(self): """Tuple representation of :class:`Row`.""" return tuple(self._row) @property def list(self): """List representation of :class:`Row`.""" return list(self._row) def has_tag(self, tag): """Returns true if current row contains tag.""" if tag is None: return False elif isinstance(tag, str): return tag in self.tags else: return bool(len(set(tag) & set(self.tags)))
Row
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/base.py
{ "start": 41926, "end": 42237 }
class ____: def literal_processor(self, dialect): def process(value): value = value.replace("'", "''") if dialect.identifier_preparer._double_percents: value = value.replace("%", "%%") return "N'%s'" % value return process
_UnicodeLiteral
python
huggingface__transformers
tests/models/wavlm/test_modeling_wavlm.py
{ "start": 16192, "end": 21509 }
class ____(unittest.TestCase): def _load_datasamples(self, num_samples): ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") # automatic decoding with librispeech speech_samples = ds.sort("id").filter( lambda x: x["id"] in [f"1272-141231-000{i}" for i in range(num_samples)] )[:num_samples]["audio"] return [x["array"] for x in speech_samples] def _load_superb(self, task, num_samples): ds = load_dataset("anton-l/superb_dummy", task, split="test") return ds[:num_samples] def test_inference_base(self): model = WavLMModel.from_pretrained("microsoft/wavlm-base-plus").to(torch_device) feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( "microsoft/wavlm-base-plus", return_attention_mask=True ) input_speech = self._load_datasamples(2) inputs = feature_extractor(input_speech, return_tensors="pt", padding=True) input_values = inputs.input_values.to(torch_device) attention_mask = inputs.attention_mask.to(torch_device) with torch.no_grad(): hidden_states_slice = ( model(input_values, attention_mask=attention_mask).last_hidden_state[:, -2:, -2:].cpu() ) EXPECTED_HIDDEN_STATES_SLICE = torch.tensor( [[[0.0577, 0.1161], [0.0579, 0.1165]], [[0.0199, 0.1237], [0.0059, 0.0605]]] ) torch.testing.assert_close(hidden_states_slice, EXPECTED_HIDDEN_STATES_SLICE, rtol=5e-2, atol=5e-2) def test_inference_large(self): model = WavLMModel.from_pretrained("microsoft/wavlm-large").to(torch_device) feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( "microsoft/wavlm-large", return_attention_mask=True ) input_speech = self._load_datasamples(2) inputs = feature_extractor(input_speech, return_tensors="pt", padding=True) input_values = inputs.input_values.to(torch_device) attention_mask = inputs.attention_mask.to(torch_device) with torch.no_grad(): hidden_states_slice = ( model(input_values, attention_mask=attention_mask).last_hidden_state[:, -2:, -2:].cpu() ) EXPECTED_HIDDEN_STATES_SLICE = torch.tensor( [[[0.2122, 0.0500], [0.2118, 0.0563]], [[0.1353, 0.1818], [0.2453, 0.0595]]] ) torch.testing.assert_close(hidden_states_slice, EXPECTED_HIDDEN_STATES_SLICE, rtol=5e-2, atol=5e-2) def test_inference_diarization(self): model = WavLMForAudioFrameClassification.from_pretrained("microsoft/wavlm-base-plus-sd").to(torch_device) processor = Wav2Vec2FeatureExtractor.from_pretrained("microsoft/wavlm-base-plus-sd") input_data = self._load_superb("sd", 4) inputs = processor(input_data["speech"], return_tensors="pt", padding=True, sampling_rate=16_000) input_values = inputs.input_values.to(torch_device) attention_mask = inputs.attention_mask.to(torch_device) with torch.no_grad(): outputs = model(input_values, attention_mask=attention_mask) # labels is a one-hot array of shape (num_frames, num_speakers) labels = (outputs.logits > 0).long() # s3prl logits for the same batch expected_logits = torch.tensor( [ [[-5.9566, -8.6554], [-5.7137, -8.9386], [-5.7906, -7.0973], [-5.7829, -5.9999]], [[-5.2086, -7.7878], [-4.8890, -7.9312], [-4.2004, -3.9101], [-5.4480, -4.6932]], [[-4.6105, -6.7178], [-5.1930, -6.1635], [-2.6228, -4.1123], [-2.7646, -3.1576]], [[-4.4477, -7.9206], [-3.9339, -7.3707], [-4.9528, -4.8242], [-3.6921, -2.9687]], ], device=torch_device, ) self.assertEqual(labels[0, :, 0].sum(), 258) self.assertEqual(labels[0, :, 1].sum(), 647) torch.testing.assert_close(outputs.logits[:, :4], expected_logits, rtol=1e-2, atol=1e-2) def test_inference_speaker_verification(self): model = WavLMForXVector.from_pretrained("microsoft/wavlm-base-plus-sv").to(torch_device) processor = Wav2Vec2FeatureExtractor.from_pretrained("microsoft/wavlm-base-plus-sv") input_data = self._load_superb("si", 4) inputs = processor(input_data["speech"], return_tensors="pt", padding=True) labels = torch.tensor([5, 1, 1, 3], device=torch_device).T with torch.no_grad(): input_values = inputs.input_values.to(torch_device) attention_mask = inputs.attention_mask.to(torch_device) outputs = model(input_values, attention_mask=attention_mask, labels=labels) embeddings = torch.nn.functional.normalize(outputs.embeddings, dim=-1) cosine_sim = torch.nn.CosineSimilarity(dim=-1) # id10002 vs id10002 self.assertAlmostEqual(cosine_sim(embeddings[1], embeddings[2]).item(), 0.9787, 3) # id10006 vs id10002 self.assertAlmostEqual(cosine_sim(embeddings[0], embeddings[1]).item(), 0.5064, 3) # id10002 vs id10004 self.assertAlmostEqual(cosine_sim(embeddings[2], embeddings[3]).item(), 0.4780, 3) self.assertAlmostEqual(outputs.loss.item(), 18.4154, 2)
WavLMModelIntegrationTest
python
walkccc__LeetCode
solutions/2439. Minimize Maximum of Array/2439.py
{ "start": 0, "end": 249 }
class ____: def minimizeArrayValue(self, nums: list[int]) -> int: ans = 0 prefix = 0 for i, num in enumerate(nums): prefix += num prefixAvg = math.ceil(prefix / (i + 1)) ans = max(ans, prefixAvg) return ans
Solution
python
pallets__werkzeug
src/werkzeug/debug/__init__.py
{ "start": 6754, "end": 20229 }
class ____: """Enables debugging support for a given application:: from werkzeug.debug import DebuggedApplication from myapp import app app = DebuggedApplication(app, evalex=True) The ``evalex`` argument allows evaluating expressions in any frame of a traceback. This works by preserving each frame with its local state. Some state, such as context globals, cannot be restored with the frame by default. When ``evalex`` is enabled, ``environ["werkzeug.debug.preserve_context"]`` will be a callable that takes a context manager, and can be called multiple times. Each context manager will be entered before evaluating code in the frame, then exited again, so they can perform setup and cleanup for each call. :param app: the WSGI application to run debugged. :param evalex: enable exception evaluation feature (interactive debugging). This requires a non-forking server. :param request_key: The key that points to the request object in this environment. This parameter is ignored in current versions. :param console_path: the URL for a general purpose console. :param console_init_func: the function that is executed before starting the general purpose console. The return value is used as initial namespace. :param show_hidden_frames: by default hidden traceback frames are skipped. You can show them by setting this parameter to `True`. :param pin_security: can be used to disable the pin based security system. :param pin_logging: enables the logging of the pin system. .. versionchanged:: 2.2 Added the ``werkzeug.debug.preserve_context`` environ key. """ _pin: str _pin_cookie: str def __init__( self, app: WSGIApplication, evalex: bool = False, request_key: str = "werkzeug.request", console_path: str = "/console", console_init_func: t.Callable[[], dict[str, t.Any]] | None = None, show_hidden_frames: bool = False, pin_security: bool = True, pin_logging: bool = True, ) -> None: if not console_init_func: console_init_func = None self.app = app self.evalex = evalex self.frames: dict[int, DebugFrameSummary | _ConsoleFrame] = {} self.frame_contexts: dict[int, list[t.ContextManager[None]]] = {} self.request_key = request_key self.console_path = console_path self.console_init_func = console_init_func self.show_hidden_frames = show_hidden_frames self.secret = gen_salt(20) self._failed_pin_auth = Value("B") self.pin_logging = pin_logging if pin_security: # Print out the pin for the debugger on standard out. if os.environ.get("WERKZEUG_RUN_MAIN") == "true" and pin_logging: _log("warning", " * Debugger is active!") if self.pin is None: _log("warning", " * Debugger PIN disabled. DEBUGGER UNSECURED!") else: _log("info", " * Debugger PIN: %s", self.pin) else: self.pin = None self.trusted_hosts: list[str] = [".localhost", "127.0.0.1"] """List of domains to allow requests to the debugger from. A leading dot allows all subdomains. This only allows ``".localhost"`` domains by default. .. versionadded:: 3.0.3 """ @property def pin(self) -> str | None: if not hasattr(self, "_pin"): pin_cookie = get_pin_and_cookie_name(self.app) self._pin, self._pin_cookie = pin_cookie # type: ignore return self._pin @pin.setter def pin(self, value: str | None) -> None: if value is None: del self._pin else: self._pin = value @property def pin_cookie_name(self) -> str: """The name of the pin cookie.""" if not hasattr(self, "_pin_cookie"): pin_cookie = get_pin_and_cookie_name(self.app) self._pin, self._pin_cookie = pin_cookie # type: ignore return self._pin_cookie def debug_application( self, environ: WSGIEnvironment, start_response: StartResponse ) -> t.Iterator[bytes]: """Run the application and conserve the traceback frames.""" contexts: list[t.ContextManager[t.Any]] = [] if self.evalex: environ["werkzeug.debug.preserve_context"] = contexts.append app_iter = None try: app_iter = self.app(environ, start_response) yield from app_iter if hasattr(app_iter, "close"): app_iter.close() except Exception as e: if hasattr(app_iter, "close"): app_iter.close() # type: ignore tb = DebugTraceback(e, skip=1, hide=not self.show_hidden_frames) for frame in tb.all_frames: self.frames[id(frame)] = frame self.frame_contexts[id(frame)] = contexts is_trusted = bool(self.check_pin_trust(environ)) html = tb.render_debugger_html( evalex=self.evalex and self.check_host_trust(environ), secret=self.secret, evalex_trusted=is_trusted, ) response = Response(html, status=500, mimetype="text/html") try: yield from response(environ, start_response) except Exception: # if we end up here there has been output but an error # occurred. in that situation we can do nothing fancy any # more, better log something into the error log and fall # back gracefully. environ["wsgi.errors"].write( "Debugging middleware caught exception in streamed " "response at a point where response headers were already " "sent.\n" ) environ["wsgi.errors"].write("".join(tb.render_traceback_text())) def execute_command( self, request: Request, command: str, frame: DebugFrameSummary | _ConsoleFrame, ) -> Response: """Execute a command in a console.""" if not self.check_host_trust(request.environ): return SecurityError() # type: ignore[return-value] contexts = self.frame_contexts.get(id(frame), []) with ExitStack() as exit_stack: for cm in contexts: exit_stack.enter_context(cm) return Response(frame.eval(command), mimetype="text/html") def display_console(self, request: Request) -> Response: """Display a standalone shell.""" if not self.check_host_trust(request.environ): return SecurityError() # type: ignore[return-value] if 0 not in self.frames: if self.console_init_func is None: ns = {} else: ns = dict(self.console_init_func()) ns.setdefault("app", self.app) self.frames[0] = _ConsoleFrame(ns) is_trusted = bool(self.check_pin_trust(request.environ)) return Response( render_console_html(secret=self.secret, evalex_trusted=is_trusted), mimetype="text/html", ) def get_resource(self, request: Request, filename: str) -> Response: """Return a static resource from the shared folder.""" path = join("shared", basename(filename)) try: data = pkgutil.get_data(__package__, path) except OSError: return NotFound() # type: ignore[return-value] else: if data is None: return NotFound() # type: ignore[return-value] etag = str(adler32(data) & 0xFFFFFFFF) return send_file( BytesIO(data), request.environ, download_name=filename, etag=etag ) def check_pin_trust(self, environ: WSGIEnvironment) -> bool | None: """Checks if the request passed the pin test. This returns `True` if the request is trusted on a pin/cookie basis and returns `False` if not. Additionally if the cookie's stored pin hash is wrong it will return `None` so that appropriate action can be taken. """ if self.pin is None: return True # If we failed too many times, then we're locked out. if self._failed_pin_auth.value >= 10: return False val = parse_cookie(environ).get(self.pin_cookie_name) if not val or "|" not in val: return False ts_str, pin_hash = val.split("|", 1) try: ts = int(ts_str) except ValueError: return False if pin_hash != hash_pin(self.pin): return None return (time.time() - PIN_TIME) < ts def check_host_trust(self, environ: WSGIEnvironment) -> bool: return host_is_trusted(environ.get("HTTP_HOST"), self.trusted_hosts) def _fail_pin_auth(self) -> None: with self._failed_pin_auth.get_lock(): count = self._failed_pin_auth.value self._failed_pin_auth.value = count + 1 time.sleep(5.0 if count > 5 else 0.5) def pin_auth(self, request: Request) -> Response: """Authenticates with the pin.""" if not self.check_host_trust(request.environ): return SecurityError() # type: ignore[return-value] exhausted = False auth = False trust = self.check_pin_trust(request.environ) pin = t.cast(str, self.pin) # If the trust return value is `None` it means that the cookie is # set but the stored pin hash value is bad. This means that the # pin was changed. In this case we count a bad auth and unset the # cookie. This way it becomes harder to guess the cookie name # instead of the pin as we still count up failures. bad_cookie = False if trust is None: self._fail_pin_auth() bad_cookie = True # If we're trusted, we're authenticated. elif trust: auth = True # If we failed too many times, then we're locked out. elif self._failed_pin_auth.value >= 10: exhausted = True # Otherwise go through pin based authentication else: entered_pin = request.args["pin"] if entered_pin.strip().replace("-", "") == pin.replace("-", ""): self._failed_pin_auth.value = 0 auth = True else: self._fail_pin_auth() rv = Response( json.dumps({"auth": auth, "exhausted": exhausted}), mimetype="application/json", ) if auth: rv.set_cookie( self.pin_cookie_name, f"{int(time.time())}|{hash_pin(pin)}", httponly=True, samesite="Strict", secure=request.is_secure, ) elif bad_cookie: rv.delete_cookie(self.pin_cookie_name) return rv def log_pin_request(self, request: Request) -> Response: """Log the pin if needed.""" if not self.check_host_trust(request.environ): return SecurityError() # type: ignore[return-value] if self.pin_logging and self.pin is not None: _log( "info", " * To enable the debugger you need to enter the security pin:" ) _log("info", " * Debugger pin code: %s", self.pin) return Response("") def __call__( self, environ: WSGIEnvironment, start_response: StartResponse ) -> t.Iterable[bytes]: """Dispatch the requests.""" # important: don't ever access a function here that reads the incoming # form data! Otherwise the application won't have access to that data # any more! request = Request(environ) response = self.debug_application if request.args.get("__debugger__") == "yes": cmd = request.args.get("cmd") arg = request.args.get("f") secret = request.args.get("s") frame = self.frames.get(request.args.get("frm", type=int)) # type: ignore if cmd == "resource" and arg: response = self.get_resource(request, arg) # type: ignore elif cmd == "pinauth" and secret == self.secret: response = self.pin_auth(request) # type: ignore elif cmd == "printpin" and secret == self.secret: response = self.log_pin_request(request) # type: ignore elif ( self.evalex and cmd is not None and frame is not None and self.secret == secret and self.check_pin_trust(environ) ): response = self.execute_command(request, cmd, frame) # type: ignore elif ( self.evalex and self.console_path is not None and request.path == self.console_path ): response = self.display_console(request) # type: ignore return response(environ, start_response)
DebuggedApplication
python
openai__gym
gym/envs/mujoco/pusher.py
{ "start": 111, "end": 2504 }
class ____(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps": 20, } def __init__(self, **kwargs): utils.EzPickle.__init__(self, **kwargs) observation_space = Box(low=-np.inf, high=np.inf, shape=(23,), dtype=np.float64) MuJocoPyEnv.__init__( self, "pusher.xml", 5, observation_space=observation_space, **kwargs ) def step(self, a): vec_1 = self.get_body_com("object") - self.get_body_com("tips_arm") vec_2 = self.get_body_com("object") - self.get_body_com("goal") reward_near = -np.linalg.norm(vec_1) reward_dist = -np.linalg.norm(vec_2) reward_ctrl = -np.square(a).sum() reward = reward_dist + 0.1 * reward_ctrl + 0.5 * reward_near self.do_simulation(a, self.frame_skip) if self.render_mode == "human": self.render() ob = self._get_obs() return ( ob, reward, False, False, dict(reward_dist=reward_dist, reward_ctrl=reward_ctrl), ) def viewer_setup(self): assert self.viewer is not None self.viewer.cam.trackbodyid = -1 self.viewer.cam.distance = 4.0 def reset_model(self): qpos = self.init_qpos self.goal_pos = np.asarray([0, 0]) while True: self.cylinder_pos = np.concatenate( [ self.np_random.uniform(low=-0.3, high=0, size=1), self.np_random.uniform(low=-0.2, high=0.2, size=1), ] ) if np.linalg.norm(self.cylinder_pos - self.goal_pos) > 0.17: break qpos[-4:-2] = self.cylinder_pos qpos[-2:] = self.goal_pos qvel = self.init_qvel + self.np_random.uniform( low=-0.005, high=0.005, size=self.model.nv ) qvel[-4:] = 0 self.set_state(qpos, qvel) return self._get_obs() def _get_obs(self): return np.concatenate( [ self.sim.data.qpos.flat[:7], self.sim.data.qvel.flat[:7], self.get_body_com("tips_arm"), self.get_body_com("object"), self.get_body_com("goal"), ] )
PusherEnv
python
django__django
django/core/management/commands/dumpdata.py
{ "start": 466, "end": 511 }
class ____(Warning): pass
ProxyModelWarning
python
keras-team__keras
keras/src/ops/linalg.py
{ "start": 3579, "end": 4445 }
class ____(Operation): def call(self, x): return _eig(x) def compute_output_spec(self, x): _assert_square(x) _assert_2d(x) return ( KerasTensor(x.shape[:-1], x.dtype), KerasTensor(x.shape, x.dtype), ) @keras_export(["keras.ops.eig", "keras.ops.linalg.eig"]) def eig(x): """Computes the eigenvalues and eigenvectors of a square matrix. Args: x: Input tensor of shape `(..., M, M)`. Returns: A tuple of two tensors: a tensor of shape `(..., M)` containing eigenvalues and a tensor of shape `(..., M, M)` containing eigenvectors. """ if any_symbolic_tensors((x,)): return Eig().symbolic_call(x) return _eig(x) def _eig(x): x = backend.convert_to_tensor(x) _assert_square(x) _assert_2d(x) return backend.linalg.eig(x)
Eig
python
pytorch__pytorch
aten/src/ATen/native/transformers/cuda/mem_eff_attention/kernels/generate_kernels.py
{ "start": 4291, "end": 13728 }
class ____: sort_index: tuple[int, ...] = field(init=False, repr=False) sm_range: tuple[int, int] dtype: str aligned: bool apply_dropout: bool preload_mmas: bool block_i: int block_j: int max_k: int dispatch_cond: Optional[str] = None keys_queries_aligned_to_blocksizes: bool = False def __post_init__(self) -> None: # Set kernel selection priority # The lowest value that matches inputs # will be selected self.sort_index = ( # First select aligned kernel 0 if self.aligned else 1, # Take a kernel without dropout if possible 1 if self.apply_dropout else 0, # Then take the smallest maxK self.max_k, # .. and the highest block_i -self.block_i, # and finally avoid bounds-checks if possible 0 if self.keys_queries_aligned_to_blocksizes else 1, ) @property def _aligned_suffix(self) -> str: return "aligned" if self.aligned else "notaligned" @property def name(self) -> str: dropout_suffix = "_dropout" if self.apply_dropout else "" seqlen_aligned_suffix = ( "_seqaligned" if self.keys_queries_aligned_to_blocksizes else "" ) return ( f"fmha_cutlassB_{self.dtype}_{self._aligned_suffix}" f"_{self.block_i}x{self.block_j}_k{self.max_k}{dropout_suffix}{seqlen_aligned_suffix}_sm{self.sm_range[0]}" ) @property def cpp_class(self) -> str: template_args = ", ".join( [ f"cutlass::arch::Sm{self.sm_range[0]}", DTYPES[self.dtype], "true" if self.aligned else "false", "true" if self.apply_dropout else "false", "true" if self.preload_mmas else "false", str(self.block_i), str(self.block_j), str(self.max_k), ] ) if self.keys_queries_aligned_to_blocksizes: template_args += ", true" return f"AttentionBackwardKernel<{template_args}>" @property def impl_group(self) -> str: # Maps to file which will contain the implementation dropout_suffix = "_dropout" if self.apply_dropout else "" return f"{self.dtype}_{self._aligned_suffix}_k{self.max_k}{dropout_suffix}" @property def cpp_impl(self) -> str: return KERNEL_IMPL_TEMPLATE.format( CPP_CLASS=self.cpp_class, NAME=self.name, SM=self.sm_range[0], SM_MAX=self.sm_range[1], ) @classmethod def get_all(cls) -> list["BwdKernel"]: kernels: list[BwdKernel] = [] for aligned, dtype, (sm, sm_max), apply_dropout, max_k in itertools.product( [True, False], DTYPES.keys(), itertools.pairwise(SM), [True, False], [32, 64, 128, 2**16], ): if dtype == "bf16" and sm < 80: continue if not aligned and sm >= 80: continue is_half = dtype in ["bf16", "f16"] bi_values = [64] # Some architectures have more shmem and can use 128 # We still need fallback to 64 for GPUs with less shmem # (Sm75, Sm86 ...) if sm >= 80 or (sm >= 70 and is_half): if max_k > 64: bi_values.append(128) for bi in bi_values: output_in_rf = is_half and max_k <= bi preload_mmas = is_half and sm >= 80 and output_in_rf bj = 128 if (preload_mmas and max_k > 64) else 64 kernels.append( cls( aligned=aligned, dtype=dtype, sm_range=(sm, sm_max), apply_dropout=apply_dropout, preload_mmas=preload_mmas, block_i=bi, block_j=bj, max_k=max_k, ) ) # A few specialized kernels that are faster if apply_dropout or max_k > 128 or not is_half or not aligned: continue if sm not in [70, 80]: continue kernels.append( cls( aligned=aligned, dtype=dtype, sm_range=(sm, sm_max), apply_dropout=apply_dropout, preload_mmas=preload_mmas, block_i=bi, block_j=bj, max_k=max_k, keys_queries_aligned_to_blocksizes=True, ) ) # Add some specialized kernels for stable diffusion BW (K=80) # This is the only kernel that can keep the outputs on RF on # Sm86/Sm89, so it's much faster than the 64x64 one for dtype in ["f16", "bf16"]: kernels.append( cls( aligned=True, dtype=dtype, sm_range=(80, SM[SM.index(80) + 1]), apply_dropout=False, preload_mmas=True, block_i=128, block_j=64, max_k=96, # Sm80 has a faster kernel for this case dispatch_cond="cc == 86 || cc == 89", ) ) return kernels T = TypeVar("T", FwdKernel, BwdKernel) def write_decl_impl( kernels: list[T], family_name: str, impl_file: str, autogen_dir: Path, disable_def: Optional[str] = None, ) -> None: cpp_file_header = """/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ // This file is auto-generated. See "generate_kernels.py" """ kernels.sort() implfile_to_kernels: dict[str, list[T]] = collections.defaultdict(list) cat_to_kernels: dict[tuple[str, int, int], list[T]] = collections.defaultdict(list) dispatch_all = "" declarations = cpp_file_header + "#pragma once\n" # declarations += f"#ifndef {disable_def}\n" declarations += f"""#include {impl_file}\n""" declarations += """using namespace PyTorchMemEffAttention;\n""" # Declaration of kernel functions for k in kernels: implfile_to_kernels[k.impl_group].append(k) cat_to_kernels[(k.dtype, k.sm_range[0], k.sm_range[1])].append(k) for (cat_dt, cat_sm, cat_sm_max), kernels in cat_to_kernels.items(): declarations += f"// ======== {cat_dt} / sm{cat_sm} ========\n" declarations += "\n".join( k.cpp_impl.split("{")[0].rstrip() + ";" for k in kernels ) dispatch_category_fn = f"dispatch_{family_name}_{cat_dt}_sm{cat_sm}" declarations += ( f"\n\ntemplate <typename T> void {dispatch_category_fn}(T cb, int cc) {{\n" ) for k in kernels: _call = f"cb({k.cpp_class}(), {k.name});\n" if k.dispatch_cond is not None: _call = f"if ({k.dispatch_cond}) {_call}" declarations += f" {_call}" declarations += "}\n\n" dispatch_all += f""" if (std::is_same_v<DT, {DTYPES[cat_dt]}> && {cat_sm} <= cc && cc < {cat_sm_max}) {{ {dispatch_category_fn}(cb, cc); }}""" declarations += f""" template <typename DT, typename T> void dispatch_{family_name}(T cb, int cc = 0) {{ {dispatch_all} }} """ # declarations += f"#endif // {disable_def}\n" # Write declarations to family header (autogen_dir / f"{family_name}.h").write_text(declarations) for f, f_kernels in implfile_to_kernels.items(): impl_cu = cpp_file_header # impl_cu += f"#ifndef {disable_def}\n" impl_cu += f"""#include {impl_file}\n""" impl_cu += """using namespace PyTorchMemEffAttention;\n""" for k in f_kernels: impl_cu += k.cpp_impl # impl_cu += f"#endif // {disable_def}\n" (autogen_dir / f"{family_name}_{f}.cu").write_text(impl_cu) def main(output_dir: Optional[str]) -> None: if output_dir is None: output_dir = Path(__file__).parent else: output_dir = Path(output_dir) write_decl_impl( FwdKernel.get_all(), "cutlassF", impl_file="<ATen/native/transformers/cuda/mem_eff_attention/kernel_forward.h>", autogen_dir=output_dir, ) write_decl_impl( BwdKernel.get_all(), "cutlassB", impl_file="<ATen/native/transformers/cuda/mem_eff_attention/kernel_backward.h>", autogen_dir=output_dir, ) if __name__ == "__main__": parser = argparse.ArgumentParser( prog="generate_kernels", description="Generate the mem-eff kernels template instantiations", ) # Set an optional output directory parser.add_argument( "-o", "--output_dir", required=False, help="Where to generate the kernels " " will default to <ATen/native/transformers/cuda/mem_eff_attention/kernels/> ", ) args = parser.parse_args() main(args.output_dir)
BwdKernel
python
gevent__gevent
src/gevent/tests/test__greenlet.py
{ "start": 12603, "end": 12657 }
class ____(object): def method(self): pass
A
python
tensorflow__tensorflow
tensorflow/python/training/session_manager_test.py
{ "start": 1588, "end": 28319 }
class ____(test.TestCase): @classmethod def setUpClass(cls): super(SessionManagerTest, cls).setUpClass() resource_variables_toggle.disable_resource_variables() def testPrepareSessionSucceeds(self): with ops.Graph().as_default(): v = variable_v1.VariableV1([1.0, 2.0, 3.0], name="v") sm = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables()) sess = sm.prepare_session( "", init_op=variables.global_variables_initializer()) self.assertAllClose([1.0, 2.0, 3.0], sess.run(v)) def testPrepareSessionSucceedsWithInitFeedDict(self): with ops.Graph().as_default(): p = array_ops.placeholder(dtypes.float32, shape=(3,)) v = variable_v1.VariableV1(p, name="v") sm = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables()) sess = sm.prepare_session( "", init_op=variables.global_variables_initializer(), init_feed_dict={p: [1.0, 2.0, 3.0]}) self.assertAllClose([1.0, 2.0, 3.0], sess.run(v)) def testPrepareSessionSucceedsWithInitFn(self): with ops.Graph().as_default(): v = variable_v1.VariableV1([125], name="v") sm = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables()) sess = sm.prepare_session( "", init_fn=lambda sess: sess.run(v.initializer)) self.assertAllClose([125], sess.run(v)) def testPrepareSessionSucceedsWithLocalInitFeedDict(self): with ops.Graph().as_default(): p = array_ops.placeholder(dtypes.float32, shape=(3,)) v = variable_v1.VariableV1( p, name="v", collections=[ops.GraphKeys.LOCAL_VARIABLES]) sm = session_manager.SessionManager( local_init_op=v.initializer, local_init_feed_dict={p: [1.0, 2.0, 3.0]}, ready_op=variables.report_uninitialized_variables()) sess = sm.prepare_session("") self.assertAllClose([1.0, 2.0, 3.0], sess.run(v)) def testPrepareSessionFails(self): checkpoint_dir = os.path.join(self.get_temp_dir(), "prepare_session") checkpoint_dir2 = os.path.join(self.get_temp_dir(), "prepare_session2") try: gfile.DeleteRecursively(checkpoint_dir) gfile.DeleteRecursively(checkpoint_dir2) except errors.OpError: pass # Ignore gfile.MakeDirs(checkpoint_dir) with ops.Graph().as_default(): v = variable_v1.VariableV1([1.0, 2.0, 3.0], name="v") sm = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables()) saver = saver_lib.Saver({"v": v}) sess = sm.prepare_session( "", init_op=variables.global_variables_initializer(), saver=saver, checkpoint_dir=checkpoint_dir) self.assertAllClose([1.0, 2.0, 3.0], sess.run(v)) checkpoint_filename = os.path.join(checkpoint_dir, "prepare_session_checkpoint") saver.save(sess, checkpoint_filename) # Create a new Graph and SessionManager and recover. with ops.Graph().as_default(): # Renames the checkpoint directory. os.rename(checkpoint_dir, checkpoint_dir2) gfile.MakeDirs(checkpoint_dir) v = variable_v1.VariableV1([6.0, 7.0, 8.0], name="v") with self.cached_session(): self.assertEqual(False, variable_v1.is_variable_initialized(v).eval()) session_manager.SessionManager( ready_op=variables.report_uninitialized_variables()) saver = saver_lib.Saver({"v": v}) # This should fail as there's no checkpoint within 2 seconds. with self.assertRaisesRegex( RuntimeError, "no init_op or init_fn or local_init_op was given"): sess = sm.prepare_session( "", init_op=None, saver=saver, checkpoint_dir=checkpoint_dir, wait_for_checkpoint=True, max_wait_secs=2) # Rename the checkpoint directory back. gfile.DeleteRecursively(checkpoint_dir) os.rename(checkpoint_dir2, checkpoint_dir) # This should succeed as there's checkpoint. sess = sm.prepare_session( "", init_op=None, saver=saver, checkpoint_dir=checkpoint_dir, wait_for_checkpoint=True, max_wait_secs=2) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("v:0")).eval(session=sess)) def _test_recovered_variable(self, checkpoint_dir=None, checkpoint_filename_with_path=None): # Create a new Graph and SessionManager and recover from a checkpoint. with ops.Graph().as_default(): v = variable_v1.VariableV1(2, name="v") with session_lib.Session(): self.assertEqual(False, variable_v1.is_variable_initialized(v).eval()) sm2 = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables()) saver = saver_lib.Saver({"v": v}) sess, initialized = sm2.recover_session( "", saver=saver, checkpoint_dir=checkpoint_dir, checkpoint_filename_with_path=checkpoint_filename_with_path) self.assertTrue(initialized) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("v:0")).eval(session=sess)) self.assertEqual(1, sess.run(v)) def testRecoverSession(self): # Create a checkpoint. checkpoint_dir = os.path.join(self.get_temp_dir(), "recover_session") try: gfile.DeleteRecursively(checkpoint_dir) except errors.OpError: pass # Ignore gfile.MakeDirs(checkpoint_dir) with ops.Graph().as_default(): v = variable_v1.VariableV1(1, name="v") sm = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables()) saver = saver_lib.Saver({"v": v}) sess, initialized = sm.recover_session( "", saver=saver, checkpoint_dir=checkpoint_dir) self.assertFalse(initialized) sess.run(v.initializer) self.assertEqual(1, sess.run(v)) saver.save(sess, os.path.join(checkpoint_dir, "recover_session_checkpoint")) self._test_recovered_variable(checkpoint_dir=checkpoint_dir) self._test_recovered_variable( checkpoint_filename_with_path=checkpoint_management.latest_checkpoint( checkpoint_dir)) # Cannot set both checkpoint_dir and checkpoint_filename_with_path. with self.assertRaises(ValueError): self._test_recovered_variable( checkpoint_dir=checkpoint_dir, checkpoint_filename_with_path=checkpoint_management.latest_checkpoint( checkpoint_dir)) def testWaitForSessionReturnsNoneAfterTimeout(self): with ops.Graph().as_default(): variable_v1.VariableV1(1, name="v") sm = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables(), recovery_wait_secs=1) # Set max_wait_secs to allow us to try a few times. with self.assertRaises(errors.DeadlineExceededError): sm.wait_for_session(master="", max_wait_secs=3) def testInitWithNoneLocalInitOpError(self): # Creating a SessionManager with a None local_init_op but # non-None ready_for_local_init_op raises ValueError with self.assertRaisesRegex( ValueError, "If you pass a ready_for_local_init_op " "you must also pass a local_init_op "): session_manager.SessionManager( ready_for_local_init_op=variables.report_uninitialized_variables( variables.global_variables()), local_init_op=None) def testRecoverSessionWithReadyForLocalInitOp(self): # Create a checkpoint. checkpoint_dir = os.path.join(self.get_temp_dir(), "recover_session_ready_for_local_init") try: gfile.DeleteRecursively(checkpoint_dir) except errors.OpError: pass # Ignore gfile.MakeDirs(checkpoint_dir) with ops.Graph().as_default(): v = variable_v1.VariableV1(1, name="v") sm = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables()) saver = saver_lib.Saver({"v": v}) sess, initialized = sm.recover_session( "", saver=saver, checkpoint_dir=checkpoint_dir) self.assertFalse(initialized) sess.run(v.initializer) self.assertEqual(1, sess.run(v)) saver.save(sess, os.path.join(checkpoint_dir, "recover_session_checkpoint")) # Create a new Graph and SessionManager and recover. with ops.Graph().as_default(): v = variable_v1.VariableV1(2, name="v") w = variable_v1.VariableV1( v, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="w") with self.cached_session(): self.assertEqual(False, variable_v1.is_variable_initialized(v).eval()) self.assertEqual(False, variable_v1.is_variable_initialized(w).eval()) sm2 = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables(), ready_for_local_init_op=variables.report_uninitialized_variables( variables.global_variables()), local_init_op=w.initializer) saver = saver_lib.Saver({"v": v}) sess, initialized = sm2.recover_session( "", saver=saver, checkpoint_dir=checkpoint_dir) self.assertTrue(initialized) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("v:0")).eval(session=sess)) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("w:0")).eval(session=sess)) self.assertEqual(1, sess.run(v)) self.assertEqual(1, sess.run(w)) def testRecoverSessionWithReadyForLocalInitOpFailsToReadyLocal(self): # We use ready_for_local_init_op=report_uninitialized_variables(), # which causes recover_session to not run local_init_op, and to return # initialized=False # Create a checkpoint. checkpoint_dir = os.path.join( self.get_temp_dir(), "recover_session_ready_for_local_init_fails_to_ready_local") try: gfile.DeleteRecursively(checkpoint_dir) except errors.OpError: pass # Ignore gfile.MakeDirs(checkpoint_dir) with ops.Graph().as_default(): v = variable_v1.VariableV1(1, name="v") sm = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables()) saver = saver_lib.Saver({"v": v}) sess, initialized = sm.recover_session( "", saver=saver, checkpoint_dir=checkpoint_dir) self.assertFalse(initialized) sess.run(v.initializer) self.assertEqual(1, sess.run(v)) saver.save(sess, os.path.join(checkpoint_dir, "recover_session_checkpoint")) # Create a new Graph and SessionManager and recover. with ops.Graph().as_default(): v = variable_v1.VariableV1(2, name="v") w = variable_v1.VariableV1( v, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="w") with self.cached_session(): self.assertEqual(False, variable_v1.is_variable_initialized(v).eval()) self.assertEqual(False, variable_v1.is_variable_initialized(w).eval()) sm2 = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables(), ready_for_local_init_op=variables.report_uninitialized_variables(), local_init_op=w.initializer) saver = saver_lib.Saver({"v": v}) sess, initialized = sm2.recover_session( "", saver=saver, checkpoint_dir=checkpoint_dir) self.assertFalse(initialized) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("v:0")).eval(session=sess)) self.assertEqual( False, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("w:0")).eval(session=sess)) self.assertEqual(1, sess.run(v)) def testRecoverSessionNoChkptStillRunsLocalInitOp(self): # This test checks for backwards compatibility. # In particular, we continue to ensure that recover_session will execute # local_init_op exactly once, regardless of whether the session was # successfully recovered. with ops.Graph().as_default(): w = variable_v1.VariableV1( 1, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="w") with self.cached_session(): self.assertEqual(False, variable_v1.is_variable_initialized(w).eval()) sm2 = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables(), ready_for_local_init_op=None, local_init_op=w.initializer) # Try to recover session from None sess, initialized = sm2.recover_session( "", saver=None, checkpoint_dir=None) # Succeeds because recover_session still run local_init_op self.assertFalse(initialized) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("w:0")).eval(session=sess)) self.assertEqual(1, sess.run(w)) def testRecoverSessionFailsStillRunsLocalInitOp(self): # Create a checkpoint. checkpoint_dir = os.path.join( self.get_temp_dir(), "recover_session_ready_for_local_init_fails_stil_run") try: gfile.DeleteRecursively(checkpoint_dir) except errors.OpError: pass # Ignore gfile.MakeDirs(checkpoint_dir) # Create a new Graph and SessionManager and recover. with ops.Graph().as_default(): v = variable_v1.VariableV1(2, name="v") w = variable_v1.VariableV1( 1, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="w") with self.cached_session(): self.assertEqual(False, variable_v1.is_variable_initialized(v).eval()) self.assertEqual(False, variable_v1.is_variable_initialized(w).eval()) sm2 = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables(), ready_for_local_init_op=None, local_init_op=w.initializer) saver = saver_lib.Saver({"v": v}) sess, initialized = sm2.recover_session( "", saver=saver, checkpoint_dir=checkpoint_dir, wait_for_checkpoint=False) self.assertFalse(initialized) self.assertEqual( False, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("v:0")).eval(session=sess)) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("w:0")).eval(session=sess)) self.assertEqual(1, sess.run(w)) def testWaitForSessionLocalInit(self): server = server_lib.Server.create_local_server() with ops.Graph().as_default() as graph: v = variable_v1.VariableV1(1, name="v") w = variable_v1.VariableV1( v, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="w") sm = session_manager.SessionManager( graph=graph, ready_op=variables.report_uninitialized_variables(), ready_for_local_init_op=variables.report_uninitialized_variables( variables.global_variables()), local_init_op=w.initializer) # Initialize v but not w s = session_lib.Session(server.target, graph=graph) s.run(v.initializer) sess = sm.wait_for_session(server.target, max_wait_secs=3) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("v:0")).eval(session=sess)) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("w:0")).eval(session=sess)) self.assertEqual(1, sess.run(v)) self.assertEqual(1, sess.run(w)) def testWaitForSessionWithReadyForLocalInitOpFailsToReadyLocal(self): with ops.Graph().as_default() as graph: v = variable_v1.VariableV1(1, name="v") w = variable_v1.VariableV1( v, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="w") sm = session_manager.SessionManager( graph=graph, ready_op=variables.report_uninitialized_variables(), ready_for_local_init_op=variables.report_uninitialized_variables(), local_init_op=w.initializer) with self.assertRaises(errors_impl.DeadlineExceededError): # Time-out because w fails to be initialized, # because of overly restrictive ready_for_local_init_op sm.wait_for_session("", max_wait_secs=3) @test_util.run_v1_only("Requires TF V1 variable behavior.") def testWaitForSessionInsufficientReadyForLocalInitCheck(self): with ops.Graph().as_default() as graph: v = variable_v1.VariableV1(1, name="v") w = variable_v1.VariableV1( v, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="w") sm = session_manager.SessionManager( graph=graph, ready_op=variables.report_uninitialized_variables(), ready_for_local_init_op=None, local_init_op=w.initializer) with self.assertRaisesRegex(errors_impl.DeadlineExceededError, "Session was not ready after waiting.*"): sm.wait_for_session("", max_wait_secs=3) def testPrepareSessionWithReadyForLocalInitOp(self): with ops.Graph().as_default(): v = variable_v1.VariableV1(1, name="v") w = variable_v1.VariableV1( v, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="w") x = variable_v1.VariableV1( 3 * v, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="x") with self.cached_session(): self.assertEqual(False, variable_v1.is_variable_initialized(v).eval()) self.assertEqual(False, variable_v1.is_variable_initialized(w).eval()) self.assertEqual(False, variable_v1.is_variable_initialized(x).eval()) sm2 = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables(), ready_for_local_init_op=variables.report_uninitialized_variables( variables.global_variables()), local_init_op=[w.initializer, x.initializer]) sess = sm2.prepare_session("", init_op=v.initializer) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("v:0")).eval(session=sess)) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("w:0")).eval(session=sess)) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("x:0")).eval(session=sess)) self.assertEqual(1, sess.run(v)) self.assertEqual(1, sess.run(w)) self.assertEqual(3, sess.run(x)) @test_util.run_v1_only("Requires TF V1 variable behavior.") def testPrepareSessionWithPartialInitOp(self): with ops.Graph().as_default(): v = variable_v1.VariableV1(1, name="v") w = variable_v1.VariableV1( v, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="w") x = variable_v1.VariableV1( 3 * v, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="x") # TODO(b/70206927): Use ResourceVariables once they are handled properly. v_res = variable_v1.VariableV1(1, name="v_res") w_res = variable_v1.VariableV1( v_res, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="w_res") x_res = variable_v1.VariableV1( 3 * v_res, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="x_res") with self.cached_session(): self.assertEqual(False, variable_v1.is_variable_initialized(v).eval()) self.assertEqual(False, variable_v1.is_variable_initialized(w).eval()) self.assertEqual(False, variable_v1.is_variable_initialized(x).eval()) self.assertEqual(False, variable_v1.is_variable_initialized(v_res).eval()) self.assertEqual(False, variable_v1.is_variable_initialized(w_res).eval()) self.assertEqual(False, variable_v1.is_variable_initialized(x_res).eval()) sm2 = session_manager.SessionManager(local_init_op=[ w.initializer, x.initializer, w_res.initializer, x_res.initializer ]) sess = sm2.prepare_session("", init_op=None) self.assertEqual( False, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("v:0")).eval(session=sess)) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("w:0")).eval(session=sess)) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("x:0")).eval(session=sess)) self.assertEqual(1, sess.run(w)) self.assertEqual(3, sess.run(x)) self.assertEqual( False, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("v_res:0")).eval(session=sess)) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("w_res:0")).eval(session=sess)) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("x_res:0")).eval(session=sess)) self.assertEqual(1, sess.run(w_res)) self.assertEqual(3, sess.run(x_res)) def testPrepareSessionWithCyclicInitializer(self): # Regression test. Previously Variable._build_initializer_expr would enter # into an infinite recursion when the variable's initial_value involved # cyclic dependencies. with ops.Graph().as_default(): i = while_loop.while_loop(lambda i: i < 1, lambda i: i + 1, [0]) v = variable_v1.VariableV1(array_ops.identity(i), name="v") with self.cached_session(): self.assertEqual(False, variable_v1.is_variable_initialized(v).eval()) sm = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables()) sess = sm.prepare_session("", init_op=v.initializer) self.assertEqual(1, sess.run(v)) self.assertEqual( True, variable_v1.is_variable_initialized( sess.graph.get_tensor_by_name("v:0")).eval(session=sess)) def testPrepareSessionDidNotInitLocalVariable(self): with ops.Graph().as_default(): v = variable_v1.VariableV1(1, name="v") w = variable_v1.VariableV1( v, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="w") with self.cached_session(): self.assertEqual(False, variable_v1.is_variable_initialized(v).eval()) self.assertEqual(False, variable_v1.is_variable_initialized(w).eval()) sm2 = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables()) with self.assertRaisesRegex(RuntimeError, "Init operations did not make model ready.*"): sm2.prepare_session("", init_op=v.initializer) def testPrepareSessionDidNotInitLocalVariableList(self): with ops.Graph().as_default(): v = variable_v1.VariableV1(1, name="v") w = variable_v1.VariableV1( v, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="w") with self.cached_session(): self.assertEqual(False, variable_v1.is_variable_initialized(v).eval()) self.assertEqual(False, variable_v1.is_variable_initialized(w).eval()) sm2 = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables()) with self.assertRaisesRegex(RuntimeError, "Init operations did not make model ready"): sm2.prepare_session("", init_op=[v.initializer]) def testPrepareSessionWithReadyNotReadyForLocal(self): with ops.Graph().as_default(): v = variable_v1.VariableV1(1, name="v") w = variable_v1.VariableV1( v, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="w") with self.cached_session(): self.assertEqual(False, variable_v1.is_variable_initialized(v).eval()) self.assertEqual(False, variable_v1.is_variable_initialized(w).eval()) sm2 = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables(), ready_for_local_init_op=variables.report_uninitialized_variables( variables.global_variables()), local_init_op=w.initializer) with self.assertRaisesRegex( RuntimeError, "Init operations did not make model ready for local_init"): sm2.prepare_session("", init_op=None) @test_util.run_v1_only("Requires TF V1 variable behavior.") def testPrepareSessionWithInsufficientReadyForLocalInitCheck(self): with ops.Graph().as_default(): v = variable_v1.VariableV1(1, name="v") w = variable_v1.VariableV1( v, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="w") with self.cached_session(): self.assertEqual(False, variable_v1.is_variable_initialized(v).eval()) self.assertEqual(False, variable_v1.is_variable_initialized(w).eval()) sm2 = session_manager.SessionManager( ready_op=variables.report_uninitialized_variables(), ready_for_local_init_op=None, local_init_op=w.initializer) with self.assertRaisesRegex(RuntimeError, "Init operations did not make model ready.*"): sm2.prepare_session("", init_op=None)
SessionManagerTest
python
django__django
tests/model_forms/models.py
{ "start": 1995, "end": 2126 }
class ____(models.Model): article = models.OneToOneField(Article, models.CASCADE, parent_link=True)
ImprovedArticleWithParentLink
python
doocs__leetcode
solution/2500-2599/2524.Maximum Frequency Score of a Subarray/Solution.py
{ "start": 0, "end": 618 }
class ____: def maxFrequencyScore(self, nums: List[int], k: int) -> int: mod = 10**9 + 7 cnt = Counter(nums[:k]) ans = cur = sum(pow(k, v, mod) for k, v in cnt.items()) % mod i = k while i < len(nums): a, b = nums[i - k], nums[i] if a != b: cur += (b - 1) * pow(b, cnt[b], mod) if cnt[b] else b cur -= (a - 1) * pow(a, cnt[a] - 1, mod) if cnt[a] > 1 else a cur %= mod cnt[b] += 1 cnt[a] -= 1 ans = max(ans, cur) i += 1 return ans
Solution
python
pexpect__pexpect
tests/test_screen.py
{ "start": 2498, "end": 9220 }
class ____ (PexpectTestCase.PexpectTestCase): def make_screen_with_put (self): s = screen.screen(10,10) s.fill ('.') for r in range (1,s.rows + 1): if r % 2: s.put_abs (r, 1, str(r)) else: s.put_abs (r, s.cols, str(r)) for c in range (1,s.cols + 1): if c % 2: s.put_abs (1, c, str(c)) else: s.put_abs (s.rows, c, str(c)) s.put_abs(1,1, '\\') s.put_abs(1,s.cols, '/') s.put_abs(s.rows,1,'/') s.put_abs(s.rows, s.cols, '\\') s.put_abs(5,5,'\\') s.put_abs(5,6,'/') s.put_abs(6,5,'/') s.put_abs(6,6,'\\') return s def test_fill (self): s = screen.screen (10,10) s.fill_region (10,1,1,10,'X') s.fill_region (2,2,9,9,'O') s.fill_region (8,8,3,3,':') s.fill_region (4,7,7,4,'o') s.fill_region (6,5,5,6,'.') assert str(s) == fill1_target s = screen.screen (11,11) s.fill_region (1,1,11,11,'X') s.fill_region (2,2,10,10,'O') s.fill_region (9,9,3,3,':') s.fill_region (4,8,8,4,'o') s.fill_region (7,5,5,7,'.') s.fill_region (6,6,6,6,'+') assert str(s) == fill2_target def test_put (self): s = self.make_screen_with_put() assert str(s) == put_target def test_get_region (self): s = self.make_screen_with_put() r = s.get_region (4,4,7,9) assert r == get_region_target def test_cursor_save (self): s = self.make_screen_with_put() s.cursor_home (5,5) c = s.get() s.cursor_save() s.cursor_home() s.cursor_forward() s.cursor_down() s.cursor_unsave() assert s.cur_r == 5 and s.cur_c == 5 assert c == s.get() def test_scroll (self): s = self.make_screen_with_put() s.scroll_screen_rows (1,4) s.scroll_down(); s.scroll_down(); s.scroll_down() s.scroll_down(); s.scroll_down(); s.scroll_down() s.scroll_screen_rows (7,10) s.scroll_up(); s.scroll_up(); s.scroll_up() s.scroll_up(); s.scroll_up(); s.scroll_up() assert str(s) == scroll_target def test_insert (self): s = self.make_screen_with_put() s.insert_abs (10,1,'Z') s.insert_abs (1,1,'Z') s.insert_abs (1,1,'Z') s.insert_abs (1,1,'Z') s.insert_abs (1,1,'Z') s.insert_abs (1,1,'Z') s.insert_abs (10,1,'Z') s.insert_abs (1,1,'Z') s.insert_abs (1,1,'Z') s.insert_abs (5,1,'Z') s.insert_abs (6,6,'Z') s.cursor_home (1,1) # Also test relative insert. s.insert ('Z') s.insert ('Z') s.insert ('Z') s.insert ('Z') s.insert_abs (1,8,'X') s.insert_abs (1,2,'X') s.insert_abs (10,9,'Z') s.insert_abs (10,9,'Z') assert str(s) == insert_target def make_screen_with_box_unicode(self, *args, **kwargs): '''Creates a screen containing a box drawn using double-line line drawing characters. The characters are fed in as unicode. ''' s = screen.screen (2,2,*args,**kwargs) s.put_abs (1,1,u'\u2554') s.put_abs (1,2,u'\u2557') s.put_abs (2,1,u'\u255A') s.put_abs (2,2,u'\u255D') return s def make_screen_with_box_cp437(self, *args, **kwargs): '''Creates a screen containing a box drawn using double-line line drawing characters. The characters are fed in as CP437. ''' s = screen.screen (2,2,*args,**kwargs) s.put_abs (1,1,b'\xc9') s.put_abs (1,2,b'\xbb') s.put_abs (2,1,b'\xc8') s.put_abs (2,2,b'\xbc') return s def make_screen_with_box_utf8(self, *args, **kwargs): '''Creates a screen containing a box drawn using double-line line drawing characters. The characters are fed in as UTF-8. ''' s = screen.screen (2,2,*args,**kwargs) s.put_abs (1,1,b'\xe2\x95\x94') s.put_abs (1,2,b'\xe2\x95\x97') s.put_abs (2,1,b'\xe2\x95\x9a') s.put_abs (2,2,b'\xe2\x95\x9d') return s def test_unicode_ascii (self): # With the default encoding set to ASCII, we should still be # able to feed in unicode strings and get them back out: s = self.make_screen_with_box_unicode('ascii') if PY3: assert str(s) == unicode_box_unicode_result else: assert unicode(s) == unicode_box_unicode_result # And we should still get something for Python 2 str(), though # it might not be very useful str(s) assert s.pretty() == unicode_box_pretty_result def test_decoding_errors(self): # With strict error handling, it should reject bytes it can't decode with self.assertRaises(UnicodeDecodeError): self.make_screen_with_box_cp437('ascii', 'strict') # replace should turn them into unicode replacement characters, U+FFFD s = self.make_screen_with_box_cp437('ascii', 'replace') expected = u'\ufffd\ufffd\n\ufffd\ufffd' if PY3: assert str(s) == expected else: assert unicode(s) == expected def test_unicode_cp437 (self): # Verify decoding from and re-encoding to CP437. s = self.make_screen_with_box_cp437('cp437','strict') if PY3: assert str(s) == unicode_box_unicode_result else: assert unicode(s) == unicode_box_unicode_result assert str(s) == unicode_box_cp437_bytes_result assert s.pretty() == unicode_box_pretty_result def test_unicode_utf8 (self): # Verify decoding from and re-encoding to UTF-8. s = self.make_screen_with_box_utf8('utf-8','strict') if PY3: assert str(s) == unicode_box_unicode_result else: assert unicode(s) == unicode_box_unicode_result assert str(s) == unicode_box_utf8_bytes_result assert s.pretty() == unicode_box_pretty_result def test_no_bytes(self): s = screen.screen(2, 2, encoding=None) s.put_abs(1, 1, u'A') s.put_abs(2, 2, u'D') with self.assertRaises(TypeError): s.put_abs(1, 2, b'B') if PY3: assert str(s) == u'A \n D' else: assert unicode(s) == u'A \n D' # This will still work if it's limited to ascii assert str(s) == b'A \n D' if __name__ == '__main__': unittest.main() suite = unittest.TestLoader().loadTestsFromTestCase(screenTestCase)
screenTestCase
python
pyca__cryptography
tests/hazmat/primitives/test_sm4.py
{ "start": 1182, "end": 1686 }
class ____: test_cbc = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "SM4"), ["draft-ribose-cfrg-sm4-10-cbc.txt"], lambda key, **kwargs: algorithms.SM4(binascii.unhexlify(key)), lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.SM4(b"\x00" * 16), OFB(b"\x00" * 16) ), skip_message="Does not support SM4 OFB", )
TestSM4ModeCBC
python
tensorflow__tensorflow
tensorflow/python/tpu/tpu_embedding_v3_checkpoint_adapter.py
{ "start": 6056, "end": 9403 }
class ____(checkpoint_adapter.ReshardCallback): """Reshard callback for embeddings.""" def __init__( self, object_local_name: str, checkpoint_local_names: Sequence[str], to_shard_layout: Optional[ Sequence[sparse_core_layout_pb2.SparseCoreTableLayout] ] = None, to_unshard_layout: Optional[ Sequence[sparse_core_layout_pb2.SparseCoreTableLayout] ] = None, ): """Initializes Reshard callback. Args: object_local_name: The local name of the object being restored. checkpoint_local_names: The local names of the checkpoint positions that need to be read. to_shard_layout: (Optional) Target layouts as specified in the embedding being restored. to_unshard_layout: (Optional) Layouts as stored in checkpoint being restored from. """ self._object_local_name = object_local_name self._checkpoint_local_names = checkpoint_local_names self._to_shard_layout = to_shard_layout self._to_unshard_layout = to_unshard_layout self._main_checkpoint_name = checkpoint_local_names[0] def object_name(self) -> str: return self._object_local_name def update_restore_inputs( self, checkpoint_key: str, shape_and_slice_spec: str ) -> tuple[Sequence[str], Sequence[str]]: """Updates checkpoint key and slice spec acorrding to the resharding plan. Args: checkpoint_key: The input checkpoint key to be read. shape_and_slice_spec: The shape and slice spec of the checkpoint key to be read. Returns: A tuple of (keys, slices) that should be passed to restore_v2 inorder to reshard according to the resharding plan. The restored tensors from restore_v2 op will usually be passed to reshard method of this class to get the final resharded value. """ keys = [] slices = [] # TODO(b/398016624): Make this a vlog this log after bug is fixed. logging.info( "Updating restore v2 inputs for %s: %s", checkpoint_key, shape_and_slice_spec, ) for i, layout in enumerate(self._to_shard_layout): sub_checkpoint_key = checkpoint_key.replace( self._main_checkpoint_name, self._checkpoint_local_names[i] ) # For resharding later, we need to read the full value here. # TODO(b/398016624): Make this a vlog this log after bug is fixed. logging.info( "Will read sub key %s: %s", sub_checkpoint_key, layout.unsharded_shape, ) keys.append(sub_checkpoint_key) slices.append( _shard_info_str( layout.unsharded_shape, trackable_base.ShardInfo( offset=[0, 0], shape=layout.unsharded_shape ), ) ) return (keys, slices) def reshard( self, checkpoint_values: tensor.Tensor, shape_and_slice: str ) -> tensor.Tensor: """Reshards the checkpoint values according to the resharding plan. Args: checkpoint_values: The checkpoint values to be resharded. shape_and_slice: The shape and slice spec to be returned after resharding. Returns: The resharded tensor slice. """ return _shard_from_cpu_to_sc( checkpoint_values, shape_and_slice, self._to_shard_layout )
EmbeddingUnshardToShardCallback
python
django__django
tests/version/tests.py
{ "start": 242, "end": 2244 }
class ____(SimpleTestCase): def test_development(self): get_git_changeset.cache_clear() ver_tuple = (1, 4, 0, "alpha", 0) # This will return a different result when it's run within or outside # of a git clone: 1.4.devYYYYMMDDHHMMSS or 1.4. ver_string = get_version(ver_tuple) self.assertRegex(ver_string, r"1\.4(\.dev[0-9]+)?") @skipUnless( hasattr(django.utils.version, "__file__"), "test_development() checks the same when __file__ is already missing, " "e.g. in a frozen environments", ) def test_development_no_file(self): get_git_changeset.cache_clear() version_file = django.utils.version.__file__ try: del django.utils.version.__file__ self.test_development() finally: django.utils.version.__file__ = version_file def test_releases(self): tuples_to_strings = ( ((1, 4, 0, "alpha", 1), "1.4a1"), ((1, 4, 0, "beta", 1), "1.4b1"), ((1, 4, 0, "rc", 1), "1.4rc1"), ((1, 4, 0, "final", 0), "1.4"), ((1, 4, 1, "rc", 2), "1.4.1rc2"), ((1, 4, 1, "final", 0), "1.4.1"), ) for ver_tuple, ver_string in tuples_to_strings: self.assertEqual(get_version(ver_tuple), ver_string) def test_get_version_tuple(self): self.assertEqual(get_version_tuple("1.2.3"), (1, 2, 3)) self.assertEqual(get_version_tuple("1.2.3b2"), (1, 2, 3)) self.assertEqual(get_version_tuple("1.2.3b2.dev0"), (1, 2, 3)) def test_get_version_invalid_version(self): tests = [ # Invalid length. (3, 2, 0, "alpha", 1, "20210315111111"), # Invalid development status. (3, 2, 0, "gamma", 1, "20210315111111"), ] for version in tests: with self.subTest(version=version), self.assertRaises(AssertionError): get_complete_version(version)
VersionTests
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/functions.py
{ "start": 66583, "end": 67435 }
class ____(GenericFunction[_T]): r"""Implement the ``GROUPING SETS`` grouping operation. This function is used as part of the GROUP BY of a statement, e.g. :meth:`_expression.Select.group_by`:: stmt = select( func.sum(table.c.value), table.c.col_1, table.c.col_2 ).group_by(func.grouping_sets(table.c.col_1, table.c.col_2)) In order to group by multiple sets, use the :func:`.tuple_` construct:: from sqlalchemy import tuple_ stmt = select( func.sum(table.c.value), table.c.col_1, table.c.col_2, table.c.col_3 ).group_by( func.grouping_sets( tuple_(table.c.col_1, table.c.col_2), tuple_(table.c.value, table.c.col_3), ) ) """ # noqa: E501 _has_args = True inherit_cache = True
grouping_sets
python
EpistasisLab__tpot
tpot/builtin_modules/feature_encoding_frequency_selector.py
{ "start": 171, "end": 5179 }
class ____(SelectorMixin, BaseEstimator): """Feature selector based on Encoding Frequency. Encoding frequency is the frequency of each unique element(0/1/2/3) present in a feature set. Features are selected on the basis of a threshold assigned for encoding frequency. If frequency of any unique element is less than or equal to threshold, the feature is removed. """ @property def __name__(self): """Instance name is the same as the class name. """ return self.__class__.__name__ def __init__(self, threshold): """Create a FeatureEncodingFrequencySelector object. Parameters ---------- threshold : float, required Threshold value for allele frequency. If frequency of A or frequency of a is less than the threshold value then the feature is dropped. Returns ------- None """ self.threshold = threshold """def fit(self, X, y=None): Fit FeatureAlleleFrequencySelector for feature selection Parameters ---------- X : numpy ndarray, {n_samples, n_features} The training input samples. y : numpy array {n_samples,} The training target values. Returns ------- self : object Returns a copy of the estimator self.selected_feature_indexes = [] self.no_of_features = X.shape[1] # Finding the no of alleles in each feature column for i in range(0, X.shape[1]): no_of_AA_featurewise = np.count_nonzero(X[:,i]==0) no_of_Aa_featurewise = np.count_nonzero(X[:,i]==1) no_of_aa_featurewise = np.count_nonzero(X[:,i]==2) frequency_A_featurewise = (2*no_of_AA_featurewise + no_of_Aa_featurewise) / (2*no_of_AA_featurewise + 2*no_of_Aa_featurewise + 2*no_of_aa_featurewise) frequency_a_featurewise = 1 - frequency_A_featurewise if(not(frequency_A_featurewise <= self.threshold) and not(frequency_a_featurewise <= self.threshold)): self.selected_feature_indexes.append(i) return self""" """def transform(self, X): Make subset after fit Parameters ---------- X : numpy ndarray, {n_samples, n_features} New data, where n_samples is the number of samples and n_features is the number of features. Returns ------- X_transformed : numpy ndarray, {n_samples, n_features} The transformed feature set. X_transformed = X[:, self.selected_feature_indexes] return X_transformed""" def fit(self, X, y=None) : """Fit FeatureEncodingFrequencySelector for feature selection. This function gets the appropriate features. """ self.selected_feature_indexes = [] self.no_of_original_features = X.shape[1] # Finding the frequency of all the unique elements present featurewise in the input variable X for i in range(0, X.shape[1]): unique, counts = np.unique(X[:,i], return_counts=True) element_count_dict_featurewise = dict(zip(unique, counts)) element_frequency_dict_featurewise = {} feature_column_selected = True for x in unique: x_frequency_featurewise = element_count_dict_featurewise[x] / sum(counts) element_frequency_dict_featurewise[x] = x_frequency_featurewise for frequency in element_frequency_dict_featurewise.values(): if frequency <= self.threshold : feature_column_selected = False break if feature_column_selected == True : self.selected_feature_indexes.append(i) if not len(self.selected_feature_indexes): """msg = "No feature in X meets the encoding frequency threshold {0:.5f}" raise ValueError(msg.format(self.threshold))""" for i in range(0, X.shape[1]): self.selected_feature_indexes.append(i) return self def transform(self, X): """ Make subset after fit. This function returns a transformed version of X. """ X_transformed = X[:, self.selected_feature_indexes] return X_transformed def _get_support_mask(self): """ Get the boolean mask indicating which features are selected It is the abstractmethod Returns ------- support : boolean array of shape [# input features] An element is True iff its corresponding feature is selected for retention. """ n_features = self.no_of_original_features mask = np.zeros(n_features, dtype=bool) mask[np.asarray(self.selected_feature_indexes)] = True return mask
FeatureEncodingFrequencySelector
python
TheAlgorithms__Python
other/least_recently_used.py
{ "start": 124, "end": 2399 }
class ____[T]: """ Page Replacement Algorithm, Least Recently Used (LRU) Caching. >>> lru_cache: LRUCache[str | int] = LRUCache(4) >>> lru_cache.refer("A") >>> lru_cache.refer(2) >>> lru_cache.refer(3) >>> lru_cache LRUCache(4) => [3, 2, 'A'] >>> lru_cache.refer("A") >>> lru_cache LRUCache(4) => ['A', 3, 2] >>> lru_cache.refer(4) >>> lru_cache.refer(5) >>> lru_cache LRUCache(4) => [5, 4, 'A', 3] """ dq_store: deque[T] # Cache store of keys key_reference: set[T] # References of the keys in cache _MAX_CAPACITY: int = 10 # Maximum capacity of cache def __init__(self, n: int) -> None: """Creates an empty store and map for the keys. The LRUCache is set the size n. """ self.dq_store = deque() self.key_reference = set() if not n: LRUCache._MAX_CAPACITY = sys.maxsize elif n < 0: raise ValueError("n should be an integer greater than 0.") else: LRUCache._MAX_CAPACITY = n def refer(self, x: T) -> None: """ Looks for a page in the cache store and adds reference to the set. Remove the least recently used key if the store is full. Update store to reflect recent access. """ if x not in self.key_reference: if len(self.dq_store) == LRUCache._MAX_CAPACITY: last_element = self.dq_store.pop() self.key_reference.remove(last_element) else: self.dq_store.remove(x) self.dq_store.appendleft(x) self.key_reference.add(x) def display(self) -> None: """ Prints all the elements in the store. """ for k in self.dq_store: print(k) def __repr__(self) -> str: return f"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store)}" if __name__ == "__main__": import doctest doctest.testmod() lru_cache: LRUCache[str | int] = LRUCache(4) lru_cache.refer("A") lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer("A") lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
LRUCache
python
great-expectations__great_expectations
great_expectations/exceptions/exceptions.py
{ "start": 1648, "end": 1920 }
class ____(DataContextError): def __init__(self) -> None: super().__init__( "No Data Docs found. Please check that you have run a checkpoint, " "and that the checkpoint has a UpdateDataDocsAction in its actions." )
NoDataDocsError
python
PyCQA__pylint
tests/functional/u/useless/useless_object_inheritance.py
{ "start": 513, "end": 602 }
class ____(D, C, object, metaclass=abc.ABCMeta): # [useless-object-inheritance] pass
E
python
pandas-dev__pandas
pandas/tests/extension/decimal/array.py
{ "start": 797, "end": 1426 }
class ____(ExtensionDtype): type = decimal.Decimal name = "decimal" na_value = decimal.Decimal("NaN") _metadata = ("context",) def __init__(self, context=None) -> None: self.context = context or decimal.getcontext() def __repr__(self) -> str: return f"DecimalDtype(context={self.context})" def construct_array_type(self) -> type_t[DecimalArray]: """ Return the array type associated with this dtype. Returns ------- type """ return DecimalArray @property def _is_numeric(self) -> bool: return True
DecimalDtype
python
huggingface__transformers
src/transformers/models/gemma3/modeling_gemma3.py
{ "start": 6486, "end": 14197 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: Gemma3TextConfig, device=None, layer_type=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self.config = config self.layer_types = list(set(config.layer_types)) self.rope_type = {} for layer_type in self.layer_types: rope_params = self.config.rope_parameters[layer_type] if rope_params is None: continue self.rope_type[layer_type] = rope_params["rope_type"] rope_init_fn: Callable = self.compute_default_rope_parameters if self.rope_type[layer_type] != "default": rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type[layer_type]] curr_inv_freq, curr_attention_scaling = rope_init_fn(self.config, device, layer_type=layer_type) self.register_buffer(f"{layer_type}_inv_freq", curr_inv_freq, persistent=False) setattr(self, f"{layer_type}_original_inv_freq", curr_inv_freq) setattr(self, f"{layer_type}_attention_scaling", curr_attention_scaling) @staticmethod def compute_default_rope_parameters( config: Optional[Gemma3TextConfig] = None, device: Optional["torch.device"] = None, seq_len: Optional[int] = None, layer_type: Optional[str] = None, ) -> tuple["torch.Tensor", float]: """ Computes the inverse frequencies according to the original RoPE implementation Args: config ([`~transformers.PreTrainedConfig`]): The model configuration. device (`torch.device`): The device to use for initialization of the inverse frequencies. seq_len (`int`, *optional*): The current sequence length. Unused for this type of RoPE. layer_type (`str`, *optional*): The current layer type if the model has different RoPE parameters per type. Should not be used unless `config.layer_types is not None` Returns: Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). """ # For backward compatibility standardize the `rope_parameters_dict` if it uses old format base = config.rope_parameters[layer_type]["rope_theta"] dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads attention_factor = 1.0 # Unused in this type of RoPE # Compute the inverse frequencies inv_freq = 1.0 / ( base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim) ) return inv_freq, attention_factor @torch.no_grad() @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids, layer_type=None): inv_freq = getattr(self, f"{layer_type}_inv_freq") attention_scaling = getattr(self, f"{layer_type}_attention_scaling") inv_freq_expanded = inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device) position_ids_expanded = position_ids[:, None, :].float() device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with torch.autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) emb = torch.cat((freqs, freqs), dim=-1) cos = emb.cos() * attention_scaling sin = emb.sin() * attention_scaling return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) @use_kernel_func_from_hub("rotary_pos_emb") def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. position_ids (`torch.Tensor`, *optional*): Deprecated and unused. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) def eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: Optional[torch.Tensor], dropout: float = 0.0, scaling: Optional[float] = None, softcap: Optional[float] = None, **kwargs, ) -> tuple[torch.Tensor, torch.Tensor]: if scaling is None: scaling = module.head_dim**-0.5 key_states = repeat_kv(key, module.num_key_value_groups) value_states = repeat_kv(value, module.num_key_value_groups) attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling if softcap is not None: attn_weights = attn_weights / softcap attn_weights = torch.tanh(attn_weights) attn_weights = attn_weights * softcap if attention_mask is not None: # no matter the length, we just slice it causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] attn_weights = attn_weights + causal_mask # upcast attention to fp32 attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) attn_output = torch.matmul(attn_weights, value_states) attn_output = attn_output.transpose(1, 2).contiguous() return attn_output, attn_weights
Gemma3RotaryEmbedding
python
jina-ai__jina
jina/proto/docarray_v1/pb/jina_pb2_grpc.py
{ "start": 10588, "end": 11624 }
class ____(object): """* jina gRPC service to expose Endpoints from Executors. """ def endpoint_discovery(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_JinaDiscoverEndpointsRPCServicer_to_server(servicer, server): rpc_method_handlers = { 'endpoint_discovery': grpc.unary_unary_rpc_method_handler( servicer.endpoint_discovery, request_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, response_serializer=jina__pb2.EndpointsProto.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'jina.JinaDiscoverEndpointsRPC', rpc_method_handlers ) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API.
JinaDiscoverEndpointsRPCServicer
python
ray-project__ray
python/ray/train/v2/_internal/execution/callback.py
{ "start": 907, "end": 2937 }
class ____(RayTrainCallback): def before_init_train_context( self, workers: List["Worker"] ) -> Dict[str, List[Any]]: """Called before initializing the TrainContext for the worker_group. Return: A dictionary of additional arguments for TrainContext. The key is the argument name and the value is a list of argument values to pass to the TrainContext constructor of each worker in the worker group. """ return {} @contextmanager def on_worker_group_start(self): yield def before_worker_group_start(self, worker_group_context: "WorkerGroupContext"): """Called before the worker group actors are initialized.""" pass def after_worker_group_start(self, worker_group: "WorkerGroup"): """Called after the worker group actors are initialized. All workers should be ready to execute tasks.""" pass def after_worker_group_training_start(self, worker_group: "WorkerGroup"): pass @contextmanager def on_worker_group_shutdown(self): yield def before_worker_group_shutdown(self, worker_group: "WorkerGroup"): """Called before the worker group is shut down. Workers may be dead at this point due to actor failures, so this method should catch and handle exceptions if attempting to execute tasks.""" pass def after_worker_group_shutdown(self, worker_group_context: "WorkerGroupContext"): """Called after the worker group is shut down.""" pass def after_worker_group_poll_status( self, worker_group_status: "WorkerGroupPollStatus" ): pass def before_worker_group_abort(self, worker_group_context: "WorkerGroupContext"): """Called before the worker group is aborted.""" pass def after_worker_group_abort(self, worker_group_context: "WorkerGroupContext"): """Called after the worker group is aborted.""" pass @DeveloperAPI
WorkerGroupCallback
python
jina-ai__jina
tests/integration/docarray_v2/csp/SampleClipExecutor/executor.py
{ "start": 804, "end": 1362 }
class ____(Executor): @requests(on="/encode") def foo( self, docs: DocList[TextAndImageDoc], **kwargs ) -> DocList[EmbeddingResponseModel]: ret = [] for doc in docs: ret.append( EmbeddingResponseModel( id=doc.id, text=doc.text, url=doc.url, bytes=doc.bytes, embeddings=np.random.random((1, 64)), ) ) return DocList[EmbeddingResponseModel](ret)
SampleClipExecutor
python
ray-project__ray
rllib/algorithms/tests/test_algorithm_imports.py
{ "start": 83, "end": 423 }
class ____(unittest.TestCase): def setUp(self): ray.init() def tearDown(self): ray.shutdown() def test_algo_import(self): for name, func in ALGORITHMS.items(): func() if __name__ == "__main__": import sys import pytest sys.exit(pytest.main(["-v", __file__]))
TestAlgorithmImport
python
numba__llvmlite
llvmlite/ir/instructions.py
{ "start": 32672, "end": 33051 }
class ____(Instruction): """ A line comment. """ def __init__(self, parent, text): super(Comment, self).__init__(parent, types.VoidType(), ";", (), name='') assert "\n" not in text, "Comment cannot contain new line" self.text = text def descr(self, buf): buf.append(f"; {self.text}")
Comment
python
langchain-ai__langchain
libs/langchain/langchain_classic/chains/llm.py
{ "start": 1295, "end": 15353 }
class ____(Chain): """Chain to run queries against LLMs. This class is deprecated. See below for an example implementation using LangChain runnables: ```python from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import PromptTemplate from langchain_openai import OpenAI prompt_template = "Tell me a {adjective} joke" prompt = PromptTemplate(input_variables=["adjective"], template=prompt_template) model = OpenAI() chain = prompt | model | StrOutputParser() chain.invoke("your adjective here") ``` Example: ```python from langchain_classic.chains import LLMChain from langchain_openai import OpenAI from langchain_core.prompts import PromptTemplate prompt_template = "Tell me a {adjective} joke" prompt = PromptTemplate(input_variables=["adjective"], template=prompt_template) model = LLMChain(llm=OpenAI(), prompt=prompt) ``` """ @classmethod @override def is_lc_serializable(cls) -> bool: return True prompt: BasePromptTemplate """Prompt object to use.""" llm: Runnable[LanguageModelInput, str] | Runnable[LanguageModelInput, BaseMessage] """Language model to call.""" output_key: str = "text" output_parser: BaseLLMOutputParser = Field(default_factory=StrOutputParser) """Output parser to use. Defaults to one that takes the most likely string but does not change it otherwise.""" return_final_only: bool = True """Whether to return only the final parsed result. If `False`, will return a bunch of extra information about the generation.""" llm_kwargs: dict = Field(default_factory=dict) model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", ) @property def input_keys(self) -> list[str]: """Will be whatever keys the prompt expects.""" return self.prompt.input_variables @property def output_keys(self) -> list[str]: """Will always return text key.""" if self.return_final_only: return [self.output_key] return [self.output_key, "full_generation"] def _call( self, inputs: dict[str, Any], run_manager: CallbackManagerForChainRun | None = None, ) -> dict[str, str]: response = self.generate([inputs], run_manager=run_manager) return self.create_outputs(response)[0] def generate( self, input_list: list[dict[str, Any]], run_manager: CallbackManagerForChainRun | None = None, ) -> LLMResult: """Generate LLM result from inputs.""" prompts, stop = self.prep_prompts(input_list, run_manager=run_manager) callbacks = run_manager.get_child() if run_manager else None if isinstance(self.llm, BaseLanguageModel): return self.llm.generate_prompt( prompts, stop, callbacks=callbacks, **self.llm_kwargs, ) results = self.llm.bind(stop=stop, **self.llm_kwargs).batch( cast("list", prompts), {"callbacks": callbacks}, ) generations: list[list[Generation]] = [] for res in results: if isinstance(res, BaseMessage): generations.append([ChatGeneration(message=res)]) else: generations.append([Generation(text=res)]) return LLMResult(generations=generations) async def agenerate( self, input_list: list[dict[str, Any]], run_manager: AsyncCallbackManagerForChainRun | None = None, ) -> LLMResult: """Generate LLM result from inputs.""" prompts, stop = await self.aprep_prompts(input_list, run_manager=run_manager) callbacks = run_manager.get_child() if run_manager else None if isinstance(self.llm, BaseLanguageModel): return await self.llm.agenerate_prompt( prompts, stop, callbacks=callbacks, **self.llm_kwargs, ) results = await self.llm.bind(stop=stop, **self.llm_kwargs).abatch( cast("list", prompts), {"callbacks": callbacks}, ) generations: list[list[Generation]] = [] for res in results: if isinstance(res, BaseMessage): generations.append([ChatGeneration(message=res)]) else: generations.append([Generation(text=res)]) return LLMResult(generations=generations) def prep_prompts( self, input_list: list[dict[str, Any]], run_manager: CallbackManagerForChainRun | None = None, ) -> tuple[list[PromptValue], list[str] | None]: """Prepare prompts from inputs.""" stop = None if len(input_list) == 0: return [], stop if "stop" in input_list[0]: stop = input_list[0]["stop"] prompts = [] for inputs in input_list: selected_inputs = {k: inputs[k] for k in self.prompt.input_variables} prompt = self.prompt.format_prompt(**selected_inputs) _colored_text = get_colored_text(prompt.to_string(), "green") _text = "Prompt after formatting:\n" + _colored_text if run_manager: run_manager.on_text(_text, end="\n", verbose=self.verbose) if "stop" in inputs and inputs["stop"] != stop: msg = "If `stop` is present in any inputs, should be present in all." raise ValueError(msg) prompts.append(prompt) return prompts, stop async def aprep_prompts( self, input_list: list[dict[str, Any]], run_manager: AsyncCallbackManagerForChainRun | None = None, ) -> tuple[list[PromptValue], list[str] | None]: """Prepare prompts from inputs.""" stop = None if len(input_list) == 0: return [], stop if "stop" in input_list[0]: stop = input_list[0]["stop"] prompts = [] for inputs in input_list: selected_inputs = {k: inputs[k] for k in self.prompt.input_variables} prompt = self.prompt.format_prompt(**selected_inputs) _colored_text = get_colored_text(prompt.to_string(), "green") _text = "Prompt after formatting:\n" + _colored_text if run_manager: await run_manager.on_text(_text, end="\n", verbose=self.verbose) if "stop" in inputs and inputs["stop"] != stop: msg = "If `stop` is present in any inputs, should be present in all." raise ValueError(msg) prompts.append(prompt) return prompts, stop def apply( self, input_list: list[dict[str, Any]], callbacks: Callbacks = None, ) -> list[dict[str, str]]: """Utilize the LLM generate method for speed gains.""" callback_manager = CallbackManager.configure( callbacks, self.callbacks, self.verbose, ) run_manager = callback_manager.on_chain_start( None, {"input_list": input_list}, name=self.get_name(), ) try: response = self.generate(input_list, run_manager=run_manager) except BaseException as e: run_manager.on_chain_error(e) raise outputs = self.create_outputs(response) run_manager.on_chain_end({"outputs": outputs}) return outputs async def aapply( self, input_list: list[dict[str, Any]], callbacks: Callbacks = None, ) -> list[dict[str, str]]: """Utilize the LLM generate method for speed gains.""" callback_manager = AsyncCallbackManager.configure( callbacks, self.callbacks, self.verbose, ) run_manager = await callback_manager.on_chain_start( None, {"input_list": input_list}, name=self.get_name(), ) try: response = await self.agenerate(input_list, run_manager=run_manager) except BaseException as e: await run_manager.on_chain_error(e) raise outputs = self.create_outputs(response) await run_manager.on_chain_end({"outputs": outputs}) return outputs @property def _run_output_key(self) -> str: return self.output_key def create_outputs(self, llm_result: LLMResult) -> list[dict[str, Any]]: """Create outputs from response.""" result = [ # Get the text of the top generated string. { self.output_key: self.output_parser.parse_result(generation), "full_generation": generation, } for generation in llm_result.generations ] if self.return_final_only: result = [{self.output_key: r[self.output_key]} for r in result] return result async def _acall( self, inputs: dict[str, Any], run_manager: AsyncCallbackManagerForChainRun | None = None, ) -> dict[str, str]: response = await self.agenerate([inputs], run_manager=run_manager) return self.create_outputs(response)[0] def predict(self, callbacks: Callbacks = None, **kwargs: Any) -> str: """Format prompt with kwargs and pass to LLM. Args: callbacks: Callbacks to pass to LLMChain **kwargs: Keys to pass to prompt template. Returns: Completion from LLM. Example: ```python completion = llm.predict(adjective="funny") ``` """ return self(kwargs, callbacks=callbacks)[self.output_key] async def apredict(self, callbacks: Callbacks = None, **kwargs: Any) -> str: """Format prompt with kwargs and pass to LLM. Args: callbacks: Callbacks to pass to LLMChain **kwargs: Keys to pass to prompt template. Returns: Completion from LLM. Example: ```python completion = llm.predict(adjective="funny") ``` """ return (await self.acall(kwargs, callbacks=callbacks))[self.output_key] def predict_and_parse( self, callbacks: Callbacks = None, **kwargs: Any, ) -> str | list[str] | dict[str, Any]: """Call predict and then parse the results.""" warnings.warn( "The predict_and_parse method is deprecated, " "instead pass an output parser directly to LLMChain.", stacklevel=2, ) result = self.predict(callbacks=callbacks, **kwargs) if self.prompt.output_parser is not None: return self.prompt.output_parser.parse(result) return result async def apredict_and_parse( self, callbacks: Callbacks = None, **kwargs: Any, ) -> str | list[str] | dict[str, str]: """Call apredict and then parse the results.""" warnings.warn( "The apredict_and_parse method is deprecated, " "instead pass an output parser directly to LLMChain.", stacklevel=2, ) result = await self.apredict(callbacks=callbacks, **kwargs) if self.prompt.output_parser is not None: return self.prompt.output_parser.parse(result) return result def apply_and_parse( self, input_list: list[dict[str, Any]], callbacks: Callbacks = None, ) -> Sequence[str | list[str] | dict[str, str]]: """Call apply and then parse the results.""" warnings.warn( "The apply_and_parse method is deprecated, " "instead pass an output parser directly to LLMChain.", stacklevel=2, ) result = self.apply(input_list, callbacks=callbacks) return self._parse_generation(result) def _parse_generation( self, generation: list[dict[str, str]], ) -> Sequence[str | list[str] | dict[str, str]]: if self.prompt.output_parser is not None: return [ self.prompt.output_parser.parse(res[self.output_key]) for res in generation ] return generation async def aapply_and_parse( self, input_list: list[dict[str, Any]], callbacks: Callbacks = None, ) -> Sequence[str | list[str] | dict[str, str]]: """Call apply and then parse the results.""" warnings.warn( "The aapply_and_parse method is deprecated, " "instead pass an output parser directly to LLMChain.", stacklevel=2, ) result = await self.aapply(input_list, callbacks=callbacks) return self._parse_generation(result) @property def _chain_type(self) -> str: return "llm_chain" @classmethod def from_string(cls, llm: BaseLanguageModel, template: str) -> LLMChain: """Create LLMChain from LLM and template.""" prompt_template = PromptTemplate.from_template(template) return cls(llm=llm, prompt=prompt_template) def _get_num_tokens(self, text: str) -> int: return _get_language_model(self.llm).get_num_tokens(text) def _get_language_model(llm_like: Runnable) -> BaseLanguageModel: if isinstance(llm_like, BaseLanguageModel): return llm_like if isinstance(llm_like, RunnableBinding): return _get_language_model(llm_like.bound) if isinstance(llm_like, RunnableWithFallbacks): return _get_language_model(llm_like.runnable) if isinstance(llm_like, (RunnableBranch, DynamicRunnable)): return _get_language_model(llm_like.default) msg = ( f"Unable to extract BaseLanguageModel from llm_like object of type " f"{type(llm_like)}" ) raise ValueError(msg)
LLMChain
python
spack__spack
lib/spack/spack/vendor/jinja2/nodes.py
{ "start": 28768, "end": 29049 }
class ____(BinExpr): """Short circuited AND.""" operator = "and" def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any: eval_ctx = get_eval_context(self, eval_ctx) return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
And
python
facebook__pyre-check
client/commands/launch_and_subscribe_handler.py
{ "start": 1176, "end": 1332 }
class ____(abc.ABC): @abc.abstractmethod def parse_response(self, response: str) -> subscription.Response: pass
PyreSubscriptionResponseParser
python
GoogleCloudPlatform__python-docs-samples
appengine/standard_python3/bundled-services/blobstore/flask/main.py
{ "start": 994, "end": 1259 }
class ____(blobstore.BlobstoreUploadHandler): def post(self): upload = self.get_uploads(request.environ)[0] photo = PhotoUpload(blob_key=upload.key()) photo.put() return redirect("/view_photo/%s" % upload.key())
PhotoUploadHandler
python
sympy__sympy
sympy/physics/quantum/grover.py
{ "start": 2091, "end": 6055 }
class ____(Gate): """A black box gate. The gate marks the desired qubits of an unknown function by flipping the sign of the qubits. The unknown function returns true when it finds its desired qubits and false otherwise. Parameters ========== qubits : int Number of qubits. oracle : callable A callable function that returns a boolean on a computational basis. Examples ======== Apply an Oracle gate that flips the sign of ``|2>`` on different qubits:: >>> from sympy.physics.quantum.qubit import IntQubit >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.grover import OracleGate >>> f = lambda qubits: qubits == IntQubit(2) >>> v = OracleGate(2, f) >>> qapply(v*IntQubit(2)) -|2> >>> qapply(v*IntQubit(3)) |3> """ gate_name = 'V' gate_name_latex = 'V' #------------------------------------------------------------------------- # Initialization/creation #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): if len(args) != 2: raise QuantumError( 'Insufficient/excessive arguments to Oracle. Please ' + 'supply the number of qubits and an unknown function.' ) sub_args = (args[0],) sub_args = UnitaryOperator._eval_args(sub_args) if not sub_args[0].is_Integer: raise TypeError('Integer expected, got: %r' % sub_args[0]) function = args[1] if not isinstance(function, OracleGateFunction): function = OracleGateFunction(function) return (sub_args[0], function) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**args[0] #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def search_function(self): """The unknown function that helps find the sought after qubits.""" return self.label[1] @property def targets(self): """A tuple of target qubits.""" return sympify(tuple(range(self.args[0]))) #------------------------------------------------------------------------- # Apply #------------------------------------------------------------------------- def _apply_operator_Qubit(self, qubits, **options): """Apply this operator to a Qubit subclass. Parameters ========== qubits : Qubit The qubit subclass to apply this operator to. Returns ======= state : Expr The resulting quantum state. """ if qubits.nqubits != self.nqubits: raise QuantumError( 'OracleGate operates on %r qubits, got: %r' % (self.nqubits, qubits.nqubits) ) # If function returns 1 on qubits # return the negative of the qubits (flip the sign) if self.search_function(qubits): return -qubits else: return qubits #------------------------------------------------------------------------- # Represent #------------------------------------------------------------------------- def _represent_ZGate(self, basis, **options): """ Represent the OracleGate in the computational basis. """ nbasis = 2**self.nqubits # compute it only once matrixOracle = eye(nbasis) # Flip the sign given the output of the oracle function for i in range(nbasis): if self.search_function(IntQubit(i, nqubits=self.nqubits)): matrixOracle[i, i] = NegativeOne() return matrixOracle
OracleGate
python
wandb__wandb
wandb/automations/events.py
{ "start": 5358, "end": 6140 }
class ____(GQLBase): # from: TriggeringRunStateEvent run: Annotated[ JsonEncoded[MongoLikeFilter], AfterValidator(wrap_run_event_run_filter), Field(alias="run_filter"), ] = And() """Filters that must match any runs that will trigger this event.""" state: Annotated[StateFilter, Field(alias="run_state_filter")] """Run state condition(s) that must be satisfied for this event to trigger.""" @model_validator(mode="before") @classmethod def _nest_state_filter(cls, v: Any) -> Any: # If no run filter is given, automatically nest the state filter and # let inner validators reshape further as needed. if pydantic_isinstance(v, StateFilter): return cls(state=v) return v
RunStateFilter
python
PrefectHQ__prefect
src/integrations/prefect-bitbucket/prefect_bitbucket/credentials.py
{ "start": 787, "end": 6369 }
class ____(CredentialsBlock): """Store BitBucket credentials to interact with private BitBucket repositories. Attributes: token: An access token to authenticate with BitBucket. This is required for accessing private repositories. username: Identification name unique across entire BitBucket site. password: The password to authenticate to BitBucket. url: The base URL of your BitBucket instance. Examples: Load stored BitBucket credentials: ```python from prefect_bitbucket import BitBucketCredentials bitbucket_credentials_block = BitBucketCredentials.load("BLOCK_NAME") ``` """ _block_type_name = "BitBucket Credentials" _logo_url = "https://cdn.sanity.io/images/3ugk85nk/production/5d729f7355fb6828c4b605268ded9cfafab3ae4f-250x250.png" # noqa token: Optional[SecretStr] = Field( title="Personal Access Token", default=None, description=( "A BitBucket Personal Access Token - required for private repositories." ), examples=["x-token-auth:my-token"], ) username: Optional[str] = Field( default=None, description="Identification name unique across entire BitBucket site.", ) password: Optional[SecretStr] = Field( default=None, description="The password to authenticate to BitBucket." ) url: Optional[str] = Field( default=None, description="The base URL of a BitBucket instance. Leave blank for BitBucket Cloud.", examples=["https://api.bitbucket.org/"], title="URL", ) @field_validator("username") def _validate_username(cls, value: str) -> str: """Allow common special characters used in Bitbucket usernames, such as email addresses.""" pattern = r"^[A-Za-z0-9@._+-]+$" if not re.match(pattern, value): raise ValueError( "Username contains invalid characters. Allowed: letters, numbers, @ . _ + -" ) if len(value) > 100: raise ValueError("Username cannot be longer than 100 characters.") return value def format_git_credentials(self, url: str) -> str: """ Format and return the full git URL with BitBucket credentials embedded. BitBucket has different authentication formats: - BitBucket Server: username:token format required - BitBucket Cloud: x-token-auth:token prefix - Self-hosted instances: If username is provided, username:token format is used regardless of hostname (supports instances without 'bitbucketserver' in URL) Args: url: Repository URL (e.g., "https://bitbucket.org/org/repo.git") Returns: Complete URL with credentials embedded Raises: ValueError: If credentials are not properly configured """ parsed = urlparse(url) # Get the token (prefer token field, fall back to password) token_value: Optional[str] = None if self.token: token_value = self.token.get_secret_value() elif self.password: token_value = self.password.get_secret_value() if not token_value: raise ValueError( "Token or password is required for BitBucket authentication" ) # BitBucket Server requires username:token format if "bitbucketserver" in parsed.netloc: if not self.username: raise ValueError( "Username is required for BitBucket Server authentication" ) credentials = ( f"{_quote_credential(self.username)}:{_quote_credential(token_value)}" ) # If username is provided, use username:password auth # This supports self-hosted BitBucket Server instances that don't have # 'bitbucketserver' in their hostname elif self.username: credentials = ( f"{_quote_credential(self.username)}:{_quote_credential(token_value)}" ) # BitBucket Cloud uses x-token-auth: prefix # If token already has a colon or prefix, use as-is elif ":" in token_value: # Split and encode each part separately parts = token_value.split(":", 1) credentials = f"{_quote_credential(parts[0])}:{_quote_credential(parts[1])}" else: credentials = f"x-token-auth:{_quote_credential(token_value)}" # Insert credentials into URL return urlunparse(parsed._replace(netloc=f"{credentials}@{parsed.netloc}")) def get_client( self, client_type: Union[str, ClientType], **client_kwargs ) -> Union[Cloud, Bitbucket]: """Get an authenticated local or cloud Bitbucket client. Args: client_type: Whether to use a local or cloud client. Returns: An authenticated Bitbucket client. """ # ref: https://atlassian-python-api.readthedocs.io/ if isinstance(client_type, str): client_type = ClientType(client_type.lower()) password = self.password.get_secret_value() input_client_kwargs = dict( url=self.url, username=self.username, password=password ) input_client_kwargs.update(**client_kwargs) if client_type == ClientType.CLOUD: client = Cloud(**input_client_kwargs) else: client = Bitbucket(**input_client_kwargs) return client
BitBucketCredentials
python
google__pytype
pytype/errors/errors.py
{ "start": 4907, "end": 5246 }
class ____: """Represents a position in an error log.""" def __init__(self, errors): self._errorlog_errors = errors self._position = len(errors) self.errors = None def revert(self): self.errors = self._errorlog_errors[self._position :] self._errorlog_errors[:] = self._errorlog_errors[: self._position]
CheckPoint
python
PrefectHQ__prefect
src/prefect/server/services/foreman.py
{ "start": 1200, "end": 10006 }
class ____(LoopService): """ Monitors the status of workers and their associated work pools """ @classmethod def service_settings(cls) -> ServicesBaseSetting: return get_current_settings().server.services.foreman def __init__( self, loop_seconds: Optional[float] = None, inactivity_heartbeat_multiple: Optional[int] = None, fallback_heartbeat_interval_seconds: Optional[int] = None, deployment_last_polled_timeout_seconds: Optional[int] = None, work_queue_last_polled_timeout_seconds: Optional[int] = None, **kwargs: Any, ): super().__init__( loop_seconds=loop_seconds or PREFECT_API_SERVICES_FOREMAN_LOOP_SECONDS.value(), **kwargs, ) self._inactivity_heartbeat_multiple = ( PREFECT_API_SERVICES_FOREMAN_INACTIVITY_HEARTBEAT_MULTIPLE.value() if inactivity_heartbeat_multiple is None else inactivity_heartbeat_multiple ) self._fallback_heartbeat_interval_seconds = ( PREFECT_API_SERVICES_FOREMAN_FALLBACK_HEARTBEAT_INTERVAL_SECONDS.value() if fallback_heartbeat_interval_seconds is None else fallback_heartbeat_interval_seconds ) self._deployment_last_polled_timeout_seconds = ( PREFECT_API_SERVICES_FOREMAN_DEPLOYMENT_LAST_POLLED_TIMEOUT_SECONDS.value() if deployment_last_polled_timeout_seconds is None else deployment_last_polled_timeout_seconds ) self._work_queue_last_polled_timeout_seconds = ( PREFECT_API_SERVICES_FOREMAN_WORK_QUEUE_LAST_POLLED_TIMEOUT_SECONDS.value() if work_queue_last_polled_timeout_seconds is None else work_queue_last_polled_timeout_seconds ) @db_injector async def run_once(self, db: PrefectDBInterface) -> None: """ Iterate over workers current marked as online. Mark workers as offline if they have an old last_heartbeat_time. Marks work pools as not ready if they do not have any online workers and are currently marked as ready. Mark deployments as not ready if they have a last_polled time that is older than the configured deployment last polled timeout. """ await self._mark_online_workers_without_a_recent_heartbeat_as_offline() await self._mark_work_pools_as_not_ready() await self._mark_deployments_as_not_ready() await self._mark_work_queues_as_not_ready() @db_injector async def _mark_online_workers_without_a_recent_heartbeat_as_offline( self, db: PrefectDBInterface ) -> None: """ Updates the status of workers that have an old last heartbeat time to OFFLINE. An old heartbeat last heartbeat that is one more than their heartbeat interval multiplied by the INACTIVITY_HEARTBEAT_MULTIPLE seconds ago. Args: session (AsyncSession): The session to use for the database operation. """ async with db.session_context(begin_transaction=True) as session: worker_update_stmt = ( sa.update(db.Worker) .values(status=WorkerStatus.OFFLINE) .where( sa.func.date_diff_seconds(db.Worker.last_heartbeat_time) > ( sa.func.coalesce( db.Worker.heartbeat_interval_seconds, sa.bindparam("default_interval", sa.Integer), ) * sa.bindparam("multiplier", sa.Integer) ), db.Worker.status == WorkerStatus.ONLINE, ) ) result = await session.execute( worker_update_stmt, { "multiplier": self._inactivity_heartbeat_multiple, "default_interval": self._fallback_heartbeat_interval_seconds, }, ) if result.rowcount: self.logger.info(f"Marked {result.rowcount} workers as offline.") @db_injector async def _mark_work_pools_as_not_ready(self, db: PrefectDBInterface): """ Marks a work pool as not ready. Emits and event and updates any bookkeeping fields on the work pool. Args: work_pool (db.WorkPool): The work pool to mark as not ready. """ async with db.session_context(begin_transaction=True) as session: work_pools_select_stmt = ( sa.select(db.WorkPool) .filter(db.WorkPool.status == "READY") .outerjoin( db.Worker, sa.and_( db.Worker.work_pool_id == db.WorkPool.id, db.Worker.status == "ONLINE", ), ) .group_by(db.WorkPool.id) .having(sa.func.count(db.Worker.id) == 0) ) result = await session.execute(work_pools_select_stmt) work_pools = result.scalars().all() for work_pool in work_pools: await models.workers.update_work_pool( session=session, work_pool_id=work_pool.id, work_pool=InternalWorkPoolUpdate(status=WorkPoolStatus.NOT_READY), emit_status_change=emit_work_pool_status_event, ) self.logger.info(f"Marked work pool {work_pool.id} as NOT_READY.") @db_injector async def _mark_deployments_as_not_ready(self, db: PrefectDBInterface) -> None: """ Marks a deployment as NOT_READY and emits a deployment status event. Emits an event and updates any bookkeeping fields on the deployment. Args: session (AsyncSession): The session to use for the database operation. """ async with db.session_context(begin_transaction=True) as session: status_timeout_threshold = now("UTC") - timedelta( seconds=self._deployment_last_polled_timeout_seconds ) deployment_id_select_stmt = ( sa.select(db.Deployment.id) .outerjoin(db.WorkQueue, db.WorkQueue.id == db.Deployment.work_queue_id) .filter(db.Deployment.status == DeploymentStatus.READY) .filter(db.Deployment.last_polled.isnot(None)) .filter( sa.or_( # if work_queue.last_polled doesn't exist, use only deployment's # last_polled sa.and_( db.WorkQueue.last_polled.is_(None), db.Deployment.last_polled < status_timeout_threshold, ), # if work_queue.last_polled exists, both times should be less than # the threshold sa.and_( db.WorkQueue.last_polled.isnot(None), db.Deployment.last_polled < status_timeout_threshold, db.WorkQueue.last_polled < status_timeout_threshold, ), ) ) ) result = await session.execute(deployment_id_select_stmt) deployment_ids_to_mark_unready = result.scalars().all() await mark_deployments_not_ready( deployment_ids=deployment_ids_to_mark_unready, ) @db_injector async def _mark_work_queues_as_not_ready(self, db: PrefectDBInterface): """ Marks work queues as NOT_READY based on their last_polled field. Args: session (AsyncSession): The session to use for the database operation. """ async with db.session_context(begin_transaction=True) as session: status_timeout_threshold = now("UTC") - timedelta( seconds=self._work_queue_last_polled_timeout_seconds ) id_select_stmt = ( sa.select(db.WorkQueue.id) .outerjoin(db.WorkPool, db.WorkPool.id == db.WorkQueue.work_pool_id) .filter(db.WorkQueue.status == "READY") .filter(db.WorkQueue.last_polled.isnot(None)) .filter(db.WorkQueue.last_polled < status_timeout_threshold) .order_by(db.WorkQueue.last_polled.asc()) ) result = await session.execute(id_select_stmt) unready_work_queue_ids = result.scalars().all() await mark_work_queues_not_ready( work_queue_ids=unready_work_queue_ids, )
Foreman
python
xlwings__xlwings
xlwings/conversion/standard.py
{ "start": 8629, "end": 8897 }
class ____(Converter): @classmethod def read_value(cls, value, options): return xlserial_to_datetime(value) @classmethod def write_value(cls, value, options): return value DatetimeConverter.register(datetime.datetime)
DatetimeConverter
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 80783, "end": 82346 }
class ____(unittest.TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.interface = "vcan0" def testCrucialConstants(self): socket.AF_CAN socket.PF_CAN socket.CAN_ISOTP socket.SOCK_DGRAM def testCreateSocket(self): with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: pass @unittest.skipUnless(hasattr(socket, "CAN_ISOTP"), 'socket.CAN_ISOTP required for this test.') def testCreateISOTPSocket(self): with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_ISOTP) as s: pass def testTooLongInterfaceName(self): # most systems limit IFNAMSIZ to 16, take 1024 to be sure with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_ISOTP) as s: with self.assertRaisesRegex(OSError, 'interface name too long'): s.bind(('x' * 1024, 1, 2)) def testBind(self): try: with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_ISOTP) as s: addr = self.interface, 0x123, 0x456 s.bind(addr) self.assertEqual(s.getsockname(), addr) except OSError as e: if e.errno == errno.ENODEV: self.skipTest('network interface `%s` does not exist' % self.interface) else: raise @unittest.skipUnless(HAVE_SOCKET_CAN_J1939, 'CAN J1939 required for this test.')
ISOTPTest
python
davidhalter__jedi
test/completion/decorators.py
{ "start": 1881, "end": 2762 }
class ____(): """Init decorator problem as an instance, #247""" @Decorator def __init__(self): """ __init__ decorators should be ignored when looking up variables in the class. """ self.c = list @Decorator def shouldnt_expose_var(not_self): """ Even though in real Python this shouldn't expose the variable, in this case Jedi exposes the variable, because these kind of decorators are normally descriptors, which SHOULD be exposed (at least 90%). """ not_self.b = 1.0 def other_method(self): #? float() self.b #? list self.c # ----------------- # not found decorators (are just ignored) # ----------------- @not_found_decorator def just_a_func(): return 1 #? int() just_a_func() #? ['__closure__'] just_a_func.__closure__
SelfVars
python
walkccc__LeetCode
solutions/679. 24 Game/679.py
{ "start": 0, "end": 740 }
class ____: def judgePoint24(self, nums: list[int]) -> bool: def generate(a: float, b: float) -> list[float]: return [a * b, math.inf if b == 0 else a / b, math.inf if a == 0 else b / a, a + b, a - b, b - a] def dfs(nums: list[float]) -> bool: if len(nums) == 1: return abs(nums[0] - 24.0) < 0.001 for i, j in itertools.combinations(range(len(nums)), 2): for num in generate(nums[i], nums[j]): nextRound = [num] for k in range(len(nums)): if k == i or k == j: continue nextRound.append(nums[k]) if dfs(nextRound): return True return False return dfs(nums)
Solution
python
pytorch__pytorch
torch/_inductor/pattern_matcher.py
{ "start": 30717, "end": 33304 }
class ____(PatternExpr): outputs: list[Optional[PatternExpr]] def __init__(self, outputs: Sequence[Optional[PatternExpr]]) -> None: super().__init__() assert isinstance(outputs[0], _TargetExpr) assert all(x is None or isinstance(x, PatternExpr) for x in outputs), outputs self.outputs = list(outputs) self.op = outputs[0].op @property def fns(self) -> Union[Callable[..., Any], str, Sequence[Any]]: # This cast is checked above in __init__() output = typing.cast(_TargetExpr, self.outputs[0]) return output.fns def __repr__(self) -> str: return f"{self.__class__.__name__}({self.outputs})" def pretty_print(self, pp: PatternPrettyPrinter) -> str: args = [pp.pretty_print(x) for x in self.outputs] joiner_str = f",\n{' '}" str_out = f"{self.__class__.__name__}([{joiner_str.join(args)}" str_out = f"{str_out}\n])" return str_out def _match(self, node: torch.fx.Node, ctx: MatchContext) -> MatchResult: output = typing.cast(_TargetExpr, self.outputs[0]) m = ctx.match(output, node) if not is_match(m): return m for pattern in self.outputs[1:]: if pattern is None: continue child_match = self._match_from_anchors(pattern, ctx) if not is_match(child_match): return child_match m.extend(child_match) return m def _match_from_anchors( self, pattern: PatternExpr, ctx: MatchContext ) -> MatchResult: prior = dict(ctx.pattern_to_node) m: MatchResult = FailedMatch("no anchor found") for node in pattern.find_anchor_nodes(ctx, OrderedSet()): m = ctx.match(pattern, node) if is_match(m): return m # revert any partial matches ctx.pattern_to_node = dict(prior) return m def match(self, node: torch.fx.Node) -> MatchResult: try: return MatchContext(self.outputs, graph=node.graph).match(self, node) except FailedMatch as e: return e def pattern_eq(self, other: Any) -> bool: other = typing.cast(Self, other) # super makes sure this is true return ( super().pattern_eq(other) and len(self.outputs) == len(other.outputs) and all( a.pattern_eq(b) if isinstance(a, PatternExpr) else a == b for a, b in zip(self.outputs, other.outputs) ) )
MultiOutputPattern
python
allegroai__clearml
clearml/backend_api/services/v2_13/queues.py
{ "start": 16232, "end": 18824 }
class ____(Request): """ Add or update queue metadata :param queue: ID of the queue :type queue: str :param metadata: Metadata items to add or update :type metadata: Metadata """ _service = "queues" _action = "add_or_update_metadata" _version = "2.13" _schema = { "definitions": { "metadata_item": { "properties": { "key": { "description": "The key uniquely identifying the metadata item inside the given entity", "type": "string", }, "type": { "description": "The type of the metadata item", "type": "string", }, "value": { "description": "The value stored in the metadata item", "type": "string", }, }, "type": "object", } }, "properties": { "metadata": { "type": "array", "items": {"$ref": "#/definitions/metadata_item"}, "description": "Queue metadata", }, "queue": {"description": "ID of the queue", "type": "string"}, }, "required": ["queue", "metadata"], "type": "object", } def __init__(self, queue: str, metadata: List[Any], **kwargs: Any) -> None: super(AddOrUpdateMetadataRequest, self).__init__(**kwargs) self.queue = queue self.metadata = metadata @schema_property("queue") def queue(self) -> str: return self._property_queue @queue.setter def queue(self, value: str) -> None: if value is None: self._property_queue = None return self.assert_isinstance(value, "queue", six.string_types) self._property_queue = value @schema_property("metadata") def metadata(self) -> List[Any]: return self._property_metadata @metadata.setter def metadata(self, value: List[Any]) -> None: if value is None: self._property_metadata = None return self.assert_isinstance(value, "metadata", (list, tuple)) if any((isinstance(v, dict) for v in value)): value = [MetadataItem.from_dict(v) if isinstance(v, dict) else v for v in value] else: self.assert_isinstance(value, "metadata", MetadataItem, is_array=True) self._property_metadata = value
AddOrUpdateMetadataRequest
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/rich/traceback.py
{ "start": 6768, "end": 6878 }
class ____: offset: int filename: str line: str lineno: int msg: str @dataclass
_SyntaxError
python
kubernetes-client__python
kubernetes/client/models/v1_flow_schema_status.py
{ "start": 383, "end": 3672 }
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 = { 'conditions': 'list[V1FlowSchemaCondition]' } attribute_map = { 'conditions': 'conditions' } def __init__(self, conditions=None, local_vars_configuration=None): # noqa: E501 """V1FlowSchemaStatus - 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._conditions = None self.discriminator = None if conditions is not None: self.conditions = conditions @property def conditions(self): """Gets the conditions of this V1FlowSchemaStatus. # noqa: E501 `conditions` is a list of the current states of FlowSchema. # noqa: E501 :return: The conditions of this V1FlowSchemaStatus. # noqa: E501 :rtype: list[V1FlowSchemaCondition] """ return self._conditions @conditions.setter def conditions(self, conditions): """Sets the conditions of this V1FlowSchemaStatus. `conditions` is a list of the current states of FlowSchema. # noqa: E501 :param conditions: The conditions of this V1FlowSchemaStatus. # noqa: E501 :type: list[V1FlowSchemaCondition] """ self._conditions = conditions 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, V1FlowSchemaStatus): 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, V1FlowSchemaStatus): return True return self.to_dict() != other.to_dict()
V1FlowSchemaStatus
python
ray-project__ray
python/ray/data/expressions.py
{ "start": 19381, "end": 20631 }
class ____(Expr): """Expression that represents a binary operation between two expressions. This expression type represents an operation with two operands (left and right). The operation is specified by the `op` field, which must be one of the supported operations from the Operation enum. Args: op: The operation to perform (from Operation enum) left: The left operand expression right: The right operand expression Example: >>> from ray.data.expressions import col, lit, Operation >>> # Manually create a binary expression (usually done via operators) >>> expr = BinaryExpr(Operation.ADD, col("x"), lit(5)) >>> # This is equivalent to: col("x") + lit(5) """ op: Operation left: Expr right: Expr data_type: DataType = field(default_factory=lambda: DataType(object), init=False) def structurally_equals(self, other: Any) -> bool: return ( isinstance(other, BinaryExpr) and self.op is other.op and self.left.structurally_equals(other.left) and self.right.structurally_equals(other.right) ) @DeveloperAPI(stability="alpha") @dataclass(frozen=True, eq=False, repr=False)
BinaryExpr
python
cherrypy__cherrypy
cherrypy/_cpwsgi.py
{ "start": 4017, "end": 5966 }
class ____(object): """WSGI middleware that handles raised cherrypy.InternalRedirect.""" def __init__(self, nextapp, recursive=False): """Initialize an internal redirector.""" self.nextapp = nextapp self.recursive = recursive def __call__(self, environ, start_response): """Process internal WSGI request redirects.""" redirections = [] while True: environ = environ.copy() try: return self.nextapp(environ, start_response) except _cherrypy.InternalRedirect: ir = _sys.exc_info()[1] sn = environ.get('SCRIPT_NAME', '') path = environ.get('PATH_INFO', '') qs = environ.get('QUERY_STRING', '') # Add the *previous* path_info + qs to redirections. old_uri = sn + path if qs: old_uri += '?' + qs redirections.append(old_uri) if not self.recursive: # Check to see if the new URI has been redirected to # already new_uri = sn + ir.path if ir.query_string: new_uri += '?' + ir.query_string if new_uri in redirections: ir.request.close() tmpl = ( 'InternalRedirector visited the same URL twice: %r' ) raise RuntimeError(tmpl % new_uri) # Munge the environment and try again. environ['REQUEST_METHOD'] = 'GET' environ['PATH_INFO'] = ir.path environ['QUERY_STRING'] = ir.query_string environ['wsgi.input'] = io.BytesIO() environ['CONTENT_LENGTH'] = '0' environ['cherrypy.previous_request'] = ir.request
InternalRedirector
python
jschneier__django-storages
storages/backends/azure_storage.py
{ "start": 995, "end": 3633 }
class ____(File): def __init__(self, name, mode, storage): self.name = name self._mode = mode self._storage = storage self._is_dirty = False self._file = None self._path = storage._get_valid_path(name) def _get_file(self): if self._file is not None: return self._file file = SpooledTemporaryFile( max_size=self._storage.max_memory_size, suffix=".AzureStorageFile", dir=setting("FILE_UPLOAD_TEMP_DIR", None), ) if "r" in self._mode or "a" in self._mode: download_stream = self._storage.client.download_blob( self._path, timeout=self._storage.timeout ) download_stream.readinto(file) if "r" in self._mode: file.seek(0) self._file = file return self._file def _set_file(self, value): self._file = value file = property(_get_file, _set_file) def read(self, *args, **kwargs): if "r" not in self._mode and "a" not in self._mode: raise AttributeError("File was not opened in read mode.") return super().read(*args, **kwargs) def write(self, content): if "w" not in self._mode and "+" not in self._mode and "a" not in self._mode: raise AttributeError("File was not opened in write mode.") self._is_dirty = True return super().write(to_bytes(content)) def close(self): if self._file is None: return if self._is_dirty: self._file.seek(0) self._storage._save(self.name, self._file) self._is_dirty = False self._file.close() self._file = None def _content_type(content): try: return content.file.content_type except AttributeError: pass try: return content.content_type except AttributeError: pass return None def _get_valid_path(s): # A blob name: # * must not end with dot or slash # * can contain any character # * must escape URL reserved characters # (not needed here since the azure client will do that) s = s.strip("./") if len(s) > _AZURE_NAME_MAX_LEN: raise ValueError("File name max len is %d" % _AZURE_NAME_MAX_LEN) if not len(s): raise ValueError("File name must contain one or more printable characters") if s.count("/") > 256: raise ValueError("File name must not contain more than 256 slashes") return s # Max len according to azure's docs _AZURE_NAME_MAX_LEN = 1024 @deconstructible
AzureStorageFile
python
pytorch__pytorch
torch/distributed/elastic/multiprocessing/errors/__init__.py
{ "start": 3791, "end": 7798 }
class ____: """ Represent the failed process result. When the worker process fails, it may record failure root cause into the file. Tries to read the failure timestamp from the provided ``error_file``, if the ``error_file`` does not exist, the timestamp is the current timestamp (seconds since epoch). The ``message`` field is a concise explanation of the failure. If the error file exists then the message is obtained from the error file. Otherwise one is generated based on the failure signature. .. note:: It is assumed that the ``error_file`` is written by ``torch.distributed.elastic.multiprocessing.errors.error_handler.ErrorHandler``. Otherwise the behavior is undefined. """ local_rank: int pid: int exitcode: int error_file: str error_file_data: JSON = field(init=False) message: str = field(init=False) timestamp: int = field(init=False) def __post_init__(self): self.error_file_data = _EMPTY_ERROR_DATA if os.path.isfile(self.error_file): try: with open(self.error_file) as fp: self.error_file_data = json.load(fp) logger.debug( "User process failed with error data: %s", json.dumps(self.error_file_data, indent=2), ) self.message, self.timestamp = self._get_error_data( self.error_file_data ) except Exception: logger.exception("Failed to parse reply file: %s", self.error_file) raise else: self._set_no_reply_file() # make up an informative message if not already present if not self.message: # signals typically do not generate an error file message if self.exitcode < 0: self.message = ( f"Signal {-self.exitcode} ({self.signal_name()})" f" received by PID {self.pid}" ) else: self.error_file_data["errorTraits"] = { "category": "system_terminated_error", "retryability": "False", } self.message = "To enable traceback see: https://pytorch.org/docs/stable/elastic/errors.html" def _get_error_data(self, error_file_data: dict[str, Any]) -> tuple[str, int]: message = error_file_data["message"] if isinstance(message, str): timestamp = int(error_file_data.get("timestamp", 0)) else: timestamp = int(message["extraInfo"]["timestamp"]) return (message, timestamp) def _set_no_reply_file(self): self.error_file = _NOT_AVAILABLE self.error_file_data = _EMPTY_ERROR_DATA self.message = "" self.timestamp = int(time.time()) def signal_name(self) -> str: if self.exitcode < 0: # We don't want to kill the parent process trying to find the signal name. # if the signal doesn't map to a known name, use not available. try: return signal.Signals(-self.exitcode).name except Exception: return _NOT_AVAILABLE else: return _NOT_AVAILABLE def timestamp_isoformat(self): """Return timestamp in ISO format (YYYY-MM-DD_HH:MM:SS).""" return datetime.fromtimestamp(self.timestamp).isoformat(sep="_") GlobalRank = int _FAILURE_FORMAT_TEMPLATE = """[${idx}]: time : ${time} host : ${hostname} rank : ${rank} (local_rank: ${local_rank}) exitcode : ${exitcode} (pid: ${pid}) error_file: ${error_file} traceback : ${message}""" # extra new lines before and after are intentional _MSG_FORMAT_TEMPLATE = """ ${boarder} ${title} ${section} Failures: ${other_failures} ${section} Root Cause (first observed failure): ${root_failure} ${boarder}"""
ProcessFailure
python
huggingface__transformers
tests/models/dinov3_convnext/test_modeling_dinov3_convnext.py
{ "start": 10739, "end": 11045 }
class ____(unittest.TestCase, BackboneTesterMixin): all_model_classes = (DINOv3ConvNextBackbone,) if is_torch_available() else () config_class = DINOv3ConvNextConfig has_attentions = False def setUp(self): self.model_tester = DINOv3ConvNextModelTester(self)
DINOv3ConvNextBackboneTest
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/eks.py
{ "start": 25964, "end": 31556 }
class ____(AwsBaseOperator[EksHook]): """ Creates an AWS Fargate profile for an Amazon EKS cluster. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:EksCreateFargateProfileOperator` :param cluster_name: The name of the Amazon EKS cluster to apply the AWS Fargate profile to. (templated) :param pod_execution_role_arn: The Amazon Resource Name (ARN) of the pod execution role to use for pods that match the selectors in the AWS Fargate profile. (templated) :param selectors: The selectors to match for pods to use this AWS Fargate profile. (templated) :param fargate_profile_name: The unique name to give your AWS Fargate profile. (templated) :param create_fargate_profile_kwargs: Optional parameters to pass to the CreateFargate Profile API (templated) :param wait_for_completion: If True, waits for operator to complete. (default: False) (templated) :param aws_conn_id: The Airflow connection used for AWS credentials. If this is ``None`` or empty then the default boto3 behaviour is used. If running Airflow in a distributed manner and aws_conn_id is None or empty, then default boto3 configuration would be used (and must be maintained on each worker node). :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used. :param verify: Whether or not to verify SSL certificates. See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html :param waiter_delay: Time (in seconds) to wait between two consecutive calls to check profile status :param waiter_max_attempts: The maximum number of attempts to check the status of the profile. :param deferrable: If True, the operator will wait asynchronously for the profile to be created. This implies waiting for completion. This mode requires aiobotocore module to be installed. (default: False) """ aws_hook_class = EksHook template_fields: Sequence[str] = aws_template_fields( "cluster_name", "pod_execution_role_arn", "selectors", "fargate_profile_name", "create_fargate_profile_kwargs", "wait_for_completion", ) def __init__( self, cluster_name: str, pod_execution_role_arn: str, selectors: list, fargate_profile_name: str = DEFAULT_FARGATE_PROFILE_NAME, create_fargate_profile_kwargs: dict | None = None, region: str | None = None, wait_for_completion: bool = False, waiter_delay: int = 10, waiter_max_attempts: int = 60, deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False), **kwargs, ) -> None: self.cluster_name = cluster_name self.selectors = selectors self.pod_execution_role_arn = pod_execution_role_arn self.fargate_profile_name = fargate_profile_name self.create_fargate_profile_kwargs = create_fargate_profile_kwargs or {} if deferrable: wait_for_completion = False self.wait_for_completion = wait_for_completion self.waiter_delay = waiter_delay self.waiter_max_attempts = waiter_max_attempts self.deferrable = deferrable self.compute = "fargate" if region is not None: warnings.warn( message="Parameter `region` is deprecated. Use the parameter `region_name` instead", category=AirflowProviderDeprecationWarning, stacklevel=2, ) kwargs["region_name"] = region super().__init__(**kwargs) def execute(self, context: Context): _create_compute( compute=self.compute, cluster_name=self.cluster_name, aws_conn_id=self.aws_conn_id, region=self.region_name, wait_for_completion=self.wait_for_completion, waiter_delay=self.waiter_delay, waiter_max_attempts=self.waiter_max_attempts, fargate_profile_name=self.fargate_profile_name, fargate_pod_execution_role_arn=self.pod_execution_role_arn, fargate_selectors=self.selectors, create_fargate_profile_kwargs=self.create_fargate_profile_kwargs, ) if self.deferrable: self.defer( trigger=EksCreateFargateProfileTrigger( cluster_name=self.cluster_name, fargate_profile_name=self.fargate_profile_name, aws_conn_id=self.aws_conn_id, waiter_delay=self.waiter_delay, waiter_max_attempts=self.waiter_max_attempts, region_name=self.region_name, ), method_name="execute_complete", # timeout is set to ensure that if a trigger dies, the timeout does not restart # 60 seconds is added to allow the trigger to exit gracefully (i.e. yield TriggerEvent) timeout=timedelta(seconds=(self.waiter_max_attempts * self.waiter_delay + 60)), ) def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> None: validated_event = validate_execute_complete_event(event) if validated_event["status"] != "success": raise AirflowException(f"Error creating Fargate profile: {validated_event}") self.log.info("Fargate profile created successfully")
EksCreateFargateProfileOperator
python
django__django
django/db/models/constraints.py
{ "start": 9975, "end": 10195 }
class ____(Enum): DEFERRED = "deferred" IMMEDIATE = "immediate" # A similar format was proposed for Python 3.10. def __repr__(self): return f"{self.__class__.__qualname__}.{self._name_}"
Deferrable
python
pyca__cryptography
tests/x509/test_x509_ext.py
{ "start": 128851, "end": 132791 }
class ____: def test_aki_keyid(self, backend): cert = _load_cert( os.path.join("x509", "cryptography.io.pem"), x509.load_pem_x509_certificate, ) ext = cert.extensions.get_extension_for_class( x509.AuthorityKeyIdentifier ) assert ext is not None assert ext.critical is False assert ext.value.key_identifier == ( b"\xc3\x9c\xf3\xfc\xd3F\x084\xbb\xceF\x7f\xa0|[\xf3\xe2\x08\xcbY" ) assert ext.value.authority_cert_issuer is None assert ext.value.authority_cert_serial_number is None def test_aki_all_fields(self, backend): cert = _load_cert( os.path.join("x509", "custom", "authority_key_identifier.pem"), x509.load_pem_x509_certificate, ) ext = cert.extensions.get_extension_for_class( x509.AuthorityKeyIdentifier ) assert ext is not None assert ext.critical is False assert ext.value.key_identifier == ( b"9E>\xca=b\x1d\xea\x86I\xf6Z\xab@\xb7\xa4p\x98\xf1\xec" ) assert ext.value.authority_cert_issuer == [ x509.DirectoryName( x509.Name( [ x509.NameAttribute(NameOID.ORGANIZATION_NAME, "PyCA"), x509.NameAttribute( NameOID.COMMON_NAME, "cryptography.io" ), ] ) ) ] assert ext.value.authority_cert_serial_number == 3 def test_aki_no_keyid(self, backend): cert = _load_cert( os.path.join( "x509", "custom", "authority_key_identifier_no_keyid.pem" ), x509.load_pem_x509_certificate, ) ext = cert.extensions.get_extension_for_class( x509.AuthorityKeyIdentifier ) assert ext is not None assert ext.critical is False assert ext.value.key_identifier is None assert ext.value.authority_cert_issuer == [ x509.DirectoryName( x509.Name( [ x509.NameAttribute(NameOID.ORGANIZATION_NAME, "PyCA"), x509.NameAttribute( NameOID.COMMON_NAME, "cryptography.io" ), ] ) ) ] assert ext.value.authority_cert_serial_number == 3 def test_from_certificate(self, backend): issuer_cert = _load_cert( os.path.join("x509", "rapidssl_sha256_ca_g3.pem"), x509.load_pem_x509_certificate, ) cert = _load_cert( os.path.join("x509", "cryptography.io.pem"), x509.load_pem_x509_certificate, ) ext = cert.extensions.get_extension_for_oid( ExtensionOID.AUTHORITY_KEY_IDENTIFIER ) public_key = issuer_cert.public_key() assert isinstance(public_key, rsa.RSAPublicKey) aki = x509.AuthorityKeyIdentifier.from_issuer_public_key(public_key) assert ext.value == aki def test_from_issuer_subject_key_identifier(self, backend): issuer_cert = _load_cert( os.path.join("x509", "rapidssl_sha256_ca_g3.pem"), x509.load_pem_x509_certificate, ) cert = _load_cert( os.path.join("x509", "cryptography.io.pem"), x509.load_pem_x509_certificate, ) ext = cert.extensions.get_extension_for_oid( ExtensionOID.AUTHORITY_KEY_IDENTIFIER ) ski_ext = issuer_cert.extensions.get_extension_for_class( x509.SubjectKeyIdentifier ) aki = x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier( ski_ext.value ) assert ext.value == aki
TestAuthorityKeyIdentifierExtension
python
PyCQA__pylint
tests/functional/a/arguments_differ.py
{ "start": 4106, "end": 4273 }
class ____(HasSpecialMethod): def __getitem__(self, cheie): # no error here, method overrides special method return cheie + 1
OverridesSpecialMethod
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/executors/batch/test_utils.py
{ "start": 11717, "end": 14031 }
class ____: """Tests for configuration key constants.""" def test_batch_submit_job_kwargs_config_keys_values(self): """Test BatchSubmitJobKwargsConfigKeys have correct string values.""" assert BatchSubmitJobKwargsConfigKeys.JOB_NAME == "job_name" assert BatchSubmitJobKwargsConfigKeys.JOB_QUEUE == "job_queue" assert BatchSubmitJobKwargsConfigKeys.JOB_DEFINITION == "job_definition" assert BatchSubmitJobKwargsConfigKeys.EKS_PROPERTIES_OVERRIDE == "eks_properties_override" assert BatchSubmitJobKwargsConfigKeys.NODE_OVERRIDE == "node_override" def test_all_batch_config_keys_values(self): """Test AllBatchConfigKeys have correct string values, including inherited ones.""" # Test keys specific to AllBatchConfigKeys assert AllBatchConfigKeys.MAX_SUBMIT_JOB_ATTEMPTS == "max_submit_job_attempts" assert AllBatchConfigKeys.AWS_CONN_ID == "conn_id" assert AllBatchConfigKeys.SUBMIT_JOB_KWARGS == "submit_job_kwargs" assert AllBatchConfigKeys.REGION_NAME == "region_name" assert AllBatchConfigKeys.CHECK_HEALTH_ON_STARTUP == "check_health_on_startup" # Test inherited keys from BatchSubmitJobKwargsConfigKeys assert AllBatchConfigKeys.JOB_NAME == "job_name" assert AllBatchConfigKeys.JOB_QUEUE == "job_queue" assert AllBatchConfigKeys.JOB_DEFINITION == "job_definition" assert AllBatchConfigKeys.EKS_PROPERTIES_OVERRIDE == "eks_properties_override" assert AllBatchConfigKeys.NODE_OVERRIDE == "node_override" def test_config_defaults(self): """Test that CONFIG_DEFAULTS is a dictionary with expected keys and values.""" assert isinstance(CONFIG_DEFAULTS, dict) assert "conn_id" in CONFIG_DEFAULTS assert CONFIG_DEFAULTS["conn_id"] == "aws_default" assert "max_submit_job_attempts" in CONFIG_DEFAULTS assert CONFIG_DEFAULTS["max_submit_job_attempts"] == "3" assert "check_health_on_startup" in CONFIG_DEFAULTS assert CONFIG_DEFAULTS["check_health_on_startup"] == "True" def test_config_group_name(self): """Test that CONFIG_GROUP_NAME is a string.""" assert isinstance(CONFIG_GROUP_NAME, str) assert CONFIG_GROUP_NAME == "aws_batch_executor"
TestConfigKeys
python
pydata__xarray
xarray/tests/test_backends.py
{ "start": 90361, "end": 97452 }
class ____(NetCDF4Base): @contextlib.contextmanager def create_store(self): with create_tmp_file() as tmp_file: with backends.NetCDF4DataStore.open(tmp_file, mode="w") as store: yield store def test_variable_order(self) -> None: # doesn't work with scipy or h5py :( ds = Dataset() ds["a"] = 1 ds["z"] = 2 ds["b"] = 3 ds.coords["c"] = 4 with self.roundtrip(ds) as actual: assert list(ds.variables) == list(actual.variables) def test_unsorted_index_raises(self) -> None: # should be fixed in netcdf4 v1.2.1 random_data = np.random.random(size=(4, 6)) dim0 = [0, 1, 2, 3] dim1 = [0, 2, 1, 3, 5, 4] # We will sort this in a later step da = xr.DataArray( data=random_data, dims=("dim0", "dim1"), coords={"dim0": dim0, "dim1": dim1}, name="randovar", ) ds = da.to_dataset() with self.roundtrip(ds) as ondisk: inds = np.argsort(dim1) ds2 = ondisk.isel(dim1=inds) # Older versions of NetCDF4 raise an exception here, and if so we # want to ensure we improve (that is, replace) the error message try: _ = ds2.randovar.values except IndexError as err: assert "first by calling .load" in str(err) def test_setncattr_string(self) -> None: list_of_strings = ["list", "of", "strings"] one_element_list_of_strings = ["one element"] one_string = "one string" attrs = { "foo": list_of_strings, "bar": one_element_list_of_strings, "baz": one_string, } ds = Dataset({"x": ("y", [1, 2, 3], attrs)}, attrs=attrs) with self.roundtrip(ds) as actual: for totest in [actual, actual["x"]]: assert_array_equal(list_of_strings, totest.attrs["foo"]) assert_array_equal(one_element_list_of_strings, totest.attrs["bar"]) assert one_string == totest.attrs["baz"] @pytest.mark.parametrize( "compression", [ None, "zlib", "szip", pytest.param( "zstd", marks=pytest.mark.xfail( not _check_compression_codec_available("zstd"), reason="zstd codec not available in netCDF4 installation", ), ), pytest.param( "blosc_lz", marks=pytest.mark.xfail( not _check_compression_codec_available("blosc_lz"), reason="blosc_lz codec not available in netCDF4 installation", ), ), pytest.param( "blosc_lz4", marks=pytest.mark.xfail( not _check_compression_codec_available("blosc_lz4"), reason="blosc_lz4 codec not available in netCDF4 installation", ), ), pytest.param( "blosc_lz4hc", marks=pytest.mark.xfail( not _check_compression_codec_available("blosc_lz4hc"), reason="blosc_lz4hc codec not available in netCDF4 installation", ), ), pytest.param( "blosc_zlib", marks=pytest.mark.xfail( not _check_compression_codec_available("blosc_zlib"), reason="blosc_zlib codec not available in netCDF4 installation", ), ), pytest.param( "blosc_zstd", marks=pytest.mark.xfail( not _check_compression_codec_available("blosc_zstd"), reason="blosc_zstd codec not available in netCDF4 installation", ), ), ], ) @requires_netCDF4_1_6_2_or_above @pytest.mark.xfail(ON_WINDOWS, reason="new compression not yet implemented") def test_compression_encoding(self, compression: str | None) -> None: data = create_test_data(dim_sizes=(20, 80, 10)) encoding_params: dict[str, Any] = dict(compression=compression, blosc_shuffle=1) data["var2"].encoding.update(encoding_params) data["var2"].encoding.update( { "chunksizes": (20, 40), "original_shape": data.var2.shape, "blosc_shuffle": 1, "fletcher32": False, } ) with self.roundtrip(data) as actual: expected_encoding = data["var2"].encoding.copy() # compression does not appear in the retrieved encoding, that differs # from the input encoding. shuffle also chantges. Here we modify the # expected encoding to account for this compression = expected_encoding.pop("compression") blosc_shuffle = expected_encoding.pop("blosc_shuffle") if compression is not None: if "blosc" in compression and blosc_shuffle: expected_encoding["blosc"] = { "compressor": compression, "shuffle": blosc_shuffle, } expected_encoding["shuffle"] = False elif compression == "szip": expected_encoding["szip"] = { "coding": "nn", "pixels_per_block": 8, } expected_encoding["shuffle"] = False else: # This will set a key like zlib=true which is what appears in # the encoding when we read it. expected_encoding[compression] = True if compression == "zstd": expected_encoding["shuffle"] = False else: expected_encoding["shuffle"] = False actual_encoding = actual["var2"].encoding assert expected_encoding.items() <= actual_encoding.items() if ( encoding_params["compression"] is not None and "blosc" not in encoding_params["compression"] ): # regression test for #156 expected = data.isel(dim1=0) with self.roundtrip(expected) as actual: assert_equal(expected, actual) @pytest.mark.skip(reason="https://github.com/Unidata/netcdf4-python/issues/1195") def test_refresh_from_disk(self) -> None: super().test_refresh_from_disk() @requires_netCDF4_1_7_0_or_above def test_roundtrip_complex(self): expected = Dataset({"x": ("y", np.ones(5) + 1j * np.ones(5))}) skwargs = dict(auto_complex=True) okwargs = dict(auto_complex=True) with self.roundtrip( expected, save_kwargs=skwargs, open_kwargs=okwargs ) as actual: assert_equal(expected, actual) @requires_netCDF4
TestNetCDF4Data
python
getsentry__sentry
tests/sentry/api/endpoints/test_organization_spans_fields.py
{ "start": 289, "end": 5124 }
class ____(BaseSpansTestCase, APITestCase): view = "sentry-api-0-organization-spans-fields" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) def do_request(self, query=None, features=None, **kwargs): if features is None: features = ["organizations:performance-trace-explorer"] if query is None: query = {} query["dataset"] = "spans" if "type" not in query: query["type"] = "string" with self.feature(features): return self.client.get( reverse( self.view, kwargs={"organization_id_or_slug": self.organization.slug}, ), query, format="json", **kwargs, ) def test_no_feature(self) -> None: response = self.do_request(features=[]) assert response.status_code == 404, response.data def test_no_project(self) -> None: response = self.do_request() assert response.status_code == 200, response.data assert response.data == [] def test_tags_list_str(self) -> None: for tag in ["foo", "bar", "baz"]: self.store_segment( self.project.id, uuid4().hex, uuid4().hex, span_id=uuid4().hex[:16], organization_id=self.organization.id, parent_span_id=None, timestamp=before_now(days=0, minutes=10).replace(microsecond=0), transaction="foo", duration=100, exclusive_time=100, tags={tag: tag}, is_eap=True, ) for features in [ None, # use the default features ["organizations:performance-trace-explorer"], ]: response = self.do_request( features=features, query={"dataset": "spans", "type": "string", "process": 1}, ) assert response.status_code == 200, response.data assert sorted( response.data, key=itemgetter("key"), ) == sorted( [ {"key": "bar", "name": "bar"}, {"key": "baz", "name": "baz"}, {"key": "foo", "name": "foo"}, {"key": "span.description", "name": "span.description"}, {"key": "transaction", "name": "transaction"}, {"key": "project", "name": "project"}, ], key=itemgetter("key"), ) def test_tags_list_nums(self) -> None: for tag in [ "foo", "bar", "baz", "lcp", "fcp", "http.decoded_response_content_length", "http.response_content_length", "http.response_transfer_size", ]: self.store_segment( self.project.id, uuid4().hex, uuid4().hex, span_id=uuid4().hex[:16], organization_id=self.organization.id, parent_span_id=None, timestamp=before_now(days=0, minutes=10).replace(microsecond=0), transaction="foo", duration=100, exclusive_time=100, measurements={tag: 0}, is_eap=True, ) for features in [ None, # use the default features ["organizations:performance-trace-explorer"], ]: response = self.do_request( features=features, query={"dataset": "spans", "type": "number", "process": 1}, ) assert response.status_code == 200, response.data assert response.data == [ {"key": "tags[bar,number]", "name": "bar"}, {"key": "tags[baz,number]", "name": "baz"}, {"key": "measurements.fcp", "name": "measurements.fcp"}, {"key": "tags[foo,number]", "name": "foo"}, { "key": "http.decoded_response_content_length", "name": "http.decoded_response_content_length", }, { "key": "http.response_content_length", "name": "http.response_content_length", }, { "key": "http.response_transfer_size", "name": "http.response_transfer_size", }, {"key": "measurements.lcp", "name": "measurements.lcp"}, {"key": "span.duration", "name": "span.duration"}, ]
OrganizationSpansTagsEndpointTest
python
scipy__scipy
scipy/special/tests/test_basic.py
{ "start": 39193, "end": 39496 }
class ____: def test_assoc_laguerre(self): a1 = special.genlaguerre(11,1) a2 = special.assoc_laguerre(.2,11,1) assert_allclose(a2, a1(.2), atol=1.5e-8, rtol=0) a2 = special.assoc_laguerre(1,11,1) assert_allclose(a2, a1(1), atol=1.5e-8, rtol=0)
TestAssocLaguerre
python
ray-project__ray
python/ray/dag/tests/experimental/test_torch_tensor_transport.py
{ "start": 21572, "end": 23545 }
class ____: """Tests worker to driver tensor transport with GPU device.""" def test_src_cpu_tensor(self, ray_start_regular): actor = Actor.remote() ref = run_worker_to_driver_dag(actor, "cuda", "cpu") # different behavior between a driver node with GPU and without GPU if torch.cuda.is_available(): tensor = ray.get(ref) assert str(tensor.device) == "cuda:0" else: with pytest.raises( RayTaskError, match="RuntimeError: No CUDA GPUs are available" ): ray.get(ref) @pytest.mark.skipif(not USE_GPU, reason="Test requires GPU") def test_src_gpu_tensor(self, ray_start_regular): actor = Actor.options(num_gpus=1).remote() ref = run_worker_to_driver_dag(actor, "cuda", "cuda") # different behavior between a driver node with GPU and without GPU if torch.cuda.is_available(): tensor = ray.get(ref) assert str(tensor.device) == "cuda:0" else: with pytest.raises( RayTaskError, match="RuntimeError: No CUDA GPUs are available" ): ray.get(ref) @pytest.mark.skipif(not USE_GPU, reason="Test requires GPU") def test_src_mix_tensors(self, ray_start_regular): actor = Actor.options(num_gpus=1).remote() ref = run_worker_to_driver_dag( actor, "cuda", {"cpu_tensor": "cpu", "gpu_tensor": "cuda"}, is_dict=True ) # different behavior between a driver node with GPU and without GPU if torch.cuda.is_available(): tensor = ray.get(ref) assert str(tensor["cpu_tensor"].device) == "cuda:0" assert str(tensor["gpu_tensor"].device) == "cuda:0" else: with pytest.raises( RayTaskError, match="RuntimeError: No CUDA GPUs are available" ): ray.get(ref)
TestWorkerToDriverDeviceGPU
python
dagster-io__dagster
python_modules/dagster/dagster_tests/storage_tests/test_daemon_cursor_storage.py
{ "start": 262, "end": 629 }
class ____(TestDaemonCursorStorage): __test__ = True @pytest.fixture( name="storage", params=[ create_in_memory_storage, create_sqlite_run_storage, create_legacy_run_storage, ], ) def cursor_storage(self, request): with request.param() as s: yield s
TestDaemonCursorStorages
python
apache__airflow
task-sdk/src/airflow/sdk/execution_time/comms.py
{ "start": 28689, "end": 28793 }
class ____(BaseModel): name: str type: Literal["GetAssetByName"] = "GetAssetByName"
GetAssetByName
python
getsentry__sentry
tests/sentry/integrations/aws_lambda/test_utils.py
{ "start": 2507, "end": 2991 }
class ____(TestCase): def test_basic(self) -> None: function = { "Layers": [ {"Arn": "arn:aws:lambda:us-east-2:1234:layer:something-else:2"}, "arn:aws:lambda:us-east-2:1234:layer:my-layer:3", ] } assert get_function_layer_arns(function) == [ "arn:aws:lambda:us-east-2:1234:layer:something-else:2", "arn:aws:lambda:us-east-2:1234:layer:my-layer:3", ]
GetFunctionLayerArns
python
pytorch__pytorch
test/export/test_torchbind.py
{ "start": 2052, "end": 47841 }
class ____(TestCase): def setUp(self): init_torchbind_implementations() test = self test.tq_push_counter = 0 test.tq_pop_counter = 0 test.tq_size_counter = 0 test.foo_add_tensor_counter = 0 # We need different fake classes, which update the counters @torch._library.register_fake_class("_TorchScriptTesting::_Foo") class FakeFoo: def __init__(self, x: int, y: int): self.x = x self.y = y @classmethod def __obj_unflatten__(cls, flattend_foo): return cls(**dict(flattend_foo)) def add_tensor(self, z): test.foo_add_tensor_counter += 1 return (self.x + self.y) * z @torch._library.register_fake_class("_TorchScriptTesting::_TensorQueue") class FakeTensorQueue: def __init__(self, queue): self.queue = queue @classmethod def __obj_unflatten__(cls, flattened_ctx): return cls(**dict(flattened_ctx)) def push(self, x): test.tq_push_counter += 1 self.queue.append(x) def pop(self): test.tq_pop_counter += 1 return self.queue.pop(0) def size(self): test.tq_size_counter += 1 return len(self.queue) def is_empty(self): return len(self.queue) == 0 def float_size(self): return float(len(self.queue)) self.torch_bind_ops = [ torch.ops._TorchScriptTesting.takes_foo, torch.ops._TorchScriptTesting.takes_foo_python_meta, torch.ops._TorchScriptTesting.takes_foo_list_return, torch.ops._TorchScriptTesting.takes_foo_tuple_return, torch.ops._TorchScriptTesting.take_an_instance, torch.ops._TorchScriptTesting.take_an_instance_inferred, torch.ops._TorchScriptTesting.takes_foo_cia, torch.ops._TorchScriptTesting.queue_pop, torch.ops._TorchScriptTesting.queue_push, torch.ops._TorchScriptTesting.queue_size, ] def tearDown(self): torch._library.fake_class_registry.deregister_fake_class( "_TorchScriptTesting::_Foo" ) torch._library.fake_class_registry.deregister_fake_class( "_TorchScriptTesting::_TensorQueue" ) def _test_export_same_as_eager( self, f, args, kwargs=None, strict=True, pre_dispatch=False ): kwargs = kwargs or {} def export_wrapper(f, args, kwargs, strict, pre_dispatch): with enable_torchbind_tracing(): if pre_dispatch: exported_program = torch.export.export( f, args, kwargs, strict=strict ).run_decompositions({}) else: exported_program = _export( f, args, kwargs, strict=strict, pre_dispatch=False ) return exported_program exported_program = export_wrapper(f, args, kwargs, strict, pre_dispatch) reversed_kwargs = {key: kwargs[key] for key in reversed(kwargs)} unlifted = exported_program.module() exp = f(*args, **kwargs) _assertEqualScriptObject(self, unlifted(*args, **kwargs), exp) _assertEqualScriptObject( self, unlifted(*args, **reversed_kwargs), exp, ) # check re-tracing retraced_ep = export_wrapper(unlifted, args, kwargs, strict, pre_dispatch) _assertEqualScriptObject(self, retraced_ep.module()(*args, **kwargs), exp) return exported_program @parametrize("pre_dispatch", [True, False]) def test_none(self, pre_dispatch): class MyModule(torch.nn.Module): def __init__(self) -> None: super().__init__() self.attr = torch.classes._TorchScriptTesting._Foo(10, 20) def forward(self, x, n): return x + self.attr.add_tensor(x) ep = self._test_export_same_as_eager( MyModule(), (torch.ones(2, 3), None), strict=False, pre_dispatch=pre_dispatch, ) self.assertExpectedInline( ep.module().code.strip(), """\ def forward(self, x, n): x, n, = fx_pytree.tree_flatten_spec(([x, n], {}), self._in_spec) attr = self.attr _guards_fn = self._guards_fn(x, n); n = _guards_fn = None call_torchbind = torch.ops.higher_order.call_torchbind(attr, 'add_tensor', x); attr = None add = torch.ops.aten.add.Tensor(x, call_torchbind); x = call_torchbind = None return pytree.tree_unflatten((add,), self._out_spec)""", ) self.assertExpectedInline( ep.graph_module.code.strip(), """\ def forward(self, token, obj_attr, x, n): with_effects = torch.ops.higher_order.with_effects(token, torch.ops.higher_order.call_torchbind, obj_attr, 'add_tensor', x); token = obj_attr = None getitem = with_effects[0] getitem_1 = with_effects[1]; with_effects = None add = torch.ops.aten.add.Tensor(x, getitem_1); x = getitem_1 = None return (getitem, add)""", # noqa: B950 ) def test_method_schema(self): tq = _empty_tensor_queue() fake_mode = torch._subclasses.fake_tensor.FakeTensorMode() fake_obj = torch._library.fake_class_registry.maybe_to_fake_obj(fake_mode, tq) self.assertExpectedInline( str(fake_obj.push.schema), """push(__torch__.torch.classes._TorchScriptTesting._TensorQueue _0, Tensor _1) -> NoneType _0""", ) self.assertExpectedInline( str(fake_obj.pop.schema), """pop(__torch__.torch.classes._TorchScriptTesting._TensorQueue _0) -> Tensor _0""", ) @parametrize("pre_dispatch", [True, False]) def test_attribute(self, pre_dispatch): class MyModule(torch.nn.Module): def __init__(self) -> None: super().__init__() self.attr = torch.classes._TorchScriptTesting._Foo(10, 20) def forward(self, x): return x + self.attr.add_tensor(x) ep = self._test_export_same_as_eager( MyModule(), (torch.ones(2, 3),), strict=False, pre_dispatch=pre_dispatch ) self.assertExpectedInline( ep.module().code.strip(), """\ def forward(self, x): x, = fx_pytree.tree_flatten_spec(([x], {}), self._in_spec) attr = self.attr _guards_fn = self._guards_fn(x); _guards_fn = None call_torchbind = torch.ops.higher_order.call_torchbind(attr, 'add_tensor', x); attr = None add = torch.ops.aten.add.Tensor(x, call_torchbind); x = call_torchbind = None return pytree.tree_unflatten((add,), self._out_spec)""", ) self.assertExpectedInline( ep.graph_module.code.strip(), """\ def forward(self, token, obj_attr, x): with_effects = torch.ops.higher_order.with_effects(token, torch.ops.higher_order.call_torchbind, obj_attr, 'add_tensor', x); token = obj_attr = None getitem = with_effects[0] getitem_1 = with_effects[1]; with_effects = None add = torch.ops.aten.add.Tensor(x, getitem_1); x = getitem_1 = None return (getitem, add)""", # noqa: B950 ) @parametrize("pre_dispatch", [True, False]) def test_attribute_as_custom_op_argument(self, pre_dispatch): class MyModule(torch.nn.Module): def __init__(self) -> None: super().__init__() self.attr = torch.classes._TorchScriptTesting._Foo(10, 20) def forward(self, x): return x + torch.ops._TorchScriptTesting.takes_foo(self.attr, x) ep = self._test_export_same_as_eager( MyModule(), (torch.ones(2, 3),), strict=False, pre_dispatch=pre_dispatch ) self.assertExpectedInline( ep.module().code.strip(), """\ def forward(self, x): x, = fx_pytree.tree_flatten_spec(([x], {}), self._in_spec) attr = self.attr _guards_fn = self._guards_fn(x); _guards_fn = None takes_foo_default = torch.ops._TorchScriptTesting.takes_foo.default(attr, x); attr = None add = torch.ops.aten.add.Tensor(x, takes_foo_default); x = takes_foo_default = None return pytree.tree_unflatten((add,), self._out_spec)""", ) self.assertExpectedInline( ep.graph_module.code.strip(), """\ def forward(self, token, obj_attr, x): with_effects = torch.ops.higher_order.with_effects(token, torch.ops._TorchScriptTesting.takes_foo.default, obj_attr, x); token = obj_attr = None getitem = with_effects[0] getitem_1 = with_effects[1]; with_effects = None add = torch.ops.aten.add.Tensor(x, getitem_1); x = getitem_1 = None return (getitem, add)""", # noqa: B950 ) @parametrize("pre_dispatch", [True, False]) def test_input(self, pre_dispatch): cc = torch.classes._TorchScriptTesting._Foo(10, 20) class MyModule(torch.nn.Module): def __init__(self) -> None: super().__init__() def forward(self, x, cc): return x + cc.add_tensor(x) ep = self._test_export_same_as_eager( MyModule(), (torch.ones(2, 3), cc), strict=False, pre_dispatch=pre_dispatch ) self.assertExpectedInline( ep.module().code.strip(), """\ def forward(self, x, cc): x, cc, = fx_pytree.tree_flatten_spec(([x, cc], {}), self._in_spec) _guards_fn = self._guards_fn(x, cc); _guards_fn = None call_torchbind = torch.ops.higher_order.call_torchbind(cc, 'add_tensor', x); cc = None add = torch.ops.aten.add.Tensor(x, call_torchbind); x = call_torchbind = None return pytree.tree_unflatten((add,), self._out_spec)""", ) self.assertExpectedInline( ep.graph_module.code.strip(), """\ def forward(self, token, x, cc): with_effects = torch.ops.higher_order.with_effects(token, torch.ops.higher_order.call_torchbind, cc, 'add_tensor', x); token = cc = None getitem = with_effects[0] getitem_1 = with_effects[1]; with_effects = None add = torch.ops.aten.add.Tensor(x, getitem_1); x = getitem_1 = None return (getitem, add)""", # noqa: B950 ) # aot_export_function runs the program twice # in run_functionalized_fw_and_collect_metadata and create_aot_dispatcher_function # We also have a re-tracing test, which doubles the count. if pre_dispatch: self.assertEqual(self.foo_add_tensor_counter, 6) else: self.assertEqual(self.foo_add_tensor_counter, 4) @parametrize("pre_dispatch", [True, False]) def test_input_as_custom_op_argument(self, pre_dispatch): cc = torch.classes._TorchScriptTesting._Foo(10, 20) class MyModule(torch.nn.Module): def __init__(self) -> None: super().__init__() def forward(self, x, cc): return x + torch.ops._TorchScriptTesting.takes_foo(cc, x) del torch.ops._TorchScriptTesting.takes_foo.default.py_kernels[ torch._C.DispatchKey.Meta ] torch.ops._TorchScriptTesting.takes_foo.default._dispatch_cache.clear() # Even though a C++ implementation for takes_foo.default is registered, # we still need the python implementation for takes_foo.default to trace with FakeFoo. with self.assertRaisesRegex(RuntimeError, "no python implementation is found"): self._test_export_same_as_eager( MyModule(), (torch.ones(2, 3), cc), strict=False, pre_dispatch=pre_dispatch, ) torch.ops._TorchScriptTesting.takes_foo.default.py_impl( torch._C.DispatchKey.Meta )(lambda cc, x: cc.add_tensor(x)) ep = self._test_export_same_as_eager( MyModule(), (torch.ones(2, 3), cc), strict=False, pre_dispatch=pre_dispatch, ) self.assertExpectedInline( ep.module().code.strip(), """\ def forward(self, x, cc): x, cc, = fx_pytree.tree_flatten_spec(([x, cc], {}), self._in_spec) _guards_fn = self._guards_fn(x, cc); _guards_fn = None takes_foo_default = torch.ops._TorchScriptTesting.takes_foo.default(cc, x); cc = None add = torch.ops.aten.add.Tensor(x, takes_foo_default); x = takes_foo_default = None return pytree.tree_unflatten((add,), self._out_spec)""", ) self.assertExpectedInline( ep.graph_module.code.strip(), """\ def forward(self, token, x, cc): with_effects = torch.ops.higher_order.with_effects(token, torch.ops._TorchScriptTesting.takes_foo.default, cc, x); token = cc = None getitem = with_effects[0] getitem_1 = with_effects[1]; with_effects = None add = torch.ops.aten.add.Tensor(x, getitem_1); x = getitem_1 = None return (getitem, add)""", # noqa: B950 ) @parametrize("pre_dispatch", [True, False]) def test_torchbind_alias(self, pre_dispatch): class F2(torch.nn.Module): def __init__(self, foo): super().__init__() self.foo = foo def forward(self, x): return x + torch.ops._TorchScriptTesting.takes_foo(self.foo, x) class F1(torch.nn.Module): def __init__(self) -> None: super().__init__() self.alpha = torch.classes._TorchScriptTesting._Foo(10, 20) self.beta = self.alpha self.gamma = self.alpha self.foo = F2(self.gamma) def forward(self, x): return ( x + torch.ops._TorchScriptTesting.takes_foo(self.gamma, x) + self.foo(x) ) self._test_export_same_as_eager( F1(), (torch.ones(2, 3),), strict=False, pre_dispatch=pre_dispatch ) def test_torchbind_register_attr_at_runtime_get_restored(self): # alias as model attribute class F3(torch.nn.Module): def forward(self, x, foo): self.foo = foo return x + self.foo.add_tensor(x) foo = torch.classes._TorchScriptTesting._Foo(10, 20) torch.export.export(F3(), (torch.ones(2, 3), foo), strict=False) self.assertFalse(hasattr(foo, "foo")) @parametrize("pre_dispatch", [True, False]) def test_torchbind_input_and_alias(self, pre_dispatch): # alias as model attribute class F3(torch.nn.Module): def __init__(self, foo): super().__init__() self.foo = foo def forward(self, x): return x + self.foo.add_tensor(x) foo = torch.classes._TorchScriptTesting._Foo(10, 20) self._test_export_same_as_eager( F3(foo), (torch.ones(2, 3),), strict=False, pre_dispatch=pre_dispatch ) @parametrize("pre_dispatch", [True, False]) def test_unlift_custom_obj(self, pre_dispatch): class MyModule(torch.nn.Module): def __init__(self) -> None: super().__init__() self.attr = torch.classes._TorchScriptTesting._Foo(10, 20) def forward(self, x): a = torch.ops._TorchScriptTesting.takes_foo(self.attr, x) b = torch.ops._TorchScriptTesting.takes_foo(self.attr, a) return x + b input = torch.ones(2, 3) ep = self._test_export_same_as_eager( MyModule(), (input,), strict=False, pre_dispatch=pre_dispatch ) self.assertExpectedInline( ep.module().code.strip(), """\ def forward(self, x): x, = fx_pytree.tree_flatten_spec(([x], {}), self._in_spec) attr = self.attr _guards_fn = self._guards_fn(x); _guards_fn = None takes_foo_default = torch.ops._TorchScriptTesting.takes_foo.default(attr, x) takes_foo_default_1 = torch.ops._TorchScriptTesting.takes_foo.default(attr, takes_foo_default); attr = takes_foo_default = None add = torch.ops.aten.add.Tensor(x, takes_foo_default_1); x = takes_foo_default_1 = None return pytree.tree_unflatten((add,), self._out_spec)""", # noqa: B950 ) self.assertExpectedInline( ep.graph_module.code.strip(), """\ def forward(self, token, obj_attr, x): with_effects = torch.ops.higher_order.with_effects(token, torch.ops._TorchScriptTesting.takes_foo.default, obj_attr, x); token = None getitem = with_effects[0] getitem_1 = with_effects[1]; with_effects = None with_effects_1 = torch.ops.higher_order.with_effects(getitem, torch.ops._TorchScriptTesting.takes_foo.default, obj_attr, getitem_1); getitem = obj_attr = getitem_1 = None getitem_2 = with_effects_1[0] getitem_3 = with_effects_1[1]; with_effects_1 = None add = torch.ops.aten.add.Tensor(x, getitem_3); x = getitem_3 = None return (getitem_2, add)""", # noqa: B950 ) @parametrize("pre_dispatch", [True, False]) def test_custom_obj_list_out(self, pre_dispatch): class MyModule(torch.nn.Module): def __init__(self) -> None: super().__init__() self.attr = torch.classes._TorchScriptTesting._Foo(10, 20) def forward(self, x): a = torch.ops._TorchScriptTesting.takes_foo_list_return(self.attr, x) y = a[0] + a[1] + a[2] b = torch.ops._TorchScriptTesting.takes_foo(self.attr, y) return x + b input = torch.ones(2, 3) ep = self._test_export_same_as_eager( MyModule(), (input,), strict=False, pre_dispatch=pre_dispatch ) self.assertExpectedInline( ep.module().code.strip(), """\ def forward(self, x): x, = fx_pytree.tree_flatten_spec(([x], {}), self._in_spec) attr = self.attr _guards_fn = self._guards_fn(x); _guards_fn = None takes_foo_list_return_default = torch.ops._TorchScriptTesting.takes_foo_list_return.default(attr, x) getitem_2 = takes_foo_list_return_default[0] getitem_3 = takes_foo_list_return_default[1] getitem_4 = takes_foo_list_return_default[2]; takes_foo_list_return_default = None add = torch.ops.aten.add.Tensor(getitem_2, getitem_3); getitem_2 = getitem_3 = None add_1 = torch.ops.aten.add.Tensor(add, getitem_4); add = getitem_4 = None takes_foo_default = torch.ops._TorchScriptTesting.takes_foo.default(attr, add_1); attr = add_1 = None add_2 = torch.ops.aten.add.Tensor(x, takes_foo_default); x = takes_foo_default = None return pytree.tree_unflatten((add_2,), self._out_spec)""", ) self.assertExpectedInline( ep.graph_module.code.strip(), """\ def forward(self, token, obj_attr, x): with_effects = torch.ops.higher_order.with_effects(token, torch.ops._TorchScriptTesting.takes_foo_list_return.default, obj_attr, x); token = None getitem = with_effects[0] getitem_1 = with_effects[1]; with_effects = None getitem_2 = getitem_1[0] getitem_3 = getitem_1[1] getitem_4 = getitem_1[2]; getitem_1 = None add = torch.ops.aten.add.Tensor(getitem_2, getitem_3); getitem_2 = getitem_3 = None add_1 = torch.ops.aten.add.Tensor(add, getitem_4); add = getitem_4 = None with_effects_1 = torch.ops.higher_order.with_effects(getitem, torch.ops._TorchScriptTesting.takes_foo.default, obj_attr, add_1); getitem = obj_attr = add_1 = None getitem_5 = with_effects_1[0] getitem_6 = with_effects_1[1]; with_effects_1 = None add_2 = torch.ops.aten.add.Tensor(x, getitem_6); x = getitem_6 = None return (getitem_5, add_2)""", # noqa: B950 ) @parametrize("pre_dispatch", [True, False]) def test_custom_obj_tuple_out(self, pre_dispatch): class MyModule(torch.nn.Module): def __init__(self) -> None: super().__init__() self.attr = torch.classes._TorchScriptTesting._Foo(10, 20) def forward(self, x): a = torch.ops._TorchScriptTesting.takes_foo_tuple_return(self.attr, x) y = a[0] + a[1] b = torch.ops._TorchScriptTesting.takes_foo(self.attr, y) return x + b input = torch.ones(2, 3) ep = self._test_export_same_as_eager( MyModule(), (input,), strict=False, pre_dispatch=pre_dispatch ) self.assertExpectedInline( ep.module().code.strip(), """\ def forward(self, x): x, = fx_pytree.tree_flatten_spec(([x], {}), self._in_spec) attr = self.attr _guards_fn = self._guards_fn(x); _guards_fn = None takes_foo_tuple_return_default = torch.ops._TorchScriptTesting.takes_foo_tuple_return.default(attr, x) getitem_1 = takes_foo_tuple_return_default[0] getitem_2 = takes_foo_tuple_return_default[1]; takes_foo_tuple_return_default = None add = torch.ops.aten.add.Tensor(getitem_1, getitem_2); getitem_1 = getitem_2 = None takes_foo_default = torch.ops._TorchScriptTesting.takes_foo.default(attr, add); attr = add = None add_1 = torch.ops.aten.add.Tensor(x, takes_foo_default); x = takes_foo_default = None return pytree.tree_unflatten((add_1,), self._out_spec)""", ) self.assertExpectedInline( ep.graph_module.code.strip(), """\ def forward(self, token, obj_attr, x): with_effects = torch.ops.higher_order.with_effects(token, torch.ops._TorchScriptTesting.takes_foo_tuple_return.default, obj_attr, x); token = None getitem = with_effects[0] getitem_1 = with_effects[1] getitem_2 = with_effects[2]; with_effects = None add = torch.ops.aten.add.Tensor(getitem_1, getitem_2); getitem_1 = getitem_2 = None with_effects_1 = torch.ops.higher_order.with_effects(getitem, torch.ops._TorchScriptTesting.takes_foo.default, obj_attr, add); getitem = obj_attr = add = None getitem_3 = with_effects_1[0] getitem_4 = with_effects_1[1]; with_effects_1 = None add_1 = torch.ops.aten.add.Tensor(x, getitem_4); x = getitem_4 = None return (getitem_3, add_1)""", # noqa: B950 ) @parametrize("pre_dispatch", [True, False]) def test_custom_obj_unbacked_symint(self, pre_dispatch): class MyModule(torch.nn.Module): def __init__(self) -> None: super().__init__() self.attr = torch.classes._TorchScriptTesting._Foo(2, 3) def forward(self, x): a = torch.ops._TorchScriptTesting.takes_foo_tensor_return(self.attr, x) return a input = torch.ones(2, 3) ep = self._test_export_same_as_eager( MyModule(), (input,), strict=False, pre_dispatch=pre_dispatch ) gm = ep.module() foo_node = next( n for n in gm.graph.nodes if n.target == torch.ops._TorchScriptTesting.takes_foo_tensor_return.default ) unbacked_bindings = foo_node.meta["unbacked_bindings"] self.assertEqual(len(unbacked_bindings), 2) u = next(iter(unbacked_bindings.keys())) path = unbacked_bindings[u] # the unbacked bindings should be CallMethodKey(name='size'), SequenceKey(idx=0) # it should not include the effect token in the path self.assertEqual( type(u).__name__, "Symbol" ) # check binding is symbol, not expr self.assertEqual(len(path), 2) self.assertEqual(path[0].name, "size") self.assertEqual(path[1].idx, 0) @parametrize("make_fx_tracing_mode", ["fake", "symbolic"]) def test_make_fx_tensor_queue_methods(self, make_fx_tracing_mode): test = self class Model(torch.nn.Module): def __init__(self) -> None: super().__init__() self.linear = torch.nn.Linear(3, 2) self.check_tq_is_fake = True def forward(self, tq, x): if self.check_tq_is_fake: test.assertTrue(isinstance(tq, FakeScriptObject)) tq.push(x.cos()) tq.push(x.sin()) x_cos = tq.pop() + tq.size() x_sin = tq.pop() - tq.size() return x_sin, x_cos, tq mod = Model() tq = torch.classes._TorchScriptTesting._TensorQueue( torch.empty( 0, ).fill_(-1) ) tq1 = torch.classes._TorchScriptTesting._TensorQueue( torch.empty( 0, ).fill_(-1) ) x = torch.ones(2, 3) gm = make_fx(mod, tracing_mode=make_fx_tracing_mode)(tq, x) self.assertEqual(self.tq_push_counter, 2) self.assertEqual(self.tq_pop_counter, 2) self.assertEqual(self.tq_size_counter, 2) self.assertEqual(tq.size(), 0) self.assertExpectedInline( gm.code.strip("\n"), """\ def forward(self, arg0_1, arg1_1): cos = torch.ops.aten.cos.default(arg1_1) call_torchbind = torch.ops.higher_order.call_torchbind(arg0_1, 'push', cos); cos = call_torchbind = None sin = torch.ops.aten.sin.default(arg1_1); arg1_1 = None call_torchbind_1 = torch.ops.higher_order.call_torchbind(arg0_1, 'push', sin); sin = call_torchbind_1 = None call_torchbind_2 = torch.ops.higher_order.call_torchbind(arg0_1, 'pop') call_torchbind_3 = torch.ops.higher_order.call_torchbind(arg0_1, 'size'); call_torchbind_3 = None add = torch.ops.aten.add.Tensor(call_torchbind_2, 1); call_torchbind_2 = None call_torchbind_4 = torch.ops.higher_order.call_torchbind(arg0_1, 'pop') call_torchbind_5 = torch.ops.higher_order.call_torchbind(arg0_1, 'size'); call_torchbind_5 = None sub = torch.ops.aten.sub.Tensor(call_torchbind_4, 0); call_torchbind_4 = None return (sub, add, arg0_1) """, ) mod.check_tq_is_fake = False _assertEqualSkipScriptObject(self, gm(tq, x), mod(tq1, x)) @parametrize("make_fx_tracing_mode", ["fake", "symbolic"]) def test_make_fx_tensor_queue_methods_fakify_internal_states( self, make_fx_tracing_mode ): test = self class Model(torch.nn.Module): def __init__(self) -> None: super().__init__() self.linear = torch.nn.Linear(3, 2) self.check_tq_is_fake = True self.current_test = test def forward(self, tq, x): if self.check_tq_is_fake: self.current_test.assertTrue(isinstance(tq, FakeScriptObject)) x_cos = tq.pop() + tq.size() + x x_sin = tq.pop() - tq.size() + x return x_sin, x_cos, tq mod = Model() tq = torch.classes._TorchScriptTesting._TensorQueue( torch.empty( 0, ).fill_(-1) ) tq1 = torch.classes._TorchScriptTesting._TensorQueue( torch.empty( 0, ).fill_(-1) ) for _ in range(2): tq.push(torch.ones(2, 3)) tq1.push(torch.ones(2, 3)) x = torch.ones(2, 3) prev_size = tq.size() gm = make_fx(mod, tracing_mode=make_fx_tracing_mode)(tq, x) self.assertEqual(self.tq_push_counter, 0) self.assertEqual(self.tq_pop_counter, 2) self.assertEqual(self.tq_size_counter, 2) self.assertEqual(tq.size(), prev_size) self.assertExpectedInline( gm.code.strip("\n"), """\ def forward(self, arg0_1, arg1_1): call_torchbind = torch.ops.higher_order.call_torchbind(arg0_1, 'pop') call_torchbind_1 = torch.ops.higher_order.call_torchbind(arg0_1, 'size'); call_torchbind_1 = None add = torch.ops.aten.add.Tensor(call_torchbind, 1); call_torchbind = None add_1 = torch.ops.aten.add.Tensor(add, arg1_1); add = None call_torchbind_2 = torch.ops.higher_order.call_torchbind(arg0_1, 'pop') call_torchbind_3 = torch.ops.higher_order.call_torchbind(arg0_1, 'size'); call_torchbind_3 = None sub = torch.ops.aten.sub.Tensor(call_torchbind_2, 0); call_torchbind_2 = None add_2 = torch.ops.aten.add.Tensor(sub, arg1_1); sub = arg1_1 = None return (add_2, add_1, arg0_1) """, ) # turn off tq type checking in eager execution mod.check_tq_is_fake = False _assertEqualSkipScriptObject(self, gm(tq, x), mod(tq1, x)) self.assertEqual(tq.size(), 0) self.assertEqual(tq1.size(), 0) def test_non_strict_export_methods(self): class Model(torch.nn.Module): def __init__(self) -> None: super().__init__() self.linear = torch.nn.Linear(2, 2) def forward(self, tq, x): x_cos = tq.pop() + tq.float_size() + self.linear(x) if tq.is_empty(): x_sin = self.linear(tq.pop()) - tq.size() + x else: x_sin = tq.pop() + tq.size() + x return x_sin, x_cos, tq mod = Model() tq = _empty_tensor_queue() a = torch.randn(2, 2) b = torch.randn(2, 2) tq.push(a) tq.push(b) ep = torch.export.export( mod, (tq, torch.randn(2, 2)), strict=False ).run_decompositions({}) self.assertExpectedInline( ep.graph_module.code.strip(), """\ def forward(self, token, p_linear_weight, p_linear_bias, tq, x): with_effects = torch.ops.higher_order.with_effects(token, torch.ops.higher_order.call_torchbind, tq, 'pop'); token = None getitem = with_effects[0] getitem_1 = with_effects[1]; with_effects = None with_effects_1 = torch.ops.higher_order.with_effects(getitem, torch.ops.higher_order.call_torchbind, tq, 'float_size'); getitem = None getitem_2 = with_effects_1[0]; with_effects_1 = None add = torch.ops.aten.add.Tensor(getitem_1, 1.0); getitem_1 = None linear = torch.ops.aten.linear.default(x, p_linear_weight, p_linear_bias); p_linear_weight = p_linear_bias = None add_1 = torch.ops.aten.add.Tensor(add, linear); add = linear = None with_effects_2 = torch.ops.higher_order.with_effects(getitem_2, torch.ops.higher_order.call_torchbind, tq, 'is_empty'); getitem_2 = None getitem_4 = with_effects_2[0]; with_effects_2 = None with_effects_3 = torch.ops.higher_order.with_effects(getitem_4, torch.ops.higher_order.call_torchbind, tq, 'pop'); getitem_4 = None getitem_6 = with_effects_3[0] getitem_7 = with_effects_3[1]; with_effects_3 = None with_effects_4 = torch.ops.higher_order.with_effects(getitem_6, torch.ops.higher_order.call_torchbind, tq, 'size'); getitem_6 = None getitem_8 = with_effects_4[0]; with_effects_4 = None add_2 = torch.ops.aten.add.Tensor(getitem_7, 0); getitem_7 = None add_3 = torch.ops.aten.add.Tensor(add_2, x); add_2 = x = None return (getitem_8, add_3, add_1, tq)""", # noqa: B950 ) self.assertEqual(tq.size(), 2) self.assertTrue(tq.pop() is a) self.assertTrue(tq.pop() is b) @skipIfCrossRef # arg names change with torch function mode def test_safe_to_trace_with_real(self): x = torch.randn(3, 3) safe_obj = torch.classes._TorchScriptTesting._ConstantTensorContainer(x) class Mod(torch.nn.Module): def forward(self, safe_obj: torch.ScriptObject) -> None: return safe_obj.get().sin() mod = Mod() backend = EagerAndRecordGraphs() out = torch.compile(mod, backend=backend, fullgraph=True)(safe_obj) self.assertEqual(out, mod(safe_obj)) self.assertExpectedInline( backend.graphs[0].code.strip(), """\ def forward(self, L_safe_obj_ : torch.ScriptObject): l_safe_obj_ = L_safe_obj_ call_torchbind = torch.ops.higher_order.call_torchbind(l_safe_obj_, 'get'); l_safe_obj_ = None sin = call_torchbind.sin(); call_torchbind = None return (sin,)""", ) with enable_torchbind_tracing(): ep = torch.export.export(mod, (safe_obj,), strict=False).run_decompositions( {} ) self.assertExpectedInline( ep.graph_module.code.strip(), """\ def forward(self, token, safe_obj): with_effects = torch.ops.higher_order.with_effects(token, torch.ops.higher_order.call_torchbind, safe_obj, 'get'); token = safe_obj = None getitem = with_effects[0] getitem_1 = with_effects[1]; with_effects = None sin = torch.ops.aten.sin.default(getitem_1); getitem_1 = None return (getitem, sin)""", # noqa: B950 ) def test_identifying_torchbind_ops(self): for op in self.torch_bind_ops: self.assertTrue(op._has_torchbind_op_overload) for op in [ torch.ops.aten.add, torch.ops.aten.cos, ]: self.assertFalse(op._has_torchbind_op_overload) def test_torchbind_op_register_fallthrough(self): TEST_DISPATCH_KEY = torch._C.DispatchKey.AutogradCPU TEST_DISPATCH_KEY_STR = "AutogradCPU" for op_packet in self.torch_bind_ops: op = op_packet.default ns, _ = torch._library.utils.parse_namespace(op_packet._qualified_op_name) with torch.library._scoped_library(ns, "FRAGMENT") as lib: lib.impl( op.name(), torch.library.fallthrough_kernel, TEST_DISPATCH_KEY_STR ) self.assertTrue( torch._C._dispatch_kernel_for_dispatch_key_is_fallthrough( op.name(), TEST_DISPATCH_KEY ) ) def test_torchbind_op_fallthrough_keys_respects_lib_impl(self): TEST_DISPATCH_KEY = torch._C.DispatchKey.AutogradCPU TEST_DISPATCH_KEY_STR = "AutogradCPU" tested = 0 for op_packet in self.torch_bind_ops: op = op_packet.default ns, _ = torch._library.utils.parse_namespace(op_packet._qualified_op_name) if ( not torch._C._dispatch_has_kernel_for_dispatch_key( op.name(), TEST_DISPATCH_KEY ) and TEST_DISPATCH_KEY not in op.py_kernels ): tested += 1 with torch.library._scoped_library(ns, "FRAGMENT") as lib: lib.impl( op.name(), lambda *args, **kwargs: args, TEST_DISPATCH_KEY_STR ) self.assertTrue(TEST_DISPATCH_KEY not in op._fallthrough_keys()) with torch.library._scoped_library(ns, "FRAGMENT") as lib: lib.impl( op.name(), torch.library.fallthrough_kernel, TEST_DISPATCH_KEY_STR, ) self.assertTrue(TEST_DISPATCH_KEY in op._fallthrough_keys()) self.assertTrue(tested > 0) def test_make_fx_schema_checking_script_object(self): class Model(torch.nn.Module): def forward(self, tq, x, foo): torch.ops._TorchScriptTesting.queue_push(foo, x.cos()) return tq class ModelCallByKW(torch.nn.Module): def forward(self, tq, x, foo): torch.ops._TorchScriptTesting.queue_push(x=x.cos(), foo=foo) return tq mod = Model() modkw = ModelCallByKW() foo = torch.classes._TorchScriptTesting._Foo(10, 20) x = torch.ones(3, 3) tq = torch.classes._TorchScriptTesting._TensorQueue( torch.empty( 0, ).fill_(-1) ) ns = "_TorchScriptTesting" with torch.library._scoped_library(ns, "FRAGMENT") as lib: op = torch.ops._TorchScriptTesting.queue_push lib.impl(op.__name__, torch.library.fallthrough_kernel, "AutogradCPU") lib.impl(op.__name__, torch.library.fallthrough_kernel, "ADInplaceOrView") lib.impl( op.__name__, torch.library.fallthrough_kernel, "PythonTLSSnapshot", ) with self.assertRaisesRegex( RuntimeError, "is expected to be a FakeScriptObject" ): _ = make_fx(mod, tracing_mode="fake")(tq, x, foo) with self.assertRaisesRegex( RuntimeError, "is expected to be a FakeScriptObject" ): _ = make_fx(modkw, tracing_mode="fake")(tq, x, foo) @parametrize("fallthrough_via", ["lib_impl", "py_impl"]) def test_make_fx_tensor_queue_operators(self, fallthrough_via): class Model(torch.nn.Module): def __init__(self) -> None: super().__init__() def forward(self, tq, x): with torch.autocast("cuda", dtype=torch.bfloat16): torch.ops._TorchScriptTesting.queue_push(tq, x.cos()) torch.ops._TorchScriptTesting.queue_push(tq, x.sin()) x_sin = torch.ops._TorchScriptTesting.queue_pop( tq ) - torch.ops._TorchScriptTesting.queue_size(tq) x_cos = torch.ops._TorchScriptTesting.queue_pop( tq ) + torch.ops._TorchScriptTesting.queue_size(tq) return x_sin, x_cos, tq mod = Model() tq1 = torch.classes._TorchScriptTesting._TensorQueue( torch.empty( 0, ).fill_(-1) ) tq2 = torch.classes._TorchScriptTesting._TensorQueue( torch.empty( 0, ).fill_(-1) ) x = torch.ones(2, 3) mod(tq1, x) ops = [ torch.ops._TorchScriptTesting.queue_push, torch.ops._TorchScriptTesting.queue_pop, torch.ops._TorchScriptTesting.queue_size, ] if fallthrough_via == "lib_impl": ns = "_TorchScriptTesting" with torch.library._scoped_library(ns, "FRAGMENT") as lib: for op in ops: lib.impl( op.__name__, torch.library.fallthrough_kernel, "AutogradCPU" ) gm = make_fx(mod, tracing_mode="fake")(tq1, x) else: for op in ops: op.default.py_impl(torch._C.DispatchKey.AutogradCPU)( torch.library.fallthrough_kernel ) gm = make_fx(mod, tracing_mode="fake")(tq1, x) for op in ops: op.default._dispatch_cache.clear() del op.default.py_kernels[torch._C.DispatchKey.AutogradCPU] self.assertExpectedInline( gm.code.strip(), """\ def forward(self, arg0_1, arg1_1): cos = torch.ops.aten.cos.default(arg1_1) queue_push = torch.ops._TorchScriptTesting.queue_push.default(arg0_1, cos); cos = queue_push = None sin = torch.ops.aten.sin.default(arg1_1); arg1_1 = None queue_push_1 = torch.ops._TorchScriptTesting.queue_push.default(arg0_1, sin); sin = queue_push_1 = None queue_pop = torch.ops._TorchScriptTesting.queue_pop.default(arg0_1) queue_size = torch.ops._TorchScriptTesting.queue_size.default(arg0_1); queue_size = None sub = torch.ops.aten.sub.Tensor(queue_pop, 1); queue_pop = None queue_pop_1 = torch.ops._TorchScriptTesting.queue_pop.default(arg0_1) queue_size_1 = torch.ops._TorchScriptTesting.queue_size.default(arg0_1); queue_size_1 = None add = torch.ops.aten.add.Tensor(queue_pop_1, 0); queue_pop_1 = None return (sub, add, arg0_1)""", ) _assertEqualSkipScriptObject(self, gm(tq1, x), mod(tq2, x)) def test_aot_export_tensor_queue_operators(self): class Model(torch.nn.Module): def __init__(self) -> None: super().__init__() def forward(self, tq, x): torch.ops._TorchScriptTesting.queue_push(tq, x.cos()) torch.ops._TorchScriptTesting.queue_push(tq, x.sin()) x_sin = torch.ops._TorchScriptTesting.queue_pop( tq ) - torch.ops._TorchScriptTesting.queue_size(tq) x_cos = torch.ops._TorchScriptTesting.queue_pop( tq ) + torch.ops._TorchScriptTesting.queue_size(tq) return x_sin, x_cos, tq mod = Model() tq1 = torch.classes._TorchScriptTesting._TensorQueue( torch.empty( 0, ).fill_(-1) ) x = torch.ones(2, 3) fake_mode = torch._subclasses.fake_tensor.FakeTensorMode() fake_tq1 = torch._library.fake_class_registry.maybe_to_fake_obj(fake_mode, tq1) fake_x = fake_mode.from_tensor(x) gm = aot_export_module(mod, (fake_tq1, fake_x), trace_joint=False)[0] # inputs: token, tq, x # return: token, x_sin, x_cos, tq self.assertExpectedInline( gm.code.strip(), """\ def forward(self, arg0_1, arg1_1, arg2_1): cos = torch.ops.aten.cos.default(arg2_1) with_effects = torch.ops.higher_order.with_effects(arg0_1, torch.ops._TorchScriptTesting.queue_push.default, arg1_1, cos); arg0_1 = cos = None getitem = with_effects[0]; with_effects = None sin = torch.ops.aten.sin.default(arg2_1); arg2_1 = None with_effects_1 = torch.ops.higher_order.with_effects(getitem, torch.ops._TorchScriptTesting.queue_push.default, arg1_1, sin); getitem = sin = None getitem_2 = with_effects_1[0]; with_effects_1 = None with_effects_2 = torch.ops.higher_order.with_effects(getitem_2, torch.ops._TorchScriptTesting.queue_pop.default, arg1_1); getitem_2 = None getitem_4 = with_effects_2[0] getitem_5 = with_effects_2[1]; with_effects_2 = None with_effects_3 = torch.ops.higher_order.with_effects(getitem_4, torch.ops._TorchScriptTesting.queue_size.default, arg1_1); getitem_4 = None getitem_6 = with_effects_3[0]; with_effects_3 = None sub = torch.ops.aten.sub.Tensor(getitem_5, 1); getitem_5 = None with_effects_4 = torch.ops.higher_order.with_effects(getitem_6, torch.ops._TorchScriptTesting.queue_pop.default, arg1_1); getitem_6 = None getitem_8 = with_effects_4[0] getitem_9 = with_effects_4[1]; with_effects_4 = None with_effects_5 = torch.ops.higher_order.with_effects(getitem_8, torch.ops._TorchScriptTesting.queue_size.default, arg1_1); getitem_8 = None getitem_10 = with_effects_5[0]; with_effects_5 = None add = torch.ops.aten.add.Tensor(getitem_9, 0); getitem_9 = None return (getitem_10, sub, add, arg1_1)""", # noqa: B950 ) def test_export_inplace_custom_op(self): class Model(torch.nn.Module): def forward(self, tq: torch.ScriptObject, x: torch.Tensor) -> None: torch.ops._TorchScriptTesting.queue_push(tq, x) return tq mod = Model() ep = self._test_export_same_as_eager( mod, (_empty_tensor_queue(), torch.randn(3, 3)), strict=False, pre_dispatch=True, ) self.assertExpectedInline( ep.module().code.strip(), """\ def forward(self, tq, x): tq, x, = fx_pytree.tree_flatten_spec(([tq, x], {}), self._in_spec) _guards_fn = self._guards_fn(tq, x); _guards_fn = None queue_push_default = torch.ops._TorchScriptTesting.queue_push.default(tq, x); x = queue_push_default = None return pytree.tree_unflatten((tq,), self._out_spec)""", ) self.assertExpectedInline( ep.graph_module.code.strip(), """\ def forward(self, token, tq, x): with_effects = torch.ops.higher_order.with_effects(token, torch.ops._TorchScriptTesting.queue_push.default, tq, x); token = x = None getitem = with_effects[0]; with_effects = None return (getitem, tq)""", # noqa: B950 ) self.assertExpectedInline( str(ep.graph_module.graph).strip(), """\ graph(): %token : [num_users=1] = placeholder[target=token] %tq : [num_users=2] = placeholder[target=tq] %x : [num_users=1] = placeholder[target=x] %with_effects : [num_users=1] = call_function[target=torch.ops.higher_order.with_effects](args = (%token, _TorchScriptTesting.queue_push.default, %tq, %x), kwargs = {}) %getitem : [num_users=1] = call_function[target=operator.getitem](args = (%with_effects, 0), kwargs = {}) return (getitem, tq)""", # noqa: B950 ) def test_deepcopy(self): tq = torch.classes._TorchScriptTesting._TensorQueue( torch.empty( 0, ).fill_(-1) ) tq_0 = copy.deepcopy(tq) tq.push(torch.zeros(2, 2)) tq.push(torch.ones(2, 2)) tq_1 = copy.deepcopy(tq) tq.push(torch.ones(2, 2) * 2) self.assertEqual(tq_0.size(), 0) self.assertEqual(tq_1.size(), 2) self.assertEqual(tq.size(), 3) foo = torch.classes._TorchScriptTesting._Foo(1, 2) foo_0 = copy.deepcopy(foo) foo.increment(1) foo_1 = copy.deepcopy(foo) foo.increment(1) self.assertEqual(foo_0.add(1), 3) self.assertEqual(foo_1.add(1), 5) self.assertEqual(foo.add(1), 7)
TestExportTorchbind
python
Textualize__textual
docs/examples/styles/offset.py
{ "start": 64, "end": 383 }
class ____(App): CSS_PATH = "offset.tcss" def compose(self): yield Label("Paul (offset 8 2)", classes="paul") yield Label("Duncan (offset 4 10)", classes="duncan") yield Label("Chani (offset 0 -3)", classes="chani") if __name__ == "__main__": app = OffsetApp() app.run()
OffsetApp
python
sqlalchemy__sqlalchemy
test/dialect/mysql/test_query.py
{ "start": 2019, "end": 3562 }
class ____(fixtures.TestBase): __only_on__ = "mysql", "mariadb" __backend__ = True @testing.combinations( (Integer, text("10")), (Integer, text("'10'")), (Integer, "10"), (Boolean, true()), (Integer, text("3+5"), testing.requires.mysql_expression_defaults), (Integer, text("3 + 5"), testing.requires.mysql_expression_defaults), (Integer, text("(3 * 5)"), testing.requires.mysql_expression_defaults), (DateTime, func.now()), ( Integer, literal_column("3") + literal_column("5"), testing.requires.mysql_expression_defaults, ), ( DateTime, text("now() ON UPDATE now()"), ), ( DateTime, text("now() on update now()"), ), ( DateTime, text("now() ON UPDATE now()"), ), ( TIMESTAMP(fsp=3), text("now(3)"), testing.requires.mysql_fsp, ), ( TIMESTAMP(fsp=3), text("CURRENT_TIMESTAMP(3)"), testing.requires.mysql_fsp, ), argnames="datatype, default", ) def test_create_server_defaults( self, connection, metadata, datatype, default ): t = Table( "t", metadata, Column("id", Integer, primary_key=True), Column("thecol", datatype, server_default=default), ) t.create(connection)
ServerDefaultCreateTest