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
pytorch__pytorch
torch/_functorch/partitioners.py
{ "start": 3019, "end": 4081 }
class ____: # Be careful about iterating over these explicitly, as their order may not # be deterministic inputs: list[fx.Node] _required_fw_nodes: OrderedSet[fx.Node] required_bw_nodes: OrderedSet[fx.Node] unclaimed_nodes: OrderedSet[fx.Node] fw_order: dict[fx.Node, int] # Effectively maps to which of our primals are parameters static_lifetime_input_nodes: OrderedSet[fx.Node] @functools.cached_property def required_fw_nodes(self) -> list[fx.Node]: return sorted( (n for n in self._required_fw_nodes), key=lambda n: self.fw_order[n] ) def is_required_fw(self, n: fx.Node) -> bool: return n in self._required_fw_nodes def is_required_bw(self, n: fx.Node) -> bool: return n in self.required_bw_nodes def is_unclaimed(self, n: fx.Node) -> bool: return n in self.unclaimed_nodes def get_fw_order(self, n: fx.Node) -> int: assert n in self._required_fw_nodes, f"Node {n} not in fw nodes!" return self.fw_order[n] @dataclass
NodeInfo
python
tensorflow__tensorflow
tensorflow/python/framework/extension_type_test.py
{ "start": 2610, "end": 2772 }
class ____(extension_type.ExtensionType): """Example subclass of ExtensionType, used for testing.""" values: tensor.Tensor mask: tensor.Tensor
MaskedTensorV1
python
kamyu104__LeetCode-Solutions
Python/maximum-points-tourist-can-earn.py
{ "start": 40, "end": 472 }
class ____(object): def maxScore(self, n, k, stayScore, travelScore): """ :type n: int :type k: int :type stayScore: List[List[int]] :type travelScore: List[List[int]] :rtype: int """ dp = [0]*n for i in xrange(k): dp = [max(dp[u]+stayScore[i][u], max(dp[v]+travelScore[v][u] for v in xrange(n))) for u in xrange(n)] return max(dp)
Solution
python
PrefectHQ__prefect
tests/server/utilities/test_database.py
{ "start": 880, "end": 1060 }
class ____(pydantic.BaseModel): x: int y: datetime.datetime = pydantic.Field( default_factory=lambda: datetime.datetime.now(datetime.timezone.utc) )
PydanticModel
python
pytorch__pytorch
torch/testing/_internal/common_fsdp.py
{ "start": 58432, "end": 58625 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.lin = nn.Linear(10, 10, bias=False) def forward(self, x): return self.lin(x)
SkipModule
python
nedbat__coveragepy
tests/test_collector.py
{ "start": 380, "end": 1698 }
class ____(CoverageTest): """Test specific aspects of the collection process.""" def test_should_trace_cache(self) -> None: # The tracers should only invoke should_trace once for each file name. # Make some files that invoke each other. self.make_file( "f1.py", """\ def f1(x, f): return f(x) """, ) self.make_file( "f2.py", """\ import f1 def func(x): return f1.f1(x, otherfunc) def otherfunc(x): return x*x for i in range(10): func(i) """, ) # Trace one file, but not the other. CheckUniqueFilenames will assert # that _should_trace hasn't been called twice for the same file. cov = coverage.Coverage(include=["f1.py"]) should_trace_hook = CheckUniqueFilenames.hook(cov, "_should_trace") # Import the Python file, executing it. self.start_import_stop(cov, "f2") # Double-check that our files were checked. abs_files = {os.path.abspath(f) for f in should_trace_hook.filenames} assert os.path.abspath("f1.py") in abs_files assert os.path.abspath("f2.py") in abs_files
CollectorTest
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/contrib/regular_languages/validation.py
{ "start": 270, "end": 2059 }
class ____(Validator): """ Validator which can be used for validation according to variables in the grammar. Each variable can have its own validator. :param compiled_grammar: `GrammarCompleter` instance. :param validators: `dict` mapping variable names of the grammar to the `Validator` instances to be used for each variable. """ def __init__( self, compiled_grammar: _CompiledGrammar, validators: dict[str, Validator] ) -> None: self.compiled_grammar = compiled_grammar self.validators = validators def validate(self, document: Document) -> None: # Parse input document. # We use `match`, not `match_prefix`, because for validation, we want # the actual, unambiguous interpretation of the input. m = self.compiled_grammar.match(document.text) if m: for v in m.variables(): validator = self.validators.get(v.varname) if validator: # Unescape text. unwrapped_text = self.compiled_grammar.unescape(v.varname, v.value) # Create a document, for the completions API (text/cursor_position) inner_document = Document(unwrapped_text, len(unwrapped_text)) try: validator.validate(inner_document) except ValidationError as e: raise ValidationError( cursor_position=v.start + e.cursor_position, message=e.message, ) from e else: raise ValidationError( cursor_position=len(document.text), message="Invalid command" )
GrammarValidator
python
tensorflow__tensorflow
tensorflow/python/client/session.py
{ "start": 66984, "end": 71306 }
class ____(BaseSession): """A TensorFlow `Session` for use in interactive contexts, such as a shell. The only difference with a regular `Session` is that an `InteractiveSession` installs itself as the default session on construction. The methods `tf.Tensor.eval` and `tf.Operation.run` will use that session to run ops. This is convenient in interactive shells and [IPython notebooks](http://ipython.org), as it avoids having to pass an explicit `Session` object to run ops. For example: ```python sess = tf.compat.v1.InteractiveSession() a = tf.constant(5.0) b = tf.constant(6.0) c = a * b # We can just use 'c.eval()' without passing 'sess' print(c.eval()) sess.close() ``` Note that a regular session installs itself as the default session when it is created in a `with` statement. The common usage in non-interactive programs is to follow that pattern: ```python a = tf.constant(5.0) b = tf.constant(6.0) c = a * b with tf.compat.v1.Session(): # We can also use 'c.eval()' here. print(c.eval()) ``` """ _count_lock = threading.Lock() _active_session_count = 0 # GUARDED_BY(_count_lock) def __init__(self, target='', graph=None, config=None): """Creates a new interactive TensorFlow session. If no `graph` argument is specified when constructing the session, the default graph will be launched in the session. If you are using more than one graph (created with `tf.Graph()`) in the same process, you will have to use different sessions for each graph, but each graph can be used in multiple sessions. In this case, it is often clearer to pass the graph to be launched explicitly to the session constructor. Args: target: (Optional.) The execution engine to connect to. Defaults to using an in-process engine. graph: (Optional.) The `Graph` to be launched (described above). config: (Optional) `ConfigProto` proto used to configure the session. """ if not config: # If config is not provided, choose some reasonable defaults for # interactive use: # # - Grow GPU memory as needed at the cost of fragmentation. gpu_options = config_pb2.GPUOptions(allow_growth=True) config = config_pb2.ConfigProto(gpu_options=gpu_options) # Interactive sessions always place pruned graphs. config.graph_options.place_pruned_graph = True super(InteractiveSession, self).__init__(target, graph, config) with InteractiveSession._count_lock: if InteractiveSession._active_session_count > 0: logging.error( 'An interactive session is already active. This can cause' ' out-of-memory errors or some other unexpected errors (due to' ' the unpredictable timing of garbage collection) in some cases.' ' You must explicitly call `InteractiveSession.close()` to release' ' resources held by the other session(s). Please use `tf.Session()`' ' if you intend to productionize.' ) InteractiveSession._active_session_count += 1 # NOTE(mrry): We do not use `Session._closed` here because it has unhelpful # semantics (in particular, it is not set to true if `Session.close()` is # called on a session that has not been "opened" by running a step) and we # cannot change those semantics without breaking existing code. self._explicitly_closed = False self._default_session = self.as_default() self._default_session.enforce_nesting = False self._default_session.__enter__() self._explicit_graph = graph if self._explicit_graph is not None: self._default_graph = graph.as_default() self._default_graph.enforce_nesting = False self._default_graph.__enter__() def close(self): """Closes an `InteractiveSession`.""" super(InteractiveSession, self).close() with InteractiveSession._count_lock: if not self._explicitly_closed: InteractiveSession._active_session_count -= 1 self._explicitly_closed = True else: return if self._explicit_graph is not None: self._default_graph.__exit__(None, None, None) self._default_graph = None self._default_session.__exit__(None, None, None) self._default_session = None
InteractiveSession
python
getsentry__sentry
src/sentry/audit_log/manager.py
{ "start": 234, "end": 1304 }
class ____(Exception): pass """ The audit log system records changes made to an organization and displays them in organization settings. To add a new audit log event: 1. Create a new instance of AuditLogEvent. You'll need an event_id, name, api_name, and optional template. Note: The template uses AuditLogEntry.data fields to construct a simple audit log message. For more complicated messages, subclass AuditLogEvent in events.py and override the render function. 2. Register the AuditLogEvent using `default_manager.add()`. default_manager.add( AuditLogEvent( event_id=1, name="MEMBER_INVITE", api_name="member.invite", template="invited member {email}", ) ) 3. Record your AuditLogEvent. self.create_audit_entry( request=request, organization_id=organization.id, target_object=member.id, data={"email": "email@gmail.com"}, event=audit_log.get_event_id(MEMBER_INVITE), ) """ @dataclass(init=False)
AuditLogEventNotRegistered
python
allegroai__clearml
clearml/utilities/pyhocon/exceptions.py
{ "start": 231, "end": 294 }
class ____(ConfigException): pass
ConfigSubstitutionException
python
django__django
tests/auth_tests/models/is_active.py
{ "start": 104, "end": 432 }
class ____(AbstractBaseUser): """ This test user class and derivatives test the default is_active behavior """ username = models.CharField(max_length=30, unique=True) custom_objects = BaseUserManager() USERNAME_FIELD = "username" # the is_active attr is provided by AbstractBaseUser
IsActiveTestUser1
python
readthedocs__readthedocs.org
readthedocs/projects/views/private.py
{ "start": 37242, "end": 37661 }
class ____(ProjectAdminMixin, PrivateViewMixin): """Environment variables to be added when building the Project.""" model = EnvironmentVariable form_class = EnvironmentVariableForm lookup_url_kwarg = "environmentvariable_pk" def get_success_url(self): return reverse( "projects_environmentvariables", args=[self.get_project().slug], )
EnvironmentVariableMixin
python
facebookresearch__faiss
tests/test_standalone_codec.py
{ "start": 2116, "end": 3497 }
class ____(unittest.TestCase): def do_test(self, key1, key2): d = 96 nb = 1000 nq = 0 nt = 2000 xt, x, _ = get_dataset_2(d, nt, nb, nq) codec_ref = faiss.index_factory(d, key1) codec_ref.train(xt) code_ref = codec_ref.sa_encode(x) x_recons_ref = codec_ref.sa_decode(code_ref) codec_new = faiss.index_factory(d, key2) codec_new.pq = codec_ref.pq # replace quantizer, avoiding mem leak oldq = codec_new.q1.quantizer oldq.this.own() codec_new.q1.own_fields = False codec_new.q1.quantizer = codec_ref.quantizer codec_new.is_trained = True code_new = codec_new.sa_encode(x) x_recons_new = codec_new.sa_decode(code_new) self.assertTrue(np.all(code_new == code_ref)) self.assertTrue(np.all(x_recons_new == x_recons_ref)) codec_new_2 = faiss.deserialize_index( faiss.serialize_index(codec_new)) code_new = codec_new_2.sa_encode(x) x_recons_new = codec_new_2.sa_decode(code_new) self.assertTrue(np.all(code_new == code_ref)) self.assertTrue(np.all(x_recons_new == x_recons_ref)) def test_IVFPQ(self): self.do_test("IVF512,PQ6np", "Residual512,PQ6") def test_IMI(self): self.do_test("IMI2x5,PQ6np", "Residual2x5,PQ6")
TestIndexEquiv
python
protocolbuffers__protobuf
python/google/protobuf/json_format.py
{ "start": 1931, "end": 5360 }
class ____(ParseError): """Thrown if unknown string enum value is encountered. This exception is suppressed if ignore_unknown_fields is set. """ def MessageToJson( message, preserving_proto_field_name=False, indent=2, sort_keys=False, use_integers_for_enums=False, descriptor_pool=None, ensure_ascii=True, always_print_fields_with_no_presence=False, ): """Converts protobuf message to JSON format. Args: message: The protocol buffers message instance to serialize. always_print_fields_with_no_presence: If True, fields without presence (implicit presence scalars, repeated fields, and map fields) will always be serialized. Any field that supports presence is not affected by this option (including singular message fields and oneof fields). preserving_proto_field_name: If True, use the original proto field names as defined in the .proto file. If False, convert the field names to lowerCamelCase. indent: The JSON object will be pretty-printed with this indent level. An indent level of 0 or negative will only insert newlines. If the indent level is None, no newlines will be inserted. sort_keys: If True, then the output will be sorted by field names. use_integers_for_enums: If true, print integers instead of enum names. descriptor_pool: A Descriptor Pool for resolving types. If None use the default. ensure_ascii: If True, strings with non-ASCII characters are escaped. If False, Unicode strings are returned unchanged. Returns: A string containing the JSON formatted protocol buffer message. """ printer = _Printer( preserving_proto_field_name, use_integers_for_enums, descriptor_pool, always_print_fields_with_no_presence, ) return printer.ToJsonString(message, indent, sort_keys, ensure_ascii) def MessageToDict( message, always_print_fields_with_no_presence=False, preserving_proto_field_name=False, use_integers_for_enums=False, descriptor_pool=None, ): """Converts protobuf message to a dictionary. When the dictionary is encoded to JSON, it conforms to ProtoJSON spec. Args: message: The protocol buffers message instance to serialize. always_print_fields_with_no_presence: If True, fields without presence (implicit presence scalars, repeated fields, and map fields) will always be serialized. Any field that supports presence is not affected by this option (including singular message fields and oneof fields). preserving_proto_field_name: If True, use the original proto field names as defined in the .proto file. If False, convert the field names to lowerCamelCase. use_integers_for_enums: If true, print integers instead of enum names. descriptor_pool: A Descriptor Pool for resolving types. If None use the default. Returns: A dict representation of the protocol buffer message. """ printer = _Printer( preserving_proto_field_name, use_integers_for_enums, descriptor_pool, always_print_fields_with_no_presence, ) # pylint: disable=protected-access return printer._MessageToJsonObject(message) def _IsMapEntry(field): return ( field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and field.message_type.has_options and field.message_type.GetOptions().map_entry )
EnumStringValueParseError
python
keras-team__keras
keras/src/callbacks/monitor_callback_test.py
{ "start": 212, "end": 2875 }
class ____(testing.TestCase): @pytest.mark.requires_trainable_backend def test_monitor_op_logic(self): x_train = np.random.random((10, 5)) y_train = np.random.random((10, 1)) x_test = np.random.random((10, 5)) y_test = np.random.random((10, 1)) model = models.Sequential( ( layers.Dense(1, activation="relu"), layers.Dense(1, activation="relu"), ) ) model.compile( loss="mae", optimizer="adam", metrics=[ "mse", "acc", "accuracy", "hinge", metrics.F1Score(name="f1_score"), ], ) cases = [ ("max", "val_mse", "max"), ("min", "val_loss", "min"), ("auto", "val_mse", "min"), ("auto", "loss", "min"), ("auto", "acc", "max"), ("auto", "val_accuracy", "max"), ("auto", "hinge", "min"), ("auto", "f1_score", "max"), ] for mode, monitor, expected_mode in cases: monitor_callback = callbacks.MonitorCallback(monitor, mode) monitor_callback.set_model(model) model.fit( x_train, y_train, batch_size=5, validation_data=(x_test, y_test), epochs=2, verbose=0, ) monitor_callback._set_monitor_op() if expected_mode == "max": monitor_op = ops.greater else: monitor_op = ops.less self.assertEqual(monitor_callback.monitor_op, monitor_op) with self.assertRaises(ValueError): monitor = "unknown" monitor_callback = callbacks.MonitorCallback(monitor) monitor_callback.set_model(model) model.fit( x_train, y_train, batch_size=5, validation_data=(x_test, y_test), epochs=2, verbose=0, ) monitor_callback._set_monitor_op() @pytest.mark.requires_trainable_backend def test_min_delta(self): monitor_callback = callbacks.MonitorCallback(mode="max", min_delta=0.5) monitor_callback._set_monitor_op() self.assertTrue(monitor_callback._is_improvement(0.75, 0)) self.assertTrue(monitor_callback._is_improvement(0.5, None)) self.assertFalse(monitor_callback._is_improvement(0.5, 0)) self.assertFalse(monitor_callback._is_improvement(0.2, 0.5))
MonitorCallbackTest
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/refurb/FURB189.py
{ "start": 476, "end": 543 }
class ____(list[str]): pass # currently not detected
SubscriptList
python
pallets__werkzeug
src/werkzeug/routing/converters.py
{ "start": 6508, "end": 7297 }
class ____(BaseConverter): """This converter only accepts UUID strings:: Rule('/object/<uuid:identifier>') .. versionadded:: 0.10 :param map: the :class:`Map`. """ regex = ( r"[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-" r"[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}" ) def to_python(self, value: str) -> uuid.UUID: return uuid.UUID(value) def to_url(self, value: uuid.UUID) -> str: return str(value) #: the default converter mapping for the map. DEFAULT_CONVERTERS: t.Mapping[str, type[BaseConverter]] = { "default": UnicodeConverter, "string": UnicodeConverter, "any": AnyConverter, "path": PathConverter, "int": IntegerConverter, "float": FloatConverter, "uuid": UUIDConverter, }
UUIDConverter
python
huggingface__transformers
src/transformers/models/esm/modeling_esm.py
{ "start": 22652, "end": 29367 }
class ____(EsmPreTrainedModel): """ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of cross-attention is added between the self-attention layers, following the architecture described in [Attention is all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass. """ def __init__(self, config, add_pooling_layer=True): r""" add_pooling_layer (bool, *optional*, defaults to `True`): Whether to add a pooling layer """ super().__init__(config) self.config = config self.embeddings = EsmEmbeddings(config) self.encoder = EsmEncoder(config) self.pooler = EsmPooler(config) if add_pooling_layer else None self.contact_head = EsmContactPredictionHead( in_features=config.num_hidden_layers * config.num_attention_heads, bias=True ) # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, value): self.embeddings.word_embeddings = value @check_model_inputs() @auto_docstring def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.Tensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]: r""" input_ids (`torch.LongTensor` of shape `((batch_size, sequence_length))`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) position_ids (`torch.LongTensor` of shape `((batch_size, sequence_length))`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids) inputs_embeds (`torch.FloatTensor` of shape `((batch_size, sequence_length), hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. """ if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if inputs_embeds is None: inputs_embeds = self.embeddings( input_ids=input_ids, position_ids=position_ids, ) attention_mask, encoder_attention_mask = self._create_attention_masks( attention_mask=attention_mask, encoder_attention_mask=encoder_attention_mask, embedding_output=inputs_embeds, encoder_hidden_states=encoder_hidden_states, # There is no real logic for decoder generation, creating values on the fly cache_position=torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device), past_key_values=None, ) encoder_outputs = self.encoder( inputs_embeds, attention_mask=attention_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, **kwargs, ) sequence_output = encoder_outputs[0] pooled_output = self.pooler(sequence_output) if self.pooler is not None else None return BaseModelOutputWithPoolingAndCrossAttentions( last_hidden_state=sequence_output, pooler_output=pooled_output, ) # Copied from transformers.models.bert.modeling_bert.BertModel._create_attention_masks def _create_attention_masks( self, attention_mask, encoder_attention_mask, embedding_output, encoder_hidden_states, cache_position, past_key_values, ): if self.config.is_decoder: attention_mask = create_causal_mask( config=self.config, input_embeds=embedding_output, attention_mask=attention_mask, cache_position=cache_position, past_key_values=past_key_values, ) else: attention_mask = create_bidirectional_mask( config=self.config, input_embeds=embedding_output, attention_mask=attention_mask, ) if encoder_attention_mask is not None: encoder_attention_mask = create_bidirectional_mask( config=self.config, input_embeds=embedding_output, attention_mask=encoder_attention_mask, encoder_hidden_states=encoder_hidden_states, ) return attention_mask, encoder_attention_mask def predict_contacts(self, tokens, attention_mask): attns = self(tokens, attention_mask=attention_mask, return_dict=True, output_attentions=True).attentions attns = torch.stack(attns, dim=1) # Matches the original model layout # In the original model, attentions for padding tokens are completely zeroed out. # This makes no difference most of the time because the other tokens won't attend to them, # but it does for the contact prediction task, which takes attentions as input, # so we have to mimic that here. attns *= attention_mask.unsqueeze(1).unsqueeze(2).unsqueeze(3) attns *= attention_mask.unsqueeze(1).unsqueeze(2).unsqueeze(4) return self.contact_head(tokens, attns) @auto_docstring
EsmModel
python
fluentpython__example-code-2e
05-data-classes/cards.py
{ "start": 58, "end": 208 }
class ____: rank: str suit: str ranks = [str(n) for n in range(2, 10)] + list('JQKA') suits = 'spades diamonds clubs hearts'.split()
Card
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 5021, "end": 5626 }
class ____: """Subclass of unittest.TestCase with thread-safe cleanup methods. This subclass protects the addCleanup() and doCleanups() methods with a recursive lock. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._cleanup_lock = threading.RLock() def addCleanup(self, *args, **kwargs): with self._cleanup_lock: return super().addCleanup(*args, **kwargs) def doCleanups(self, *args, **kwargs): with self._cleanup_lock: return super().doCleanups(*args, **kwargs)
ThreadSafeCleanupTestCase
python
python__mypy
mypy/server/astmerge.py
{ "start": 15438, "end": 20982 }
class ____(SyntheticTypeVisitor[None]): """Similar to NodeReplaceVisitor, but for type objects. Note: this visitor may sometimes visit unanalyzed types such as 'UnboundType' and 'RawExpressionType' For example, see NodeReplaceVisitor.process_base_func. """ def __init__(self, replacements: dict[SymbolNode, SymbolNode]) -> None: self.replacements = replacements def visit_instance(self, typ: Instance) -> None: typ.type = self.fixup(typ.type) for arg in typ.args: arg.accept(self) if typ.last_known_value: typ.last_known_value.accept(self) def visit_type_alias_type(self, typ: TypeAliasType) -> None: assert typ.alias is not None typ.alias = self.fixup(typ.alias) for arg in typ.args: arg.accept(self) def visit_any(self, typ: AnyType) -> None: pass def visit_none_type(self, typ: NoneType) -> None: pass def visit_callable_type(self, typ: CallableType) -> None: for arg in typ.arg_types: arg.accept(self) typ.ret_type.accept(self) if typ.definition: # No need to fixup since this is just a cross-reference. typ.definition = self.replacements.get(typ.definition, typ.definition) # Fallback can be None for callable types that haven't been semantically analyzed. if typ.fallback is not None: typ.fallback.accept(self) for tv in typ.variables: if isinstance(tv, TypeVarType): tv.upper_bound.accept(self) for value in tv.values: value.accept(self) def visit_overloaded(self, t: Overloaded) -> None: for item in t.items: item.accept(self) # Fallback can be None for overloaded types that haven't been semantically analyzed. if t.fallback is not None: t.fallback.accept(self) def visit_erased_type(self, t: ErasedType) -> None: # This type should exist only temporarily during type inference raise RuntimeError("Cannot handle erased type") def visit_deleted_type(self, typ: DeletedType) -> None: pass def visit_partial_type(self, typ: PartialType) -> None: raise RuntimeError("Cannot handle partial type") def visit_tuple_type(self, typ: TupleType) -> None: for item in typ.items: item.accept(self) # Fallback can be None for implicit tuple types that haven't been semantically analyzed. if typ.partial_fallback is not None: typ.partial_fallback.accept(self) def visit_type_type(self, typ: TypeType) -> None: typ.item.accept(self) def visit_type_var(self, typ: TypeVarType) -> None: typ.upper_bound.accept(self) typ.default.accept(self) for value in typ.values: value.accept(self) def visit_param_spec(self, typ: ParamSpecType) -> None: typ.upper_bound.accept(self) typ.default.accept(self) typ.prefix.accept(self) def visit_type_var_tuple(self, typ: TypeVarTupleType) -> None: typ.upper_bound.accept(self) typ.default.accept(self) def visit_unpack_type(self, typ: UnpackType) -> None: typ.type.accept(self) def visit_parameters(self, typ: Parameters) -> None: for arg in typ.arg_types: arg.accept(self) def visit_typeddict_type(self, typ: TypedDictType) -> None: for value_type in typ.items.values(): value_type.accept(self) typ.fallback.accept(self) def visit_raw_expression_type(self, t: RawExpressionType) -> None: pass def visit_literal_type(self, typ: LiteralType) -> None: typ.fallback.accept(self) def visit_unbound_type(self, typ: UnboundType) -> None: for arg in typ.args: arg.accept(self) def visit_type_list(self, typ: TypeList) -> None: for item in typ.items: item.accept(self) def visit_callable_argument(self, typ: CallableArgument) -> None: typ.typ.accept(self) def visit_ellipsis_type(self, typ: EllipsisType) -> None: pass def visit_uninhabited_type(self, typ: UninhabitedType) -> None: pass def visit_union_type(self, typ: UnionType) -> None: for item in typ.items: item.accept(self) def visit_placeholder_type(self, t: PlaceholderType) -> None: for item in t.args: item.accept(self) # Helpers def fixup(self, node: SN) -> SN: if node in self.replacements: new = self.replacements[node] return cast(SN, new) return node def replace_nodes_in_symbol_table( symbols: SymbolTable, replacements: dict[SymbolNode, SymbolNode] ) -> None: for node in symbols.values(): if node.node: if node.node in replacements: new = replacements[node.node] old = node.node replace_object_state(new, old, skip_slots=_get_ignored_slots(new)) node.node = new if isinstance(node.node, (Var, TypeAlias)): # Handle them here just in case these aren't exposed through the AST. node.node.accept(NodeReplaceVisitor(replacements)) def _get_ignored_slots(node: SymbolNode) -> tuple[str, ...]: if isinstance(node, OverloadedFuncDef): return ("setter",) if isinstance(node, TypeInfo): return ("special_alias",) return ()
TypeReplaceVisitor
python
viewflow__viewflow
viewflow/forms/renderers.py
{ "start": 22585, "end": 23920 }
class ____(LayoutNode): """Span a form field over several columns. Example:: layout = Layout( Row(Span('first_name'), Span('last_name')) Row( Span('email', tablet=6, mobile=3), 'sex' ) ) By default span is auto-sized. On a desktop all auto-sized elements would be spread equally over the free place of a row, non occupied by elements with specific sizes. On mobile and tablet if all elements in a row have auto-sizes, each element would be placed in a new line. If even one element in a row has a specific size, all auto-sized elements would be kept in a single line, like on a desktop. """ def __init__(self, field_name, **kwargs): self.field_name = field_name super().__init__(**kwargs) def __str__(self): return f"Field {self.field_name} <{self.desktop}, {self.tablet}, {self.mobile}>" def append(self, layout: FormLayout, form: forms.Form, root: ElementTree.Element): try: bound_field = form[self.field_name] except KeyError as exc: raise ValueError( f"{self.field_name} field not found in the {type(form).__name__}" ) from exc layout.append_field(root, bound_field, layout_node=self)
Span
python
huggingface__transformers
tests/models/pop2piano/test_tokenization_pop2piano.py
{ "start": 1310, "end": 17241 }
class ____(unittest.TestCase): def setUp(self): super().setUp() self.tokenizer = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano") def get_input_notes(self): notes = [ [ pretty_midi.Note(start=0.441179, end=2.159456, pitch=70, velocity=77), pretty_midi.Note(start=0.673379, end=0.905578, pitch=73, velocity=77), pretty_midi.Note(start=0.905578, end=2.159456, pitch=73, velocity=77), pretty_midi.Note(start=1.114558, end=2.159456, pitch=78, velocity=77), pretty_midi.Note(start=1.323537, end=1.532517, pitch=80, velocity=77), ], [ pretty_midi.Note(start=0.441179, end=2.159456, pitch=70, velocity=77), ], ] return notes def test_call(self): notes = self.get_input_notes() output = self.tokenizer( notes, return_tensors="pt", padding="max_length", truncation=True, max_length=10, return_attention_mask=True, ) # check the output type self.assertTrue(isinstance(output, BatchEncoding)) # check the values expected_output_token_ids = torch.tensor( [[134, 133, 74, 135, 77, 132, 77, 133, 77, 82], [134, 133, 74, 136, 132, 74, 134, 134, 134, 134]] ) expected_output_attention_mask = torch.tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 0, 0, 0, 0]]) torch.testing.assert_close(output["token_ids"], expected_output_token_ids, rtol=1e-4, atol=1e-4) torch.testing.assert_close(output["attention_mask"], expected_output_attention_mask, rtol=1e-4, atol=1e-4) def test_batch_decode(self): # test batch decode with model, feature-extractor outputs(beatsteps, extrapolated_beatstep) # Please note that this test does not test the accuracy of the outputs, instead it is designed to make sure that # the tokenizer's batch_decode can deal with attention_mask in feature-extractor outputs. For the accuracy check # please see the `test_batch_decode_outputs` test. model_output = torch.concatenate( [ torch.randint(size=[120, 96], low=0, high=70, dtype=torch.long), torch.zeros(size=[1, 96], dtype=torch.long), torch.randint(size=[50, 96], low=0, high=40, dtype=torch.long), torch.zeros(size=[1, 96], dtype=torch.long), ], axis=0, ) input_features = BatchFeature( { "beatsteps": torch.ones([2, 955]), "extrapolated_beatstep": torch.ones([2, 1000]), "attention_mask": torch.concatenate( [ torch.ones([120, 96], dtype=torch.long), torch.zeros([1, 96], dtype=torch.long), torch.ones([50, 96], dtype=torch.long), torch.zeros([1, 96], dtype=torch.long), ], axis=0, ), "attention_mask_beatsteps": torch.ones([2, 955]), "attention_mask_extrapolated_beatstep": torch.ones([2, 1000]), } ) output = self.tokenizer.batch_decode(token_ids=model_output, feature_extractor_output=input_features)[ "pretty_midi_objects" ] # check length self.assertTrue(len(output) == 2) # check object type self.assertTrue(isinstance(output[0], pretty_midi.pretty_midi.PrettyMIDI)) self.assertTrue(isinstance(output[1], pretty_midi.pretty_midi.PrettyMIDI)) def test_batch_decode_outputs(self): # test batch decode with model, feature-extractor outputs(beatsteps, extrapolated_beatstep) # Please note that this test tests the accuracy of the outputs of the tokenizer's `batch_decode` method. model_output = torch.tensor( [ [134, 133, 74, 135, 77, 82, 84, 136, 132, 74, 77, 82, 84], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], ] ) input_features = BatchEncoding( { "beatsteps": torch.tensor([[0.0697, 0.1103, 0.1509, 0.1916]]), "extrapolated_beatstep": torch.tensor([[0.0000, 0.0406, 0.0813, 0.1219]]), } ) output = self.tokenizer.batch_decode(token_ids=model_output, feature_extractor_output=input_features) # check outputs self.assertEqual(len(output["notes"]), 4) predicted_start_timings, predicted_end_timings = [], [] for i in output["notes"]: predicted_start_timings.append(i.start) predicted_end_timings.append(i.end) # Checking note start timings expected_start_timings = torch.tensor( [ 0.069700, 0.110300, 0.110300, 0.110300, ] ) predicted_start_timings = torch.tensor(predicted_start_timings) torch.testing.assert_close(expected_start_timings, predicted_start_timings, rtol=1e-4, atol=1e-4) # Checking note end timings expected_end_timings = torch.tensor( [ 0.191600, 0.191600, 0.191600, 0.191600, ] ) predicted_end_timings = torch.tensor(predicted_end_timings) torch.testing.assert_close(expected_end_timings, predicted_end_timings, rtol=1e-4, atol=1e-4) def test_get_vocab(self): vocab_dict = self.tokenizer.get_vocab() self.assertIsInstance(vocab_dict, dict) self.assertGreaterEqual(len(self.tokenizer), len(vocab_dict)) vocab = [self.tokenizer.convert_ids_to_tokens(i) for i in range(len(self.tokenizer))] self.assertEqual(len(vocab), len(self.tokenizer)) self.tokenizer.add_tokens(["asdfasdfasdfasdf"]) vocab = [self.tokenizer.convert_ids_to_tokens(i) for i in range(len(self.tokenizer))] self.assertEqual(len(vocab), len(self.tokenizer)) def test_save_and_load_tokenizer(self): tmpdirname = tempfile.mkdtemp() sample_notes = self.get_input_notes() self.tokenizer.add_tokens(["bim", "bambam"]) additional_special_tokens = self.tokenizer.additional_special_tokens additional_special_tokens.append("new_additional_special_token") self.tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens}) before_token_ids = self.tokenizer(sample_notes)["token_ids"] before_vocab = self.tokenizer.get_vocab() self.tokenizer.save_pretrained(tmpdirname) after_tokenizer = self.tokenizer.__class__.from_pretrained(tmpdirname) after_token_ids = after_tokenizer(sample_notes)["token_ids"] after_vocab = after_tokenizer.get_vocab() self.assertDictEqual(before_vocab, after_vocab) self.assertListEqual(before_token_ids, after_token_ids) self.assertIn("bim", after_vocab) self.assertIn("bambam", after_vocab) self.assertIn("new_additional_special_token", after_tokenizer.additional_special_tokens) shutil.rmtree(tmpdirname) def test_padding_side_in_kwargs(self): tokenizer_p = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano", padding_side="left") self.assertEqual(tokenizer_p.padding_side, "left") tokenizer_p = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano", padding_side="right") self.assertEqual(tokenizer_p.padding_side, "right") self.assertRaises( ValueError, Pop2PianoTokenizer.from_pretrained, "sweetcocoa/pop2piano", padding_side="unauthorized", ) def test_truncation_side_in_kwargs(self): tokenizer_p = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano", truncation_side="left") self.assertEqual(tokenizer_p.truncation_side, "left") tokenizer_p = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano", truncation_side="right") self.assertEqual(tokenizer_p.truncation_side, "right") self.assertRaises( ValueError, Pop2PianoTokenizer.from_pretrained, "sweetcocoa/pop2piano", truncation_side="unauthorized", ) def test_right_and_left_padding(self): tokenizer = self.tokenizer notes = self.get_input_notes() notes = notes[0] max_length = 20 padding_idx = tokenizer.pad_token_id # RIGHT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True tokenizer.padding_side = "right" padded_notes = tokenizer(notes, padding="max_length", max_length=max_length)["token_ids"] padded_notes_length = len(padded_notes) notes_without_padding = tokenizer(notes, padding="do_not_pad")["token_ids"] padding_size = max_length - len(notes_without_padding) self.assertEqual(padded_notes_length, max_length) self.assertEqual(notes_without_padding + [padding_idx] * padding_size, padded_notes) # LEFT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True tokenizer.padding_side = "left" padded_notes = tokenizer(notes, padding="max_length", max_length=max_length)["token_ids"] padded_notes_length = len(padded_notes) notes_without_padding = tokenizer(notes, padding="do_not_pad")["token_ids"] padding_size = max_length - len(notes_without_padding) self.assertEqual(padded_notes_length, max_length) self.assertEqual([padding_idx] * padding_size + notes_without_padding, padded_notes) # RIGHT & LEFT PADDING - Check that nothing is done for 'longest' and 'no_padding' notes_without_padding = tokenizer(notes)["token_ids"] tokenizer.padding_side = "right" padded_notes_right = tokenizer(notes, padding=False)["token_ids"] self.assertEqual(len(padded_notes_right), len(notes_without_padding)) self.assertEqual(padded_notes_right, notes_without_padding) tokenizer.padding_side = "left" padded_notes_left = tokenizer(notes, padding="longest")["token_ids"] self.assertEqual(len(padded_notes_left), len(notes_without_padding)) self.assertEqual(padded_notes_left, notes_without_padding) tokenizer.padding_side = "right" padded_notes_right = tokenizer(notes, padding="longest")["token_ids"] self.assertEqual(len(padded_notes_right), len(notes_without_padding)) self.assertEqual(padded_notes_right, notes_without_padding) tokenizer.padding_side = "left" padded_notes_left = tokenizer(notes, padding=False)["token_ids"] self.assertEqual(len(padded_notes_left), len(notes_without_padding)) self.assertEqual(padded_notes_left, notes_without_padding) def test_right_and_left_truncation(self): tokenizer = self.tokenizer notes = self.get_input_notes() notes = notes[0] truncation_size = 3 # RIGHT TRUNCATION - Check that it correctly truncates when a maximum length is specified along with the truncation flag set to True tokenizer.truncation_side = "right" full_encoded_notes = tokenizer(notes)["token_ids"] full_encoded_notes_length = len(full_encoded_notes) truncated_notes = tokenizer(notes, max_length=full_encoded_notes_length - truncation_size, truncation=True)[ "token_ids" ] self.assertEqual(full_encoded_notes_length, len(truncated_notes) + truncation_size) self.assertEqual(full_encoded_notes[:-truncation_size], truncated_notes) # LEFT TRUNCATION - Check that it correctly truncates when a maximum length is specified along with the truncation flag set to True tokenizer.truncation_side = "left" full_encoded_notes = tokenizer(notes)["token_ids"] full_encoded_notes_length = len(full_encoded_notes) truncated_notes = tokenizer(notes, max_length=full_encoded_notes_length - truncation_size, truncation=True)[ "token_ids" ] self.assertEqual(full_encoded_notes_length, len(truncated_notes) + truncation_size) self.assertEqual(full_encoded_notes[truncation_size:], truncated_notes) # RIGHT & LEFT TRUNCATION - Check that nothing is done for 'longest' and 'no_truncation' tokenizer.truncation_side = "right" truncated_notes_right = tokenizer(notes, truncation=True)["token_ids"] self.assertEqual(full_encoded_notes_length, len(truncated_notes_right)) self.assertEqual(full_encoded_notes, truncated_notes_right) tokenizer.truncation_side = "left" truncated_notes_left = tokenizer(notes, truncation="longest_first")["token_ids"] self.assertEqual(len(truncated_notes_left), full_encoded_notes_length) self.assertEqual(truncated_notes_left, full_encoded_notes) tokenizer.truncation_side = "right" truncated_notes_right = tokenizer(notes, truncation="longest_first")["token_ids"] self.assertEqual(len(truncated_notes_right), full_encoded_notes_length) self.assertEqual(truncated_notes_right, full_encoded_notes) tokenizer.truncation_side = "left" truncated_notes_left = tokenizer(notes, truncation=True)["token_ids"] self.assertEqual(len(truncated_notes_left), full_encoded_notes_length) self.assertEqual(truncated_notes_left, full_encoded_notes) def test_padding_to_multiple_of(self): notes = self.get_input_notes() if self.tokenizer.pad_token is None: self.skipTest(reason="No padding token.") else: normal_tokens = self.tokenizer(notes[0], padding=True, pad_to_multiple_of=8) for key, value in normal_tokens.items(): self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") normal_tokens = self.tokenizer(notes[0], pad_to_multiple_of=8) for key, value in normal_tokens.items(): self.assertNotEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") # Should also work with truncation normal_tokens = self.tokenizer(notes[0], padding=True, truncation=True, pad_to_multiple_of=8) for key, value in normal_tokens.items(): self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") # truncation to something which is not a multiple of pad_to_multiple_of raises an error self.assertRaises( ValueError, self.tokenizer.__call__, notes[0], padding=True, truncation=True, max_length=12, pad_to_multiple_of=8, ) def test_padding_with_attention_mask(self): if self.tokenizer.pad_token is None: self.skipTest(reason="No padding token.") if "attention_mask" not in self.tokenizer.model_input_names: self.skipTest(reason="This model does not use attention mask.") features = [ {"token_ids": [1, 2, 3, 4, 5, 6], "attention_mask": [1, 1, 1, 1, 1, 0]}, {"token_ids": [1, 2, 3], "attention_mask": [1, 1, 0]}, ] padded_features = self.tokenizer.pad(features) if self.tokenizer.padding_side == "right": self.assertListEqual(padded_features["attention_mask"], [[1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 0]]) else: self.assertListEqual(padded_features["attention_mask"], [[1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 0]])
Pop2PianoTokenizerTest
python
huggingface__transformers
src/transformers/models/yoso/modeling_yoso.py
{ "start": 4601, "end": 8451 }
class ____(torch.autograd.Function): @staticmethod def forward(ctx, query_mask, key_mask, query, key, value, config): if query_mask.size(0) != key_mask.size(0): raise ValueError("Query mask and Key mask differ in sizes in dimension 0") if query_mask.size(0) != query.size(0): raise ValueError("Query mask and Query differ in sizes in dimension 0") if query_mask.size(0) != key.size(0): raise ValueError("Query mask and Key differ in sizes in dimension 0") if query_mask.size(0) != value.size(0): raise ValueError("Query mask and Value mask differ in sizes in dimension 0") if key.size(1) != value.size(1): raise ValueError("Key and Value differ in sizes in dimension 1") if query.size(2) != key.size(2): raise ValueError("Query and Key differ in sizes in dimension 2") query_mask, key_mask, query, key, value = to_contiguous([query_mask, key_mask, query, key, value]) use_cuda = query_mask.is_cuda num_hash = config["num_hash"] hash_code_len = config["hash_code_len"] hashtable_capacity = int(2**hash_code_len) if config["use_fast_hash"]: query_hash_code, key_hash_code = lsh_cumulation.fast_hash( query_mask, query, key_mask, key, num_hash, hash_code_len, use_cuda, 1 ) else: query_hash_code, key_hash_code = hashing(query, key, num_hash, hash_code_len) cumulation_value = lsh_cumulation.lsh_cumulation( query_mask, query_hash_code, key_mask, key_hash_code, value, hashtable_capacity, use_cuda, 1 ) ctx.save_for_backward(query_mask, key_mask, query_hash_code, key_hash_code, query, key, value) ctx.config = config return cumulation_value @staticmethod def backward(ctx, grad): grad = to_contiguous(grad) query_mask, key_mask, query_hash_code, key_hash_code, query, key, value = ctx.saved_tensors config = ctx.config use_cuda = grad.is_cuda hash_code_len = config["hash_code_len"] hashtable_capacity = int(2**hash_code_len) if config["lsh_backward"]: grad_value = lsh_cumulation.lsh_cumulation( key_mask, key_hash_code, query_mask, query_hash_code, grad, hashtable_capacity, use_cuda, 1 ) grad_query = lsh_cumulation.lsh_weighted_cumulation( query_mask, query_hash_code, grad, key_mask, key_hash_code, value, (hash_code_len / 2) * key, hashtable_capacity, use_cuda, 4, ) grad_key = lsh_cumulation.lsh_weighted_cumulation( key_mask, key_hash_code, value, query_mask, query_hash_code, grad, (hash_code_len / 2) * query, hashtable_capacity, use_cuda, 4, ) else: expectation = (1 - torch.acos(torch.matmul(query, key.transpose(-1, -2))) / math.pi) ** hash_code_len expectation = expectation * query_mask[:, :, None] * key_mask[:, None, :] weighted_exp = torch.matmul(grad, value.transpose(-1, -2)) * expectation grad_query = torch.matmul(weighted_exp, (hash_code_len / 2) * key) grad_key = torch.matmul(weighted_exp.transpose(-1, -2), (hash_code_len / 2) * query) grad_value = torch.matmul(expectation.transpose(-1, -2), grad) return None, None, grad_query, grad_key, grad_value, None # Copied from transformers.models.nystromformer.modeling_nystromformer.NystromformerEmbeddings
YosoLSHCumulation
python
squidfunk__mkdocs-material
material/plugins/blog/structure/options.py
{ "start": 4366, "end": 4870 }
class ____(BaseConfigOption[Navigation]): # Create navigation from structured items - we don't need to provide a # configuration object to the function, because it will not be used def run_validation(self, value: object): items = _data_to_navigation(value, Files([]), None) _add_parent_links(items) # Return navigation return Navigation(items, []) # ----------------------------------------------------------------------------- # Unique list of items
PostLinks
python
python__mypy
mypy/nodes.py
{ "start": 148652, "end": 157767 }
class ____: """Description of a name binding in a symbol table. These are only used as values in module (global), function (local) and class symbol tables (see SymbolTable). The name that is bound is the key in SymbolTable. Symbol tables don't contain direct references to AST nodes primarily because there can be multiple symbol table references to a single AST node (due to imports and aliases), and different references can behave differently. This class describes the unique properties of each reference. The most fundamental attribute is 'node', which is the AST node that the name refers to. The kind is usually one of LDEF, GDEF or MDEF, depending on the scope of the definition. These three kinds can usually be used interchangeably and the difference between local, global and class scopes is mostly descriptive, with no semantic significance. However, some tools that consume mypy ASTs may care about these so they should be correct. Attributes: node: AST node of definition. Among others, this can be one of FuncDef, Var, TypeInfo, TypeVarExpr or MypyFile -- or None for cross_ref that hasn't been fixed up yet. kind: Kind of node. Possible values: - LDEF: local definition - GDEF: global (module-level) definition - MDEF: class member definition - UNBOUND_IMPORTED: temporary kind for imported names (we don't know the final kind yet) module_public: If False, this name won't be imported via 'from <module> import *'. This has no effect on names within classes. module_hidden: If True, the name will be never exported (needed for stub files) cross_ref: For deserialized MypyFile nodes, the referenced module name; for other nodes, optionally the name of the referenced object. implicit: Was this defined by assignment to self attribute? plugin_generated: Was this symbol generated by a plugin? (And therefore needs to be removed in aststrip.) no_serialize: Do not serialize this node if True. This is used to prevent keys in the cache that refer to modules on which this file does not depend. Currently this can happen if there is a module not in build used e.g. like this: import a.b.c # type: ignore This will add a submodule symbol to parent module `a` symbol table, but `a.b` is _not_ added as its dependency. Therefore, we should not serialize these symbols as they may not be found during fixup phase, instead they will be re-added during subsequent patch parents phase. TODO: Refactor build.py to make dependency tracking more transparent and/or refactor look-up functions to not require parent patching. NOTE: No other attributes should be added to this class unless they are shared by all node kinds. """ __slots__ = ( "kind", "node", "module_public", "module_hidden", "cross_ref", "implicit", "plugin_generated", "no_serialize", ) def __init__( self, kind: int, node: SymbolNode | None, module_public: bool = True, implicit: bool = False, module_hidden: bool = False, *, plugin_generated: bool = False, no_serialize: bool = False, ) -> None: self.kind = kind self.node = node self.module_public = module_public self.implicit = implicit self.module_hidden = module_hidden self.cross_ref: str | None = None self.plugin_generated = plugin_generated self.no_serialize = no_serialize @property def fullname(self) -> str | None: if self.node is not None: return self.node.fullname else: return None @property def type(self) -> mypy.types.Type | None: node = self.node if isinstance(node, (Var, SYMBOL_FUNCBASE_TYPES)) and node.type is not None: return node.type elif isinstance(node, Decorator): return node.var.type else: return None def copy(self) -> SymbolTableNode: new = SymbolTableNode( self.kind, self.node, self.module_public, self.implicit, self.module_hidden ) new.cross_ref = self.cross_ref return new def __str__(self) -> str: s = f"{node_kinds[self.kind]}/{short_type(self.node)}" if isinstance(self.node, SymbolNode): s += f" ({self.node.fullname})" # Include declared type of variables and functions. if self.type is not None: s += f" : {self.type}" if self.cross_ref: s += f" cross_ref:{self.cross_ref}" return s def serialize(self, prefix: str, name: str) -> JsonDict: """Serialize a SymbolTableNode. Args: prefix: full name of the containing module or class; or None name: name of this object relative to the containing object """ data: JsonDict = {".class": "SymbolTableNode", "kind": node_kinds[self.kind]} if self.module_hidden: data["module_hidden"] = True if not self.module_public: data["module_public"] = False if self.implicit: data["implicit"] = True if self.plugin_generated: data["plugin_generated"] = True if isinstance(self.node, MypyFile): data["cross_ref"] = self.node.fullname else: assert self.node is not None, f"{prefix}:{name}" if prefix is not None: fullname = self.node.fullname if ( "." in fullname and fullname != prefix + "." + name and not (isinstance(self.node, Var) and self.node.from_module_getattr) ): assert not isinstance( self.node, PlaceholderNode ), f"Definition of {fullname} is unexpectedly incomplete" data["cross_ref"] = fullname return data data["node"] = self.node.serialize() return data @classmethod def deserialize(cls, data: JsonDict) -> SymbolTableNode: assert data[".class"] == "SymbolTableNode" kind = inverse_node_kinds[data["kind"]] if "cross_ref" in data: # This will be fixed up later. stnode = SymbolTableNode(kind, None) stnode.cross_ref = data["cross_ref"] else: assert "node" in data, data node = SymbolNode.deserialize(data["node"]) stnode = SymbolTableNode(kind, node) if "module_hidden" in data: stnode.module_hidden = data["module_hidden"] if "module_public" in data: stnode.module_public = data["module_public"] if "implicit" in data: stnode.implicit = data["implicit"] if "plugin_generated" in data: stnode.plugin_generated = data["plugin_generated"] return stnode def write(self, data: WriteBuffer, prefix: str, name: str) -> None: write_tag(data, SYMBOL_TABLE_NODE) write_int(data, self.kind) write_bool(data, self.module_hidden) write_bool(data, self.module_public) write_bool(data, self.implicit) write_bool(data, self.plugin_generated) cross_ref = None if isinstance(self.node, MypyFile): cross_ref = self.node.fullname else: assert self.node is not None, f"{prefix}:{name}" if prefix is not None: fullname = self.node.fullname if ( "." in fullname and fullname != prefix + "." + name and not (isinstance(self.node, Var) and self.node.from_module_getattr) ): assert not isinstance( self.node, PlaceholderNode ), f"Definition of {fullname} is unexpectedly incomplete" cross_ref = fullname write_str_opt(data, cross_ref) if cross_ref is None: assert self.node is not None self.node.write(data) write_tag(data, END_TAG) @classmethod def read(cls, data: ReadBuffer) -> SymbolTableNode: assert read_tag(data) == SYMBOL_TABLE_NODE sym = SymbolTableNode(read_int(data), None) sym.module_hidden = read_bool(data) sym.module_public = read_bool(data) sym.implicit = read_bool(data) sym.plugin_generated = read_bool(data) cross_ref = read_str_opt(data) if cross_ref is None: sym.node = read_symbol(data) else: sym.cross_ref = cross_ref assert read_tag(data) == END_TAG return sym
SymbolTableNode
python
huggingface__transformers
src/transformers/models/superglue/modeling_superglue.py
{ "start": 19587, "end": 20137 }
class ____(PreTrainedModel): config: SuperGlueConfig base_model_prefix = "superglue" main_input_name = "pixel_values" input_modalities = ("image",) @torch.no_grad() def _init_weights(self, module: nn.Module) -> None: """Initialize the weights""" super()._init_weights(module) if hasattr(module, "bin_score"): init.ones_(module.bin_score) @auto_docstring( custom_intro=""" SuperGlue model taking images as inputs and outputting the matching of them. """ )
SuperGluePreTrainedModel
python
tensorflow__tensorflow
tensorflow/python/keras/mixed_precision/test_util.py
{ "start": 5258, "end": 7458 }
class ____(AssertTypeLayer): """A layer which multiplies its input by a scalar variable.""" def __init__(self, regularizer=None, activity_regularizer=None, use_operator=False, var_name='v', **kwargs): """Initializes the MultiplyLayer. Args: regularizer: The weight regularizer on the scalar variable. activity_regularizer: The activity regularizer. use_operator: If True, add using the * operator. If False, add using tf.multiply. var_name: The name of the variable. It can be useful to pass a name other than 'v', to test having the attribute name (self.v) being different from the variable name. **kwargs: Passed to AssertTypeLayer constructor. """ self._regularizer = regularizer if isinstance(regularizer, dict): self._regularizer = regularizers.deserialize(regularizer, custom_objects=globals()) self._activity_regularizer = activity_regularizer if isinstance(activity_regularizer, dict): self._activity_regularizer = regularizers.deserialize( activity_regularizer, custom_objects=globals()) self._use_operator = use_operator self._var_name = var_name super(MultiplyLayer, self).__init__( activity_regularizer=self._activity_regularizer, **kwargs) def build(self, _): self.v = self.add_weight( self._var_name, (), initializer='ones', regularizer=self._regularizer) self.built = True def call(self, inputs): self.assert_input_types(inputs) return self._multiply(inputs, self.v) def _multiply(self, x, y): if self._use_operator: return x * y else: return math_ops.multiply(x, y) def get_config(self): config = super(MultiplyLayer, self).get_config() config['regularizer'] = regularizers.serialize(self._regularizer) config['activity_regularizer'] = regularizers.serialize( self._activity_regularizer) config['use_operator'] = self._use_operator config['var_name'] = self._var_name config['assert_type'] = self._assert_type return config
MultiplyLayer
python
patrick-kidger__equinox
equinox/_module/_module.py
{ "start": 2995, "end": 3468 }
class ____(eqx.Module): vmap_linear: Callable def __init__(self, ...): self.vmap_linear = jax.vmap(eqx.nn.Linear(...)) def __call__(self, ...): ... = self.vmap_linear(...) ``` This is because the callable returned from `jax.vmap` is *not* a PyTree. This means that the parameters inside the `eqx.nn.Linear` layer will not receive gradient updates. You can most easily fix this either by applying the wrapper at `__call__` time: ```python
MyModule
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_hyperlink44.py
{ "start": 315, "end": 910 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("hyperlink44.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet("Sheet 1") worksheet.insert_image( "E9", self.image_dir + "red.png", {"url": "internal:'Sheet 1'!A1"} ) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/sparse_ops/sparse_cross_op_test.py
{ "start": 2869, "end": 21206 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def test_simple(self): """Tests a simple scenario.""" op = sparse_ops.sparse_cross([ self._sparse_tensor([['batch1-FC1-F1'], ['batch2-FC1-F1', 'batch2-FC1-F2']]), self._sparse_tensor([['batch1-FC2-F1'], ['batch2-FC2-F1', 'batch2-FC2-F2']]) ]) expected_out = self._sparse_tensor([['batch1-FC1-F1_X_batch1-FC2-F1'], [ 'batch2-FC1-F1_X_batch2-FC2-F1', 'batch2-FC1-F1_X_batch2-FC2-F2', 'batch2-FC1-F2_X_batch2-FC2-F1', 'batch2-FC1-F2_X_batch2-FC2-F2' ]]) with self.cached_session(): self._assert_sparse_tensor_equals(expected_out, self.evaluate(op)) @test_util.run_deprecated_v1 def test_dense(self): """Tests only dense inputs.""" op = sparse_ops.sparse_cross([ constant_op.constant([['batch1-FC1-F1', 'batch1-FC1-F2'], ['batch2-FC1-F1', 'batch2-FC1-F2']], dtypes.string), constant_op.constant([['batch1-FC2-F1', 'batch1-FC2-F2'], ['batch2-FC2-F1', 'batch2-FC2-F2']], dtypes.string), ]) expected_out = self._sparse_tensor([[ 'batch1-FC1-F1_X_batch1-FC2-F1', 'batch1-FC1-F1_X_batch1-FC2-F2', 'batch1-FC1-F2_X_batch1-FC2-F1', 'batch1-FC1-F2_X_batch1-FC2-F2' ], [ 'batch2-FC1-F1_X_batch2-FC2-F1', 'batch2-FC1-F1_X_batch2-FC2-F2', 'batch2-FC1-F2_X_batch2-FC2-F1', 'batch2-FC1-F2_X_batch2-FC2-F2' ]]) with self.cached_session(): self._assert_sparse_tensor_equals(expected_out, self.evaluate(op)) @test_util.run_deprecated_v1 def test_integer_mixed_string_sparse(self): """Tests mixed type.""" op = sparse_ops.sparse_cross([ self._sparse_tensor([[11], [333, 55555]]), self._sparse_tensor([['batch1-FC2-F1'], ['batch2-FC2-F1', 'batch2-FC2-F2']]) ]) expected_out = self._sparse_tensor([['11_X_batch1-FC2-F1'], [ '333_X_batch2-FC2-F1', '333_X_batch2-FC2-F2', '55555_X_batch2-FC2-F1', '55555_X_batch2-FC2-F2' ]]) with self.cached_session(): self._assert_sparse_tensor_equals(expected_out, self.evaluate(op)) @test_util.run_deprecated_v1 def test_integer_mixed_string_dense(self): """Tests mixed dense inputs.""" op = sparse_ops.sparse_cross([ constant_op.constant([[11, 333], [55555, 999999]], dtypes.int64), constant_op.constant([['batch1-FC2-F1', 'batch1-FC2-F2'], ['batch2-FC2-F1', 'batch2-FC2-F2']], dtypes.string), ]) expected_out = self._sparse_tensor([[ '11_X_batch1-FC2-F1', '11_X_batch1-FC2-F2', '333_X_batch1-FC2-F1', '333_X_batch1-FC2-F2' ], [ '55555_X_batch2-FC2-F1', '55555_X_batch2-FC2-F2', '999999_X_batch2-FC2-F1', '999999_X_batch2-FC2-F2' ]]) with self.cached_session(): self._assert_sparse_tensor_equals(expected_out, self.evaluate(op)) @test_util.run_deprecated_v1 def test_sparse_cross_dense(self): """Tests sparse and dense inputs.""" op = sparse_ops.sparse_cross([ self._sparse_tensor([['batch1-FC1-F1'], ['batch2-FC1-F1', 'batch2-FC1-F2']]), constant_op.constant([['batch1-FC2-F1', 'batch1-FC2-F2'], ['batch2-FC2-F1', 'batch2-FC2-F2']], dtypes.string), ]) expected_out = self._sparse_tensor( [['batch1-FC1-F1_X_batch1-FC2-F1', 'batch1-FC1-F1_X_batch1-FC2-F2'], [ 'batch2-FC1-F1_X_batch2-FC2-F1', 'batch2-FC1-F1_X_batch2-FC2-F2', 'batch2-FC1-F2_X_batch2-FC2-F1', 'batch2-FC1-F2_X_batch2-FC2-F2' ]]) with self.cached_session(): self._assert_sparse_tensor_equals(expected_out, self.evaluate(op)) @test_util.run_deprecated_v1 def test_integer_sparse_input(self): """Tests mixed type sparse and dense inputs.""" op = sparse_ops.sparse_cross([ self._sparse_tensor([[11], [333, 5555]]), constant_op.constant([['batch1-FC2-F1', 'batch1-FC2-F2'], ['batch2-FC2-F1', 'batch2-FC2-F2']], dtypes.string), ]) expected_out = self._sparse_tensor( [['11_X_batch1-FC2-F1', '11_X_batch1-FC2-F2'], [ '333_X_batch2-FC2-F1', '333_X_batch2-FC2-F2', '5555_X_batch2-FC2-F1', '5555_X_batch2-FC2-F2' ]]) with self.cached_session(): self._assert_sparse_tensor_equals(expected_out, self.evaluate(op)) @test_util.run_deprecated_v1 def test_permutation_3x3x3(self): """Tests 3x3x3 permutation.""" op = sparse_ops.sparse_cross([ self._sparse_tensor( [['batch1-FC1-F1', 'batch1-FC1-F2', 'batch1-FC1-F3']]), self._sparse_tensor( [['batch1-FC2-F1', 'batch1-FC2-F2', 'batch1-FC2-F3']]), self._sparse_tensor( [['batch1-FC3-F1', 'batch1-FC3-F2', 'batch1-FC3-F3']]) ]) expected_out = self._sparse_tensor([[ 'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F1', 'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F2', 'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F3', 'batch1-FC1-F1_X_batch1-FC2-F2_X_batch1-FC3-F1', 'batch1-FC1-F1_X_batch1-FC2-F2_X_batch1-FC3-F2', 'batch1-FC1-F1_X_batch1-FC2-F2_X_batch1-FC3-F3', 'batch1-FC1-F1_X_batch1-FC2-F3_X_batch1-FC3-F1', 'batch1-FC1-F1_X_batch1-FC2-F3_X_batch1-FC3-F2', 'batch1-FC1-F1_X_batch1-FC2-F3_X_batch1-FC3-F3', 'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F1', 'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F2', 'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F3', 'batch1-FC1-F2_X_batch1-FC2-F2_X_batch1-FC3-F1', 'batch1-FC1-F2_X_batch1-FC2-F2_X_batch1-FC3-F2', 'batch1-FC1-F2_X_batch1-FC2-F2_X_batch1-FC3-F3', 'batch1-FC1-F2_X_batch1-FC2-F3_X_batch1-FC3-F1', 'batch1-FC1-F2_X_batch1-FC2-F3_X_batch1-FC3-F2', 'batch1-FC1-F2_X_batch1-FC2-F3_X_batch1-FC3-F3', 'batch1-FC1-F3_X_batch1-FC2-F1_X_batch1-FC3-F1', 'batch1-FC1-F3_X_batch1-FC2-F1_X_batch1-FC3-F2', 'batch1-FC1-F3_X_batch1-FC2-F1_X_batch1-FC3-F3', 'batch1-FC1-F3_X_batch1-FC2-F2_X_batch1-FC3-F1', 'batch1-FC1-F3_X_batch1-FC2-F2_X_batch1-FC3-F2', 'batch1-FC1-F3_X_batch1-FC2-F2_X_batch1-FC3-F3', 'batch1-FC1-F3_X_batch1-FC2-F3_X_batch1-FC3-F1', 'batch1-FC1-F3_X_batch1-FC2-F3_X_batch1-FC3-F2', 'batch1-FC1-F3_X_batch1-FC2-F3_X_batch1-FC3-F3' ]]) with self.cached_session(): self._assert_sparse_tensor_equals(expected_out, self.evaluate(op)) @test_util.run_deprecated_v1 def test_permutation_3x1x2(self): """Tests 3x1x2 permutation.""" op = sparse_ops.sparse_cross([ self._sparse_tensor( [['batch1-FC1-F1', 'batch1-FC1-F2', 'batch1-FC1-F3']]), self._sparse_tensor([['batch1-FC2-F1']]), self._sparse_tensor([['batch1-FC3-F1', 'batch1-FC3-F2']]) ]) expected_out = self._sparse_tensor([[ 'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F1', 'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F2', 'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F1', 'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F2', 'batch1-FC1-F3_X_batch1-FC2-F1_X_batch1-FC3-F1', 'batch1-FC1-F3_X_batch1-FC2-F1_X_batch1-FC3-F2' ]]) with self.cached_session(): self._assert_sparse_tensor_equals(expected_out, self.evaluate(op)) @test_util.run_deprecated_v1 def test_large_batch(self): """Tests with large batch size to force multithreading.""" batch_size = 5000 col1 = [] col2 = [] col3 = [] for b in range(batch_size): col1.append( ['batch%d-FC1-F1' % b, 'batch%d-FC1-F2' % b, 'batch%d-FC1-F3' % b]) col2.append(['batch%d-FC2-F1' % b]) col3.append(['batch%d-FC3-F1' % b, 'batch%d-FC3-F2' % b]) op = sparse_ops.sparse_cross([ self._sparse_tensor(col1), self._sparse_tensor(col2), self._sparse_tensor(col3) ]) col_out = [] for b in range(batch_size): col_out.append([ 'batch%d-FC1-F1_X_batch%d-FC2-F1_X_batch%d-FC3-F1' % (b, b, b), 'batch%d-FC1-F1_X_batch%d-FC2-F1_X_batch%d-FC3-F2' % (b, b, b), 'batch%d-FC1-F2_X_batch%d-FC2-F1_X_batch%d-FC3-F1' % (b, b, b), 'batch%d-FC1-F2_X_batch%d-FC2-F1_X_batch%d-FC3-F2' % (b, b, b), 'batch%d-FC1-F3_X_batch%d-FC2-F1_X_batch%d-FC3-F1' % (b, b, b), 'batch%d-FC1-F3_X_batch%d-FC2-F1_X_batch%d-FC3-F2' % (b, b, b) ]) expected_out = self._sparse_tensor(col_out) with self.cached_session(): self._assert_sparse_tensor_equals(expected_out, self.evaluate(op)) @test_util.run_deprecated_v1 def test_one_column_empty(self): """Tests when one column is empty. The crossed tensor should be empty. """ op = sparse_ops.sparse_cross([ self._sparse_tensor([['batch1-FC1-F1', 'batch1-FC1-F2']]), self._sparse_tensor([], 1), self._sparse_tensor([['batch1-FC3-F1', 'batch1-FC3-F2']]) ]) with self.cached_session(): self._assert_sparse_tensor_empty(self.evaluate(op)) @test_util.run_deprecated_v1 def test_some_columns_empty(self): """Tests when more than one columns are empty. Cross for the corresponding batch should be empty. """ op = sparse_ops.sparse_cross([ self._sparse_tensor([['batch1-FC1-F1', 'batch1-FC1-F2']], 2), self._sparse_tensor([['batch1-FC2-F1'], ['batch2-FC2-F1']], 2), self._sparse_tensor([['batch1-FC3-F1', 'batch1-FC3-F2']], 2) ]) expected_out = self._sparse_tensor([[ 'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F1', 'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F2', 'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F1', 'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F2' ]], 2) with self.cached_session(): self._assert_sparse_tensor_equals(expected_out, self.evaluate(op)) @test_util.run_deprecated_v1 def test_all_columns_empty(self): """Tests when all columns are empty. The crossed tensor should be empty. """ op = sparse_ops.sparse_cross([ self._sparse_tensor([]), self._sparse_tensor([]), self._sparse_tensor([]) ]) with self.cached_session(): self._assert_sparse_tensor_empty(self.evaluate(op)) @test_util.run_deprecated_v1 def test_hashed_zero_bucket_no_hash_key(self): op = sparse_ops.sparse_cross_hashed([ self._sparse_tensor([['batch1-FC1-F1']]), self._sparse_tensor([['batch1-FC2-F1']]), self._sparse_tensor([['batch1-FC3-F1']]) ]) # Check actual hashed output to prevent unintentional hashing changes. expected_out = self._sparse_tensor([[1971693436396284976]]) with self.cached_session(): self._assert_sparse_tensor_equals(expected_out, self.evaluate(op)) @test_util.run_deprecated_v1 def test_hashed_zero_bucket(self): op = sparse_ops.sparse_cross_hashed( [ self._sparse_tensor([['batch1-FC1-F1']]), self._sparse_tensor([['batch1-FC2-F1']]), self._sparse_tensor([['batch1-FC3-F1']]) ], hash_key=sparse_ops._DEFAULT_HASH_KEY + 1) # Check actual hashed output to prevent unintentional hashing changes. expected_out = self._sparse_tensor([[4847552627144134031]]) with self.cached_session(): self._assert_sparse_tensor_equals(expected_out, self.evaluate(op)) # TODO(sibyl-Aix6ihai): Add benchmark to compare Hashed vs Non-hashed. @test_util.run_deprecated_v1 def test_hashed_no_hash_key(self): op = sparse_ops.sparse_cross_hashed( [ self._sparse_tensor([['batch1-FC1-F1']]), self._sparse_tensor([['batch1-FC2-F1']]), self._sparse_tensor([['batch1-FC3-F1']]) ], num_buckets=100) # Check actual hashed output to prevent unintentional hashing changes. expected_out = self._sparse_tensor([[83]]) with self.cached_session(): self._assert_sparse_tensor_equals(expected_out, self.evaluate(op)) @test_util.run_deprecated_v1 def test_hashed_output(self): op = sparse_ops.sparse_cross_hashed( [ self._sparse_tensor([['batch1-FC1-F1']]), self._sparse_tensor([['batch1-FC2-F1']]), self._sparse_tensor([['batch1-FC3-F1']]) ], num_buckets=100, hash_key=sparse_ops._DEFAULT_HASH_KEY + 1) # Check actual hashed output to prevent unintentional hashing changes. expected_out = self._sparse_tensor([[31]]) with self.cached_session(): self._assert_sparse_tensor_equals(expected_out, self.evaluate(op)) @test_util.run_deprecated_v1 def test_hashed__has_no_collision(self): """Tests that fingerprint concatenation has no collisions.""" # Although the last 10 bits of 359 and 1024+359 are identical. # As a result, all the crosses shouldn't collide. t1 = constant_op.constant([[359], [359 + 1024]]) t2 = constant_op.constant([list(range(10)), list(range(10))]) cross = sparse_ops.sparse_cross_hashed( [t2, t1], num_buckets=1024, hash_key=sparse_ops._DEFAULT_HASH_KEY + 1) cross_dense = sparse_ops.sparse_tensor_to_dense(cross) with session.Session(): values = self.evaluate(cross_dense) self.assertTrue(numpy.not_equal(values[0], values[1]).all()) def test_hashed_3x1x2(self): """Tests 3x1x2 permutation with hashed output.""" op = sparse_ops.sparse_cross_hashed( [ self._sparse_tensor( [['batch1-FC1-F1', 'batch1-FC1-F2', 'batch1-FC1-F3']]), self._sparse_tensor([['batch1-FC2-F1']]), self._sparse_tensor([['batch1-FC3-F1', 'batch1-FC3-F2']]) ], num_buckets=1000) with self.cached_session(): out = self.evaluate(op) self.assertEqual(6, len(out.values)) self.assertAllEqual([[0, i] for i in range(6)], out.indices) self.assertTrue(all(x < 1000 and x >= 0 for x in out.values)) all_values_are_different = len(out.values) == len(set(out.values)) self.assertTrue(all_values_are_different) def _assert_sparse_tensor_empty(self, sp): self.assertEqual(0, sp.indices.size) self.assertEqual(0, sp.values.size) # TODO(zakaria): check if we can ignore the first dim of the shape. self.assertEqual(0, sp.dense_shape[1]) def _assert_sparse_tensor_equals(self, sp1, sp2): self.assertAllEqual(sp1.indices, sp2.indices) self.assertAllEqual(sp1.values, sp2.values) self.assertAllEqual(sp1.dense_shape, sp2.dense_shape) def _sparse_tensor(self, data, batch_size=-1): """Generates a SparseTensor. Args: data: Should be a list of list of strings or int64. Each item of the outer list represents a batch. Each item of the batch is a feature of a specific feature column. batch_size: optional batch size, especially for cases when data has no entry for some batches. Returns: A SparseTensor. """ indices = [] values = [] max_col_count = 0 for batch, batch_ix in zip(data, range(len(data))): for column, column_ix in zip(batch, range(len(batch))): indices.append([batch_ix, column_ix]) values.append(column) max_col_count = max(max_col_count, column_ix + 1) shape = [batch_size if batch_size != -1 else len(data), max_col_count] value_type = (dtypes.string if not values or isinstance(values[0], str) else dtypes.int64) return sparse_tensor.SparseTensor( constant_op.constant(indices, dtypes.int64, [len(indices), 2]), constant_op.constant(values, value_type, [len(indices)]), constant_op.constant(shape, dtypes.int64)) def test_invalid_sparse_tensors(self): # Test validation of invalid SparseTensors. The SparseTensor constructor # prevents us from creating invalid SparseTensors (eps. in eager mode), # so we create valid SparseTensors and then modify them to be invalid. st1 = sparse_tensor.SparseTensor([[0, 0]], [0], [2, 2]) st1._indices = array_ops.zeros([], dtypes.int64) with self.assertRaisesRegex((errors.InvalidArgumentError, ValueError), 'Input indices should be a matrix'): self.evaluate(sparse_ops.sparse_cross([st1])) st2 = sparse_tensor.SparseTensor([[0, 0]], [0], [2, 2]) st2._values = array_ops.zeros([], dtypes.int64) with self.assertRaisesRegex((errors.InvalidArgumentError, ValueError), 'Input values should be a vector'): self.evaluate(sparse_ops.sparse_cross([st2])) st3 = sparse_tensor.SparseTensor([[0, 0]], [0], [2, 2]) st3._dense_shape = array_ops.zeros([], dtypes.int64) with self.assertRaisesRegex((errors.InvalidArgumentError, ValueError), 'Input shapes should be a vector'): self.evaluate(sparse_ops.sparse_cross([st3])) def test_bad_tensor_shapes(self): # All inputs must be 2D. with self.assertRaisesRegex((errors.InvalidArgumentError, ValueError), 'Expected D2 of index to be 2'): st = sparse_tensor.SparseTensor([[0]], [0], [10]) # 1D SparseTensor self.evaluate(sparse_ops.sparse_cross([st])) with self.assertRaisesRegex((errors.InvalidArgumentError, ValueError), 'Dense inputs should be a matrix'): dt = array_ops.zeros([0]) # 1D DenseTensor. self.evaluate(sparse_ops.sparse_cross([dt])) def test_batch_size_mismatch(self): st1 = sparse_tensor.SparseTensor([[0, 0]], [0], [10, 10]) # batch size 10 st2 = sparse_tensor.SparseTensor([[0, 0]], [0], [7, 10]) # batch size 7 dt = array_ops.zeros([5, 0]) # batch size 5 with self.assertRaisesRegex((errors.InvalidArgumentError, ValueError), 'Expected batch size'): self.evaluate(sparse_ops.sparse_cross([st1, dt])) with self.assertRaisesRegex((errors.InvalidArgumentError, ValueError), 'Expected batch size'): self.evaluate(sparse_ops.sparse_cross([st1, st2]))
SparseCrossOpTest
python
jina-ai__jina
jina/proto/docarray_v1/pb/jina_pb2_grpc.py
{ "start": 22148, "end": 22665 }
class ____(object): """* jina gRPC service to trigger a restore at the Executor Runtime. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.restore = channel.unary_unary( '/jina.JinaExecutorRestore/restore', request_serializer=jina__pb2.RestoreSnapshotCommand.SerializeToString, response_deserializer=jina__pb2.RestoreSnapshotStatusProto.FromString, )
JinaExecutorRestoreStub
python
matplotlib__matplotlib
lib/matplotlib/hatch.py
{ "start": 5825, "end": 8206 }
class ____(Shapes): size = 1.0 / 3.0 filled = True def __init__(self, hatch, density): self.num_rows = (hatch.count('*')) * density path = Path.unit_regular_star(5) self.shape_vertices = path.vertices self.shape_codes = np.full(len(self.shape_vertices), Path.LINETO, dtype=Path.code_type) self.shape_codes[0] = Path.MOVETO self.shape_codes[-1] = Path.CLOSEPOLY super().__init__(hatch, density) _hatch_types = [ HorizontalHatch, VerticalHatch, NorthEastHatch, SouthEastHatch, SmallCircles, LargeCircles, SmallFilledCircles, Stars ] def _validate_hatch_pattern(hatch): valid_hatch_patterns = set(r'-+|/\xXoO.*') if hatch is not None: invalids = set(hatch).difference(valid_hatch_patterns) if invalids: valid = ''.join(sorted(valid_hatch_patterns)) invalids = ''.join(sorted(invalids)) _api.warn_deprecated( '3.4', removal='3.11', # one release after custom hatches (#20690) message=f'hatch must consist of a string of "{valid}" or ' 'None, but found the following invalid values ' f'"{invalids}". Passing invalid values is deprecated ' 'since %(since)s and will become an error in %(removal)s.' ) def get_path(hatchpattern, density=6): """ Given a hatch specifier, *hatchpattern*, generates Path to render the hatch in a unit square. *density* is the number of lines per unit square. """ density = int(density) patterns = [hatch_type(hatchpattern, density) for hatch_type in _hatch_types] num_vertices = sum([pattern.num_vertices for pattern in patterns]) if num_vertices == 0: return Path(np.empty((0, 2))) vertices = np.empty((num_vertices, 2)) codes = np.empty(num_vertices, Path.code_type) cursor = 0 for pattern in patterns: if pattern.num_vertices != 0: vertices_chunk = vertices[cursor:cursor + pattern.num_vertices] codes_chunk = codes[cursor:cursor + pattern.num_vertices] pattern.set_vertices_and_codes(vertices_chunk, codes_chunk) cursor += pattern.num_vertices return Path(vertices, codes)
Stars
python
huggingface__transformers
tests/models/zamba2/test_modeling_zamba2.py
{ "start": 1562, "end": 10474 }
class ____: def __init__( self, parent, batch_size=14, seq_length=7, is_training=True, use_input_mask=True, use_labels=True, vocab_size=99, hidden_size=16, mamba_d_state=2, chunk_size=8, mamba_dt_rank="auto", num_hidden_layers=2, num_attention_heads=2, n_mamba_heads=8, mamba_ngroups=8, intermediate_size=4, hidden_act="gelu", hidden_mamba_act="silu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, type_sequence_label_size=2, initializer_range=0.02, num_labels=3, num_choices=4, scope=None, layers_block_type=["mamba", "hybrid"], num_mem_blocks=1, use_mem_rope=True, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_mask = use_input_mask self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.mamba_dt_rank = mamba_dt_rank self.mamba_d_state = mamba_d_state self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.n_mamba_heads = n_mamba_heads self.mamba_ngroups = mamba_ngroups self.chunk_size = chunk_size self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_mamba_act = hidden_mamba_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_labels = num_labels self.num_choices = num_choices self.scope = scope self.layers_block_type = layers_block_type self.num_mem_blocks = num_mem_blocks self.use_mem_rope = use_mem_rope def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) input_mask = None if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) sequence_labels = None token_labels = None choice_labels = None if self.use_labels: sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) choice_labels = ids_tensor([self.batch_size], self.num_choices) config = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def get_config(self): return Zamba2Config( vocab_size=self.vocab_size, hidden_size=self.hidden_size, mamba_dt_rank=self.mamba_dt_rank, mamba_d_state=self.mamba_d_state, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, n_mamba_heads=self.n_mamba_heads, intermediate_size=self.intermediate_size, chunk_size=self.chunk_size, hidden_act=self.hidden_act, mamba_ngroups=self.mamba_ngroups, hidden_mamba_act=self.hidden_mamba_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=True, initializer_range=self.initializer_range, use_mamba_kernels=False, layers_block_type=self.layers_block_type, num_mem_blocks=self.num_mem_blocks, use_mem_rope=self.use_mem_rope, ) def prepare_config_and_inputs_for_decoder(self): ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, ) = self.prepare_config_and_inputs() config.is_decoder = True return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, ) def create_and_check_model(self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels): model = Zamba2Model(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask) result = model(input_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def create_and_check_for_causal_lm( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, ): model = Zamba2ForCausalLM(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, labels=token_labels) result = model(input_ids, attention_mask=input_mask) result = model(input_ids, labels=token_labels) result = model(input_ids) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def create_and_check_decoder_model_past_large_inputs( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, ): config.is_decoder = True config.add_cross_attention = False model = Zamba2ForCausalLM(config=config) model.to(torch_device) model.eval() # first forward pass # Attention: Zamba2 needs the cache to be initialized to return a cache! past_key_values = Zamba2HybridDynamicCache(config, input_ids.shape[0], model.dtype, device=model.device) outputs = model( input_ids, attention_mask=input_mask, past_key_values=past_key_values, use_cache=True, ) past_key_values = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) next_mask = ids_tensor((self.batch_size, 1), vocab_size=2) # append to next input_ids and next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) output_from_no_past = model( next_input_ids, attention_mask=next_attention_mask, output_hidden_states=True, )["hidden_states"][0] output_from_past = model( next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values, output_hidden_states=True, cache_position=torch.arange( input_ids.shape[1], input_ids.shape[1] + next_tokens.shape[1], device=model.device ), )["hidden_states"][0] # select random slice random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() output_from_no_past_slice = output_from_no_past[:, -1:, random_slice_idx].detach() output_from_past_slice = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) def create_and_check_for_sequence_classification( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_labels = self.num_labels model = Zamba2ForSequenceClassification(config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, labels=sequence_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, ) = config_and_inputs inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch
Zamba2ModelTester
python
pytorch__pytorch
torch/cuda/__init__.py
{ "start": 18551, "end": 19015 }
class ____(RuntimeError): def __init__(self, code: int) -> None: # pyrefly: ignore [missing-attribute] msg = _cudart.cudaGetErrorString(_cudart.cudaError(code)) super().__init__(f"{msg} ({code})") def check_error(res: int) -> None: r"""Raise an error if the result of a CUDA runtime API call is not success.""" # pyrefly: ignore [missing-attribute] if res != _cudart.cudaError.success: raise CudaError(res)
CudaError
python
encode__starlette
starlette/datastructures.py
{ "start": 418, "end": 733 }
class ____(NamedTuple): host: str port: int _KeyType = TypeVar("_KeyType") # Mapping keys are invariant but their values are covariant since # you can only read them # that is, you can't do `Mapping[str, Animal]()["fido"] = Dog()` _CovariantValueType = TypeVar("_CovariantValueType", covariant=True)
Address
python
ansible__ansible
lib/ansible/module_utils/six/__init__.py
{ "start": 19156, "end": 19805 }
class ____(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_robotparser""" _urllib_robotparser_moved_attributes = [ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), ] for attr in _urllib_robotparser_moved_attributes: setattr(Module_six_moves_urllib_robotparser, attr.name, attr) del attr Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), "moves.urllib_robotparser", "moves.urllib.robotparser")
Module_six_moves_urllib_robotparser
python
getsentry__sentry
tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py
{ "start": 15777, "end": 16269 }
class ____(BaseSafeMigrationTest, ColExistsMixin): app = "good_flow_delete_field_simple_app" migrate_from = "0001" migrate_to = "0003" def test(self) -> None: self._run_migration(self.app, "0001_initial") assert self.col_exists("field") self._run_migration(self.app, "0002_set_pending") assert self.col_exists("field") self._run_migration(self.app, "0003_delete") assert not self.col_exists("field")
DeletionFieldGoodDeleteSimple
python
Pylons__pyramid
docs/quick_tutorial/static_assets/tutorial/tests.py
{ "start": 675, "end": 1265 }
class ____(unittest.TestCase): def setUp(self): from tutorial import main app = main({}) from webtest import TestApp self.testapp = TestApp(app) def test_home(self): res = self.testapp.get('/', status=200) self.assertIn(b'<h1>Hi Home View', res.body) def test_hello(self): res = self.testapp.get('/howdy', status=200) self.assertIn(b'<h1>Hi Hello View', res.body) def test_css(self): res = self.testapp.get('/static/app.css', status=200) self.assertIn(b'body', res.body)
TutorialFunctionalTests
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_bar03.py
{ "start": 315, "end": 1972 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_bar03.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart1 = workbook.add_chart({"type": "bar"}) chart2 = workbook.add_chart({"type": "bar"}) chart1.axis_ids = [64265216, 64447616] chart2.axis_ids = [86048128, 86058112] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart1.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$B$1:$B$5", } ) chart1.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$C$1:$C$5", } ) worksheet.insert_chart("E9", chart1) chart2.add_series( { "categories": "=Sheet1!$A$1:$A$4", "values": "=Sheet1!$B$1:$B$4", } ) chart2.add_series( { "categories": "=Sheet1!$A$1:$A$4", "values": "=Sheet1!$C$1:$C$4", } ) worksheet.insert_chart("F25", chart2) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
pydantic__pydantic
pydantic/types.py
{ "start": 33703, "end": 35268 }
class ____: """A field metadata class to indicate a [UUID](https://docs.python.org/3/library/uuid.html) version. Use this class as an annotation via [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated), as seen below. Attributes: uuid_version: The version of the UUID. Must be one of 1, 3, 4, 5, 6, 7 or 8. Example: ```python from typing import Annotated from uuid import UUID from pydantic.types import UuidVersion UUID1 = Annotated[UUID, UuidVersion(1)] ``` """ uuid_version: Literal[1, 3, 4, 5, 6, 7, 8] def __get_pydantic_json_schema__( self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler ) -> JsonSchemaValue: field_schema = handler(core_schema) field_schema.pop('anyOf', None) # remove the bytes/str union field_schema.update(type='string', format=f'uuid{self.uuid_version}') return field_schema def __get_pydantic_core_schema__(self, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: schema = handler(source) _check_annotated_type(schema['type'], 'uuid', self.__class__.__name__) schema['version'] = self.uuid_version # type: ignore return schema def __hash__(self) -> int: return hash(type(self.uuid_version)) UUID1 = Annotated[UUID, UuidVersion(1)] """A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 1. ```python import uuid from pydantic import UUID1, BaseModel
UuidVersion
python
getsentry__sentry
src/sentry/integrations/bitbucket/integration.py
{ "start": 6684, "end": 9919 }
class ____(IntegrationProvider): key = IntegrationProviderSlug.BITBUCKET.value name = "Bitbucket" metadata = metadata scopes = scopes integration_cls = BitbucketIntegration features = frozenset( [ IntegrationFeatures.ISSUE_BASIC, IntegrationFeatures.COMMITS, IntegrationFeatures.STACKTRACE_LINK, IntegrationFeatures.CODEOWNERS, ] ) def get_pipeline_views(self) -> Sequence[PipelineView[IntegrationPipeline]]: return [ NestedPipelineView( bind_key="identity", provider_key=IntegrationProviderSlug.BITBUCKET.value, pipeline_cls=IdentityPipeline, config={"redirect_url": absolute_uri("/extensions/bitbucket/setup/")}, ), VerifyInstallation(), ] def post_install( self, integration: Integration, organization: RpcOrganization, *, extra: dict[str, Any], ) -> None: repos = repository_service.get_repositories( organization_id=organization.id, providers=[IntegrationProviderSlug.BITBUCKET.value, "integrations:bitbucket"], has_integration=False, ) for repo in repos: migrate_repo.apply_async( kwargs={ "repo_id": repo.id, "integration_id": integration.id, "organization_id": organization.id, } ) def build_integration(self, state: Mapping[str, Any]) -> IntegrationData: if state.get("publicKey"): principal_data = state["principal"] base_url = state["baseUrl"].replace("https://", "") # fall back to display name, user installations will use this primarily username = principal_data.get("username", principal_data["display_name"]) account_type = principal_data["type"] domain = f"{base_url}/{username}" if account_type == "team" else username secret = generate_token() return { "provider": self.key, "external_id": state["clientKey"], "name": username, "metadata": { "public_key": state["publicKey"], "shared_secret": state["sharedSecret"], "webhook_secret": secret, "base_url": state["baseApiUrl"], "domain_name": domain, "icon": principal_data["links"]["avatar"]["href"], "scopes": self.scopes, "uuid": principal_data["uuid"], "type": account_type, # team or user account }, } else: return { "provider": self.key, "external_id": state["external_id"], "expect_exists": True, } def setup(self): from sentry.plugins.base import bindings bindings.add( "integration-repository.provider", BitbucketRepositoryProvider, id=f"integrations:{self.key}", )
BitbucketIntegrationProvider
python
pytorch__pytorch
torch/_export/db/examples/cond_branch_class_method.py
{ "start": 231, "end": 1327 }
class ____(torch.nn.Module): """ The branch functions (`true_fn` and `false_fn`) passed to cond() must follow these rules: - both branches must take the same args, which must also match the branch args passed to cond. - both branches must return a single tensor - returned tensor must have the same tensor metadata, e.g. shape and dtype - branch function can be free function, nested function, lambda, class methods - branch function can not have closure variables - no inplace mutations on inputs or global variables This example demonstrates using class method in cond(). NOTE: If the `pred` is test on a dim with batch size < 2, it will be specialized. """ def __init__(self) -> None: super().__init__() self.subm = MySubModule() def bar(self, x): return x.sin() def forward(self, x): return cond(x.shape[0] <= 2, self.subm.forward, self.bar, [x]) example_args = (torch.randn(3),) tags = { "torch.cond", "torch.dynamic-shape", } model = CondBranchClassMethod()
CondBranchClassMethod
python
lazyprogrammer__machine_learning_examples
nlp_class2/bow_classifier.py
{ "start": 941, "end": 2398 }
class ____: def __init__(self): # load in pre-trained word vectors print('Loading word vectors...') word2vec = {} embedding = [] idx2word = [] with open('../large_files/glove.6B/glove.6B.50d.txt') as f: # is just a space-separated text file in the format: # word vec[0] vec[1] vec[2] ... for line in f: values = line.split() word = values[0] vec = np.asarray(values[1:], dtype='float32') word2vec[word] = vec embedding.append(vec) idx2word.append(word) print('Found %s word vectors.' % len(word2vec)) # save for later self.word2vec = word2vec self.embedding = np.array(embedding) self.word2idx = {v:k for k,v in enumerate(idx2word)} self.V, self.D = self.embedding.shape def fit(self, data): pass def transform(self, data): X = np.zeros((len(data), self.D)) n = 0 emptycount = 0 for sentence in data: tokens = sentence.lower().split() vecs = [] for word in tokens: if word in self.word2vec: vec = self.word2vec[word] vecs.append(vec) if len(vecs) > 0: vecs = np.array(vecs) X[n] = vecs.mean(axis=0) else: emptycount += 1 n += 1 print("Numer of samples with no words found: %s / %s" % (emptycount, len(data))) return X def fit_transform(self, data): self.fit(data) return self.transform(data)
GloveVectorizer
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 459108, "end": 459841 }
class ____(sgqlc.types.Interface): """A subject that may be upvoted.""" __schema__ = github_schema __field_names__ = ("upvote_count", "viewer_can_upvote", "viewer_has_upvoted") upvote_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="upvoteCount") """Number of upvotes that this subject has received.""" viewer_can_upvote = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="viewerCanUpvote") """Whether or not the current user can add or remove an upvote on this subject. """ viewer_has_upvoted = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="viewerHasUpvoted") """Whether or not the current user has already upvoted this subject."""
Votable
python
huggingface__transformers
tests/models/llava_next/test_modeling_llava_next.py
{ "start": 12034, "end": 23000 }
class ____(unittest.TestCase): def setUp(self): self.processor = AutoProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf") url = "https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true" self.image = Image.open(requests.get(url, stream=True).raw) self.prompt = "[INST] <image>\nWhat is shown in this image? [/INST]" def tearDown(self): cleanup(torch_device, gc_collect=True) @slow @require_bitsandbytes def test_small_model_integration_test(self): model = LlavaNextForConditionalGeneration.from_pretrained( "llava-hf/llava-v1.6-mistral-7b-hf", quantization_config=BitsAndBytesConfig(load_in_4bit=True), ) inputs = self.processor(images=self.image, text=self.prompt, return_tensors="pt").to(torch_device) # verify inputs against original implementation filepath = hf_hub_download( repo_id="nielsr/test-image", filename="llava_1_6_input_ids.pt", repo_type="dataset", ) check_torch_load_is_safe() original_input_ids = torch.load(filepath, map_location="cpu", weights_only=True) # replace -200 by image_token_index (since we use token ID = 32000 for the image token) # remove image token indices because HF impl expands image tokens `image_seq_length` times original_input_ids = original_input_ids[original_input_ids != -200] observed_input_ids = inputs.input_ids[inputs.input_ids != model.config.image_token_index] assert original_input_ids[0].tolist() == observed_input_ids[0].tolist() filepath = hf_hub_download( repo_id="nielsr/test-image", filename="llava_1_6_pixel_values.pt", repo_type="dataset", ) check_torch_load_is_safe() original_pixel_values = torch.load(filepath, map_location="cpu", weights_only=True) assert torch.allclose( original_pixel_values, inputs.pixel_values.to(device="cpu", dtype=original_pixel_values.dtype) ) # verify generation output = model.generate(**inputs, max_new_tokens=100) EXPECTED_DECODED_TEXT = '[INST] \nWhat is shown in this image? [/INST] The image appears to be a radar chart, which is a type of multi-dimensional plot that displays values for multiple quantitative variables represented on axes starting from the same point. This particular radar chart is showing the performance of various models or systems across different metrics or datasets.\n\nThe chart is divided into several sections, each representing a different model or dataset. The axes represent different metrics or datasets, such as "MMM-Vet," "MMM-Bench," "L' self.assertEqual( self.processor.decode(output[0], skip_special_tokens=True), EXPECTED_DECODED_TEXT, ) @slow @require_bitsandbytes def test_small_model_integration_test_batch(self): model = LlavaNextForConditionalGeneration.from_pretrained( "llava-hf/llava-v1.6-mistral-7b-hf", quantization_config=BitsAndBytesConfig(load_in_4bit=True) ) url = "http://images.cocodataset.org/val2017/000000039769.jpg" cats_image = Image.open(requests.get(url, stream=True).raw) inputs = self.processor( images=[self.image, cats_image], text=[self.prompt, self.prompt], return_tensors="pt", padding=True, ).to(torch_device) # it should not matter whether two images are the same size or not output = model.generate(**inputs, max_new_tokens=20) EXPECTED_DECODED_TEXT = ['[INST] \nWhat is shown in this image? [/INST] The image appears to be a radar chart, which is a type of multi-dimensional plot that displays', '[INST] \nWhat is shown in this image? [/INST] The image shows two cats lying on a pink surface, which appears to be a couch or a cush'] # fmt: skip self.assertEqual( self.processor.batch_decode(output, skip_special_tokens=True), EXPECTED_DECODED_TEXT, ) @slow @require_bitsandbytes def test_small_model_integration_test_unk_token(self): # related to (#29835) model = LlavaNextForConditionalGeneration.from_pretrained( "llava-hf/llava-v1.6-mistral-7b-hf", quantization_config=BitsAndBytesConfig(load_in_4bit=True), ) prompt_with_unk = "[INST] <image>\nWhat is shown in this <unk> image? [/INST]" inputs = self.processor(images=self.image, text=prompt_with_unk, return_tensors="pt") # verify single forward pass inputs = inputs.to(torch_device) with torch.no_grad(): output = model(**inputs) # verify generation output = model.generate(**inputs, max_new_tokens=40) EXPECTED_DECODED_TEXT = '[INST] \nWhat is shown in this image? [/INST] The image appears to be a radar chart, which is a type of multi-dimensional plot that displays values for multiple quantitative variables represented on axes starting from the same point. This particular radar chart' # fmt: skip self.assertEqual( self.processor.decode(output[0], skip_special_tokens=True), EXPECTED_DECODED_TEXT, ) @slow @require_bitsandbytes def test_small_model_integration_test_batch_different_resolutions(self): model = LlavaNextForConditionalGeneration.from_pretrained( "llava-hf/llava-v1.6-mistral-7b-hf", quantization_config=BitsAndBytesConfig(load_in_4bit=True), ) url = "http://images.cocodataset.org/val2017/000000039769.jpg" lowres_url = "https://4.img-dpreview.com/files/p/TS560x560~forums/56876524/03975b28741443319e9a94615e35667e" cats_image = Image.open(requests.get(url, stream=True).raw) lowres_img = Image.open(requests.get(lowres_url, stream=True).raw) inputs = self.processor( images=[lowres_img, cats_image], text=[self.prompt, self.prompt], return_tensors="pt", padding=True ).to(torch_device) pixel_values = inputs["pixel_values"] # verify pixel values are padded correctly with 0 when one image has more num_patches than the other image_num_patches = [ image_size_to_num_patches( image_size=imsize, grid_pinpoints=model.config.image_grid_pinpoints, patch_size=model.config.vision_config.image_size, ) for imsize in inputs["image_sizes"] ] for pix_val, num_patch in zip(pixel_values, image_num_patches): self.assertTrue(torch.all(pix_val[num_patch:] == 0)) # pad on the right for i in range(num_patch): self.assertFalse(torch.all(pix_val[i : i + 1] == 0)) # no padding expected in any of patches # verify generation output = model.generate(**inputs, max_new_tokens=50) EXPECTED_DECODED_TEXT = "[INST] \nWhat is shown in this image? [/INST] The image shows two deer, likely fawns, in a grassy area with trees in the background. The setting appears to be a forest or woodland, and the photo is taken during what seems to be either dawn or dusk, given" self.assertEqual( self.processor.decode(output[0], skip_special_tokens=True), EXPECTED_DECODED_TEXT, ) @slow @require_bitsandbytes def test_small_model_integration_test_batch_matches_single(self): model = LlavaNextForConditionalGeneration.from_pretrained( "llava-hf/llava-v1.6-mistral-7b-hf", quantization_config=BitsAndBytesConfig(load_in_4bit=True), ) url = "http://images.cocodataset.org/val2017/000000039769.jpg" lowres_url = "https://4.img-dpreview.com/files/p/TS560x560~forums/56876524/03975b28741443319e9a94615e35667e" cats_image = Image.open(requests.get(url, stream=True).raw) lowres_img = Image.open(requests.get(lowres_url, stream=True).raw) inputs_batched = self.processor( images=[lowres_img, cats_image], text=[self.prompt, self.prompt], return_tensors="pt", padding=True ).to(torch_device) inputs_single = self.processor(images=lowres_img, text=self.prompt, return_tensors="pt", padding=True).to( torch_device ) # verify generation output_batched = model.generate(**inputs_batched, max_new_tokens=50) output_single = model.generate(**inputs_single, max_new_tokens=50) self.assertEqual( self.processor.decode(output_batched[0], skip_special_tokens=True), self.processor.decode(output_single[0], skip_special_tokens=True), ) @slow @require_bitsandbytes def test_small_model_integration_test_full_vision_state_selection(self): model = LlavaNextForConditionalGeneration.from_pretrained( "llava-hf/llava-v1.6-mistral-7b-hf", quantization_config=BitsAndBytesConfig(load_in_4bit=True), ) # test that changing `strategy` won't error out model.vision_feature_select_strategy = "full" inputs = self.processor(text=self.prompt, images=self.image, return_tensors="pt").to(model.device) # verify generation output = model.generate(**inputs, max_new_tokens=30) EXPECTED_DECODED_TEXT = '[INST] \nWhat is shown in this image? [/INST] The image appears to be a radar chart, which is a type of multi-dimensional plot that displays values for multiple quantitative variables represented on axes' # fmt: skip self.assertEqual( self.processor.decode(output[0], skip_special_tokens=True), EXPECTED_DECODED_TEXT, ) @slow def test_granite_vision(self): """ Check the expected output of a granite vision model, which leverages multiple vision feature layers and a visual encoder with no CLS (siglip). """ granite_model_path = "ibm-granite/granite-vision-3.1-2b-preview" model = LlavaNextForConditionalGeneration.from_pretrained(granite_model_path) self.processor = AutoProcessor.from_pretrained(granite_model_path) prompt = "<|user|>\n<image>\nWhat is shown in this image?\n<|assistant|>\n" inputs = self.processor(text=prompt, images=self.image, return_tensors="pt").to(model.device) # verify generation output = model.generate(**inputs, max_new_tokens=30) EXPECTED_DECODED_TEXT = "<|user|>\n\nWhat is shown in this image?\n<|assistant|>\nThe image displays a radar chart comparing the performance of various machine learning models." # fmt: skip self.assertEqual( self.processor.decode(output[0], skip_special_tokens=True), EXPECTED_DECODED_TEXT, )
LlavaNextForConditionalGenerationIntegrationTest
python
protocolbuffers__protobuf
python/google/protobuf/message.py
{ "start": 565, "end": 639 }
class ____(Exception): """Base error type for this module.""" pass
Error
python
doocs__leetcode
solution/1400-1499/1473.Paint House III/Solution.py
{ "start": 0, "end": 1460 }
class ____: def minCost( self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int ) -> int: f = [[[inf] * (target + 1) for _ in range(n + 1)] for _ in range(m)] if houses[0] == 0: for j, c in enumerate(cost[0], 1): f[0][j][1] = c else: f[0][houses[0]][1] = 0 for i in range(1, m): if houses[i] == 0: for j in range(1, n + 1): for k in range(1, min(target + 1, i + 2)): for j0 in range(1, n + 1): if j == j0: f[i][j][k] = min( f[i][j][k], f[i - 1][j][k] + cost[i][j - 1] ) else: f[i][j][k] = min( f[i][j][k], f[i - 1][j0][k - 1] + cost[i][j - 1] ) else: j = houses[i] for k in range(1, min(target + 1, i + 2)): for j0 in range(1, n + 1): if j == j0: f[i][j][k] = min(f[i][j][k], f[i - 1][j][k]) else: f[i][j][k] = min(f[i][j][k], f[i - 1][j0][k - 1]) ans = min(f[-1][j][target] for j in range(1, n + 1)) return -1 if ans >= inf else ans
Solution
python
keras-team__keras
keras/src/backend/numpy/core.py
{ "start": 12708, "end": 13515 }
class ____: """Decorator for custom gradients. Args: fun: Forward pass function. """ def __init__(self, fun): warnings.warn( "`custom_gradient` for the numpy backend acts as a pass-through to " "support the forward pass. No gradient computation or modification " "takes place." ) self.fun = fun def __call__(self, *args, **kwargs): outputs, _ = self.fun(*args, **kwargs) return outputs @contextlib.contextmanager def device_scope(device_name): yield def remat(f): warnings.warn( "Rematerialization memory optimization is not supported by the " "Numpy backend. Please switch to JAX, TensorFlow, or PyTorch to " "utilize this feature." ) return f
custom_gradient
python
openai__openai-python
src/openai/resources/beta/assistants.py
{ "start": 45007, "end": 45662 }
class ____: def __init__(self, assistants: Assistants) -> None: self._assistants = assistants self.create = _legacy_response.to_raw_response_wrapper( assistants.create, ) self.retrieve = _legacy_response.to_raw_response_wrapper( assistants.retrieve, ) self.update = _legacy_response.to_raw_response_wrapper( assistants.update, ) self.list = _legacy_response.to_raw_response_wrapper( assistants.list, ) self.delete = _legacy_response.to_raw_response_wrapper( assistants.delete, )
AssistantsWithRawResponse
python
kamyu104__LeetCode-Solutions
Python/queries-on-a-permutation-with-key.py
{ "start": 406, "end": 964 }
class ____(object): def processQueries(self, queries, m): """ :type queries: List[int] :type m: int :rtype: List[int] """ bit = BIT(2*m+1) lookup = {} for i in xrange(1, m+1): bit.add(m+i, 1) lookup[i] = m+i result, curr = [], m for q in queries: i = lookup.pop(q) result.append(bit.sum(i-1)) bit.add(i, -1) lookup[q] = curr bit.add(curr, 1) curr -= 1 return result
Solution
python
scipy__scipy
scipy/stats/tests/test_qmc.py
{ "start": 25900, "end": 27223 }
class ____(QMCEngineTests): qmce = qmc.Halton can_scramble = True # theoretical values known from Van der Corput unscramble_nd = np.array([[0, 0], [1 / 2, 1 / 3], [1 / 4, 2 / 3], [3 / 4, 1 / 9], [1 / 8, 4 / 9], [5 / 8, 7 / 9], [3 / 8, 2 / 9], [7 / 8, 5 / 9]]) # theoretical values unknown: convergence properties checked scramble_nd = np.array([[0.50246036, 0.93382481], [0.00246036, 0.26715815], [0.75246036, 0.60049148], [0.25246036, 0.8227137 ], [0.62746036, 0.15604704], [0.12746036, 0.48938037], [0.87746036, 0.71160259], [0.37746036, 0.04493592]]) def test_workers(self): ref_sample = self.reference(scramble=True) engine = self.engine(d=2, scramble=True) sample = engine.random(n=len(ref_sample), workers=8) assert_allclose(sample, ref_sample, atol=1e-3) # worker + integers engine.reset() ref_sample = engine.integers(10) engine.reset() sample = engine.integers(10, workers=8) assert_equal(sample, ref_sample)
TestHalton
python
ray-project__ray
python/ray/_private/telemetry/metric_cardinality.py
{ "start": 399, "end": 2395 }
class ____(str, Enum): """Cardinality level configuration for all Ray metrics (ray_tasks, ray_actors, etc.). This configurtion is used to determine whether to globally drop high cardinality labels. This is important for high scale clusters that might consist thousands of workers, millions of tasks. - LEGACY: Keep all labels. This is the default behavior. - RECOMMENDED: Drop high cardinality labels. The set of high cardinality labels are determined internally by Ray and not exposed to users. Currently, this includes the following labels: WorkerId - LOW: Same as RECOMMENDED, but also drop the Name label for tasks and actors. """ LEGACY = "legacy" RECOMMENDED = "recommended" LOW = "low" @staticmethod def get_cardinality_level() -> "MetricCardinality": global _CARDINALITY_LEVEL if _CARDINALITY_LEVEL is not None: return _CARDINALITY_LEVEL try: _CARDINALITY_LEVEL = MetricCardinality(RAY_METRIC_CARDINALITY_LEVEL.lower()) except ValueError: _CARDINALITY_LEVEL = MetricCardinality.LEGACY return _CARDINALITY_LEVEL @staticmethod def get_high_cardinality_labels_to_drop(metric_name: str) -> List[str]: """ Get the high cardinality labels of the metric. """ if metric_name in _HIGH_CARDINALITY_LABELS: return _HIGH_CARDINALITY_LABELS[metric_name] cardinality_level = MetricCardinality.get_cardinality_level() if cardinality_level == MetricCardinality.LEGACY: _HIGH_CARDINALITY_LABELS[metric_name] = [] return [] _HIGH_CARDINALITY_LABELS[metric_name] = [WORKER_ID_TAG_KEY] if cardinality_level == MetricCardinality.LOW and metric_name in [ "tasks", "actors", ]: _HIGH_CARDINALITY_LABELS[metric_name].append(TASK_OR_ACTOR_NAME_TAG_KEY) return _HIGH_CARDINALITY_LABELS[metric_name]
MetricCardinality
python
ray-project__ray
python/ray/air/util/tensor_extensions/arrow.py
{ "start": 23552, "end": 24562 }
class ____(_BaseFixedShapeArrowTensorType): """Arrow ExtensionType (v1) for tensors. NOTE: This type does *NOT* support tensors larger than 4Gb (due to overflow of int32 offsets utilized inside Pyarrow `ListType`) """ OFFSET_DTYPE = pa.int32() def __init__(self, shape: Tuple[int, ...], dtype: pa.DataType): """ Construct the Arrow extension type for array of fixed-shaped tensors. Args: shape: Shape of contained tensors. dtype: pyarrow dtype of tensor elements. """ super().__init__(shape, pa.list_(dtype), "ray.data.arrow_tensor") @classmethod def _get_deserialize_parameter(cls, storage_type, serialized): return (serialized, storage_type.value_type) @classmethod def _arrow_ext_deserialize_compute(cls, serialized, value_type): shape = tuple(_deserialize_with_fallback(serialized, "shape")) return cls(shape, value_type) @PublicAPI(stability="alpha")
ArrowTensorType
python
pytorch__pytorch
torch/_higher_order_ops/scan.py
{ "start": 17244, "end": 18724 }
class ____(enum.Enum): """ Partitioner can add interemdiates to the output of original graph. These intermediates fall into 4 categories and we want to have different policies for handling them by modifying the graph: CLONE: we clone the intermediate when it is a carried input (i.e. init). In this case, this carry will be replaced with new values at each forward step so we need to clone the carry as part of return (i.e. ys) so as to remove the aliasing and that each step's intermediate will be stacked together and saved in bacwkard. REMOVE_XS: we remove the intermediate from output when it is part of xs. Since xs is read-only, in this case, we can directly save them for backward to use. REMOVE_ADDITIONAL_INPUTS: we remove the intermediate from output when it is part of additinonal_inputs. additional_inputs are also read-only in each step, we can directly save them for bacwkard to use. We differentiate XS and ADDITIONAL_INPUTS so that we could have different treatment for them in backward. In backward, we need to put xs intermediates in carry but put additional_inputs as backward scan's additional_inputs. KEEP: this corresponds to a real intermediate tensor operations' output. It varies at each forward step, we could just keep it as part of ys. """ KEEP = 0 CLONE = 1 REMOVE_XS = 2 REMOVE_ADDITIONAL_INPUTS = 3
ScanForwardIntermediatesHandlingPolicy
python
huggingface__transformers
src/transformers/models/efficientloftr/image_processing_efficientloftr.py
{ "start": 1561, "end": 5140 }
class ____(ImagesKwargs, total=False): r""" do_grayscale (`bool`, *optional*, defaults to `True`): Whether to convert the image to grayscale. Can be overridden by `do_grayscale` in the `preprocess` method. """ do_grayscale: bool # Copied from transformers.models.superpoint.image_processing_superpoint.is_grayscale def is_grayscale( image: np.ndarray, input_data_format: Optional[Union[str, ChannelDimension]] = None, ): if input_data_format == ChannelDimension.FIRST: if image.shape[0] == 1: return True return np.all(image[0, ...] == image[1, ...]) and np.all(image[1, ...] == image[2, ...]) elif input_data_format == ChannelDimension.LAST: if image.shape[-1] == 1: return True return np.all(image[..., 0] == image[..., 1]) and np.all(image[..., 1] == image[..., 2]) # Copied from transformers.models.superpoint.image_processing_superpoint.convert_to_grayscale def convert_to_grayscale( image: ImageInput, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> ImageInput: """ Converts an image to grayscale format using the NTSC formula. Only support numpy and PIL Image. This function is supposed to return a 1-channel image, but it returns a 3-channel image with the same value in each channel, because of an issue that is discussed in : https://github.com/huggingface/transformers/pull/25786#issuecomment-1730176446 Args: image (Image): The image to convert. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the input image. """ requires_backends(convert_to_grayscale, ["vision"]) if isinstance(image, np.ndarray): if is_grayscale(image, input_data_format=input_data_format): return image if input_data_format == ChannelDimension.FIRST: gray_image = image[0, ...] * 0.2989 + image[1, ...] * 0.5870 + image[2, ...] * 0.1140 gray_image = np.stack([gray_image] * 3, axis=0) elif input_data_format == ChannelDimension.LAST: gray_image = image[..., 0] * 0.2989 + image[..., 1] * 0.5870 + image[..., 2] * 0.1140 gray_image = np.stack([gray_image] * 3, axis=-1) return gray_image if not isinstance(image, PIL.Image.Image): return image image = image.convert("L") return image # Copied from transformers.models.superglue.image_processing_superglue.validate_and_format_image_pairs def validate_and_format_image_pairs(images: ImageInput): error_message = ( "Input images must be a one of the following :", " - A pair of PIL images.", " - A pair of 3D arrays.", " - A list of pairs of PIL images.", " - A list of pairs of 3D arrays.", ) def _is_valid_image(image): """images is a PIL Image or a 3D array.""" return is_pil_image(image) or ( is_valid_image(image) and get_image_type(image) != ImageType.PIL and len(image.shape) == 3 ) if isinstance(images, list): if len(images) == 2 and all((_is_valid_image(image)) for image in images): return images if all( isinstance(image_pair, list) and len(image_pair) == 2 and all(_is_valid_image(image) for image in image_pair) for image_pair in images ): return [image for image_pair in images for image in image_pair] raise ValueError(error_message)
EfficientLoFTRImageProcessorKwargs
python
cython__cython
tests/run/pep3135_class_cell.py
{ "start": 4224, "end": 5255 }
class ____: """ >>> N().method().__name__ 'N' """ __class__ = 'N' def method(self): return __class__ if cython.compiled: @cython.cclass class CDefFuncTest: """ >>> obj = CDefFuncTest() >>> obj.call_cfunc1().__name__ 'CDefFuncTest' #>>> obj.call_cfunc2()().__name__ - GH 4092 #'CDefFuncTest' >>> obj.call_cfunc3() ['__class__', 'self'] """ @cython.cfunc def cfunc1(self): return __class__ def call_cfunc1(self): return self.cfunc1() #@cython.cfunc - disabled, GH 4092. This works outside pure Python mode #def cfunc2(self): # def inner(): # return __class__ # return inner def call_cfunc2(self): return self.cfunc2() @cython.cfunc def cfunc3(self): __class__ return sorted(list(locals().keys())) def call_cfunc3(self): return self.cfunc3()
N
python
huggingface__transformers
src/transformers/models/esm/openfold_utils/rigid_utils.py
{ "start": 7696, "end": 24209 }
class ____: """ A 3D rotation. Depending on how the object is initialized, the rotation is represented by either a rotation matrix or a quaternion, though both formats are made available by helper functions. To simplify gradient computation, the underlying format of the rotation cannot be changed in-place. Like Rigid, the class is designed to mimic the behavior of a torch Tensor, almost as if each Rotation object were a tensor of rotations, in one format or another. """ def __init__( self, rot_mats: torch.Tensor | None = None, quats: torch.Tensor | None = None, normalize_quats: bool = True, ): """ Args: rot_mats: A [*, 3, 3] rotation matrix tensor. Mutually exclusive with quats quats: A [*, 4] quaternion. Mutually exclusive with rot_mats. If normalize_quats is not True, must be a unit quaternion normalize_quats: If quats is specified, whether to normalize quats """ if (rot_mats is None and quats is None) or (rot_mats is not None and quats is not None): raise ValueError("Exactly one input argument must be specified") if (rot_mats is not None and rot_mats.shape[-2:] != (3, 3)) or (quats is not None and quats.shape[-1] != 4): raise ValueError("Incorrectly shaped rotation matrix or quaternion") # Force full-precision if quats is not None: quats = quats.to(dtype=torch.float32) if rot_mats is not None: rot_mats = rot_mats.to(dtype=torch.float32) if quats is not None and normalize_quats: quats = quats / torch.linalg.norm(quats, dim=-1, keepdim=True) self._rot_mats = rot_mats self._quats = quats @staticmethod def identity( shape, dtype: torch.dtype | None = None, device: torch.device | None = None, requires_grad: bool = True, fmt: str = "quat", ) -> Rotation: """ Returns an identity Rotation. Args: shape: The "shape" of the resulting Rotation object. See documentation for the shape property dtype: The torch dtype for the rotation device: The torch device for the new rotation requires_grad: Whether the underlying tensors in the new rotation object should require gradient computation fmt: One of "quat" or "rot_mat". Determines the underlying format of the new object's rotation Returns: A new identity rotation """ if fmt == "rot_mat": rot_mats = identity_rot_mats( shape, dtype, device, requires_grad, ) return Rotation(rot_mats=rot_mats, quats=None) elif fmt == "quat": quats = identity_quats(shape, dtype, device, requires_grad) return Rotation(rot_mats=None, quats=quats, normalize_quats=False) else: raise ValueError(f"Invalid format: f{fmt}") # Magic methods def __getitem__(self, index: Any) -> Rotation: """ Allows torch-style indexing over the virtual shape of the rotation object. See documentation for the shape property. Args: index: A torch index. E.g. (1, 3, 2), or (slice(None,)) Returns: The indexed rotation """ if type(index) is not tuple: index = (index,) if self._rot_mats is not None: rot_mats = self._rot_mats[index + (slice(None), slice(None))] return Rotation(rot_mats=rot_mats) elif self._quats is not None: quats = self._quats[index + (slice(None),)] return Rotation(quats=quats, normalize_quats=False) else: raise ValueError("Both rotations are None") def __mul__(self, right: torch.Tensor) -> Rotation: """ Pointwise left multiplication of the rotation with a tensor. Can be used to e.g. mask the Rotation. Args: right: The tensor multiplicand Returns: The product """ if not (isinstance(right, torch.Tensor)): raise TypeError("The other multiplicand must be a Tensor") if self._rot_mats is not None: rot_mats = self._rot_mats * right[..., None, None] return Rotation(rot_mats=rot_mats, quats=None) elif self._quats is not None: quats = self._quats * right[..., None] return Rotation(rot_mats=None, quats=quats, normalize_quats=False) else: raise ValueError("Both rotations are None") def __rmul__(self, left: torch.Tensor) -> Rotation: """ Reverse pointwise multiplication of the rotation with a tensor. Args: left: The left multiplicand Returns: The product """ return self.__mul__(left) # Properties @property def shape(self) -> torch.Size: """ Returns the virtual shape of the rotation object. This shape is defined as the batch dimensions of the underlying rotation matrix or quaternion. If the Rotation was initialized with a [10, 3, 3] rotation matrix tensor, for example, the resulting shape would be [10]. Returns: The virtual shape of the rotation object """ if self._rot_mats is not None: return self._rot_mats.shape[:-2] elif self._quats is not None: return self._quats.shape[:-1] else: raise ValueError("Both rotations are None") @property def dtype(self) -> torch.dtype: """ Returns the dtype of the underlying rotation. Returns: The dtype of the underlying rotation """ if self._rot_mats is not None: return self._rot_mats.dtype elif self._quats is not None: return self._quats.dtype else: raise ValueError("Both rotations are None") @property def device(self) -> torch.device: """ The device of the underlying rotation Returns: The device of the underlying rotation """ if self._rot_mats is not None: return self._rot_mats.device elif self._quats is not None: return self._quats.device else: raise ValueError("Both rotations are None") @property def requires_grad(self) -> bool: """ Returns the requires_grad property of the underlying rotation Returns: The requires_grad property of the underlying tensor """ if self._rot_mats is not None: return self._rot_mats.requires_grad elif self._quats is not None: return self._quats.requires_grad else: raise ValueError("Both rotations are None") def get_rot_mats(self) -> torch.Tensor: """ Returns the underlying rotation as a rotation matrix tensor. Returns: The rotation as a rotation matrix tensor """ if self._rot_mats is not None: return self._rot_mats elif self._quats is not None: return quat_to_rot(self._quats) else: raise ValueError("Both rotations are None") def get_quats(self) -> torch.Tensor: """ Returns the underlying rotation as a quaternion tensor. Depending on whether the Rotation was initialized with a quaternion, this function may call torch.linalg.eigh. Returns: The rotation as a quaternion tensor. """ if self._rot_mats is not None: return rot_to_quat(self._rot_mats) elif self._quats is not None: return self._quats else: raise ValueError("Both rotations are None") def get_cur_rot(self) -> torch.Tensor: """ Return the underlying rotation in its current form Returns: The stored rotation """ if self._rot_mats is not None: return self._rot_mats elif self._quats is not None: return self._quats else: raise ValueError("Both rotations are None") # Rotation functions def compose_q_update_vec(self, q_update_vec: torch.Tensor, normalize_quats: bool = True) -> Rotation: """ Returns a new quaternion Rotation after updating the current object's underlying rotation with a quaternion update, formatted as a [*, 3] tensor whose final three columns represent x, y, z such that (1, x, y, z) is the desired (not necessarily unit) quaternion update. Args: q_update_vec: A [*, 3] quaternion update tensor normalize_quats: Whether to normalize the output quaternion Returns: An updated Rotation """ quats = self.get_quats() new_quats = quats + quat_multiply_by_vec(quats, q_update_vec) return Rotation( rot_mats=None, quats=new_quats, normalize_quats=normalize_quats, ) def compose_r(self, r: Rotation) -> Rotation: """ Compose the rotation matrices of the current Rotation object with those of another. Args: r: An update rotation object Returns: An updated rotation object """ r1 = self.get_rot_mats() r2 = r.get_rot_mats() new_rot_mats = rot_matmul(r1, r2) return Rotation(rot_mats=new_rot_mats, quats=None) def compose_q(self, r: Rotation, normalize_quats: bool = True) -> Rotation: """ Compose the quaternions of the current Rotation object with those of another. Depending on whether either Rotation was initialized with quaternions, this function may call torch.linalg.eigh. Args: r: An update rotation object Returns: An updated rotation object """ q1 = self.get_quats() q2 = r.get_quats() new_quats = quat_multiply(q1, q2) return Rotation(rot_mats=None, quats=new_quats, normalize_quats=normalize_quats) def apply(self, pts: torch.Tensor) -> torch.Tensor: """ Apply the current Rotation as a rotation matrix to a set of 3D coordinates. Args: pts: A [*, 3] set of points Returns: [*, 3] rotated points """ rot_mats = self.get_rot_mats() return rot_vec_mul(rot_mats, pts) def invert_apply(self, pts: torch.Tensor) -> torch.Tensor: """ The inverse of the apply() method. Args: pts: A [*, 3] set of points Returns: [*, 3] inverse-rotated points """ rot_mats = self.get_rot_mats() inv_rot_mats = invert_rot_mat(rot_mats) return rot_vec_mul(inv_rot_mats, pts) def invert(self) -> Rotation: """ Returns the inverse of the current Rotation. Returns: The inverse of the current Rotation """ if self._rot_mats is not None: return Rotation(rot_mats=invert_rot_mat(self._rot_mats), quats=None) elif self._quats is not None: return Rotation( rot_mats=None, quats=invert_quat(self._quats), normalize_quats=False, ) else: raise ValueError("Both rotations are None") # "Tensor" stuff def unsqueeze(self, dim: int) -> Rotation: """ Analogous to torch.unsqueeze. The dimension is relative to the shape of the Rotation object. Args: dim: A positive or negative dimension index. Returns: The unsqueezed Rotation. """ if dim >= len(self.shape): raise ValueError("Invalid dimension") if self._rot_mats is not None: rot_mats = self._rot_mats.unsqueeze(dim if dim >= 0 else dim - 2) return Rotation(rot_mats=rot_mats, quats=None) elif self._quats is not None: quats = self._quats.unsqueeze(dim if dim >= 0 else dim - 1) return Rotation(rot_mats=None, quats=quats, normalize_quats=False) else: raise ValueError("Both rotations are None") @staticmethod def cat(rs: Sequence[Rotation], dim: int) -> Rotation: """ Concatenates rotations along one of the batch dimensions. Analogous to torch.cat(). Note that the output of this operation is always a rotation matrix, regardless of the format of input rotations. Args: rs: A list of rotation objects dim: The dimension along which the rotations should be concatenated Returns: A concatenated Rotation object in rotation matrix format """ rot_mats = torch.cat( [r.get_rot_mats() for r in rs], dim=dim if dim >= 0 else dim - 2, ) return Rotation(rot_mats=rot_mats, quats=None) def map_tensor_fn(self, fn: Callable[[torch.Tensor], torch.Tensor]) -> Rotation: """ Apply a Tensor -> Tensor function to underlying rotation tensors, mapping over the rotation dimension(s). Can be used e.g. to sum out a one-hot batch dimension. Args: fn: A Tensor -> Tensor function to be mapped over the Rotation Returns: The transformed Rotation object """ if self._rot_mats is not None: rot_mats = self._rot_mats.view(self._rot_mats.shape[:-2] + (9,)) rot_mats = torch.stack(list(map(fn, torch.unbind(rot_mats, dim=-1))), dim=-1) rot_mats = rot_mats.view(rot_mats.shape[:-1] + (3, 3)) return Rotation(rot_mats=rot_mats, quats=None) elif self._quats is not None: quats = torch.stack(list(map(fn, torch.unbind(self._quats, dim=-1))), dim=-1) return Rotation(rot_mats=None, quats=quats, normalize_quats=False) else: raise ValueError("Both rotations are None") def cuda(self) -> Rotation: """ Analogous to the cuda() method of torch Tensors Returns: A copy of the Rotation in CUDA memory """ if self._rot_mats is not None: return Rotation(rot_mats=self._rot_mats.cuda(), quats=None) elif self._quats is not None: return Rotation(rot_mats=None, quats=self._quats.cuda(), normalize_quats=False) else: raise ValueError("Both rotations are None") def to(self, device: torch.device | None, dtype: torch.dtype | None) -> Rotation: """ Analogous to the to() method of torch Tensors Args: device: A torch device dtype: A torch dtype Returns: A copy of the Rotation using the new device and dtype """ if self._rot_mats is not None: return Rotation( rot_mats=self._rot_mats.to(device=device, dtype=dtype), quats=None, ) elif self._quats is not None: return Rotation( rot_mats=None, quats=self._quats.to(device=device, dtype=dtype), normalize_quats=False, ) else: raise ValueError("Both rotations are None") def detach(self) -> Rotation: """ Returns a copy of the Rotation whose underlying Tensor has been detached from its torch graph. Returns: A copy of the Rotation whose underlying Tensor has been detached from its torch graph """ if self._rot_mats is not None: return Rotation(rot_mats=self._rot_mats.detach(), quats=None) elif self._quats is not None: return Rotation( rot_mats=None, quats=self._quats.detach(), normalize_quats=False, ) else: raise ValueError("Both rotations are None")
Rotation
python
doocs__leetcode
solution/3600-3699/3633.Earliest Finish Time for Land and Water Rides I/Solution.py
{ "start": 0, "end": 547 }
class ____: def earliestFinishTime( self, landStartTime: List[int], landDuration: List[int], waterStartTime: List[int], waterDuration: List[int], ) -> int: def calc(a1, t1, a2, t2): min_end = min(a + t for a, t in zip(a1, t1)) return min(max(a, min_end) + t for a, t in zip(a2, t2)) x = calc(landStartTime, landDuration, waterStartTime, waterDuration) y = calc(waterStartTime, waterDuration, landStartTime, landDuration) return min(x, y)
Solution
python
tensorflow__tensorflow
tensorflow/python/framework/extension_type.py
{ "start": 15230, "end": 21123 }
class ____(type_spec.TypeSpec): """Base class for tf.ExtensionType TypeSpec.""" def _serialize(self): # TypeSpec API. # Use a tuple of (name, value) pairs, to ensure we preserve field ordering. fields = [f.name for f in self._tf_extension_type_fields()] if self._tf_extension_type_is_packed: fields.append('_tf_extension_type_is_packed') return tuple( (f, _change_nested_mappings_to(self.__dict__[f], dict)) for f in fields ) @classmethod def _deserialize(cls, state): # TypeSpec API. state = _change_nested_mappings_to(state, immutable_dict.ImmutableDict) return _create_object_from_type_and_dict(cls, state) def __reduce__(self): # Use value_type instead of spec_type, as spec_type is a nested class. # Pickle support of nested class requires Pickle protocol version 4, which # is not enabled by default until py 3.8. # # https://www.python.org/dev/peps/pep-3154/#serializing-more-lookupable-objects # https://docs.python.org/3/library/pickle.html#pickle.DEFAULT_PROTOCOL return _deserialize_for_reduce, (self.value_type, self._serialize()) def _to_components(self, value): # TypeSpec API. if self._tf_extension_type_is_packed: return value._tf_extension_type_packed_variant # pylint: disable=protected-access tensor_or_composite = (tensor.Tensor, composite_tensor.CompositeTensor) # Retrieve fields by the order of spec dict to preserve field ordering. This # is needed as nest.flatten would sort dictionary entries by key. value_tuple = tuple(value.__dict__[key] for key in self.__dict__) return tuple( x for x in nest.flatten(value_tuple) if isinstance(x, tensor_or_composite) ) def _from_components(self, components): # TypeSpec API. if self._tf_extension_type_is_packed: return _create_object_from_type_and_dict( self.value_type, { '_tf_extension_type_cached_type_spec': self, '_tf_extension_type_packed_variant': components, }, ) spec_tuple = tuple(self.__dict__.values()) components_iter = iter(components) flat = [ next(components_iter) if isinstance(x, type_spec.TypeSpec) else x for x in nest.flatten(spec_tuple) ] if list(components_iter): raise ValueError( 'Cannot build an ExtensionType instance from components ' 'because more components are provided than the number expected ' 'by the type spec.' ) value_tuple = nest.pack_sequence_as(spec_tuple, flat) fields = dict(zip(self.__dict__.keys(), value_tuple)) # Build the new value. Bypass the constructor (__init__), in case the user # who defined the ExtensionType used a custom constructor. return _create_object_from_type_and_dict(self.value_type, fields) @property def _component_specs(self): # TypeSpec API. if self._tf_extension_type_is_packed: return tensor.TensorSpec((), dtypes.variant) components = [] def push_if_type_spec(x): if isinstance(x, type_spec.TypeSpec): components.append(x) nest.map_structure(push_if_type_spec, tuple(self.__dict__.values())) return tuple(components) @classmethod def from_value(cls, value): cached_spec = getattr(value, '_tf_extension_type_cached_type_spec', None) if cached_spec is not None: return cached_spec value_fields = value.__dict__ spec_fields = nest.map_structure(_replace_tensor_with_spec, value_fields) spec_fields.pop('_tf_extension_type_cached_fields', None) return _create_object_from_type_and_dict(cls, spec_fields) def __setattr__(self, name, value): if (hasattr(self, _IN_CONSTRUCTOR) and self._tf_extension_type_has_field(name)): self.__dict__[name] = value elif name in type_spec.CACHED_FIXED_PROPERTIES: super().__setattr__(name, value) else: raise AttributeError( f'Cannot mutate attribute `{name}` ' 'outside the custom constructor of ExtensionTypeSpec.' ) def __delattr__(self, name): if hasattr(self, _IN_CONSTRUCTOR) and self._tf_extension_type_has_field( name ): del self.__dict__[name] else: raise AttributeError( f'Cannot mutate attribute `{name}` ' 'outside the custom constructor of ExtensionTypeSpec.' ) def __validate__(self): """Perform post-construction validation.""" @classmethod def _tf_extension_type_fields(cls): return cls.value_type._tf_extension_type_fields() # pylint: disable=protected-access @classmethod def _tf_extension_type_has_field(cls, name): return any(name == field.name for field in cls._tf_extension_type_fields()) def _tf_extension_type_convert_fields(self): extension_type_field.convert_fields_for_spec( self._tf_extension_type_fields(), self.__dict__ ) def __repr__(self): fields = ', '.join([f'{k}={v!r}' for (k, v) in self._serialize()]) return f'{type(self).__qualname__}({fields})' _tf_extension_type_is_packed = False def _tf_extension_type_with_packed(self, value): """Returns a copy of this `TypeSpec` with `packed=value`. Args: value: A boolean value. Returns: A copy of `self` with `_tf_extension_type_is_packed=value`. """ copy = _create_object_from_type_and_dict(type(self), self.__dict__) copy.__dict__['_tf_extension_type_is_packed'] = value return copy def _to_legacy_output_shapes(self): """Returns the shape property.""" try: return self.shape except AttributeError as e: raise NotImplementedError( 'It appears that the Spec of the ExtensionType is missing a shape' ' property. In order to support tf.Data, it is recommended that you' ' implement a shape property on the Spec.' ) from e
ExtensionTypeSpec
python
tensorflow__tensorflow
tensorflow/python/keras/layers/legacy_rnn/rnn_cell_impl.py
{ "start": 14353, "end": 16254 }
class ____(RNNCell): """Subclass of RNNCells that act like proper `tf.Layer` objects. For backwards compatibility purposes, most `RNNCell` instances allow their `call` methods to instantiate variables via `tf.compat.v1.get_variable`. The underlying variable scope thus keeps track of any variables, and returning cached versions. This is atypical of `tf.layer` objects, which separate this part of layer building into a `build` method that is only called once. Here we provide a subclass for `RNNCell` objects that act exactly as `Layer` objects do. They must provide a `build` method and their `call` methods do not access Variables `tf.compat.v1.get_variable`. """ def __call__(self, inputs, state, scope=None, *args, **kwargs): """Run this RNN cell on inputs, starting from the given state. Args: inputs: `2-D` tensor with shape `[batch_size, input_size]`. state: if `self.state_size` is an integer, this should be a `2-D Tensor` with shape `[batch_size, self.state_size]`. Otherwise, if `self.state_size` is a tuple of integers, this should be a tuple with shapes `[batch_size, s] for s in self.state_size`. scope: optional cell scope. *args: Additional positional arguments. **kwargs: Additional keyword arguments. Returns: A pair containing: - Output: A `2-D` tensor with shape `[batch_size, self.output_size]`. - New state: Either a single `2-D` tensor, or a tuple of tensors matching the arity and shapes of `state`. """ # Bypass RNNCell's variable capturing semantics for LayerRNNCell. # Instead, it is up to subclasses to provide a proper build # method. See the class docstring for more details. return base_layer.Layer.__call__( self, inputs, state, scope=scope, *args, **kwargs) @tf_export(v1=["nn.rnn_cell.BasicRNNCell"])
LayerRNNCell
python
sqlalchemy__sqlalchemy
test/orm/test_dynamic.py
{ "start": 4919, "end": 24172 }
class ____(_DynamicFixture, _fixtures.FixtureTest, AssertsCompiledSQL): __dialect__ = "default" def test_basic(self, user_address_fixture): User, Address = user_address_fixture() sess = fixture_session() q = sess.query(User) eq_( [ User( id=7, addresses=[Address(id=1, email_address="jack@bean.com")], ) ], q.filter(User.id == 7).all(), ) eq_(self.static.user_address_result, q.all()) eq_( [ User( id=7, addresses=[Address(id=1, email_address="jack@bean.com")], ) ], q.filter_by(id=7).all(), ) def test_slice_access(self, user_address_fixture): User, Address = user_address_fixture() sess = fixture_session() u1 = sess.get(User, 8) eq_(u1.addresses.limit(1).one(), Address(id=2)) eq_(u1.addresses[0], Address(id=2)) eq_(u1.addresses[0:2], [Address(id=2), Address(id=3)]) def test_negative_slice_access_raises(self, user_address_fixture): User, Address = user_address_fixture() sess = fixture_session(future=True) u1 = sess.get(User, 8) with expect_raises_message( IndexError, "negative indexes are not accepted by SQL index / slice operators", ): u1.addresses[-1] with expect_raises_message( IndexError, "negative indexes are not accepted by SQL index / slice operators", ): u1.addresses[-5:-2] with expect_raises_message( IndexError, "negative indexes are not accepted by SQL index / slice operators", ): u1.addresses[-2] with expect_raises_message( IndexError, "negative indexes are not accepted by SQL index / slice operators", ): u1.addresses[:-2] def test_statement(self, user_address_fixture): """test that the .statement accessor returns the actual statement that would render, without any _clones called.""" User, Address = user_address_fixture() sess = fixture_session() q = sess.query(User) u = q.filter(User.id == 7).first() self.assert_compile( u.addresses.statement, "SELECT addresses.id, addresses.user_id, addresses.email_address " "FROM " "addresses WHERE :param_1 = addresses.user_id", use_default_dialect=True, ) def test_query_class_custom_method(self, user_address_fixture): class MyClass(Query): def my_filter(self, arg): return self.filter(Address.email_address == arg) User, Address = user_address_fixture( addresses_args=dict(query_class=MyClass) ) sess = fixture_session() q = sess.query(User) u = q.filter(User.id == 7).first() assert isinstance(u.addresses, MyClass) self.assert_compile( u.addresses.my_filter("x").statement, "SELECT addresses.id, addresses.user_id, addresses.email_address " "FROM " "addresses WHERE :param_1 = addresses.user_id AND " "addresses.email_address = :email_address_1", use_default_dialect=True, ) @testing.combinations( ("all", []), ("one", exc.NoResultFound), ("one_or_none", None), argnames="method, expected", ) @testing.variation("add_to_session", [True, False]) def test_transient_raise( self, user_address_fixture, method, expected, add_to_session ): """test 11562""" User, Address = user_address_fixture() u1 = User(name="u1") if add_to_session: sess = fixture_session() sess.add(u1) meth = getattr(u1.addresses, method) if expected is exc.NoResultFound: with expect_raises_message( exc.NoResultFound, "No row was found when one was required" ): meth() else: eq_(meth(), expected) def test_detached_raise(self, user_address_fixture): """so filtering on a detached dynamic list raises an error...""" User, Address = user_address_fixture() sess = fixture_session() u = sess.get(User, 8) sess.expunge(u) assert_raises( orm_exc.DetachedInstanceError, u.addresses.filter_by, email_address="e", ) def test_detached_all_empty_list(self, user_address_fixture): """test #6426 - but you can call .all() on it and you get an empty list. This is legacy stuff, as this should be raising DetachedInstanceError. """ User, Address = user_address_fixture() sess = fixture_session() u = sess.get(User, 8) sess.expunge(u) with testing.expect_warnings( r"Instance <User .*> is detached, dynamic relationship" ): eq_(u.addresses.all(), []) with testing.expect_warnings( r"Instance <User .*> is detached, dynamic relationship" ): eq_(list(u.addresses), []) def test_transient_all_empty_list(self, user_address_fixture): User, Address = user_address_fixture() u1 = User() eq_(u1.addresses.all(), []) eq_(list(u1.addresses), []) def test_no_uselist_false(self, user_address_fixture): User, Address = user_address_fixture(addresses_args={"uselist": False}) assert_raises_message( exc.InvalidRequestError, "On relationship User.addresses, 'dynamic' loaders cannot be " "used with many-to-one/one-to-one relationships and/or " "uselist=False.", configure_mappers, ) @testing.combinations(False, True, None, argnames="uselist") def test_no_m2o(self, uselist): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) if uselist in (True, False): kw = {"uselist": uselist} else: kw = {} self.mapper_registry.map_imperatively( Address, addresses, properties={"user": relationship(User, lazy="dynamic", **kw)}, ) self.mapper_registry.map_imperatively(User, users) with expect_raises_message( exc.InvalidRequestError, "On relationship Address.user, 'dynamic' loaders cannot be " "used with many-to-one/one-to-one relationships and/or " "uselist=False.", ): configure_mappers() def test_order_by(self, user_address_fixture): User, Address = user_address_fixture() sess = fixture_session() u = sess.get(User, 8) eq_( list(u.addresses.order_by(desc(Address.email_address))), [ Address(email_address="ed@wood.com"), Address(email_address="ed@lala.com"), Address(email_address="ed@bettyboop.com"), ], ) @testing.requires.dupe_order_by_ok def test_order_by_composition_uses_immutable_tuple( self, user_address_fixture ): addresses = self.tables.addresses User, Address = user_address_fixture( addresses_args={"order_by": addresses.c.email_address.desc()} ) sess = fixture_session() u = sess.get(User, 8) with self.sql_execution_asserter() as asserter: for i in range(3): eq_( list(u.addresses.order_by(desc(Address.email_address))), [ Address(email_address="ed@wood.com"), Address(email_address="ed@lala.com"), Address(email_address="ed@bettyboop.com"), ], ) asserter.assert_( *[ CompiledSQL( "SELECT addresses.id AS addresses_id, addresses.user_id " "AS addresses_user_id, addresses.email_address " "AS addresses_email_address FROM addresses " "WHERE :param_1 = addresses.user_id " "ORDER BY addresses.email_address DESC, " "addresses.email_address DESC", [{"param_1": 8}], ) for i in range(3) ] ) def test_configured_order_by(self, user_address_fixture): addresses = self.tables.addresses User, Address = user_address_fixture( addresses_args={"order_by": addresses.c.email_address.desc()} ) sess = fixture_session() u = sess.get(User, 8) eq_( list(u.addresses), [ Address(email_address="ed@wood.com"), Address(email_address="ed@lala.com"), Address(email_address="ed@bettyboop.com"), ], ) # test cancellation of None, replacement with something else eq_( list(u.addresses.order_by(None).order_by(Address.email_address)), [ Address(email_address="ed@bettyboop.com"), Address(email_address="ed@lala.com"), Address(email_address="ed@wood.com"), ], ) # test cancellation of None, replacement with nothing eq_( set(u.addresses.order_by(None)), { Address(email_address="ed@bettyboop.com"), Address(email_address="ed@lala.com"), Address(email_address="ed@wood.com"), }, ) def test_count(self, user_address_fixture): User, Address = user_address_fixture() sess = fixture_session() u = sess.query(User).first() eq_(u.addresses.count(), 1) def test_dynamic_on_backref(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively( Address, addresses, properties={ "user": relationship( User, backref=backref("addresses", lazy="dynamic") ) }, ) self.mapper_registry.map_imperatively(User, users) sess = fixture_session() ad = sess.get(Address, 1) def go(): ad.user = None self.assert_sql_count(testing.db, go, 0) sess.flush() u = sess.get(User, 7) assert ad not in u.addresses def test_no_count(self, user_address_fixture): User, Address = user_address_fixture() sess = fixture_session() q = sess.query(User) # dynamic collection cannot implement __len__() (at least one that # returns a live database result), else additional count() queries are # issued when evaluating in a list context def go(): eq_( q.filter(User.id == 7).all(), [ User( id=7, addresses=[ Address(id=1, email_address="jack@bean.com") ], ) ], ) self.assert_sql_count(testing.db, go, 2) def test_no_populate(self, user_address_fixture): User, Address = user_address_fixture() u1 = User() assert_raises_message( NotImplementedError, "Dynamic attributes don't support collection population.", attributes.set_committed_value, u1, "addresses", [], ) def test_m2m(self, order_item_fixture): Order, Item = order_item_fixture( items_args={"backref": backref("orders", lazy="dynamic")} ) sess = fixture_session() o1 = Order(id=15, description="order 10") i1 = Item(id=10, description="item 8") o1.items.add(i1) sess.add(o1) sess.flush() assert o1 in i1.orders.all() assert i1 in o1.items.all() def test_association_nonaliased(self): items, Order, orders, order_items, Item = ( self.tables.items, self.classes.Order, self.tables.orders, self.tables.order_items, self.classes.Item, ) self.mapper_registry.map_imperatively( Order, orders, properties={ "items": relationship( Item, secondary=order_items, order_by=order_items.c.item_id, lazy="dynamic", ) }, ) self.mapper_registry.map_imperatively(Item, items) sess = fixture_session() o = sess.query(Order).first() self.assert_compile( o.items, "SELECT items.id AS items_id, items.description AS " "items_description FROM items," " order_items WHERE :param_1 = order_items.order_id AND " "items.id = order_items.item_id" " ORDER BY order_items.item_id", use_default_dialect=True, ) # filter criterion against the secondary table # works eq_(o.items.filter(order_items.c.item_id == 2).all(), [Item(id=2)]) def test_secondary_as_join(self): # test [ticket:4349] User, users = self.classes.User, self.tables.users items, orders, order_items, Item = ( self.tables.items, self.tables.orders, self.tables.order_items, self.classes.Item, ) self.mapper_registry.map_imperatively( User, users, properties={ "items": relationship( Item, secondary=order_items.join(orders), lazy="dynamic" ) }, ) item_mapper = self.mapper_registry.map_imperatively(Item, items) sess = fixture_session() u1 = sess.query(User).first() dyn = u1.items # test for #7868 eq_(dyn._from_obj[0]._annotations["parententity"], item_mapper) self.assert_compile( u1.items, "SELECT items.id AS items_id, " "items.description AS items_description " "FROM items, order_items JOIN orders " "ON orders.id = order_items.order_id " "WHERE :param_1 = orders.user_id " "AND items.id = order_items.item_id", use_default_dialect=True, ) def test_secondary_as_join_complex_entity(self, decl_base): """integration test for #7868""" class GrandParent(decl_base): __tablename__ = "grandparent" id = Column(Integer, primary_key=True) grand_children = relationship( "Child", secondary="parent", lazy="dynamic", viewonly=True ) class Parent(decl_base): __tablename__ = "parent" id = Column(Integer, primary_key=True) grand_parent_id = Column( Integer, ForeignKey("grandparent.id"), nullable=False ) class Child(decl_base): __tablename__ = "child" id = Column(Integer, primary_key=True) type = Column(String) parent_id = Column( Integer, ForeignKey("parent.id"), nullable=False ) __mapper_args__ = { "polymorphic_on": type, "polymorphic_identity": "unknown", "with_polymorphic": "*", } class SubChild(Child): __tablename__ = "subchild" id = Column(Integer, ForeignKey("child.id"), primary_key=True) __mapper_args__ = { "polymorphic_identity": "sub", } gp = GrandParent(id=1) make_transient_to_detached(gp) sess = fixture_session() sess.add(gp) self.assert_compile( gp.grand_children.filter_by(id=1), "SELECT child.id AS child_id, child.type AS child_type, " "child.parent_id AS child_parent_id, subchild.id AS subchild_id " "FROM child LEFT OUTER JOIN subchild " "ON child.id = subchild.id, parent " "WHERE :param_1 = parent.grand_parent_id " "AND parent.id = child.parent_id AND child.id = :id_1", {"id_1": 1}, ) def test_secondary_doesnt_interfere_w_join_to_fromlist(self): # tests that the "secondary" being added to the FROM # as part of [ticket:4349] does not prevent a subsequent join to # an entity that does not provide any "left side". Query right now # does not know how to join() like this unambiguously if _from_obj is # more than one element long. Order, orders = self.classes.Order, self.tables.orders items, order_items, Item = ( self.tables.items, self.tables.order_items, self.classes.Item, ) item_keywords = self.tables.item_keywords class ItemKeyword: pass self.mapper_registry.map_imperatively( Order, orders, properties={ "items": relationship( Item, secondary=order_items, lazy="dynamic" ) }, ) self.mapper_registry.map_imperatively( ItemKeyword, item_keywords, primary_key=[item_keywords.c.item_id, item_keywords.c.keyword_id], ) self.mapper_registry.map_imperatively( Item, items, properties={"item_keywords": relationship(ItemKeyword)}, ) sess = fixture_session() order = sess.query(Order).first() self.assert_compile( order.items.join(ItemKeyword), "SELECT items.id AS items_id, " "items.description AS items_description " "FROM items " "JOIN item_keywords ON items.id = item_keywords.item_id, " "order_items " "WHERE :param_1 = order_items.order_id " "AND items.id = order_items.item_id", use_default_dialect=True, ) def test_transient_count(self, user_address_fixture): User, Address = user_address_fixture() u1 = User() u1.addresses.add(Address()) eq_(u1.addresses.count(), 1) def test_transient_access(self, user_address_fixture): User, Address = user_address_fixture() u1 = User() u1.addresses.add(Address()) eq_(u1.addresses[0], Address())
DynamicTest
python
PrefectHQ__prefect
src/prefect/client/schemas/filters.py
{ "start": 23237, "end": 23914 }
class ____(PrefectBaseModel, OperatorMixin): """Filter BlockSchemas""" block_type_id: Optional[BlockSchemaFilterBlockTypeId] = Field( default=None, description="Filter criteria for `BlockSchema.block_type_id`" ) block_capabilities: Optional[BlockSchemaFilterCapabilities] = Field( default=None, description="Filter criteria for `BlockSchema.capabilities`" ) id: Optional[BlockSchemaFilterId] = Field( default=None, description="Filter criteria for `BlockSchema.id`" ) version: Optional[BlockSchemaFilterVersion] = Field( default=None, description="Filter criteria for `BlockSchema.version`" )
BlockSchemaFilter
python
pytest-dev__pytest
src/_pytest/junitxml.py
{ "start": 16050, "end": 25522 }
class ____: def __init__( self, logfile, prefix: str | None, suite_name: str = "pytest", logging: str = "no", report_duration: str = "total", family="xunit1", log_passing_tests: bool = True, ) -> None: logfile = os.path.expanduser(os.path.expandvars(logfile)) self.logfile = os.path.normpath(os.path.abspath(logfile)) self.prefix = prefix self.suite_name = suite_name self.logging = logging self.log_passing_tests = log_passing_tests self.report_duration = report_duration self.family = family self.stats: dict[str, int] = dict.fromkeys( ["error", "passed", "failure", "skipped"], 0 ) self.node_reporters: dict[tuple[str | TestReport, object], _NodeReporter] = {} self.node_reporters_ordered: list[_NodeReporter] = [] self.global_properties: list[tuple[str, str]] = [] # List of reports that failed on call but teardown is pending. self.open_reports: list[TestReport] = [] self.cnt_double_fail_tests = 0 # Replaces convenience family with real family. if self.family == "legacy": self.family = "xunit1" def finalize(self, report: TestReport) -> None: nodeid = getattr(report, "nodeid", report) # Local hack to handle xdist report order. workernode = getattr(report, "node", None) reporter = self.node_reporters.pop((nodeid, workernode)) for propname, propvalue in report.user_properties: reporter.add_property(propname, str(propvalue)) if reporter is not None: reporter.finalize() def node_reporter(self, report: TestReport | str) -> _NodeReporter: nodeid: str | TestReport = getattr(report, "nodeid", report) # Local hack to handle xdist report order. workernode = getattr(report, "node", None) key = nodeid, workernode if key in self.node_reporters: # TODO: breaks for --dist=each return self.node_reporters[key] reporter = _NodeReporter(nodeid, self) self.node_reporters[key] = reporter self.node_reporters_ordered.append(reporter) return reporter def add_stats(self, key: str) -> None: if key in self.stats: self.stats[key] += 1 def _opentestcase(self, report: TestReport) -> _NodeReporter: reporter = self.node_reporter(report) reporter.record_testreport(report) return reporter def pytest_runtest_logreport(self, report: TestReport) -> None: """Handle a setup/call/teardown report, generating the appropriate XML tags as necessary. Note: due to plugins like xdist, this hook may be called in interlaced order with reports from other nodes. For example: Usual call order: -> setup node1 -> call node1 -> teardown node1 -> setup node2 -> call node2 -> teardown node2 Possible call order in xdist: -> setup node1 -> call node1 -> setup node2 -> call node2 -> teardown node2 -> teardown node1 """ close_report = None if report.passed: if report.when == "call": # ignore setup/teardown reporter = self._opentestcase(report) reporter.append_pass(report) elif report.failed: if report.when == "teardown": # The following vars are needed when xdist plugin is used. report_wid = getattr(report, "worker_id", None) report_ii = getattr(report, "item_index", None) close_report = next( ( rep for rep in self.open_reports if ( rep.nodeid == report.nodeid and getattr(rep, "item_index", None) == report_ii and getattr(rep, "worker_id", None) == report_wid ) ), None, ) if close_report: # We need to open new testcase in case we have failure in # call and error in teardown in order to follow junit # schema. self.finalize(close_report) self.cnt_double_fail_tests += 1 reporter = self._opentestcase(report) if report.when == "call": reporter.append_failure(report) self.open_reports.append(report) if not self.log_passing_tests: reporter.write_captured_output(report) else: reporter.append_error(report) elif report.skipped: reporter = self._opentestcase(report) reporter.append_skipped(report) self.update_testcase_duration(report) if report.when == "teardown": reporter = self._opentestcase(report) reporter.write_captured_output(report) self.finalize(report) report_wid = getattr(report, "worker_id", None) report_ii = getattr(report, "item_index", None) close_report = next( ( rep for rep in self.open_reports if ( rep.nodeid == report.nodeid and getattr(rep, "item_index", None) == report_ii and getattr(rep, "worker_id", None) == report_wid ) ), None, ) if close_report: self.open_reports.remove(close_report) def update_testcase_duration(self, report: TestReport) -> None: """Accumulate total duration for nodeid from given report and update the Junit.testcase with the new total if already created.""" if self.report_duration in {"total", report.when}: reporter = self.node_reporter(report) reporter.duration += getattr(report, "duration", 0.0) def pytest_collectreport(self, report: TestReport) -> None: if not report.passed: reporter = self._opentestcase(report) if report.failed: reporter.append_collect_error(report) else: reporter.append_collect_skipped(report) def pytest_internalerror(self, excrepr: ExceptionRepr) -> None: reporter = self.node_reporter("internal") reporter.attrs.update(classname="pytest", name="internal") reporter._add_simple("error", "internal error", str(excrepr)) def pytest_sessionstart(self) -> None: self.suite_start = timing.Instant() def pytest_sessionfinish(self) -> None: dirname = os.path.dirname(os.path.abspath(self.logfile)) # exist_ok avoids filesystem race conditions between checking path existence and requesting creation os.makedirs(dirname, exist_ok=True) with open(self.logfile, "w", encoding="utf-8") as logfile: duration = self.suite_start.elapsed() numtests = ( self.stats["passed"] + self.stats["failure"] + self.stats["skipped"] + self.stats["error"] - self.cnt_double_fail_tests ) logfile.write('<?xml version="1.0" encoding="utf-8"?>') suite_node = ET.Element( "testsuite", name=self.suite_name, errors=str(self.stats["error"]), failures=str(self.stats["failure"]), skipped=str(self.stats["skipped"]), tests=str(numtests), time=f"{duration.seconds:.3f}", timestamp=self.suite_start.as_utc().astimezone().isoformat(), hostname=platform.node(), ) global_properties = self._get_global_properties_node() if global_properties is not None: suite_node.append(global_properties) for node_reporter in self.node_reporters_ordered: suite_node.append(node_reporter.to_xml()) testsuites = ET.Element("testsuites") testsuites.set("name", "pytest tests") testsuites.append(suite_node) logfile.write(ET.tostring(testsuites, encoding="unicode")) def pytest_terminal_summary( self, terminalreporter: TerminalReporter, config: pytest.Config ) -> None: if config.get_verbosity() >= 0: terminalreporter.write_sep("-", f"generated xml file: {self.logfile}") def add_global_property(self, name: str, value: object) -> None: __tracebackhide__ = True _check_record_param_type("name", name) self.global_properties.append((name, bin_xml_escape(value))) def _get_global_properties_node(self) -> ET.Element | None: """Return a Junit node containing custom properties, if any.""" if self.global_properties: properties = ET.Element("properties") for name, value in self.global_properties: properties.append(ET.Element("property", name=name, value=value)) return properties return None
LogXML
python
getsentry__sentry
src/sentry/preprod/migrations/0017_break_commit_fks.py
{ "start": 222, "end": 1781 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # of a table. # Here are some things that make sense to mark as post deployment: # - Large data migrations. Typically we want these to be run manually so that they can be # monitored and not block the deploy for a long period of time while they run. # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to # run this outside deployments so that we don't block them. Note that while adding an index # is a schema change, it's completely safe to run the operation after the code has deployed. # Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment is_post_deployment = False dependencies = [ ("preprod", "0016_add_preprod_artifact_size_comparison_table"), ("sentry", "0978_break_commit_fks"), ] operations = [ migrations.AlterField( model_name="preprodartifact", name="commit", field=sentry.db.models.fields.foreignkey.FlexibleForeignKey( db_constraint=False, null=True, on_delete=django.db.models.deletion.SET_NULL, to="sentry.commit", ), ), ]
Migration
python
spyder-ide__spyder
spyder/plugins/statusbar/confpage.py
{ "start": 352, "end": 2068 }
class ____(PluginConfigPage): def setup_page(self): newcb = self.create_checkbox # --- Status bar sbar_group = QGroupBox(_("Display")) memory_box = newcb(_("Show memory usage every"), 'memory_usage/enable') memory_spin = self.create_spinbox("", _(" ms"), 'memory_usage/timeout', min_=100, max_=1000000, step=100, tip=self.plugin.mem_status.toolTip()) memory_box.checkbox.toggled.connect(memory_spin.setEnabled) memory_spin.setEnabled(self.get_option('memory_usage/enable')) cpu_box = newcb(_("Show CPU usage every"), 'cpu_usage/enable') cpu_spin = self.create_spinbox("", _(" ms"), 'cpu_usage/timeout', min_=100, max_=1000000, step=100, tip=self.plugin.cpu_status.toolTip()) cpu_box.checkbox.toggled.connect(cpu_spin.setEnabled) cpu_spin.setEnabled(self.get_option('cpu_usage/enable')) clock_box = newcb(_("Show clock"), 'clock/enable') # Layout status bar cpu_memory_layout = QGridLayout() cpu_memory_layout.addWidget(memory_box, 0, 0) cpu_memory_layout.addWidget(memory_spin, 0, 1) cpu_memory_layout.addWidget(cpu_box, 1, 0) cpu_memory_layout.addWidget(cpu_spin, 1, 1) cpu_memory_layout.addWidget(clock_box, 2, 0) sbar_layout = QVBoxLayout() sbar_layout.addLayout(cpu_memory_layout) sbar_group.setLayout(sbar_layout) vlayout = QVBoxLayout() vlayout.addWidget(sbar_group) vlayout.addStretch(1) self.setLayout(vlayout)
StatusBarConfigPage
python
ansible__ansible
lib/ansible/modules/file.py
{ "start": 8705, "end": 8903 }
class ____(Exception): def __init__(self, results): self.results = results def __repr__(self): return 'AnsibleModuleError(results={0})'.format(self.results)
AnsibleModuleError
python
pypa__pipenv
pipenv/patched/pip/_internal/models/pylock.py
{ "start": 1959, "end": 5344 }
class ____: name: str version: Optional[str] = None # (not supported) marker: Optional[str] # (not supported) requires_python: Optional[str] # (not supported) dependencies vcs: Optional[PackageVcs] = None directory: Optional[PackageDirectory] = None archive: Optional[PackageArchive] = None # (not supported) index: Optional[str] sdist: Optional[PackageSdist] = None wheels: Optional[List[PackageWheel]] = None # (not supported) attestation_identities: Optional[List[Dict[str, Any]]] # (not supported) tool: Optional[Dict[str, Any]] @classmethod def from_install_requirement(cls, ireq: InstallRequirement, base_dir: Path) -> Self: base_dir = base_dir.resolve() dist = ireq.get_dist() download_info = ireq.download_info assert download_info package = cls(name=dist.canonical_name) if ireq.is_direct: if isinstance(download_info.info, VcsInfo): package.vcs = PackageVcs( type=download_info.info.vcs, url=download_info.url, requested_revision=download_info.info.requested_revision, commit_id=download_info.info.commit_id, subdirectory=download_info.subdirectory, ) elif isinstance(download_info.info, DirInfo): package.directory = PackageDirectory( path=( Path(url_to_path(download_info.url)) .resolve() .relative_to(base_dir) .as_posix() ), editable=( download_info.info.editable if download_info.info.editable else None ), subdirectory=download_info.subdirectory, ) elif isinstance(download_info.info, ArchiveInfo): if not download_info.info.hashes: raise NotImplementedError() package.archive = PackageArchive( url=download_info.url, hashes=download_info.info.hashes, subdirectory=download_info.subdirectory, ) else: # should never happen raise NotImplementedError() else: package.version = str(dist.version) if isinstance(download_info.info, ArchiveInfo): if not download_info.info.hashes: raise NotImplementedError() link = Link(download_info.url) if link.is_wheel: package.wheels = [ PackageWheel( name=link.filename, url=download_info.url, hashes=download_info.info.hashes, ) ] else: package.sdist = PackageSdist( name=link.filename, url=download_info.url, hashes=download_info.info.hashes, ) else: # should never happen raise NotImplementedError() return package @dataclass
Package
python
keon__algorithms
algorithms/graph/cycle_detection.py
{ "start": 288, "end": 1634 }
class ____(Enum): """ For a given node: - WHITE: has not been visited yet - GRAY: is currently being investigated for a cycle - BLACK: is not part of a cycle """ WHITE = 0 GRAY = 1 BLACK = 2 def is_in_cycle(graph, traversal_states, vertex): """ Determines if the given vertex is in a cycle. :param: traversal_states: for each vertex, the state it is in """ if traversal_states[vertex] == TraversalState.GRAY: return True traversal_states[vertex] = TraversalState.GRAY for neighbor in graph[vertex]: if is_in_cycle(graph, traversal_states, neighbor): return True traversal_states[vertex] = TraversalState.BLACK return False def contains_cycle(graph): """ Determines if there is a cycle in the given graph. The graph should be given as a dictionary: graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['F'], 'D': ['E', 'F'], 'E': ['B'], 'F': []} """ traversal_states = {vertex: TraversalState.WHITE for vertex in graph} for vertex, state in traversal_states.items(): if (state == TraversalState.WHITE and is_in_cycle(graph, traversal_states, vertex)): return True return False
TraversalState
python
pytorch__pytorch
torch/_subclasses/fake_tensor.py
{ "start": 42305, "end": 43160 }
class ____: """ Key for the FakeTensor dispatch cache. """ key: tuple[object, ...] hashvalue: int def __init__(self, tup: tuple[object, ...]) -> None: self.key = tup self.hashvalue = hash(tup) def __eq__(self, other: object) -> bool: return isinstance(other, _DispatchCacheKey) and self.key == other.key def __hash__(self) -> int: return self.hashvalue def strip_shape_env(self) -> None: # We need to strip the ShapeEnv from any values before we store in the # cache so the cache doesn't keep our ShapeEnvs alive. for v in self.key: if isinstance(v, _PySymInputStub): v.strip_shape_env() # Default value for constant_value in _DispatchCacheEntryOutputInfo. This is # only for checking and differentiates from None.
_DispatchCacheKey
python
pytorch__pytorch
.ci/lumen_cli/tests/test_cli_helper.py
{ "start": 1324, "end": 3892 }
class ____(unittest.TestCase): def test_metavar_lists_targets(self): specs: dict[str, TargetSpec] = { "foo": {"runner": FooRunner, "add_arguments": add_foo_args}, "bar": {"runner": BarRunner}, } parser = build_parser(specs) subparsers_action = next( a for a in parser._subparsers._group_actions # type: ignore[attr-defined] if isinstance(a, argparse._SubParsersAction) ) self.assertEqual(subparsers_action.metavar, "{foo,bar}") def test_add_arguments_and_common_args_present(self): specs: dict[str, TargetSpec] = { "foo": {"runner": FooRunner, "add_arguments": add_foo_args}, } parser = build_parser(specs) foo = get_subparser(parser, "foo") help_text = foo.format_help() self.assertIn("--x", help_text) self.assertIn("--verbose", help_text) def test_runner_constructed_with_ns_and_run_called(self): specs: dict[str, TargetSpec] = { "foo": {"runner": FooRunner, "add_arguments": add_foo_args}, } parser = build_parser(specs) with ( patch.object(FooRunner, "__init__", return_value=None) as mock_init, patch.object(FooRunner, "run", return_value=None) as mock_run, ): ns = parser.parse_args(["foo", "--x", "3", "--verbose"]) ns.func(ns) # set by register_targets # __init__ received the Namespace self.assertEqual(mock_init.call_count, 1) (called_ns,), _ = mock_init.call_args self.assertIsInstance(called_ns, argparse.Namespace) # run() called with no args mock_run.assert_called_once_with() def test_runner_docstring_used_as_description_when_missing(self): specs: dict[str, TargetSpec] = { "foo": {"runner": FooRunner, "add_arguments": add_foo_args}, } parser = build_parser(specs) foo = get_subparser(parser, "foo") help_text = foo.format_help() self.assertIn("Foo description from docstring.", help_text) def test_missing_target_raises_systemexit_with_usage(self): specs: dict[str, TargetSpec] = {"foo": {"runner": FooRunner}} parser = build_parser(specs) buf = io.StringIO() with self.assertRaises(SystemExit), redirect_stderr(buf): parser.parse_args([]) err = buf.getvalue() self.assertIn("usage:", err) if __name__ == "__main__": unittest.main()
TestRegisterTargets
python
mlflow__mlflow
mlflow/pyfunc/model.py
{ "start": 9536, "end": 10712 }
class ____(PythonModel): """ When a user specifies a ``python_model`` argument that is a function, we wrap the function in an instance of this class. """ def __init__(self, func, signature=None): self.signature = signature # only wrap `func` if @pyfunc is not already applied if not getattr(func, "_is_pyfunc", False): self.func = pyfunc(func) else: self.func = func @property def predict_type_hints(self): if hasattr(self, "_predict_type_hints"): return self._predict_type_hints self._predict_type_hints = _extract_type_hints(self.func, input_arg_index=0) return self._predict_type_hints def predict( self, model_input, params: dict[str, Any] | None = None, ): """ Args: model_input: A pyfunc-compatible input for the model to evaluate. params: Additional parameters to pass to the model for inference. Returns: Model predictions. """ # callable only supports one input argument for now return self.func(model_input)
_FunctionPythonModel
python
PrefectHQ__prefect
src/prefect/settings/models/server/services.py
{ "start": 7430, "end": 8921 }
class ____(ServicesBaseSetting): """ Settings for controlling the late runs service """ model_config: ClassVar[SettingsConfigDict] = build_settings_config( ("server", "services", "late_runs") ) enabled: bool = Field( default=True, description="Whether or not to start the late runs service in the server application.", validation_alias=AliasChoices( AliasPath("enabled"), "prefect_server_services_late_runs_enabled", "prefect_api_services_late_runs_enabled", ), ) loop_seconds: float = Field( default=5, description=""" The late runs service will look for runs to mark as late this often. Defaults to `5`. """, validation_alias=AliasChoices( AliasPath("loop_seconds"), "prefect_server_services_late_runs_loop_seconds", "prefect_api_services_late_runs_loop_seconds", ), ) after_seconds: SecondsTimeDelta = Field( default=timedelta(seconds=15), description=""" The late runs service will mark runs as late after they have exceeded their scheduled start time by this many seconds. Defaults to `5` seconds. """, validation_alias=AliasChoices( AliasPath("after_seconds"), "prefect_server_services_late_runs_after_seconds", "prefect_api_services_late_runs_after_seconds", ), )
ServerServicesLateRunsSettings
python
huggingface__transformers
tests/models/siglip2/test_modeling_siglip2.py
{ "start": 13658, "end": 16885 }
class ____: def __init__( self, parent, batch_size=12, seq_length=7, is_training=True, use_input_mask=True, use_labels=True, vocab_size=99, hidden_size=64, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, dropout=0.1, attention_dropout=0.1, max_position_embeddings=512, initializer_range=0.02, scope=None, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_mask = use_input_mask self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.dropout = dropout self.attention_dropout = attention_dropout self.max_position_embeddings = max_position_embeddings self.initializer_range = initializer_range self.scope = scope def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) input_mask = None if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) if input_mask is not None: batch_size, seq_length = input_mask.shape rnd_start_indices = np.random.randint(1, seq_length - 1, size=(batch_size,)) for batch_idx, start_index in enumerate(rnd_start_indices): input_mask[batch_idx, :start_index] = 1 input_mask[batch_idx, start_index:] = 0 config = self.get_config() return config, input_ids, input_mask def get_config(self): return Siglip2TextConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, dropout=self.dropout, attention_dropout=self.attention_dropout, max_position_embeddings=self.max_position_embeddings, initializer_range=self.initializer_range, ) def create_and_check_model(self, config, input_ids, input_mask): model = Siglip2TextModel(config=config) model.to(torch_device) model.eval() with torch.no_grad(): result = model(input_ids, attention_mask=input_mask) result = model(input_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, input_ids, input_mask = config_and_inputs inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch
Siglip2TextModelTester
python
openai__openai-python
tests/api_resources/audio/test_translations.py
{ "start": 2283, "end": 4357 }
class ____: parametrize = pytest.mark.parametrize( "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] ) @parametrize async def test_method_create(self, async_client: AsyncOpenAI) -> None: translation = await async_client.audio.translations.create( file=b"raw file contents", model="whisper-1", ) assert_matches_type(TranslationCreateResponse, translation, path=["response"]) @parametrize async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: translation = await async_client.audio.translations.create( file=b"raw file contents", model="whisper-1", prompt="prompt", response_format="json", temperature=0, ) assert_matches_type(TranslationCreateResponse, translation, path=["response"]) @parametrize async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: response = await async_client.audio.translations.with_raw_response.create( file=b"raw file contents", model="whisper-1", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" translation = response.parse() assert_matches_type(TranslationCreateResponse, translation, path=["response"]) @parametrize async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: async with async_client.audio.translations.with_streaming_response.create( file=b"raw file contents", model="whisper-1", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" translation = await response.parse() assert_matches_type(TranslationCreateResponse, translation, path=["response"]) assert cast(Any, response.is_closed) is True
TestAsyncTranslations
python
walkccc__LeetCode
solutions/2264. Largest 3-Same-Digit Number in String/2264.py
{ "start": 0, "end": 202 }
class ____: def largestGoodInteger(self, num: str) -> str: return max(num[i - 2:i + 1] if num[i] == num[i - 1] == num[i - 2] else '' for i in range(2, len(num)))
Solution
python
boto__boto3
boto3/resources/model.py
{ "start": 1389, "end": 2415 }
class ____: """ A service operation action. :type name: string :param name: The name of the action :type definition: dict :param definition: The JSON definition :type resource_defs: dict :param resource_defs: All resources defined in the service """ def __init__(self, name, definition, resource_defs): self._definition = definition #: (``string``) The name of the action self.name = name #: (:py:class:`Request`) This action's request or ``None`` self.request = None if 'request' in definition: self.request = Request(definition.get('request', {})) #: (:py:class:`ResponseResource`) This action's resource or ``None`` self.resource = None if 'resource' in definition: self.resource = ResponseResource( definition.get('resource', {}), resource_defs ) #: (``string``) The JMESPath search path or ``None`` self.path = definition.get('path')
Action
python
huggingface__transformers
src/transformers/generation/continuous_batching/cache_manager.py
{ "start": 15444, "end": 20690 }
class ____(CacheAllocator): """Cache manager for sliding window attention layers.""" def __init__(self, index: int, block_size: int, sliding_window: int) -> None: """Initializes the cache manager for a group of sliding window attention layers. Args: - index: the index of the associated layer group - block_size: the size of the blocks in the cache - sliding_window: the size of the sliding window """ self._index = index self.block_size = block_size self.sliding_window = sliding_window self._max_blocks_per_request = ceil(self.sliding_window / self.block_size) self.block_table = {} def allocate_blocks(self, n_blocks: int, request_id: str, block_manager: BlockManager) -> int | None: """Allocate (n_blocks) for a given (request_id) using the (block_manager). Returns the number of blocks allocated otherwise. For group of sliding window attention layers, we only allocate up to the point where we can fit an entire sliding window in the cache tensor.""" if request_id not in self.block_table: self.block_table[request_id] = [] # Early return if we are already at the max number of blocks per request already_allocated = len(self.block_table[request_id]) if already_allocated == self._max_blocks_per_request: return 0 # Compute actual number of blocks to allocate after_allocation = min(already_allocated + n_blocks, self._max_blocks_per_request) actual_n_blocks = after_allocation - already_allocated # Classic allocation allocated_blocks = block_manager.get_free_blocks(actual_n_blocks, None) # no prefix caching w/ sliding window if allocated_blocks is None: return None self.block_table[request_id].extend(allocated_blocks) return actual_n_blocks def get_read_indices(self, request_id: str, past_length: int, query_length: int) -> list[int]: """Returns the physical indices of where to read request_id's cache in the cache tensor. For a group of sliding window attention layers, we read from the cache tensor before writing on it, because the new cache can overwrite the old one. To form the cache + new key / values states, we read the at most sliding_window - 1 cache page and then manually add the new key / values states after. Hence the -1 indices which indicate where to store the new key or values indices.""" # Retrieve the block table for the request and raise an error if it doesn't exist block_table = self.block_table.get(request_id) if block_table is None: raise ValueError(f"No block table found for request {request_id}") # Apply sliding window start_index = 0 if past_length < self.sliding_window else past_length % self.sliding_window cache_length = min(past_length, self.sliding_window - 1) # Compute the physical indices physical_indices = [] for i in range(start_index, start_index + cache_length): i %= self.sliding_window block_idx = i // self.block_size block_offset = i % self.block_size physical_index = block_table[block_idx] * self.block_size + block_offset physical_indices.append(physical_index) return physical_indices + [-1] * query_length def get_write_indices(self, request_id: str, past_length: int, query_length: int) -> list[int]: """Returns the physical indices of where to write request_id's cache in the cache tensor. For a group of sliding window attention layers, we write the new cache in rolling-buffer kind of way: if we reach the end of the allocated physical cache, we start writing from the beginning of the physical cache again.""" # Retrieve the block table for the request and raise an error if it doesn't exist block_table = self.block_table.get(request_id) if block_table is None: raise ValueError(f"No block table found for request {request_id}") # Apply sliding window start_index = past_length % self.sliding_window cache_length = min(query_length, self.sliding_window) padding_length = query_length - cache_length # Compute the physical indices physical_indices = [] for i in range(start_index, start_index + cache_length): i %= self.sliding_window block_idx = i // self.block_size block_offset = i % self.block_size physical_index = block_table[block_idx] * self.block_size + block_offset physical_indices.append(physical_index) if padding_length > 0: physical_indices = [-1] * padding_length + physical_indices return physical_indices def get_seqlens_k(self, request_id: str, past_length: int, query_length: int) -> tuple[str, int]: """Returns the attention type of the cache allocator and the key sequence length for the given request_id.""" seqlens_k = query_length + min(past_length, self.sliding_window - 1) return "sliding_attention", seqlens_k
SlidingAttentionCacheAllocator
python
great-expectations__great_expectations
docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/column_aggregate_expectation_template.py
{ "start": 1062, "end": 2541 }
class ____(ColumnAggregateMetricProvider): # </snippet> # This is the id string that will be used to reference your Metric. # <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_aggregate_expectation_template.py metric_name"> metric_name = "METRIC NAME GOES HERE" # </snippet> # This method implements the core logic for the PandasExecutionEngine # <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_aggregate_expectation_template.py pandas"> @column_aggregate_value(engine=PandasExecutionEngine) def _pandas(cls, column, **kwargs): raise NotImplementedError # This method defines the business logic for evaluating your Metric when using a SqlAlchemyExecutionEngine # @column_aggregate_partial(engine=SqlAlchemyExecutionEngine) # def _sqlalchemy(cls, column, _dialect, **kwargs): # raise NotImplementedError # # This method defines the business logic for evaluating your Metric when using a SparkDFExecutionEngine # @column_aggregate_partial(engine=SparkDFExecutionEngine) # def _spark(cls, column, **kwargs): # raise NotImplementedError # This class defines the Expectation itself # <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_aggregate_expectation_template.py ExpectColumnAggregateToMatchSomeCriteria class_def">
ColumnAggregateMatchesSomeCriteria
python
ray-project__ray
rllib/utils/spaces/simplex.py
{ "start": 107, "end": 1881 }
class ____(gym.Space): """Represents a d - 1 dimensional Simplex in R^d. That is, all coordinates are in [0, 1] and sum to 1. The dimension d of the simplex is assumed to be shape[-1]. Additionally one can specify the underlying distribution of the simplex as a Dirichlet distribution by providing concentration parameters. By default, sampling is uniform, i.e. concentration is all 1s. Example usage: self.action_space = spaces.Simplex(shape=(3, 4)) --> 3 independent 4d Dirichlet with uniform concentration """ def __init__(self, shape, concentration=None, dtype=np.float32): assert type(shape) in [tuple, list] super().__init__(shape, dtype) self.dim = self.shape[-1] if concentration is not None: assert ( concentration.shape[0] == shape[-1] ), f"{concentration.shape[0]} vs {shape[-1]}" self.concentration = concentration else: self.concentration = np.array([1] * self.dim) def sample(self): return np.random.dirichlet(self.concentration, size=self.shape[:-1]).astype( self.dtype ) def contains(self, x): return x.shape == self.shape and np.allclose( np.sum(x, axis=-1), np.ones_like(x[..., 0]) ) def to_jsonable(self, sample_n): return np.array(sample_n).tolist() def from_jsonable(self, sample_n): return [np.asarray(sample) for sample in sample_n] def __repr__(self): return "Simplex({}; {})".format(self.shape, self.concentration) def __eq__(self, other): return ( np.allclose(self.concentration, other.concentration) and self.shape == other.shape )
Simplex
python
mlflow__mlflow
tests/langchain/test_langchain_databricks_dependency_extraction.py
{ "start": 2721, "end": 21398 }
class ____(VectorSearchIndex): def __init__(self, endpoint_name, index_name, has_embedding_endpoint=False) -> None: self.endpoint_name = endpoint_name self.name = index_name self.has_embedding_endpoint = has_embedding_endpoint def describe(self): if self.has_embedding_endpoint: return { "name": self.name, "endpoint_name": self.endpoint_name, "primary_key": "id", "index_type": "DELTA_SYNC", "delta_sync_index_spec": { "source_table": "ml.schema.databricks_documentation", "embedding_source_columns": [ {"name": "content", "embedding_model_endpoint_name": "embedding-model"} ], "pipeline_type": "TRIGGERED", "pipeline_id": "79a76fcc-67ad-4ac6-8d8e-20f7d485ffa6", }, "status": { "detailed_state": "OFFLINE_FAILED", "message": "Index creation failed.", "indexed_row_count": 0, "failed_status": {"error_message": ""}, "ready": False, "index_url": "e2-dogfood.staging.cloud.databricks.com/rest_of_url", }, "creator": "first.last@databricks.com", } else: return { "name": self.name, "endpoint_name": self.endpoint_name, "primary_key": "id", "index_type": "DELTA_SYNC", "delta_sync_index_spec": { "source_table": "ml.schema.databricks_documentation", "embedding_vector_columns": [], "pipeline_type": "TRIGGERED", "pipeline_id": "fbbd5bf1-2b9b-4a7e-8c8d-c0f6cc1030de", }, "status": { "detailed_state": "ONLINE", "message": "Index is currently online", "indexed_row_count": 17183, "ready": True, "index_url": "e2-dogfood.staging.cloud.databricks.com/rest_of_url", }, "creator": "first.last@databricks.com", } def get_vector_search( endpoint_name: str, index_name: str, has_embedding_endpoint=False, **kwargs, ): index = MockVectorSearchIndex(endpoint_name, index_name, has_embedding_endpoint) from databricks_langchain import DatabricksVectorSearch with mock.patch("databricks.vector_search.client.VectorSearchClient") as mock_client: mock_client().get_index.return_value = index return DatabricksVectorSearch( endpoint=endpoint_name, index_name=index_name, **kwargs, ) def test_parsing_dependency_from_databricks_retriever(monkeypatch): from databricks_langchain import ChatDatabricks, DatabricksEmbeddings remove_langchain_community(monkeypatch) with pytest.raises(ImportError, match="No module named 'langchain_community"): from langchain_community.embeddings import DatabricksEmbeddings embedding_model = DatabricksEmbeddings(endpoint="databricks-bge-large-en") # vs_index_1 is a direct access index vectorstore_1 = get_vector_search( endpoint_name="vs_endpoint", index_name="mlflow.rag.vs_index_1", text_column="content", embedding=embedding_model, ) retriever_1 = vectorstore_1.as_retriever() # vs_index_2 has builtin embedding endpoint "embedding-model" vectorstore_2 = get_vector_search( endpoint_name="vs_endpoint", index_name="mlflow.rag.vs_index_2", has_embedding_endpoint=True, ) retriever_2 = vectorstore_2.as_retriever() llm = ChatDatabricks(endpoint="databricks-llama-2-70b-chat", temperature=0) assert list(_extract_databricks_dependencies_from_retriever(retriever_1)) == [ DatabricksVectorSearchIndex(index_name="mlflow.rag.vs_index_1"), DatabricksServingEndpoint(endpoint_name="databricks-bge-large-en"), ] assert list(_extract_databricks_dependencies_from_retriever(retriever_2)) == [ DatabricksVectorSearchIndex(index_name="mlflow.rag.vs_index_2"), DatabricksServingEndpoint(endpoint_name="embedding-model"), ] try: from langchain.retrievers import ( ContextualCompressionRetriever, EnsembleRetriever, TimeWeightedVectorStoreRetriever, ) from langchain.retrievers.document_compressors import LLMChainExtractor from langchain.retrievers.multi_query import MultiQueryRetriever except ImportError: from langchain_classic.retrievers import ( ContextualCompressionRetriever, EnsembleRetriever, TimeWeightedVectorStoreRetriever, ) from langchain_classic.retrievers.document_compressors import LLMChainExtractor from langchain_classic.retrievers.multi_query import MultiQueryRetriever multi_query_retriever = MultiQueryRetriever.from_llm(retriever=retriever_1, llm=llm) assert list(_extract_databricks_dependencies_from_retriever(multi_query_retriever)) == [ DatabricksVectorSearchIndex(index_name="mlflow.rag.vs_index_1"), DatabricksServingEndpoint(endpoint_name="databricks-bge-large-en"), ] compressor = LLMChainExtractor.from_llm(llm) compression_retriever = ContextualCompressionRetriever( base_compressor=compressor, base_retriever=retriever_1 ) assert list(_extract_databricks_dependencies_from_retriever(compression_retriever)) == [ DatabricksVectorSearchIndex(index_name="mlflow.rag.vs_index_1"), DatabricksServingEndpoint(endpoint_name="databricks-bge-large-en"), ] ensemble_retriever = EnsembleRetriever( retrievers=[retriever_1, retriever_2], weights=[0.5, 0.5] ) assert list(_extract_databricks_dependencies_from_retriever(ensemble_retriever)) == [ DatabricksVectorSearchIndex(index_name="mlflow.rag.vs_index_1"), DatabricksServingEndpoint(endpoint_name="databricks-bge-large-en"), DatabricksVectorSearchIndex(index_name="mlflow.rag.vs_index_2"), DatabricksServingEndpoint(endpoint_name="embedding-model"), ] time_weighted_retriever = TimeWeightedVectorStoreRetriever( vectorstore=vectorstore_1, decay_rate=0.0000000000000000000000001, k=1 ) assert list(_extract_databricks_dependencies_from_retriever(time_weighted_retriever)) == [ DatabricksVectorSearchIndex(index_name="mlflow.rag.vs_index_1"), DatabricksServingEndpoint(endpoint_name="databricks-bge-large-en"), ] def test_parsing_dependency_from_retriever_with_embedding_endpoint_in_index(): vectorstore = get_vector_search( endpoint_name="dbdemos_vs_endpoint", index_name="mlflow.rag.vs_index", has_embedding_endpoint=True, ) retriever = vectorstore.as_retriever() resources = list(_extract_databricks_dependencies_from_retriever(retriever)) assert resources == [ DatabricksVectorSearchIndex(index_name="mlflow.rag.vs_index"), DatabricksServingEndpoint(endpoint_name="embedding-model"), ] def test_parsing_dependency_from_agent(monkeypatch: pytest.MonkeyPatch): from databricks.sdk.service.catalog import FunctionInfo from databricks_langchain import ChatDatabricks from langchain.agents import initialize_agent try: from langchain_community.tools.databricks import UCFunctionToolkit except Exception: return # When get is called return a function def mock_function_get(self, function_name): components = function_name.split(".") # Initialize agent used below requires functions to take in exactly one parameter param_dict = { "parameters": [ { "name": "param", "parameter_type": "PARAM", "position": 0, "type_json": '{"name":"param","type":"string","nullable":true,"metadata":{}}', "type_name": "STRING", "type_precision": 0, "type_scale": 0, "type_text": "string", } ] } # Add the catalog, schema and name to the function Info followed by the parameter return FunctionInfo.from_dict( { "catalog_name": components[0], "schema_name": components[1], "name": components[2], "input_params": param_dict, } ) monkeypatch.setenv("DATABRICKS_HOST", "my-default-host") monkeypatch.setenv("DATABRICKS_TOKEN", "my-default-token") monkeypatch.setattr("databricks.sdk.service.catalog.FunctionsAPI.get", mock_function_get) toolkit = UCFunctionToolkit(warehouse_id="testId1").include("rag.test.test_function") llm = ChatDatabricks(endpoint="databricks-llama-2-70b-chat", temperature=0) agent = initialize_agent( toolkit.get_tools(), llm, verbose=True, ) resources = sorted(_extract_dependency_list_from_lc_model(agent), key=lambda x: x.name) assert resources == [ DatabricksServingEndpoint(endpoint_name="databricks-llama-2-70b-chat"), DatabricksFunction(function_name="rag.test.test_function"), DatabricksSQLWarehouse(warehouse_id="testId1"), ] def test_parsing_multiple_dependency_from_agent(monkeypatch): from databricks.sdk.service.catalog import FunctionInfo from databricks_langchain import ChatDatabricks from langchain.agents import initialize_agent from langchain.tools.retriever import create_retriever_tool remove_langchain_community(monkeypatch) def mock_function_get(self, function_name): components = function_name.split(".") param_dict = { "parameters": [ { "name": "param", "parameter_type": "PARAM", "position": 0, "type_json": '{"name":"param","type":"string","nullable":true,"metadata":{}}', "type_name": "STRING", "type_precision": 0, "type_scale": 0, "type_text": "string", } ] } return FunctionInfo.from_dict( { "catalog_name": components[0], "schema_name": components[1], "name": components[2], "input_params": param_dict, } ) # In addition to above now handle the case where a '*' is passed in and list all the functions def mock_function_list(self, catalog_name, schema_name): assert catalog_name == "rag" assert schema_name == "test" return [ FunctionInfo(full_name="rag.test.test_function"), FunctionInfo(full_name="rag.test.test_function_2"), FunctionInfo(full_name="rag.test.test_function_3"), ] monkeypatch.setenv("DATABRICKS_HOST", "my-default-host") monkeypatch.setenv("DATABRICKS_TOKEN", "my-default-token") monkeypatch.setattr("databricks.sdk.service.catalog.FunctionsAPI.get", mock_function_get) monkeypatch.setattr("databricks.sdk.service.catalog.FunctionsAPI.list", mock_function_list) include_uc_function_tools = False try: from langchain_community.tools.databricks import UCFunctionToolkit include_uc_function_tools = True except Exception: include_uc_function_tools = False uc_function_tools = ( (UCFunctionToolkit(warehouse_id="testId1").include("rag.test.*").get_tools()) if include_uc_function_tools else [] ) chat_model = ChatDatabricks(endpoint="databricks-llama-2-70b-chat", max_tokens=500) vectorstore = get_vector_search( endpoint_name="dbdemos_vs_endpoint", index_name="mlflow.rag.vs_index", has_embedding_endpoint=True, ) retriever = vectorstore.as_retriever() retriever_tool = create_retriever_tool(retriever, "vs_index_name", "vs_index_desc") agent = initialize_agent( uc_function_tools + [retriever_tool], chat_model, verbose=True, ) resources = list(_extract_dependency_list_from_lc_model(agent)) # Ensure all resources are added in expected = [ DatabricksVectorSearchIndex(index_name="mlflow.rag.vs_index"), DatabricksServingEndpoint(endpoint_name="embedding-model"), DatabricksServingEndpoint(endpoint_name="databricks-llama-2-70b-chat"), ] if include_uc_function_tools: expected = [ DatabricksServingEndpoint(endpoint_name="databricks-llama-2-70b-chat"), DatabricksFunction(function_name="rag.test.test_function"), DatabricksFunction(function_name="rag.test.test_function_2"), DatabricksFunction(function_name="rag.test.test_function_3"), DatabricksVectorSearchIndex(index_name="mlflow.rag.vs_index"), DatabricksServingEndpoint(endpoint_name="embedding-model"), DatabricksSQLWarehouse(warehouse_id="testId1"), ] def build_resource_map(resources): resource_map = defaultdict(list) for resource in resources: resource_type = resource.type.value resource_name = resource.to_dict()[resource_type][0]["name"] resource_map[resource_type].append(resource_name) return dict(resource_map) # Build maps for resources and expected resources resource_maps = build_resource_map(resources) expected_maps = build_resource_map(expected) assert len(resource_maps) == len(expected_maps) for resource_type in resource_maps: assert Counter(resource_maps[resource_type]) == Counter( expected_maps.get(resource_type, []) ) def test_parsing_dependency_from_databricks_chat(monkeypatch): from databricks_langchain import ChatDatabricks # in databricks-langchain > 0.7.0, ChatDatabricks instantiates # workspace client in __init__ which requires Databricks creds monkeypatch.setenv("DATABRICKS_HOST", "my-default-host") monkeypatch.setenv("DATABRICKS_TOKEN", "my-default-token") remove_langchain_community(monkeypatch) with pytest.raises(ImportError, match="No module named 'langchain_community"): from langchain_community.chat_models import ChatDatabricks chat_model = ChatDatabricks(endpoint="databricks-llama-2-70b-chat", max_tokens=500) resources = list(_extract_databricks_dependencies_from_chat_model(chat_model)) assert resources == [DatabricksServingEndpoint(endpoint_name="databricks-llama-2-70b-chat")] def test_parsing_dependency_from_databricks(monkeypatch): from databricks_langchain import ChatDatabricks # in databricks-langchain > 0.7.0, ChatDatabricks instantiates # workspace client in __init__ which requires Databricks creds monkeypatch.setenv("DATABRICKS_HOST", "my-default-host") monkeypatch.setenv("DATABRICKS_TOKEN", "my-default-token") remove_langchain_community(monkeypatch) with pytest.raises(ImportError, match="No module named 'langchain_community"): from langchain_community.chat_models import ChatDatabricks vectorstore = get_vector_search( endpoint_name="dbdemos_vs_endpoint", index_name="mlflow.rag.vs_index", has_embedding_endpoint=True, ) retriever = vectorstore.as_retriever() llm = ChatDatabricks(endpoint="databricks-llama-2-70b-chat", max_tokens=500) llm2 = ChatDatabricks(endpoint="databricks-llama-2-70b-chat", max_tokens=500) model = retriever | llm | llm2 resources = _detect_databricks_dependencies(model) assert resources == [ DatabricksVectorSearchIndex(index_name="mlflow.rag.vs_index"), DatabricksServingEndpoint(endpoint_name="embedding-model"), DatabricksServingEndpoint(endpoint_name="databricks-llama-2-70b-chat"), ] def test_parsing_unitycatalog_tool_as_dependency(monkeypatch: pytest.MonkeyPatch): from databricks.sdk.service.catalog import FunctionInfo from databricks_langchain import ChatDatabricks from langchain.agents import initialize_agent from unitycatalog.ai.core.databricks import DatabricksFunctionClient from unitycatalog.ai.langchain.toolkit import UCFunctionToolkit # When get is called return a function def mock_function_get(self, function_name): components = function_name.split(".") # Initialize agent used below requires functions to take in exactly one parameter param_dict = { "parameters": [ { "name": "param", "parameter_type": "PARAM", "position": 0, "type_json": '{"name":"param","type":"string","nullable":true,"metadata":{}}', "type_name": "STRING", "type_precision": 0, "type_scale": 0, "type_text": "string", } ] } # Add the catalog, schema and name to the function Info followed by the parameter return FunctionInfo.from_dict( { "catalog_name": components[0], "schema_name": components[1], "name": components[2], "input_params": param_dict, } ) monkeypatch.setenv("DATABRICKS_HOST", "my-default-host") monkeypatch.setenv("DATABRICKS_TOKEN", "my-default-token") monkeypatch.setattr("databricks.sdk.service.catalog.FunctionsAPI.get", mock_function_get) # TODO: remove this mock after unitycatalog-ai release a new version to avoid setting # spark session during initialization with mock.patch("unitycatalog.ai.core.databricks.DatabricksFunctionClient.set_spark_session"): client = DatabricksFunctionClient() toolkit = UCFunctionToolkit(function_names=["rag.test.test_function"], client=client) llm = ChatDatabricks(endpoint="databricks-llama-2-70b-chat", temperature=0) agent = initialize_agent( toolkit.tools, llm, verbose=True, ) resources = sorted(_extract_dependency_list_from_lc_model(agent), key=lambda x: x.name) assert resources == [ DatabricksServingEndpoint(endpoint_name="databricks-llama-2-70b-chat"), DatabricksFunction(function_name="rag.test.test_function"), ]
MockVectorSearchIndex
python
google__pytype
pytype/vm_utils.py
{ "start": 3848, "end": 4196 }
class ____(_NameErrorDetails): def __init__(self, attr, class_name): super().__init__() self._attr = attr self._class_name = class_name def to_error_message(self): return ( f"Cannot reference {self._attr!r} from class {self._class_name!r} " "before the class is fully defined" )
_NameInInnerClassErrorDetails
python
cython__cython
Cython/Debugger/libcython.py
{ "start": 49135, "end": 49947 }
class ____(gdb.Function, CythonBase, EvaluateOrExecuteCodeMixin): """ Evaluate Python code in the nearest Python or Cython frame and return """ @libpython.dont_suppress_errors @gdb_function_value_to_unicode def invoke(self, python_expression): input_type = libpython.PythonCodeExecutor.Py_eval_input return self.evalcode(python_expression, input_type) cython_info = CythonInfo() cy = CyCy.register() cython_info.cy = cy def register_defines(): libpython.source_gdb_script(textwrap.dedent("""\ define cy step cy -step end define cy next cy -next end document cy step %s end document cy next %s end """) % (CyStep.__doc__, CyNext.__doc__)) register_defines()
CyEval
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_function_base.py
{ "start": 71439, "end": 76054 }
class ____(TestCase): x1 = np.array([[0, 2], [1, 1], [2, 0]]).T res1 = np.array([[1.0, -1.0], [-1.0, 1.0]]) x2 = np.array([0.0, 1.0, 2.0], ndmin=2) frequencies = np.array([1, 4, 1]) x2_repeats = np.array([[0.0], [1.0], [1.0], [1.0], [1.0], [2.0]]).T res2 = np.array([[0.4, -0.4], [-0.4, 0.4]]) unit_frequencies = np.ones(3, dtype=np.int_) weights = np.array([1.0, 4.0, 1.0]) res3 = np.array([[2.0 / 3.0, -2.0 / 3.0], [-2.0 / 3.0, 2.0 / 3.0]]) unit_weights = np.ones(3) x3 = np.array([0.3942, 0.5969, 0.7730, 0.9918, 0.7964]) def test_basic(self): assert_allclose(cov(self.x1), self.res1) def test_complex(self): x = np.array([[1, 2, 3], [1j, 2j, 3j]]) res = np.array([[1.0, -1.0j], [1.0j, 1.0]]) assert_allclose(cov(x), res) assert_allclose(cov(x, aweights=np.ones(3)), res) def test_xy(self): x = np.array([[1, 2, 3]]) y = np.array([[1j, 2j, 3j]]) assert_allclose(cov(x, y), np.array([[1.0, -1.0j], [1.0j, 1.0]])) def test_empty(self): with warnings.catch_warnings(record=True): warnings.simplefilter("always", RuntimeWarning) assert_array_equal(cov(np.array([])), np.nan) assert_array_equal( cov(np.array([]).reshape(0, 2)), np.array([]).reshape(0, 0) ) assert_array_equal( cov(np.array([]).reshape(2, 0)), np.array([[np.nan, np.nan], [np.nan, np.nan]]), ) def test_wrong_ddof(self): with warnings.catch_warnings(record=True): warnings.simplefilter("always", RuntimeWarning) assert_array_equal( cov(self.x1, ddof=5), np.array([[np.inf, -np.inf], [-np.inf, np.inf]]) ) def test_1D_rowvar(self): assert_allclose(cov(self.x3), cov(self.x3, rowvar=False)) y = np.array([0.0780, 0.3107, 0.2111, 0.0334, 0.8501]) assert_allclose(cov(self.x3, y), cov(self.x3, y, rowvar=False)) def test_1D_variance(self): assert_allclose(cov(self.x3, ddof=1), np.var(self.x3, ddof=1)) def test_fweights(self): assert_allclose(cov(self.x2, fweights=self.frequencies), cov(self.x2_repeats)) assert_allclose(cov(self.x1, fweights=self.frequencies), self.res2) assert_allclose(cov(self.x1, fweights=self.unit_frequencies), self.res1) nonint = self.frequencies + 0.5 assert_raises((TypeError, RuntimeError), cov, self.x1, fweights=nonint) f = np.ones((2, 3), dtype=np.int_) assert_raises(RuntimeError, cov, self.x1, fweights=f) f = np.ones(2, dtype=np.int_) assert_raises(RuntimeError, cov, self.x1, fweights=f) f = -1 * np.ones(3, dtype=np.int_) assert_raises((ValueError, RuntimeError), cov, self.x1, fweights=f) def test_aweights(self): assert_allclose(cov(self.x1, aweights=self.weights), self.res3) assert_allclose( cov(self.x1, aweights=3.0 * self.weights), cov(self.x1, aweights=self.weights), ) assert_allclose(cov(self.x1, aweights=self.unit_weights), self.res1) w = np.ones((2, 3)) assert_raises(RuntimeError, cov, self.x1, aweights=w) w = np.ones(2) assert_raises(RuntimeError, cov, self.x1, aweights=w) w = -1.0 * np.ones(3) assert_raises((ValueError, RuntimeError), cov, self.x1, aweights=w) def test_unit_fweights_and_aweights(self): assert_allclose( cov(self.x2, fweights=self.frequencies, aweights=self.unit_weights), cov(self.x2_repeats), ) assert_allclose( cov(self.x1, fweights=self.frequencies, aweights=self.unit_weights), self.res2, ) assert_allclose( cov(self.x1, fweights=self.unit_frequencies, aweights=self.unit_weights), self.res1, ) assert_allclose( cov(self.x1, fweights=self.unit_frequencies, aweights=self.weights), self.res3, ) assert_allclose( cov(self.x1, fweights=self.unit_frequencies, aweights=3.0 * self.weights), cov(self.x1, aweights=self.weights), ) assert_allclose( cov(self.x1, fweights=self.unit_frequencies, aweights=self.unit_weights), self.res1, ) @parametrize("test_type", [np.half, np.single, np.double]) def test_cov_dtype(self, test_type): cast_x1 = self.x1.astype(test_type) res = cov(cast_x1, dtype=test_type) assert test_type == res.dtype
TestCov
python
pennersr__django-allauth
allauth/headless/mfa/inputs.py
{ "start": 857, "end": 1292 }
class ____(inputs.Input): id = inputs.ModelChoiceField(queryset=Authenticator.objects.none()) name = inputs.CharField(required=True, max_length=100) def __init__(self, *args, **kwargs): self.user = kwargs.pop("user") super().__init__(*args, **kwargs) self.fields["id"].queryset = Authenticator.objects.filter( user=self.user, type=Authenticator.Type.WEBAUTHN )
UpdateWebAuthnInput
python
fluentpython__example-code
attic/functions/accgen.py
{ "start": 162, "end": 483 }
class ____: def __init__(self, n): self.n = n def __call__(self, i): self.n += i return self.n def foo0(n): def bar(i): bar.s += i return bar.s bar.s = n return bar def foo(n): def bar(i): nonlocal n n += i return n return bar
foo0
python
facebook__pyre-check
tools/upgrade/commands/pysa_version_update.py
{ "start": 492, "end": 2509 }
class ____(Command): def __init__( self, *, repository: Repository, hash: str, no_commit: bool, ) -> None: super().__init__(repository) self._hash: str = hash self._no_commit: bool = no_commit @staticmethod def from_arguments( arguments: argparse.Namespace, repository: Repository ) -> "PysaVersionUpdate": return PysaVersionUpdate( repository=repository, hash=arguments.hash, no_commit=arguments.no_commit, ) @classmethod def add_arguments(cls, parser: argparse.ArgumentParser) -> None: super(PysaVersionUpdate, PysaVersionUpdate).add_arguments(parser) parser.set_defaults(command=cls.from_arguments) parser.add_argument("hash", help="Hash of new Pysa version") parser.add_argument( "--no-commit", action="store_true", help="Keep changes in working state." ) @override def run(self) -> None: global_configuration = Configuration.find_project_configuration() # Update to new pysa version in `.pyre_configuration` configuration = Configuration(global_configuration) old_version = configuration.pysa_version if not old_version: LOG.error( "Global configuration at %s has no pysa_version field.", global_configuration, ) return configuration.set_pysa_version(self._hash) configuration.write() # Update to new pysa version in `.pysa_configuration` path = Configuration.find_parent_file(".pysa_configuration") if path: # TODO(T224086333): move `.pysa_configuration`'s `pysa_version` to less nested `version` field contents = json.loads(path.read_text(encoding="utf-8")) contents["pyre_configuration"]["pysa_version"] = self._hash path.write_text(json.dumps(contents, indent=2), encoding="utf-8")
PysaVersionUpdate
python
great-expectations__great_expectations
tests/core/factory/test_validation_definition_factory.py
{ "start": 14868, "end": 22083 }
class ____: def _build_batch_definition(self, context: AbstractDataContext): name = random_name() ds = context.data_sources.add_pandas(name=name) asset = ds.add_csv_asset(name=name, filepath_or_buffer=pathlib.Path("data.csv")) return asset.add_batch_definition(name=name) def _build_suite(self) -> ExpectationSuite: return ExpectationSuite( name=random_name(), expectations=[ gxe.ExpectColumnValuesToBeBetween( column="passenger_count", min_value=0, max_value=10 ) ], ) def test_add_new_validation( self, unset_gx_env_variables: None, data_context: AbstractDataContext, ) -> None: # arrange vd_name = random_name() batch_def = self._build_batch_definition(data_context) suite = self._build_suite() vd = ValidationDefinition( name=vd_name, data=batch_def, suite=data_context.suites.add(suite), ) # act created_vd = data_context.validation_definitions.add_or_update(validation=vd) # assert assert created_vd.id data_context.validation_definitions.get(vd_name) def test_add_new_validation_with_new_suite( self, unset_gx_env_variables: None, data_context: AbstractDataContext, ) -> None: # arrange vd_name = random_name() batch_def = self._build_batch_definition(data_context) suite = self._build_suite() vd = ValidationDefinition( name=vd_name, data=batch_def, suite=suite, ) # act created_vd = data_context.validation_definitions.add_or_update(validation=vd) # assert assert created_vd.id data_context.validation_definitions.get(vd_name) def test_update_expectation_suite( self, unset_gx_env_variables: None, data_context: AbstractDataContext, ) -> None: # arrange vd_name = random_name() batch_def = self._build_batch_definition(data_context) suite = self._build_suite() vd = ValidationDefinition( name=vd_name, data=batch_def, suite=data_context.suites.add(suite), ) existing_vd = data_context.validation_definitions.add(validation=vd) # act vd.suite.expectations = [ gxe.ExpectColumnMaxToBeBetween(column="passenger_count", min_value=0, max_value=5) ] updated_vd = data_context.validation_definitions.add_or_update(validation=vd) # assert assert updated_vd.id == existing_vd.id assert len(updated_vd.suite.expectations) == 1 and isinstance( updated_vd.suite.expectations[0], gxe.ExpectColumnMaxToBeBetween ) data_context.validation_definitions.get(vd_name) def test_replace_expectation_suite( self, unset_gx_env_variables: None, data_context: AbstractDataContext, ) -> None: # arrange vd_name = random_name() batch_def = self._build_batch_definition(data_context) suite = data_context.suites.add(self._build_suite()) vd = ValidationDefinition( name=vd_name, data=batch_def, suite=suite, ) existing_vd = data_context.validation_definitions.add(validation=vd) # act new_suite = data_context.suites.add(self._build_suite()) new_vd = ValidationDefinition( name=vd_name, data=batch_def, suite=new_suite, ) updated_vd = data_context.validation_definitions.add_or_update(validation=new_vd) # assert assert updated_vd.suite.id != existing_vd.suite.id # New suite should have a different ID assert updated_vd.data.id == existing_vd.data.id assert updated_vd.id == existing_vd.id data_context.validation_definitions.get(vd_name) @pytest.mark.xfail( raises=ValidationError, reason="GX-481: Changing a BatchDefinition breaks loading a Validation Definition.", strict=True, ) def test_update_batch_definition( self, unset_gx_env_variables: None, data_context: AbstractDataContext, ) -> None: # arrange vd_name = random_name() batch_def = self._build_batch_definition(data_context) suite = data_context.suites.add(self._build_suite()) vd = ValidationDefinition( name=vd_name, data=batch_def, suite=suite, ) data_context.validation_definitions.add(validation=vd) # act new_batch_def_name = random_name() batch_def.name = new_batch_def_name new_vd = ValidationDefinition( name=vd_name, data=batch_def, suite=suite, ) updated_vd = data_context.validation_definitions.add_or_update(validation=new_vd) # assert assert updated_vd.data.name == new_batch_def_name data_context.validation_definitions.get(vd_name) def test_replace_batch_definition( self, unset_gx_env_variables: None, data_context: AbstractDataContext, ) -> None: # arrange vd_name = random_name() batch_def = self._build_batch_definition(data_context) suite = data_context.suites.add(self._build_suite()) vd = ValidationDefinition( name=vd_name, data=batch_def, suite=suite, ) existing_vd = data_context.validation_definitions.add(validation=vd) # act new_batch_def = self._build_batch_definition(data_context) new_vd = ValidationDefinition( name=vd_name, data=new_batch_def, suite=suite, ) updated_vd = data_context.validation_definitions.add_or_update(validation=new_vd) # assert assert updated_vd.suite.id == existing_vd.suite.id assert ( updated_vd.data.id != existing_vd.data.id ) # New batch definition should have a different ID assert updated_vd.data.id # should not be None assert updated_vd.data.id == new_batch_def.id assert updated_vd.id == existing_vd.id data_context.validation_definitions.get(vd_name) def test_add_or_update_is_idempotent( self, unset_gx_env_variables: None, data_context: AbstractDataContext, ) -> None: # arrange vd_name = random_name() batch_def = self._build_batch_definition(data_context) suite = self._build_suite() vd = ValidationDefinition( name=vd_name, data=batch_def, suite=suite, ) # act vd_1 = data_context.validation_definitions.add_or_update(validation=vd) vd_2 = data_context.validation_definitions.add_or_update(validation=vd) vd_3 = data_context.validation_definitions.add_or_update(validation=vd) # assert assert vd_1 == vd_2 == vd_3
TestValidationDefinitionFactoryAddOrUpdate
python
django__django
tests/gis_tests/inspectapp/tests.py
{ "start": 2424, "end": 9637 }
class ____(SimpleTestCase): maxDiff = 1024 def test_poly(self): shp_file = os.path.join(TEST_DATA, "test_poly", "test_poly.shp") model_def = ogrinspect(shp_file, "MyModel") expected = [ "# This is an auto-generated Django model module created by ogrinspect.", "from django.contrib.gis.db import models", "", "", "class MyModel(models.Model):", " float = models.FloatField()", " int = models.BigIntegerField()", " str = models.CharField(max_length=80)", " geom = models.PolygonField()", ] self.assertEqual(model_def, "\n".join(expected)) def test_poly_multi(self): shp_file = os.path.join(TEST_DATA, "test_poly", "test_poly.shp") model_def = ogrinspect(shp_file, "MyModel", multi_geom=True) self.assertIn("geom = models.MultiPolygonField()", model_def) # Same test with a 25D-type geometry field shp_file = os.path.join(TEST_DATA, "gas_lines", "gas_leitung.shp") model_def = ogrinspect(shp_file, "MyModel", multi_geom=True) self.assertIn("geom = models.MultiLineStringField(srid=31253)", model_def) def test_date_field(self): shp_file = os.path.join(TEST_DATA, "cities", "cities.shp") model_def = ogrinspect(shp_file, "City") expected = [ "# This is an auto-generated Django model module created by ogrinspect.", "from django.contrib.gis.db import models", "", "", "class City(models.Model):", " name = models.CharField(max_length=80)", " population = models.BigIntegerField()", " density = models.FloatField()", " created = models.DateField()", " geom = models.PointField()", ] self.assertEqual(model_def, "\n".join(expected)) def test_time_field(self): # Getting the database identifier used by OGR, if None returned # GDAL does not have the support compiled in. ogr_db = get_ogr_db_string() if not ogr_db: self.skipTest("Unable to setup an OGR connection to your database") try: # Writing shapefiles via GDAL currently does not support writing # OGRTime fields, so we need to actually use a database model_def = ogrinspect( ogr_db, "Measurement", layer_key=AllOGRFields._meta.db_table, decimal=["f_decimal"], ) except GDALException: self.skipTest("Unable to setup an OGR connection to your database") self.assertTrue( model_def.startswith( "# This is an auto-generated Django model module created by " "ogrinspect.\n" "from django.contrib.gis.db import models\n" "\n" "\n" "class Measurement(models.Model):\n" ) ) # The ordering of model fields might vary depending on several factors # (version of GDAL, etc.). if connection.vendor == "sqlite" and GDAL_VERSION < (3, 4): # SpatiaLite introspection is somewhat lacking on GDAL < 3.4 # (#29461). self.assertIn(" f_decimal = models.CharField(max_length=0)", model_def) else: self.assertIn( " f_decimal = models.DecimalField(max_digits=0, decimal_places=0)", model_def, ) self.assertIn(" f_int = models.IntegerField()", model_def) if not connection.ops.mariadb: # Probably a bug between GDAL and MariaDB on time fields. self.assertIn(" f_datetime = models.DateTimeField()", model_def) self.assertIn(" f_time = models.TimeField()", model_def) if connection.vendor == "sqlite" and GDAL_VERSION < (3, 4): self.assertIn(" f_float = models.CharField(max_length=0)", model_def) else: self.assertIn(" f_float = models.FloatField()", model_def) max_length = 0 if connection.vendor == "sqlite" else 10 self.assertIn( " f_char = models.CharField(max_length=%s)" % max_length, model_def ) self.assertIn(" f_date = models.DateField()", model_def) # Some backends may have srid=-1 self.assertIsNotNone( re.search(r" geom = models.PolygonField\(([^\)])*\)", model_def) ) def test_management_command(self): shp_file = os.path.join(TEST_DATA, "cities", "cities.shp") out = StringIO() call_command("ogrinspect", shp_file, "City", stdout=out) output = out.getvalue() self.assertIn("class City(models.Model):", output) def test_mapping_option(self): expected = ( " geom = models.PointField()\n" "\n" "\n" "# Auto-generated `LayerMapping` dictionary for City model\n" "city_mapping = {\n" " 'name': 'Name',\n" " 'population': 'Population',\n" " 'density': 'Density',\n" " 'created': 'Created',\n" " 'geom': 'POINT',\n" "}\n" ) shp_file = os.path.join(TEST_DATA, "cities", "cities.shp") out = StringIO() call_command("ogrinspect", shp_file, "--mapping", "City", stdout=out) self.assertIn(expected, out.getvalue()) def get_ogr_db_string(): """ Construct the DB string that GDAL will use to inspect the database. GDAL will create its own connection to the database, so we re-use the connection settings from the Django test. """ db = connections.settings["default"] # Map from the django backend into the OGR driver name and database # identifier https://gdal.org/drivers/vector/ # # TODO: Support Oracle (OCI). drivers = { "django.contrib.gis.db.backends.postgis": ( "PostgreSQL", "PG:dbname='%(db_name)s'", " ", ), "django.contrib.gis.db.backends.mysql": ("MySQL", 'MYSQL:"%(db_name)s"', ","), "django.contrib.gis.db.backends.spatialite": ("SQLite", "%(db_name)s", ""), } db_engine = db["ENGINE"] if db_engine not in drivers: return None drv_name, db_str, param_sep = drivers[db_engine] # Ensure that GDAL library has driver support for the database. try: Driver(drv_name) except GDALException: return None # SQLite/SpatiaLite in-memory databases if DatabaseCreation.is_in_memory_db(db["NAME"]): return None # Build the params of the OGR database connection string params = [db_str % {"db_name": db["NAME"]}] def add(key, template): value = db.get(key, None) # Don't add the parameter if it is not in django's settings if value: params.append(template % value) add("HOST", "host='%s'") add("PORT", "port='%s'") add("USER", "user='%s'") add("PASSWORD", "password='%s'") return param_sep.join(params)
OGRInspectTest
python
scikit-learn__scikit-learn
sklearn/externals/array_api_compat/common/_typing.py
{ "start": 1109, "end": 1341 }
class ____(Protocol): @property def __class__(self, /) -> type[float]: ... @__class__.setter def __class__(self, value: type[float], /) -> None: ... # pyright: ignore[reportIncompatibleMethodOverride] @final
JustFloat
python
google__jax
examples/ffi/tests/cpu_examples_test.py
{ "start": 2166, "end": 2994 }
class ____(jtu.JaxTestCase): def setUp(self): super().setUp() if not jtu.test_device_matches(["cpu"]): self.skipTest("Unsupported platform") def test_basic(self): self.assertEqual(cpu_examples.counter(0), 0) self.assertEqual(cpu_examples.counter(0), 1) self.assertEqual(cpu_examples.counter(0), 2) self.assertEqual(cpu_examples.counter(1), 0) self.assertEqual(cpu_examples.counter(0), 3) def test_jit(self): @jax.jit def counter_fun(x): return x, cpu_examples.counter(2) self.assertEqual(counter_fun(0)[1], 0) self.assertEqual(counter_fun(0)[1], 1) # Persists across different cache hits self.assertEqual(counter_fun(1)[1], 2) # Persists after the cache is cleared counter_fun.clear_cache() self.assertEqual(counter_fun(0)[1], 3)
CounterTests
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-rabbitmq/destination_rabbitmq/destination.py
{ "start": 1116, "end": 3618 }
class ____(Destination): def write( self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage] ) -> Iterable[AirbyteMessage]: exchange = config.get("exchange") routing_key = config["routing_key"] connection = create_connection(config=config) channel = connection.channel() streams = {s.stream.name for s in configured_catalog.streams} try: for message in input_messages: if message.type == Type.STATE: # Emitting a state message means all records that came before it # have already been published. yield message elif message.type == Type.RECORD: record = message.record if record.stream not in streams: # Message contains record from a stream that is not in the catalog. Skip it! continue headers = {"stream": record.stream, "emitted_at": record.emitted_at, "namespace": record.namespace} properties = BasicProperties(content_type="application/json", headers=headers) channel.basic_publish( exchange=exchange or "", routing_key=routing_key, properties=properties, body=json.dumps(record.data) ) else: # Let's ignore other message types for now continue finally: connection.close() def check(self, logger: logging.Logger, config: Mapping[str, Any]) -> AirbyteConnectionStatus: try: connection = create_connection(config=config) except Exception as e: logger.error(f"Failed to create connection. Error: {e}") return AirbyteConnectionStatus(status=Status.FAILED, message=f"Could not create connection: {repr(e)}") try: channel = connection.channel() if channel.is_open: return AirbyteConnectionStatus(status=Status.SUCCEEDED) return AirbyteConnectionStatus(status=Status.FAILED, message="Could not open channel") except Exception as e: logger.error(f"Failed to open RabbitMQ channel. Error: {e}") return AirbyteConnectionStatus(status=Status.FAILED, message=f"An exception occurred: {repr(e)}") finally: connection.close()
DestinationRabbitmq
python
django__django
django/contrib/staticfiles/storage.py
{ "start": 496, "end": 1530 }
class ____(FileSystemStorage): """ Standard file system storage for static files. The defaults for ``location`` and ``base_url`` are ``STATIC_ROOT`` and ``STATIC_URL``. """ def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = settings.STATIC_ROOT if base_url is None: base_url = settings.STATIC_URL check_settings(base_url) super().__init__(location, base_url, *args, **kwargs) # FileSystemStorage fallbacks to MEDIA_ROOT when location # is empty, so we restore the empty value. if not location: self.base_location = None self.location = None def path(self, name): if not self.location: raise ImproperlyConfigured( "You're using the staticfiles app " "without having set the STATIC_ROOT " "setting to a filesystem path." ) return super().path(name)
StaticFilesStorage
python
optuna__optuna
optuna/cli.py
{ "start": 5835, "end": 9619 }
class ____: def __init__(self, value: Any) -> None: self.value = value if value is None: self.value_type = ValueType.NONE elif isinstance(value, (int, float)): self.value_type = ValueType.NUMERIC else: self.value_type = ValueType.STRING def __str__(self) -> str: if isinstance(self.value, datetime.datetime): return self.value.strftime(_DATETIME_FORMAT) else: return str(self.value) def width(self) -> int: return len(str(self.value)) def get_string(self, value_type: ValueType, width: int) -> str: value = str(self.value) if self.value is None: return " " * width elif value_type == ValueType.NUMERIC: return f"{value:>{width}}" else: return f"{value:<{width}}" def _dump_value(records: list[dict[str, Any]], header: list[str]) -> str: values = [] for record in records: row = [] for column_name in header: # Below follows the table formatting convention where record[column_name] is treated as # an empty string if record[column_name] is None. e.g., {"a": None} is replaced with # {"a": ""} row.append(str(record[column_name]) if record.get(column_name) is not None else "") values.append(" ".join(row)) return "\n".join(values) def _dump_table(records: list[dict[str, Any]], header: list[str]) -> str: rows = [] for record in records: row = [] for column_name in header: row.append(CellValue(record.get(column_name))) rows.append(row) separator = "+" header_string = "|" rows_string = ["|" for _ in rows] for column in range(len(header)): value_types = [row[column].value_type for row in rows] value_type = ValueType.NUMERIC for t in value_types: if t == ValueType.STRING: value_type = ValueType.STRING if len(rows) == 0: max_width = len(header[column]) else: max_width = max(len(header[column]), max(row[column].width() for row in rows)) separator += "-" * (max_width + 2) + "+" if value_type == ValueType.NUMERIC: header_string += f" {header[column]:>{max_width}} |" else: header_string += f" {header[column]:<{max_width}} |" for i, row in enumerate(rows): rows_string[i] += " " + row[column].get_string(value_type, max_width) + " |" ret = "" ret += separator + "\n" ret += header_string + "\n" ret += separator + "\n" for row_string in rows_string: ret += row_string + "\n" ret += separator + "\n" return ret def _format_output( records: list[dict[tuple[str, str], Any]] | dict[tuple[str, str], Any], columns: list[tuple[str, str]], output_format: str, flatten: bool, ) -> str: if isinstance(records, list): values, header = _convert_to_dict(records, columns, flatten) else: values, header = _convert_to_dict([records], columns, flatten) if output_format == "value": return _dump_value(values, header).strip() elif output_format == "table": return _dump_table(values, header).strip() elif output_format == "json": if isinstance(records, list): return json.dumps(values).strip() else: return json.dumps(values[0]).strip() elif output_format == "yaml": if isinstance(records, list): return yaml.safe_dump(values).strip() else: return yaml.safe_dump(values[0]).strip() else: raise CLIUsageError(f"Optuna CLI does not supported the {output_format} format.")
CellValue
python
etianen__django-reversion
tests/test_app/tests/test_api.py
{ "start": 5973, "end": 7268 }
class ____(TestBase): def testCreateRevisionFollow(self): reversion.register(TestModel, follow=("related",)) reversion.register(TestModelRelated) obj_related = TestModelRelated.objects.create() with reversion.create_revision(): obj = TestModel.objects.create() obj.related.add(obj_related) self.assertSingleRevision((obj, obj_related)) def testCreateRevisionFollowThrough(self): reversion.register(TestModel, follow=("related_through",)) reversion.register(TestModelThrough, follow=("test_model", "test_model_related",)) reversion.register(TestModelRelated) obj_related = TestModelRelated.objects.create() with reversion.create_revision(): obj = TestModel.objects.create() obj_through = TestModelThrough.objects.create( test_model=obj, test_model_related=obj_related, ) self.assertSingleRevision((obj, obj_through, obj_related)) def testCreateRevisionFollowInvalid(self): reversion.register(TestModel, follow=("name",)) with reversion.create_revision(): with self.assertRaises(reversion.RegistrationError): TestModel.objects.create()
CreateRevisionFollowTest
python
getsentry__sentry
src/sentry/shared_integrations/exceptions/__init__.py
{ "start": 5354, "end": 5664 }
class ____(IntegrationError): def __init__(self, field_errors: Mapping[str, Any] | None = None) -> None: error = "Invalid integration action" if field_errors: error = str(field_errors) super().__init__(error) self.field_errors = field_errors
IntegrationFormError
python
dagster-io__dagster
helm/dagster/schema/schema/charts/utils/kubernetes.py
{ "start": 756, "end": 865 }
class ____(str, Enum): ALWAYS = "Always" IF_NOT_PRESENT = "IfNotPresent" NEVER = "Never"
PullPolicy
python
huggingface__transformers
src/transformers/models/pop2piano/modeling_pop2piano.py
{ "start": 19961, "end": 23858 }
class ____(GradientCheckpointingLayer): def __init__(self, config, has_relative_attention_bias=False, layer_idx: Optional[int] = None): super().__init__() self.is_decoder = config.is_decoder self.layer = nn.ModuleList() self.layer.append( Pop2PianoLayerSelfAttention( config, has_relative_attention_bias=has_relative_attention_bias, layer_idx=layer_idx ) ) if self.is_decoder: self.layer.append(Pop2PianoLayerCrossAttention(config, layer_idx=layer_idx)) self.layer.append(Pop2PianoLayerFF(config)) def forward( self, hidden_states, attention_mask=None, position_bias=None, encoder_hidden_states=None, encoder_attention_mask=None, encoder_decoder_position_bias=None, past_key_values=None, use_cache=False, output_attentions=False, return_dict=True, cache_position=None, ): self_attention_outputs = self.layer[0]( hidden_states, attention_mask=attention_mask, position_bias=position_bias, past_key_values=past_key_values, use_cache=use_cache, output_attentions=output_attentions, cache_position=cache_position, ) hidden_states = self_attention_outputs[0] attention_outputs = self_attention_outputs[1:] # Keep self-attention outputs and relative position weights # clamp inf values to enable fp16 training if hidden_states.dtype == torch.float16: clamp_value = torch.where( torch.isinf(hidden_states).any(), torch.finfo(hidden_states.dtype).max - 1000, torch.finfo(hidden_states.dtype).max, ) hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value) do_cross_attention = self.is_decoder and encoder_hidden_states is not None if do_cross_attention: cross_attention_outputs = self.layer[1]( hidden_states, key_value_states=encoder_hidden_states, attention_mask=encoder_attention_mask, position_bias=encoder_decoder_position_bias, past_key_values=past_key_values, query_length=cache_position[-1] + 1, use_cache=use_cache, output_attentions=output_attentions, ) hidden_states = cross_attention_outputs[0] # clamp inf values to enable fp16 training if hidden_states.dtype == torch.float16: clamp_value = torch.where( torch.isinf(hidden_states).any(), torch.finfo(hidden_states.dtype).max - 1000, torch.finfo(hidden_states.dtype).max, ) hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value) # Keep cross-attention outputs and relative position weights attention_outputs = attention_outputs + cross_attention_outputs[1:] # Apply Feed Forward layer hidden_states = self.layer[-1](hidden_states) # clamp inf values to enable fp16 training if hidden_states.dtype == torch.float16: clamp_value = torch.where( torch.isinf(hidden_states).any(), torch.finfo(hidden_states.dtype).max - 1000, torch.finfo(hidden_states.dtype).max, ) hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value) outputs = (hidden_states,) return ( outputs + attention_outputs ) # hidden-states, (self-attention position bias), (self-attention weights), (cross-attention position bias), (cross-attention weights) @auto_docstring
Pop2PianoBlock
python
django__django
tests/admin_utils/models.py
{ "start": 1615, "end": 1800 }
class ____(models.Model): event = models.OneToOneField(Event, models.CASCADE) name = models.CharField(max_length=255) class Meta: verbose_name = "awesome guest"
Guest
python
pytorch__pytorch
torch/utils/data/datapipes/iter/utils.py
{ "start": 237, "end": 2109 }
class ____(IterDataPipe[_T]): r""" Wraps an iterable object to create an IterDataPipe. Args: iterable: Iterable object to be wrapped into an IterDataPipe deepcopy: Option to deepcopy input iterable object for each iterator. The copy is made when the first element is read in ``iter()``. .. note:: If ``deepcopy`` is explicitly set to ``False``, users should ensure that the data pipeline doesn't contain any in-place operations over the iterable instance to prevent data inconsistency across iterations. Example: >>> # xdoctest: +SKIP >>> from torchdata.datapipes.iter import IterableWrapper >>> dp = IterableWrapper(range(10)) >>> list(dp) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] """ def __init__(self, iterable: Iterable[_T], deepcopy: bool = True) -> None: self.iterable = iterable self.deepcopy = deepcopy def __iter__(self) -> Iterator[_T]: source_data = self.iterable if self.deepcopy: try: source_data = copy.deepcopy(self.iterable) # For the case that data cannot be deep-copied, # all in-place operations will affect iterable variable. # When this DataPipe is iterated second time, it will # yield modified items. except TypeError: warnings.warn( "The input iterable can not be deepcopied, " "please be aware of in-place modification would affect source data.", stacklevel=2, ) yield from source_data def __len__(self) -> int: if isinstance(self.iterable, Sized): return len(self.iterable) raise TypeError(f"{type(self).__name__} instance doesn't have valid length")
IterableWrapperIterDataPipe