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
google__pytype
pytype_extensions/test_pytype_extensions.py
{ "start": 5173, "end": 5654 }
class ____(test_base.BaseTest): _PYI_DEP = None @classmethod def setUpClass(cls): super().setUpClass() deps = [('foo.pyi', cls._PYI_DEP)] cls.Check = _WrapWithDeps(cls.Check, deps) cls.CheckWithErrors = _WrapWithDeps(cls.CheckWithErrors, deps) cls.Infer = _WrapWithDeps(cls.Infer, deps) cls.InferWithErrors = _WrapWithDeps(cls.InferWithErrors, deps) _ATTRS_PYI = """ import attrs @attrs.define class Foo: x: int y: int """
PyiCodeTest
python
kamyu104__LeetCode-Solutions
Python/search-suggestions-system.py
{ "start": 711, "end": 1508 }
class ____(object): def suggestedProducts(self, products, searchWord): """ :type products: List[str] :type searchWord: str :rtype: List[List[str]] """ trie = TrieNode() for i in xrange(len(products)): trie.insert(products, i) result = [[] for _ in xrange(len(searchWord))] for i, c in enumerate(searchWord): if c not in trie.leaves: break trie = trie.leaves[c] result[i] = map(lambda x: products[x], trie.infos) return result # Time: ctor: O(n * l * log(n * l)), n is the number of products # , l is the average length of product name # suggest: O(l^2) # Space: O(t), t is the number of nodes in trie
Solution
python
jschneier__django-storages
storages/backends/s3.py
{ "start": 10881, "end": 26761 }
class ____(CompressStorageMixin, BaseStorage): """ Amazon Simple Storage Service using Boto3 This storage backend supports opening files in read or write mode and supports streaming(buffering) data in chunks to S3 when writing. """ default_content_type = "application/octet-stream" # If config provided in subclass, signature_version and addressing_style # settings/args are ignored. config = None _signers = {} # noqa: RUF012 def __init__(self, **settings): omitted = object() if not hasattr(self, "cloudfront_signer"): self.cloudfront_signer = settings.pop("cloudfront_signer", omitted) super().__init__(**settings) check_location(self) if (self.access_key or self.secret_key) and self.session_profile: raise ImproperlyConfigured( "AWS_S3_SESSION_PROFILE/session_profile should not be provided with " "AWS_S3_ACCESS_KEY_ID/access_key and " "AWS_S3_SECRET_ACCESS_KEY/secret_key" ) self._bucket = None self._connections = threading.local() self._unsigned_connections = threading.local() if self.config is not None: warnings.warn( "The 'config' class property is deprecated and will be " "removed in a future version. Use AWS_S3_CLIENT_CONFIG " "to customize any of the botocore.config.Config parameters.", DeprecationWarning, ) self.client_config = self.config if self.client_config is None: self.client_config = Config( s3={"addressing_style": self.addressing_style}, signature_version=self.signature_version, proxies=self.proxies, ) if self.use_threads is False: warnings.warn( "The AWS_S3_USE_THREADS setting is deprecated. Use " "AWS_S3_TRANSFER_CONFIG to customize any of the " "boto.s3.transfer.TransferConfig parameters.", DeprecationWarning, ) if self.transfer_config is None: self.transfer_config = TransferConfig(use_threads=self.use_threads) if self.cloudfront_signer is omitted: if self.cloudfront_key_id and self.cloudfront_key: self.cloudfront_signer = self.get_cloudfront_signer( self.cloudfront_key_id, self.cloudfront_key ) elif bool(self.cloudfront_key_id) ^ bool(self.cloudfront_key): raise ImproperlyConfigured( "Both AWS_CLOUDFRONT_KEY_ID/cloudfront_key_id and " "AWS_CLOUDFRONT_KEY/cloudfront_key must be provided together." ) else: self.cloudfront_signer = None def get_cloudfront_signer(self, key_id, key): cache_key = f"{key_id}:{key}" if cache_key not in self.__class__._signers: self.__class__._signers[cache_key] = _cloud_front_signer_from_pem( key_id, key ) return self.__class__._signers[cache_key] def get_default_settings(self): return { "access_key": setting( "AWS_S3_ACCESS_KEY_ID", setting( "AWS_ACCESS_KEY_ID", lookup_env(["AWS_S3_ACCESS_KEY_ID", "AWS_ACCESS_KEY_ID"]), ), ), "secret_key": setting( "AWS_S3_SECRET_ACCESS_KEY", setting( "AWS_SECRET_ACCESS_KEY", lookup_env(["AWS_S3_SECRET_ACCESS_KEY", "AWS_SECRET_ACCESS_KEY"]), ), ), "security_token": setting( "AWS_SESSION_TOKEN", setting( "AWS_SECURITY_TOKEN", lookup_env(["AWS_SESSION_TOKEN", "AWS_SECURITY_TOKEN"]), ), ), "session_profile": setting( "AWS_S3_SESSION_PROFILE", lookup_env(["AWS_S3_SESSION_PROFILE"]) ), "file_overwrite": setting("AWS_S3_FILE_OVERWRITE", True), "object_parameters": setting("AWS_S3_OBJECT_PARAMETERS", {}), "bucket_name": setting("AWS_STORAGE_BUCKET_NAME"), "querystring_auth": setting("AWS_QUERYSTRING_AUTH", True), "querystring_expire": setting("AWS_QUERYSTRING_EXPIRE", 3600), "signature_version": setting("AWS_S3_SIGNATURE_VERSION"), "location": setting("AWS_LOCATION", ""), "custom_domain": setting("AWS_S3_CUSTOM_DOMAIN"), "cloudfront_key_id": setting("AWS_CLOUDFRONT_KEY_ID"), "cloudfront_key": setting("AWS_CLOUDFRONT_KEY"), "addressing_style": setting("AWS_S3_ADDRESSING_STYLE"), "file_name_charset": setting("AWS_S3_FILE_NAME_CHARSET", "utf-8"), "gzip": setting("AWS_IS_GZIPPED", False), "gzip_content_types": setting( "GZIP_CONTENT_TYPES", ( "text/css", "text/javascript", "application/javascript", "application/x-javascript", "image/svg+xml", ), ), "url_protocol": setting("AWS_S3_URL_PROTOCOL") or "https:", "endpoint_url": setting("AWS_S3_ENDPOINT_URL"), "proxies": setting("AWS_S3_PROXIES"), "region_name": setting("AWS_S3_REGION_NAME"), "use_ssl": setting("AWS_S3_USE_SSL", True), "verify": setting("AWS_S3_VERIFY", None), "max_memory_size": setting("AWS_S3_MAX_MEMORY_SIZE", 0), "default_acl": setting("AWS_DEFAULT_ACL", None), "use_threads": setting("AWS_S3_USE_THREADS", True), "transfer_config": setting("AWS_S3_TRANSFER_CONFIG", None), "client_config": setting("AWS_S3_CLIENT_CONFIG", None), } def __getstate__(self): state = self.__dict__.copy() state.pop("_connections", None) state.pop("_unsigned_connections", None) state.pop("_bucket", None) return state def __setstate__(self, state): state["_connections"] = threading.local() state["_unsigned_connections"] = threading.local() state["_bucket"] = None self.__dict__ = state @property def connection(self): connection = getattr(self._connections, "connection", None) if connection is None: session = self._create_session() self._connections.connection = session.resource( "s3", region_name=self.region_name, use_ssl=self.use_ssl, endpoint_url=self.endpoint_url, config=self.client_config, verify=self.verify, ) return self._connections.connection @property def unsigned_connection(self): unsigned_connection = getattr(self._unsigned_connections, "connection", None) if unsigned_connection is None: session = self._create_session() config = self.client_config.merge( Config(signature_version=botocore.UNSIGNED) ) self._unsigned_connections.connection = session.resource( "s3", region_name=self.region_name, use_ssl=self.use_ssl, endpoint_url=self.endpoint_url, config=config, verify=self.verify, ) return self._unsigned_connections.connection def _create_session(self): """ If a user specifies a profile name and this class obtains access keys from another source such as environment variables,we want the profile name to take precedence. """ if self.session_profile: session = boto3.Session(profile_name=self.session_profile) else: session = boto3.Session( aws_access_key_id=self.access_key, aws_secret_access_key=self.secret_key, aws_session_token=self.security_token, ) return session @property def bucket(self): """ Get the current bucket. If there is no current bucket object create it. """ if self._bucket is None: self._bucket = self.connection.Bucket(self.bucket_name) return self._bucket def _normalize_name(self, name): """ Normalizes the name so that paths like /path/to/ignored/../something.txt work. We check to make sure that the path pointed to is not outside the directory specified by the LOCATION setting. """ try: return safe_join(self.location, name) except ValueError: raise SuspiciousOperation("Attempted access to '%s' denied." % name) def _open(self, name, mode="rb"): name = self._normalize_name(clean_name(name)) try: f = S3File(name, mode, self) except ClientError as err: if err.response["ResponseMetadata"]["HTTPStatusCode"] == 404: raise FileNotFoundError("File does not exist: %s" % name) raise # Let it bubble up if it was some other error return f def _save(self, name, content): cleaned_name = clean_name(name) name = self._normalize_name(cleaned_name) params = self._get_write_parameters(name, content) if is_seekable(content): content.seek(0, os.SEEK_SET) # wrap content so read() always returns bytes. This is required for passing it # to obj.upload_fileobj() or self._compress_content() content = ReadBytesWrapper(content) if ( self.gzip and params["ContentType"] in self.gzip_content_types and "ContentEncoding" not in params ): content = self._compress_content(content) params["ContentEncoding"] = "gzip" obj = self.bucket.Object(name) # Workaround file being closed errantly see: https://github.com/boto/s3transfer/issues/80 original_close = content.close content.close = lambda: None try: obj.upload_fileobj(content, ExtraArgs=params, Config=self.transfer_config) finally: content.close = original_close return cleaned_name def delete(self, name): try: name = self._normalize_name(clean_name(name)) self.bucket.Object(name).delete() except ClientError as err: if err.response["ResponseMetadata"]["HTTPStatusCode"] == 404: # Not an error to delete something that does not exist return # Some other error was encountered. Re-raise it raise def exists(self, name): name = self._normalize_name(clean_name(name)) params = _filter_download_params(self.get_object_parameters(name)) try: self.connection.meta.client.head_object( Bucket=self.bucket_name, Key=name, **params ) return True except ClientError as err: if err.response["ResponseMetadata"]["HTTPStatusCode"] == 404: return False # Some other error was encountered. Re-raise it. raise def listdir(self, name): path = self._normalize_name(clean_name(name)) # The path needs to end with a slash, but if the root is empty, leave it. if path and not path.endswith("/"): path += "/" directories = [] files = [] paginator = self.connection.meta.client.get_paginator("list_objects") pages = paginator.paginate(Bucket=self.bucket_name, Delimiter="/", Prefix=path) for page in pages: directories += [ posixpath.relpath(entry["Prefix"], path) for entry in page.get("CommonPrefixes", ()) ] for entry in page.get("Contents", ()): key = entry["Key"] if key != path: files.append(posixpath.relpath(key, path)) return directories, files def size(self, name): name = self._normalize_name(clean_name(name)) try: return self.bucket.Object(name).content_length except ClientError as err: if err.response["ResponseMetadata"]["HTTPStatusCode"] == 404: raise FileNotFoundError("File does not exist: %s" % name) raise # Let it bubble up if it was some other error def _get_write_parameters(self, name, content=None): params = self.get_object_parameters(name) if "ContentType" not in params: _type, encoding = mimetypes.guess_type(name) content_type = getattr(content, "content_type", None) content_type = content_type or _type or self.default_content_type params["ContentType"] = content_type if encoding: params["ContentEncoding"] = encoding if "ACL" not in params and self.default_acl: params["ACL"] = self.default_acl return params def get_object_parameters(self, name): """ Returns a dictionary that is passed to file upload. Override this method to adjust this on a per-object basis to set e.g ContentDisposition. By default, returns the value of AWS_S3_OBJECT_PARAMETERS. Setting ContentEncoding will prevent objects from being automatically gzipped. """ return self.object_parameters.copy() def get_modified_time(self, name): """ Returns an (aware) datetime object containing the last modified time if USE_TZ is True, otherwise returns a naive datetime in the local timezone. """ name = self._normalize_name(clean_name(name)) entry = self.bucket.Object(name) if setting("USE_TZ"): # boto3 returns TZ aware timestamps return entry.last_modified else: return make_naive(entry.last_modified) def url(self, name, parameters=None, expire=None, http_method=None): # Preserve the trailing slash after normalizing the path. name = self._normalize_name(clean_name(name)) params = parameters.copy() if parameters else {} if expire is None: expire = self.querystring_expire if self.custom_domain: url = "{}//{}/{}{}".format( self.url_protocol, self.custom_domain, filepath_to_uri(name), "?{}".format(urlencode(params)) if params else "", ) if self.querystring_auth and self.cloudfront_signer: expiration = datetime.utcnow() + timedelta(seconds=expire) return self.cloudfront_signer.generate_presigned_url( url, date_less_than=expiration ) return url params["Bucket"] = self.bucket.name params["Key"] = name connection = ( self.connection if self.querystring_auth else self.unsigned_connection ) url = connection.meta.client.generate_presigned_url( "get_object", Params=params, ExpiresIn=expire, HttpMethod=http_method ) return url def get_available_name(self, name, max_length=None): """Overwrite existing file with the same name.""" name = clean_name(name) if self.file_overwrite: return get_available_overwrite_name(name, max_length) return super().get_available_name(name, max_length)
S3Storage
python
Netflix__metaflow
metaflow/plugins/argo/argo_workflows.py
{ "start": 197607, "end": 198942 }
class ____(object): # https://argoproj.github.io/argo-workflows/fields/#metadata def __init__(self): tree = lambda: defaultdict(tree) self.payload = tree() def annotation(self, key, value): self.payload["annotations"][key] = str(value) return self def annotations(self, annotations): if "annotations" not in self.payload: self.payload["annotations"] = {} self.payload["annotations"].update(annotations) return self def label(self, key, value): self.payload["labels"][key] = str(value) return self def labels(self, labels): if "labels" not in self.payload: self.payload["labels"] = {} self.payload["labels"].update(labels or {}) return self def labels_from(self, labels_from): # Only available in workflow_metadata # https://github.com/argoproj/argo-workflows/blob/master/examples/label-value-from-workflow.yaml if "labelsFrom" not in self.payload: self.payload["labelsFrom"] = {} for k, v in labels_from.items(): self.payload["labelsFrom"].update({k: {"expression": v}}) return self def to_json(self): return self.payload def __str__(self): return json.dumps(self.to_json(), indent=4)
Metadata
python
ansible__ansible
lib/ansible/executor/module_common.py
{ "start": 24659, "end": 28282 }
class ____(ModuleUtilLocatorBase): def __init__(self, fq_name_parts, is_ambiguous=False, child_is_redirected=False, is_optional=False): super(CollectionModuleUtilLocator, self).__init__(fq_name_parts, is_ambiguous, child_is_redirected, is_optional) if fq_name_parts[0] != 'ansible_collections': raise Exception('CollectionModuleUtilLocator can only locate from ansible_collections, got {0}'.format(fq_name_parts)) elif len(fq_name_parts) >= 6 and fq_name_parts[3:5] != ('plugins', 'module_utils'): raise Exception('CollectionModuleUtilLocator can only locate below ansible_collections.(ns).(coll).plugins.module_utils, got {0}' .format(fq_name_parts)) self._collection_name = '.'.join(fq_name_parts[1:3]) self._locate() def _find_module(self, name_parts): # synthesize empty inits for packages down through module_utils- we don't want to allow those to be shipped over, but the # package hierarchy needs to exist if len(name_parts) < 6: self.source_code = '' self.is_package = True return True # NB: we can't use pkgutil.get_data safely here, since we don't want to import/execute package/module code on # the controller while analyzing/assembling the module, so we'll have to manually import the collection's # Python package to locate it (import root collection, reassemble resource path beneath, fetch source) collection_pkg_name = '.'.join(name_parts[0:3]) resource_base_path = os.path.join(*name_parts[3:]) src = None # look for package_dir first, then module src_path = to_native(os.path.join(resource_base_path, '__init__.py')) try: collection_pkg = importlib.import_module(collection_pkg_name) pkg_path = os.path.dirname(collection_pkg.__file__) except (ImportError, AttributeError): pkg_path = None try: src = pkgutil.get_data(collection_pkg_name, src_path) except ImportError: pass # TODO: we might want to synthesize fake inits for py3-style packages, for now they're required beneath module_utils if src is not None: # empty string is OK self.is_package = True else: src_path = to_native(resource_base_path + '.py') try: src = pkgutil.get_data(collection_pkg_name, src_path) except ImportError: pass if src is None: # empty string is OK return False # TODO: this feels brittle and funky; we should be able to more definitively assure the source path if pkg_path: origin = Origin(path=os.path.join(pkg_path, src_path)) else: # DTFIX-FUTURE: not sure if this case is even reachable origin = Origin(description=f'<synthetic collection package for {collection_pkg_name}!r>') self.source_code = origin.tag(src) return True def _get_module_utils_remainder_parts(self, name_parts): return name_parts[5:] # eg, foo.bar for ansible_collections.ns.coll.plugins.module_utils.foo.bar def _make_zinfo(filename: str, date_time: datetime.datetime, zf: zipfile.ZipFile | None = None) -> zipfile.ZipInfo: zinfo = zipfile.ZipInfo( filename=filename, date_time=date_time.utctimetuple()[:6], ) if zf: zinfo.compress_type = zf.compression return zinfo @dataclasses.dataclass(frozen=True, kw_only=True, slots=True)
CollectionModuleUtilLocator
python
jina-ai__jina
jina/clients/mixin.py
{ "start": 6886, "end": 7605 }
class ____: """The Profile Mixin for Client and Flow to expose `profile` API""" async def profiling(self, show_table: bool = True) -> Dict[str, float]: """Profiling a single query's roundtrip including network and computation latency. Results is summarized in a Dict. :param show_table: whether to show the table or not. :return: the latency report in a dict. """ from docarray import Document st = time.perf_counter() async for r in self.client.post( on='/', inputs=Document(), return_responses=True ): ed = time.perf_counter() return _render_response_table(r, st, ed, show_table=show_table)
AsyncProfileMixin
python
huggingface__transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
{ "start": 96621, "end": 102290 }
class ____(SeamlessM4Tv2PreTrainedModel, GenerationMixin): _keys_to_ignore_on_load_missing = [ "vocoder", "speech_encoder", "text_encoder", "text_decoder", ] _tied_weights_keys = {"lm_head.weight": "model.decoder.embed_tokens.weight"} # Copied from transformers.models.seamless_m4t.modeling_seamless_m4t.SeamlessM4TTextToUnitForConditionalGeneration.__init__ with SeamlessM4T->SeamlessM4Tv2 def __init__( self, config: SeamlessM4Tv2Config, embed_tokens_decoder: Optional[nn.Embedding] = None, ): r""" embed_tokens_decoder (`nn.Embedding`, *optional*): input embedding of the decoder. """ # update config - used principality for bos_token_id etc. config = copy.deepcopy(config) for param, val in config.to_dict().items(): if param.startswith("t2u_"): config.__setattr__(param[4:], val) super().__init__(config) self.model = SeamlessM4Tv2TextToUnitModel(config, embed_tokens_decoder) self.lm_head = nn.Linear(config.hidden_size, config.t2u_vocab_size, bias=False) # Initialize weights and apply final processing self.post_init() # Copied from transformers.models.seamless_m4t.modeling_seamless_m4t.SeamlessM4TTextToUnitForConditionalGeneration.get_encoder def get_encoder(self): return self.model.encoder # Copied from transformers.models.seamless_m4t.modeling_seamless_m4t.SeamlessM4TTextToUnitForConditionalGeneration.get_decoder def get_decoder(self): return self.model.decoder # Copied from transformers.models.seamless_m4t.modeling_seamless_m4t.SeamlessM4TTextToUnitForConditionalGeneration.get_input_embeddings def get_input_embeddings(self): return self.model.decoder.embed_tokens # Copied from transformers.models.seamless_m4t.modeling_seamless_m4t.SeamlessM4TTextToUnitForConditionalGeneration.set_input_embeddings def set_input_embeddings(self, value): self.model.decoder.embed_tokens = value @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, char_input_ids: Optional[torch.LongTensor] = None, char_count_per_id: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, encoder_outputs: Optional[tuple[tuple[torch.FloatTensor]]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, **kwargs, ) -> Union[Seq2SeqLMOutput, tuple[torch.FloatTensor]]: r""" char_input_ids (`torch.LongTensor` of shape `(batch_size, char_sequence_length)`): Character indices. The correspondence between characters and indices can be found in `char_to_id`, a dictionary in the generation configuration. char_count_per_id (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Number of characters per input id. 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. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.model( input_ids, char_input_ids=char_input_ids, char_count_per_id=char_count_per_id, attention_mask=attention_mask, encoder_outputs=encoder_outputs, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) lm_logits = self.lm_head(outputs[0]) masked_lm_loss = None if labels is not None: loss_fct = CrossEntropyLoss() labels = labels.to(lm_logits.device) masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1)) if not return_dict: output = (lm_logits,) + outputs[1:] return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output return SeamlessM4Tv2TextToUnitOutput( last_hidden_state=lm_logits, padding_mask=outputs.padding_mask, decoder_hidden_states=outputs.decoder_hidden_states, decoder_attentions=outputs.decoder_attentions, encoder_last_hidden_state=outputs.encoder_last_hidden_state, encoder_hidden_states=outputs.encoder_hidden_states, encoder_attentions=outputs.encoder_attentions, loss=masked_lm_loss, ) ############ VOCODER related code ################ # Copied from transformers.models.speecht5.modeling_speecht5.HifiGanResidualBlock
SeamlessM4Tv2TextToUnitForConditionalGeneration
python
aio-libs__aiohttp
aiohttp/web_exceptions.py
{ "start": 4762, "end": 4868 }
class ____(HTTPException): """Base class for exceptions with status codes in the 200s."""
HTTPSuccessful
python
google__pytype
pytype/overlays/named_tuple.py
{ "start": 19804, "end": 20276 }
class ____: """Construct dict abstract classes for namedtuple members.""" def __init__(self, ctx): self.ctx = ctx self.dict_cls = ctx.convert.lookup_value("builtins", "dict") def make(self, typ): # Normally, we would use abstract_utils.K and abstract_utils.V, but # collections.pyi doesn't conform to that standard. return abstract.ParameterizedClass( self.dict_cls, {"K": self.ctx.convert.str_type, "V": typ}, self.ctx )
_DictBuilder
python
weaviate__weaviate-python-client
weaviate/collections/batch/client.py
{ "start": 4419, "end": 8019 }
class ____(_BatchBaseNew): def add_object( self, collection: str, properties: Optional[WeaviateProperties] = None, references: Optional[ReferenceInputs] = None, uuid: Optional[UUID] = None, vector: Optional[VECTORS] = None, tenant: Optional[Union[str, Tenant]] = None, ) -> UUID: """Add one object to this batch. NOTE: If the UUID of one of the objects already exists then the existing object will be replaced by the new object. Args: collection: The name of the collection this object belongs to. properties: The data properties of the object to be added as a dictionary. references: The references of the object to be added as a dictionary. uuid: The UUID of the object as an uuid.UUID object or str. It can be a Weaviate beacon or Weaviate href. If it is None an UUIDv4 will generated, by default None vector: The embedding of the object. Can be used when a collection does not have a vectorization module or the given vector was generated using the _identical_ vectorization module that is configured for the class. In this case this vector takes precedence. Supported types are: - for single vectors: `list`, 'numpy.ndarray`, `torch.Tensor` and `tf.Tensor`, by default None. - for named vectors: Dict[str, *list above*], where the string is the name of the vector. tenant: The tenant name or Tenant object to be used for this request. Returns: The UUID of the added object. If one was not provided a UUIDv4 will be auto-generated for you and returned here. Raises: WeaviateBatchValidationError: If the provided options are in the format required by Weaviate. """ return super()._add_object( collection=collection, properties=properties, references=references, uuid=uuid, vector=vector, tenant=tenant.name if isinstance(tenant, Tenant) else tenant, ) def add_reference( self, from_uuid: UUID, from_collection: str, from_property: str, to: ReferenceInput, tenant: Optional[Union[str, Tenant]] = None, ) -> None: """Add one reference to this batch. Args: from_uuid: The UUID of the object, as an uuid.UUID object or str, that should reference another object. from_collection: The name of the collection that should reference another object. from_property: The name of the property that contains the reference. to: The UUID of the referenced object, as an uuid.UUID object or str, that is actually referenced. For multi-target references use wvc.Reference.to_multi_target(). tenant: The tenant name or Tenant object to be used for this request. Raises: WeaviateBatchValidationError: If the provided options are in the format required by Weaviate. """ super()._add_reference( from_object_uuid=from_uuid, from_object_collection=from_collection, from_property_name=from_property, to=to, tenant=tenant.name if isinstance(tenant, Tenant) else tenant, ) BatchClient = _BatchClient BatchClientNew = _BatchClientNew ClientBatchingContextManager = _ContextManagerWrapper[ Union[BatchClient, BatchClientNew], BatchClientProtocol ]
_BatchClientNew
python
PyCQA__pylint
tests/functional/n/no/no_method_argument_py38.py
{ "start": 55, "end": 521 }
class ____: def __init__(self, obj, /): self.obj = obj # regression tests for no-method-argument getting reported # instead of no-self-argument def varargs(*args): """A method without a self argument but with *args.""" def kwargs(**kwargs): """A method without a self argument but with **kwargs.""" def varargs_and_kwargs(*args, **kwargs): """A method without a self argument but with *args and **kwargs."""
Cls
python
plotly__plotly.py
plotly/graph_objs/treemap/_hoverlabel.py
{ "start": 233, "end": 11241 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "treemap" _path_str = "treemap.hoverlabel" _valid_props = { "align", "alignsrc", "bgcolor", "bgcolorsrc", "bordercolor", "bordercolorsrc", "font", "namelength", "namelengthsrc", "showarrow", } @property def align(self): """ Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines The 'align' property is an enumeration that may be specified as: - One of the following enumeration values: ['left', 'right', 'auto'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["align"] @align.setter def align(self, val): self["align"] = val @property def alignsrc(self): """ Sets the source reference on Chart Studio Cloud for `align`. The 'alignsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["alignsrc"] @alignsrc.setter def alignsrc(self, val): self["alignsrc"] = val @property def bgcolor(self): """ Sets the background color of the hover labels for this trace The 'bgcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list - A list or array of any of the above Returns ------- str|numpy.ndarray """ return self["bgcolor"] @bgcolor.setter def bgcolor(self, val): self["bgcolor"] = val @property def bgcolorsrc(self): """ Sets the source reference on Chart Studio Cloud for `bgcolor`. The 'bgcolorsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["bgcolorsrc"] @bgcolorsrc.setter def bgcolorsrc(self, val): self["bgcolorsrc"] = val @property def bordercolor(self): """ Sets the border color of the hover labels for this trace. The 'bordercolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list - A list or array of any of the above Returns ------- str|numpy.ndarray """ return self["bordercolor"] @bordercolor.setter def bordercolor(self, val): self["bordercolor"] = val @property def bordercolorsrc(self): """ Sets the source reference on Chart Studio Cloud for `bordercolor`. The 'bordercolorsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["bordercolorsrc"] @bordercolorsrc.setter def bordercolorsrc(self, val): self["bordercolorsrc"] = val @property def font(self): """ Sets the font used in hover labels. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.treemap.hoverlabel.Font` - A dict of string/value properties that will be passed to the Font constructor Returns ------- plotly.graph_objs.treemap.hoverlabel.Font """ return self["font"] @font.setter def font(self, val): self["font"] = val @property def namelength(self): """ Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. The 'namelength' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [-1, 9223372036854775807] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|numpy.ndarray """ return self["namelength"] @namelength.setter def namelength(self, val): self["namelength"] = val @property def namelengthsrc(self): """ Sets the source reference on Chart Studio Cloud for `namelength`. The 'namelengthsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["namelengthsrc"] @namelengthsrc.setter def namelengthsrc(self, val): self["namelengthsrc"] = val @property def showarrow(self): """ Sets whether or not to show the hover label arrow/triangle pointing to the data point. The 'showarrow' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showarrow"] @showarrow.setter def showarrow(self, val): self["showarrow"] = val @property def _prop_descriptions(self): return """\ align Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines alignsrc Sets the source reference on Chart Studio Cloud for `align`. bgcolor Sets the background color of the hover labels for this trace bgcolorsrc Sets the source reference on Chart Studio Cloud for `bgcolor`. bordercolor Sets the border color of the hover labels for this trace. bordercolorsrc Sets the source reference on Chart Studio Cloud for `bordercolor`. font Sets the font used in hover labels. namelength Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. namelengthsrc Sets the source reference on Chart Studio Cloud for `namelength`. showarrow Sets whether or not to show the hover label arrow/triangle pointing to the data point. """ def __init__( self, arg=None, align=None, alignsrc=None, bgcolor=None, bgcolorsrc=None, bordercolor=None, bordercolorsrc=None, font=None, namelength=None, namelengthsrc=None, showarrow=None, **kwargs, ): """ Construct a new Hoverlabel object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.treemap.Hoverlabel` align Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines alignsrc Sets the source reference on Chart Studio Cloud for `align`. bgcolor Sets the background color of the hover labels for this trace bgcolorsrc Sets the source reference on Chart Studio Cloud for `bgcolor`. bordercolor Sets the border color of the hover labels for this trace. bordercolorsrc Sets the source reference on Chart Studio Cloud for `bordercolor`. font Sets the font used in hover labels. namelength Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. namelengthsrc Sets the source reference on Chart Studio Cloud for `namelength`. showarrow Sets whether or not to show the hover label arrow/triangle pointing to the data point. Returns ------- Hoverlabel """ super().__init__("hoverlabel") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.treemap.Hoverlabel constructor must be a dict or an instance of :class:`plotly.graph_objs.treemap.Hoverlabel`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("align", arg, align) self._set_property("alignsrc", arg, alignsrc) self._set_property("bgcolor", arg, bgcolor) self._set_property("bgcolorsrc", arg, bgcolorsrc) self._set_property("bordercolor", arg, bordercolor) self._set_property("bordercolorsrc", arg, bordercolorsrc) self._set_property("font", arg, font) self._set_property("namelength", arg, namelength) self._set_property("namelengthsrc", arg, namelengthsrc) self._set_property("showarrow", arg, showarrow) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Hoverlabel
python
scrapy__scrapy
scrapy/core/downloader/handlers/http11.py
{ "start": 1869, "end": 2119 }
class ____(TypedDict): txresponse: TxResponse body: bytes flags: list[str] | None certificate: ssl.Certificate | None ip_address: ipaddress.IPv4Address | ipaddress.IPv6Address | None failure: NotRequired[Failure | None]
_ResultT
python
rapidsai__cudf
python/cudf/cudf/core/udf/strings_typing.py
{ "start": 6423, "end": 6599 }
class ____(AbstractTemplate): key = "StringView.count" def generic(self, args, kws): return nb_signature(size_type, string_view, recvr=self.this)
StringViewCount
python
crytic__slither
slither/core/solidity_types/type_alias.py
{ "start": 1168, "end": 1550 }
class ____(TypeAlias, TopLevel): def __init__(self, underlying_type: ElementaryType, name: str, scope: "FileScope") -> None: super().__init__(underlying_type, name) self.file_scope: "FileScope" = scope # operators redefined self.operators: Dict[str, "FunctionTopLevel"] = {} def __str__(self) -> str: return self.name
TypeAliasTopLevel
python
pandas-dev__pandas
asv_bench/benchmarks/indexing.py
{ "start": 5759, "end": 6971 }
class ____: params = [ (np.int64, np.uint64, np.float64), ("unique_monotonic_inc", "nonunique_monotonic_inc"), ] param_names = ["dtype", "index_structure"] def setup(self, dtype, index_structure): N = 10**5 indices = { "unique_monotonic_inc": Index(range(N), dtype=dtype), "nonunique_monotonic_inc": Index( list(range(55)) + [54] + list(range(55, N - 1)), dtype=dtype ), } self.idx_dupe = np.array(range(30)) * 99 self.df = DataFrame(np.random.randn(N, 5), index=indices[index_structure]) self.df_dup = concat([self.df, 2 * self.df, 3 * self.df]) self.bool_indexer = [True] * (N // 2) + [False] * (N - N // 2) def time_iloc_dups(self, index, index_structure): self.df_dup.iloc[self.idx_dupe] def time_loc_dups(self, index, index_structure): self.df_dup.loc[self.idx_dupe] def time_iloc(self, index, index_structure): self.df.iloc[:100, 0] def time_loc(self, index, index_structure): self.df.loc[:100, 0] def time_bool_indexer(self, index, index_structure): self.df[self.bool_indexer]
DataFrameNumericIndexing
python
getsentry__sentry
src/sentry/sentry_metrics/indexer/base.py
{ "start": 653, "end": 806 }
class ____(NamedTuple): is_global: bool OrgId = int KR = TypeVar("KR", bound="KeyResult") UR = TypeVar("UR", bound="UseCaseKeyResult")
FetchTypeExt
python
dagster-io__dagster
python_modules/dagster/dagster/_core/snap/mode.py
{ "start": 2766, "end": 3868 }
class ____( NamedTuple( "_ResourceDefSnap", [ ("name", str), ("description", Optional[str]), ("config_field_snap", Optional[ConfigFieldSnap]), ], ) ): def __new__( cls, name: str, description: Optional[str], config_field_snap: Optional[ConfigFieldSnap] ): return super().__new__( cls, name=check.str_param(name, "name"), description=check.opt_str_param(description, "description"), config_field_snap=check.opt_inst_param( config_field_snap, "config_field_snap", ConfigFieldSnap ), ) def build_logger_def_snap(name, logger_def): check.str_param(name, "name") check.inst_param(logger_def, "logger_def", LoggerDefinition) return LoggerDefSnap( name=name, description=logger_def.description, config_field_snap=( snap_from_field("config", logger_def.config_field) if logger_def.has_config_field else None ), ) @whitelist_for_serdes
ResourceDefSnap
python
pytorch__pytorch
test/test_serialization.py
{ "start": 3614, "end": 3664 }
class ____: class Nested: pass
ClassAMock
python
aimacode__aima-python
agents.py
{ "start": 27709, "end": 27838 }
class ____(Thing): def __eq__(self, rhs): """All Gold are equal""" return rhs.__class__ == Gold pass
Gold
python
pennersr__django-allauth
allauth/idp/oidc/views.py
{ "start": 4284, "end": 9885 }
class ____(FormView): form_class = AuthorizationForm template_name = "idp/oidc/authorization_form." + account_settings.TEMPLATE_EXTENSION def get(self, request, *args, **kwargs): response = self._login_required(request) if response: return response orequest = extract_params(self.request) try: server = get_server() self._scopes, self._request_info = server.validate_authorization_request( *orequest ) if "none" in self._request_info.get("prompt", ()): oresponse = server.create_authorization_response( *orequest, scopes=self._scopes ) return convert_response(*oresponse) # Errors that should be shown to the user on the provider website except errors.FatalClientError as e: return respond_html_error(request, error=e) except errors.OAuth2Error as e: return HttpResponseRedirect(e.in_uri(e.redirect_uri)) if self._request_info["request"].client.skip_consent: return self._skip_consent() return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): signed_request_info = request.POST.get("request") if not signed_request_info: return HttpResponseRedirect( reverse("idp:oidc:authorization") + "?" + request.POST.urlencode() ) response = self._login_required(request) if response: return response csrf_resp = _enforce_csrf(request) if csrf_resp: return csrf_resp try: signer = Signer() self._scopes, self._request_info = signer.unsign_object(signed_request_info) except BadSignature: raise PermissionDenied if request.POST.get("action") != "grant": return self._respond_with_access_denied() return super().post(request, *args, **kwargs) def _login_required(self, request) -> Optional[HttpResponse]: prompts = [] prompt = request.GET.get("prompt") if prompt: prompts = prompt.split() if "login" in prompts: return self._handle_login_prompt(request, prompts) if "none" in prompts: return None if request.user.is_authenticated: return None return login_required()(None)(request) # type:ignore[misc,type-var] def _handle_login_prompt( self, request: HttpRequest, prompts: List[str] ) -> HttpResponse: prompts.remove("login") next_url = request.get_full_path() if prompts: next_url = add_query_params(next_url, {"prompt": " ".join(prompts)}) else: next_url = del_query_params(next_url, "prompt") params = {} params[REDIRECT_FIELD_NAME] = next_url path = reverse( "account_reauthenticate" if request.user.is_authenticated else "account_login" ) return HttpResponseRedirect(add_query_params(path, params)) def _skip_consent(self): scopes = self._request_info["request"].scopes form_kwargs = self.get_form_kwargs() form_kwargs["data"] = { "scopes": scopes, "request": "not-relevant-for-skip-consent", } form = self.form_class(**form_kwargs) if not form.is_valid(): # Shouldn't occur. raise PermissionDenied() return self.form_valid(form) def _respond_with_access_denied(self): redirect_uri = self._request_info.get("redirect_uri") state = self._request_info.get("state") params = {"error": "access_denied"} if state: params["state"] = state return HttpResponseRedirect(add_query_params(redirect_uri, params)) def get_form_kwargs(self) -> dict: ret = super().get_form_kwargs() ret.update({"requested_scopes": self._scopes, "user": self.request.user}) return ret def get_initial(self): signer = Signer() ret = {} request_info = self._request_info request_info.pop("request", None) prompt = request_info.get("prompt") if isinstance(prompt, set): request_info["prompt"] = list(prompt) ret["request"] = signer.sign_object((self._scopes, request_info)) return ret def form_valid(self, form): orequest = extract_params(self.request) scopes = form.cleaned_data["scopes"] credentials = {"user": self.request.user} credentials.update(self._request_info) try: email = form.cleaned_data.get("email") if email: credentials["email"] = email oresponse = get_server().create_authorization_response( *orequest, scopes=scopes, credentials=credentials ) return convert_response(*oresponse) except errors.FatalClientError as e: return respond_html_error(self.request, error=e) def get_context_data(self, **kwargs): ret = super().get_context_data(**kwargs) ret.update( { "client": Client.objects.get(id=self._request_info["client_id"]), "site": get_current_site(self.request), } ) return ret authorization = AuthorizationView.as_view() @method_decorator(csrf_exempt, name="dispatch") @method_decorator(login_not_required, name="dispatch")
AuthorizationView
python
chroma-core__chroma
chromadb/utils/embedding_functions/voyageai_embedding_function.py
{ "start": 249, "end": 4884 }
class ____(EmbeddingFunction[Documents]): """ This class is used to generate embeddings for a list of texts using the VoyageAI API. """ def __init__( self, api_key: Optional[str] = None, model_name: str = "voyage-large-2", api_key_env_var: str = "CHROMA_VOYAGE_API_KEY", input_type: Optional[str] = None, truncation: bool = True, ): """ Initialize the VoyageAIEmbeddingFunction. Args: api_key_env_var (str, optional): Environment variable name that contains your API key for the VoyageAI API. Defaults to "CHROMA_VOYAGE_API_KEY". model_name (str, optional): The name of the model to use for text embeddings. Defaults to "voyage-large-2". api_key (str, optional): API key for the VoyageAI API. If not provided, will look for it in the environment variable. input_type (str, optional): The type of input to use for the VoyageAI API. Defaults to None. truncation (bool): Whether to truncate the input text. Defaults to True. """ try: import voyageai except ImportError: raise ValueError( "The voyageai python package is not installed. Please install it with `pip install voyageai`" ) if api_key is not None: warnings.warn( "Direct api_key configuration will not be persisted. " "Please use environment variables via api_key_env_var for persistent storage.", DeprecationWarning, ) if os.getenv("VOYAGE_API_KEY") is not None: self.api_key_env_var = "VOYAGE_API_KEY" else: self.api_key_env_var = api_key_env_var self.api_key = api_key or os.getenv(self.api_key_env_var) if not self.api_key: raise ValueError( f"The {self.api_key_env_var} environment variable is not set." ) self.model_name = model_name self.input_type = input_type self.truncation = truncation self._client = voyageai.Client(api_key=self.api_key) def __call__(self, input: Documents) -> Embeddings: """ Generate embeddings for the given documents. Args: input: Documents to generate embeddings for. Returns: Embeddings for the documents. """ embeddings = self._client.embed( texts=input, model=self.model_name, input_type=self.input_type, truncation=self.truncation, ) # Convert to numpy arrays return [ np.array(embedding, dtype=np.float32) for embedding in embeddings.embeddings ] @staticmethod def name() -> str: return "voyageai" def default_space(self) -> Space: return "cosine" def supported_spaces(self) -> List[Space]: return ["cosine", "l2", "ip"] @staticmethod def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": api_key_env_var = config.get("api_key_env_var") model_name = config.get("model_name") input_type = config.get("input_type") truncation = config.get("truncation") if api_key_env_var is None or model_name is None: assert False, "This code should not be reached" return VoyageAIEmbeddingFunction( api_key_env_var=api_key_env_var, model_name=model_name, input_type=input_type, truncation=truncation if truncation is not None else True, ) def get_config(self) -> Dict[str, Any]: return { "api_key_env_var": self.api_key_env_var, "model_name": self.model_name, "input_type": self.input_type, "truncation": self.truncation, } def validate_config_update( self, old_config: Dict[str, Any], new_config: Dict[str, Any] ) -> None: if "model_name" in new_config: raise ValueError( "The model name cannot be changed after the embedding function has been initialized." ) @staticmethod def validate_config(config: Dict[str, Any]) -> None: """ Validate the configuration using the JSON schema. Args: config: Configuration to validate Raises: ValidationError: If the configuration does not match the schema """ validate_config_schema(config, "voyageai")
VoyageAIEmbeddingFunction
python
sphinx-doc__sphinx
sphinx/config.py
{ "start": 6204, "end": 34643 }
class ____: r"""Configuration file abstraction. The Config object makes the values of all config options available as attributes. It is exposed via the :py:class:`~sphinx.application.Sphinx`\ ``.config`` and :py:class:`sphinx.environment.BuildEnvironment`\ ``.config`` attributes. For example, to get the value of :confval:`language`, use either ``app.config.language`` or ``env.config.language``. """ # The values are: # 1. Default # 2. What needs to be rebuilt if changed # 3. Valid types # If you add a value here, remember to include it in the docs! config_values: dict[str, _Opt] = { # general options 'project': _Opt('Project name not set', 'env', frozenset((str,))), 'author': _Opt('Author name not set', 'env', frozenset((str,))), 'project_copyright': _Opt('', 'html', frozenset((str, tuple, list))), 'copyright': _Opt( lambda config: config.project_copyright, 'html', frozenset((str, tuple, list)), ), 'version': _Opt('', 'env', frozenset((str,))), 'release': _Opt('', 'env', frozenset((str,))), 'today': _Opt('', 'env', frozenset((str,))), # the real default is locale-dependent 'today_fmt': _Opt(None, 'env', frozenset((str,))), 'language': _Opt('en', 'env', frozenset((str,))), 'locale_dirs': _Opt(['locales'], 'env', frozenset((list, tuple))), 'figure_language_filename': _Opt( '{root}.{language}{ext}', 'env', frozenset((str,)) ), 'gettext_allow_fuzzy_translations': _Opt(False, 'gettext', frozenset((bool,))), 'translation_progress_classes': _Opt( False, 'env', ENUM(True, False, 'translated', 'untranslated') ), 'master_doc': _Opt('index', 'env', frozenset((str,))), 'root_doc': _Opt(lambda config: config.master_doc, 'env', frozenset((str,))), # ``source_suffix`` type is actually ``dict[str, str | None]``: # see ``convert_source_suffix()`` below. 'source_suffix': _Opt({'.rst': 'restructuredtext'}, 'env', Any), # type: ignore[arg-type] 'source_encoding': _Opt('utf-8-sig', 'env', frozenset((str,))), 'exclude_patterns': _Opt([], 'env', frozenset((str,))), 'include_patterns': _Opt(['**'], 'env', frozenset((str,))), 'default_role': _Opt(None, 'env', frozenset((str,))), 'add_function_parentheses': _Opt(True, 'env', frozenset((bool,))), 'add_module_names': _Opt(True, 'env', frozenset((bool,))), 'toc_object_entries': _Opt(True, 'env', frozenset((bool,))), 'toc_object_entries_show_parents': _Opt( 'domain', 'env', ENUM('domain', 'all', 'hide') ), 'trim_footnote_reference_space': _Opt(False, 'env', frozenset((bool,))), 'show_authors': _Opt(False, 'env', frozenset((bool,))), 'pygments_style': _Opt(None, 'html', frozenset((str,))), 'highlight_language': _Opt('default', 'env', frozenset((str,))), 'highlight_options': _Opt({}, 'env', frozenset((dict,))), 'templates_path': _Opt([], 'html', frozenset((list,))), 'template_bridge': _Opt(None, 'html', frozenset((str,))), 'keep_warnings': _Opt(False, 'env', frozenset((bool,))), 'suppress_warnings': _Opt([], 'env', frozenset((list, tuple))), 'show_warning_types': _Opt(True, 'env', frozenset((bool,))), 'modindex_common_prefix': _Opt([], 'html', frozenset((list, tuple))), 'rst_epilog': _Opt(None, 'env', frozenset((str,))), 'rst_prolog': _Opt(None, 'env', frozenset((str,))), 'trim_doctest_flags': _Opt(True, 'env', frozenset((bool,))), 'primary_domain': _Opt('py', 'env', frozenset((types.NoneType,))), 'needs_sphinx': _Opt(None, '', frozenset((str,))), 'needs_extensions': _Opt({}, '', frozenset((dict,))), 'manpages_url': _Opt(None, 'env', frozenset((str, types.NoneType))), 'nitpicky': _Opt(False, '', frozenset((bool,))), 'nitpick_ignore': _Opt([], '', frozenset((set, list, tuple))), 'nitpick_ignore_regex': _Opt([], '', frozenset((set, list, tuple))), 'numfig': _Opt(False, 'env', frozenset((bool,))), 'numfig_secnum_depth': _Opt(1, 'env', frozenset((int, types.NoneType))), # numfig_format will be initialized in init_numfig_format() 'numfig_format': _Opt({}, 'env', frozenset((dict,))), 'maximum_signature_line_length': _Opt( None, 'env', frozenset((int, types.NoneType)) ), 'math_number_all': _Opt(False, 'env', frozenset((bool,))), 'math_eqref_format': _Opt(None, 'env', frozenset((str,))), 'math_numfig': _Opt(True, 'env', frozenset((bool,))), 'math_numsep': _Opt('.', 'env', frozenset((str,))), 'tls_verify': _Opt(True, 'env', frozenset((bool,))), 'tls_cacerts': _Opt(None, 'env', frozenset((str, dict, types.NoneType))), 'user_agent': _Opt(None, 'env', frozenset((str,))), 'smartquotes': _Opt(True, 'env', frozenset((bool,))), 'smartquotes_action': _Opt('qDe', 'env', frozenset((str,))), 'smartquotes_excludes': _Opt( {'languages': ['ja', 'zh_CN', 'zh_TW'], 'builders': ['man', 'text']}, 'env', frozenset((dict,)), ), 'option_emphasise_placeholders': _Opt(False, 'env', frozenset((bool,))), } def __init__( self, config: dict[str, Any] | None = None, overrides: dict[str, Any] | None = None, ) -> None: raw_config: dict[str, Any] = config or {} self._overrides = dict(overrides) if overrides is not None else {} self._options = Config.config_values.copy() self._raw_config = raw_config for name in list(self._overrides.keys()): if '.' in name: real_name, _, key = name.partition('.') raw_config.setdefault(real_name, {})[key] = self._overrides.pop(name) self.setup: _ExtensionSetupFunc | None = raw_config.get('setup') if 'extensions' in self._overrides: extensions = self._overrides.pop('extensions') if isinstance(extensions, str): raw_config['extensions'] = extensions.split(',') else: raw_config['extensions'] = extensions self.extensions: list[str] = raw_config.get('extensions', []) self._verbosity: int = 0 # updated in Sphinx.__init__() @property def values(self) -> dict[str, _Opt]: return self._options @property def overrides(self) -> dict[str, Any]: return self._overrides @property def verbosity(self) -> int: return self._verbosity @classmethod def read( cls: type[Config], confdir: str | os.PathLike[str], *, overrides: dict[str, Any], tags: Tags, ) -> Config: """Create a Config object from configuration file.""" filename = Path(confdir, CONFIG_FILENAME) if not filename.is_file(): raise ConfigError( __("config directory doesn't contain a conf.py file (%s)") % confdir ) return _read_conf_py(filename, overrides=overrides, tags=tags) def convert_overrides(self, name: str, value: str) -> Any: opt = self._options[name] default = opt.default valid_types = opt.valid_types if valid_types == Any: return value if isinstance(valid_types, ENUM): if False in valid_types._candidates and value == '0': return False if True in valid_types._candidates and value == '1': return True return value elif type(default) is bool or (bool in valid_types): if value == '0': return False if value == '1': return True if len(valid_types) > 1: return value msg = __("'%s' must be '0' or '1', got '%s'") % (name, value) raise ConfigError(msg) if isinstance(default, dict): raise ValueError( # NoQA: TRY004 __( 'cannot override dictionary config setting %r, ' 'ignoring (use %r to set individual elements)' ) % (name, f'{name}.key=value') ) if isinstance(default, list): return value.split(',') if isinstance(default, int): try: return int(value) except ValueError as exc: raise ValueError( __('invalid number %r for config value %r, ignoring') % (value, name) ) from exc if callable(default): return value if isinstance(default, str) or default is None: return value raise ValueError( __('cannot override config setting %r with unsupported type, ignoring') % name ) @staticmethod def pre_init_values() -> None: # method only retained for compatibility pass # warnings.warn( # 'Config.pre_init_values() will be removed in Sphinx 9.0 or later', # RemovedInSphinx90Warning, stacklevel=2) def init_values(self) -> None: # method only retained for compatibility self._report_override_warnings() # warnings.warn( # 'Config.init_values() will be removed in Sphinx 9.0 or later', # RemovedInSphinx90Warning, stacklevel=2) def _report_override_warnings(self) -> None: for name in self._overrides: if name not in self._options: logger.warning( __('unknown config value %r in override, ignoring'), name ) def __repr__(self) -> str: values = [] for opt_name in self._options: try: opt_value = getattr(self, opt_name) except Exception: opt_value = '<error!>' values.append(f'{opt_name}={opt_value!r}') return self.__class__.__qualname__ + '(' + ', '.join(values) + ')' def __setattr__(self, key: str, value: object) -> None: # Ensure aliases update their counterpart. if key == 'master_doc': super().__setattr__('root_doc', value) elif key == 'root_doc': super().__setattr__('master_doc', value) elif key == 'copyright': super().__setattr__('project_copyright', value) elif key == 'project_copyright': super().__setattr__('copyright', value) super().__setattr__(key, value) def __getattr__(self, name: str) -> Any: if name in self._options: # first check command-line overrides if name in self._overrides: value = self._overrides[name] if not isinstance(value, str): self.__dict__[name] = value return value try: value = self.convert_overrides(name, value) except ValueError as exc: logger.warning('%s', exc) else: self.__setattr__(name, value) return value # then check values from 'conf.py' if name in self._raw_config: value = self._raw_config[name] self.__setattr__(name, value) return value # finally, fall back to the default value default = self._options[name].default if callable(default): return default(self) self.__dict__[name] = default return default if name.startswith('_'): msg = f'{self.__class__.__name__!r} object has no attribute {name!r}' raise AttributeError(msg) msg = __('No such config value: %r') % name raise AttributeError(msg) def __getitem__(self, name: str) -> Any: return getattr(self, name) def __setitem__(self, name: str, value: Any) -> None: setattr(self, name, value) def __delitem__(self, name: str) -> None: delattr(self, name) def __contains__(self, name: str) -> bool: return name in self._options def __iter__(self) -> Iterator[ConfigValue]: for name, opt in self._options.items(): yield ConfigValue(name, getattr(self, name), opt.rebuild) def add( self, name: str, default: Any, rebuild: _ConfigRebuild, types: type | Collection[type] | ENUM, description: str = '', ) -> None: if name in self._options: raise ExtensionError(__('Config value %r already present') % name) # standardise rebuild if isinstance(rebuild, bool): rebuild = 'env' if rebuild else '' # standardise valid_types valid_types = _validate_valid_types(types) self._options[name] = _Opt(default, rebuild, valid_types, description) def filter(self, rebuild: Set[_ConfigRebuild]) -> Iterator[ConfigValue]: if isinstance(rebuild, str): return (value for value in self if value.rebuild == rebuild) return (value for value in self if value.rebuild in rebuild) def __getstate__(self) -> dict[str, Any]: """Obtains serializable data for pickling.""" # remove potentially pickling-problematic values from config __dict__ = { key: value for key, value in self.__dict__.items() if not key.startswith('_') and is_serializable(value) } # create a pickleable copy of ``self._options`` __dict__['_options'] = _options = {} for name, opt in self._options.items(): if not isinstance(opt, _Opt) and isinstance(opt, tuple) and len(opt) <= 3: # Fix for Furo's ``_update_default``. self._options[name] = opt = _Opt(*opt) real_value = getattr(self, name) if not is_serializable(real_value): if opt.rebuild: # if the value is not cached, then any build that utilises this cache # will always mark the config value as changed, # and thus always invalidate the cache and perform a rebuild. logger.warning( __( 'cannot cache unpickleable configuration value: %r ' '(because it contains a function, class, or module object)' ), name, type='config', subtype='cache', once=True, ) # omit unserializable value real_value = None # valid_types is also omitted _options[name] = real_value, opt.rebuild return __dict__ def __setstate__(self, state: dict[str, Any]) -> None: self._overrides = {} self._options = { name: _Opt(real_value, rebuild, frozenset()) for name, (real_value, rebuild) in state.pop('_options').items() } self._raw_config = {} self.__dict__.update(state) def _read_conf_py(conf_path: Path, *, overrides: dict[str, Any], tags: Tags) -> Config: """Create a Config object from a conf.py file.""" namespace = eval_config_file(conf_path, tags) # Note: Old sphinx projects have been configured as "language = None" because # sphinx-quickstart previously generated this by default. # To keep compatibility, they should be fallback to 'en' for a while # (This conversion should not be removed before 2025-01-01). if namespace.get('language', ...) is None: logger.warning( __( "Invalid configuration value found: 'language = None'. " 'Update your configuration to a valid language code. ' "Falling back to 'en' (English)." ) ) namespace['language'] = 'en' return Config(namespace, overrides) def eval_config_file(filename: Path, tags: Tags) -> dict[str, Any]: """Evaluate a config file.""" namespace: dict[str, Any] = { '__file__': str(filename), 'tags': tags, } with chdir(filename.parent): # during executing config file, current dir is changed to ``confdir``. try: code = compile(filename.read_bytes(), filename, 'exec') exec(code, namespace) # NoQA: S102 except SyntaxError as err: msg = __('There is a syntax error in your configuration file: %s\n') raise ConfigError(msg % err) from err except SystemExit as exc: msg = __( 'The configuration file (or one of the modules it imports) ' 'called sys.exit()' ) raise ConfigError(msg) from exc except ConfigError: # pass through ConfigError from conf.py as is. It will be shown in console. raise except Exception as exc: msg = __('There is a programmable error in your configuration file:\n\n%s') raise ConfigError(msg % traceback.format_exc()) from exc return namespace def _validate_valid_types( valid_types: type | Collection[type] | ENUM, / ) -> frozenset[type] | ENUM: if not valid_types: return frozenset() if isinstance(valid_types, (frozenset, ENUM)): return valid_types if isinstance(valid_types, type): return frozenset((valid_types,)) if valid_types is Any: return frozenset({Any}) if isinstance(valid_types, set): return frozenset(valid_types) try: return frozenset(valid_types) except TypeError: logger.warning(__('Failed to convert %r to a frozenset'), valid_types) return frozenset() def convert_source_suffix(app: Sphinx, config: Config) -> None: """Convert old styled source_suffix to new styled one. * old style: str or list * new style: a dict which maps from fileext to filetype """ source_suffix = config.source_suffix if isinstance(source_suffix, str): # if str, considers as default filetype (None) # # The default filetype is determined on later step. # By default, it is considered as restructuredtext. config.source_suffix = {source_suffix: 'restructuredtext'} logger.info( __('Converting `source_suffix = %r` to `source_suffix = %r`.'), source_suffix, config.source_suffix, ) elif isinstance(source_suffix, (list, tuple)): # if list, considers as all of them are default filetype config.source_suffix = dict.fromkeys(source_suffix, 'restructuredtext') logger.info( __('Converting `source_suffix = %r` to `source_suffix = %r`.'), source_suffix, config.source_suffix, ) elif not isinstance(source_suffix, dict): msg = __( "The config value `source_suffix' expects a dictionary, " "a string, or a list of strings. Got `%r' instead (type %s)." ) raise ConfigError(msg % (source_suffix, type(source_suffix))) def convert_highlight_options(app: Sphinx, config: Config) -> None: """Convert old styled highlight_options to new styled one. * old style: options * new style: a dict which maps from language name to options """ options = config.highlight_options if options and not all(isinstance(v, dict) for v in options.values()): # old styled option detected because all values are not dictionary. config.highlight_options = {config.highlight_language: options} def init_numfig_format(app: Sphinx, config: Config) -> None: """Initialize :confval:`numfig_format`.""" numfig_format = { 'section': _('Section %s'), 'figure': _('Fig. %s'), 'table': _('Table %s'), 'code-block': _('Listing %s'), } # override default labels by configuration numfig_format.update(config.numfig_format) config.numfig_format = numfig_format def evaluate_copyright_placeholders(_app: Sphinx, config: Config) -> None: """Replace copyright year placeholders (%Y) with the current year.""" replace_yr = str(time.localtime().tm_year) for k in ('copyright', 'epub_copyright'): if k in config: value: str | Sequence[str] = config[k] if isinstance(value, str): if '%Y' in value: config[k] = value.replace('%Y', replace_yr) else: if any('%Y' in line for line in value): items = (line.replace('%Y', replace_yr) for line in value) config[k] = type(value)(items) # type: ignore[call-arg] def correct_copyright_year(_app: Sphinx, config: Config) -> None: """Correct values of copyright year that are not coherent with the SOURCE_DATE_EPOCH environment variable (if set) See https://reproducible-builds.org/specs/source-date-epoch/ """ if source_date_epoch := int(getenv('SOURCE_DATE_EPOCH', '0')): source_date_epoch_year = time.gmtime(source_date_epoch).tm_year else: return # If the current year is the replacement year, there's no work to do. # We also skip replacement years that are in the future. current_year = time.localtime().tm_year if current_year <= source_date_epoch_year: return current_yr = str(current_year) replace_yr = str(source_date_epoch_year) for k in ('copyright', 'epub_copyright'): if k in config: value: str | Sequence[str] = config[k] if isinstance(value, str): config[k] = _substitute_copyright_year(value, current_yr, replace_yr) else: items = ( _substitute_copyright_year(x, current_yr, replace_yr) for x in value ) config[k] = type(value)(items) # type: ignore[call-arg] def _substitute_copyright_year( copyright_line: str, current_year: str, replace_year: str ) -> str: """Replace the year in a single copyright line. Legal formats are: * ``YYYY`` * ``YYYY,`` * ``YYYY `` * ``YYYY-YYYY`` * ``YYYY-YYYY,`` * ``YYYY-YYYY `` The final year in the string is replaced with ``replace_year``. """ if len(copyright_line) < 4 or not copyright_line[:4].isdigit(): return copyright_line if copyright_line[:4] == current_year and copyright_line[4:5] in {'', ' ', ','}: return replace_year + copyright_line[4:] if copyright_line[4:5] != '-': return copyright_line if ( copyright_line[5:9].isdigit() and copyright_line[5:9] == current_year and copyright_line[9:10] in {'', ' ', ','} ): return copyright_line[:5] + replace_year + copyright_line[9:] return copyright_line def check_confval_types(app: Sphinx | None, config: Config) -> None: """Check all values for deviation from the default value's type, since that can result in TypeErrors all over the place NB. """ for name, opt in config._options.items(): default = opt.default valid_types = opt.valid_types value = getattr(config, name) if callable(default): default = default(config) # evaluate default value if default is None and not valid_types: continue # neither inferable nor explicitly annotated types if valid_types == frozenset({Any}): # any type of value is accepted continue if isinstance(valid_types, ENUM): if not valid_types.match(value): msg = __( 'The config value `{name}` has to be a one of {candidates}, ' 'but `{current}` is given.' ) logger.warning( msg.format( name=name, current=value, candidates=valid_types._candidates ), once=True, ) continue type_value = type(value) type_default = type(default) if type_value is type_default: # attempt to infer the type continue if type_value in valid_types: # check explicitly listed types if frozenset in valid_types and type_value in {list, tuple, set}: setattr(config, name, frozenset(value)) elif tuple in valid_types and type_value is list: setattr(config, name, tuple(value)) continue common_bases = {*type_value.__bases__, type_value} & set(type_default.__bases__) common_bases.discard(object) if common_bases: continue # at least we share a non-trivial base class if valid_types: msg = __( "The config value `{name}' has type `{current.__name__}'; " 'expected {permitted}.' ) wrapped_valid_types = sorted(f"`{c.__name__}'" for c in valid_types) if len(wrapped_valid_types) > 2: permitted = ( ', '.join(wrapped_valid_types[:-1]) + f', or {wrapped_valid_types[-1]}' ) else: permitted = ' or '.join(wrapped_valid_types) logger.warning( msg.format(name=name, current=type_value, permitted=permitted), once=True, ) else: msg = __( "The config value `{name}' has type `{current.__name__}', " "defaults to `{default.__name__}'." ) logger.warning( msg.format(name=name, current=type_value, default=type_default), once=True, ) def check_primary_domain(app: Sphinx, config: Config) -> None: primary_domain = config.primary_domain if primary_domain and not app.registry.has_domain(primary_domain): logger.warning(__('primary_domain %r not found, ignored.'), primary_domain) config.primary_domain = None def check_master_doc( app: Sphinx, env: BuildEnvironment, added: Set[str], changed: Set[str], removed: Set[str], ) -> Iterable[str]: """Sphinx 2.0 changed the default from 'contents' to 'index'.""" docnames = app.project.docnames if ( app.config.master_doc == 'index' and 'index' not in docnames and 'contents' in docnames ): logger.warning( __( 'Sphinx now uses "index" as the master document by default. ' 'To keep pre-2.0 behaviour, set "master_doc = \'contents\'".' ) ) app.config.master_doc = 'contents' return changed def deprecate_source_encoding(_app: Sphinx, config: Config) -> None: """Warn on non-UTF 8 source_encoding.""" # RemovedInSphinx10Warning if config.source_encoding.lower() not in {'utf-8', 'utf-8-sig', 'utf8'}: msg = _( 'Support for source encodings other than UTF-8 ' 'is deprecated and will be removed in Sphinx 10. ' 'Please comment at https://github.com/sphinx-doc/sphinx/issues/13665 ' 'if this causes a problem.' ) logger.warning(msg) def setup(app: Sphinx) -> ExtensionMetadata: app.connect('config-inited', deprecate_source_encoding, priority=790) app.connect('config-inited', convert_source_suffix, priority=800) app.connect('config-inited', convert_highlight_options, priority=800) app.connect('config-inited', init_numfig_format, priority=800) app.connect('config-inited', evaluate_copyright_placeholders, priority=795) app.connect('config-inited', correct_copyright_year, priority=800) app.connect('config-inited', check_confval_types, priority=800) app.connect('config-inited', check_primary_domain, priority=800) app.connect('env-get-outdated', check_master_doc) return { 'version': 'builtin', 'parallel_read_safe': True, 'parallel_write_safe': True, }
Config
python
pypa__virtualenv
tasks/make_zipapp.py
{ "start": 3473, "end": 11545 }
class ____: def __init__(self, into) -> None: if into.exists(): shutil.rmtree(into) into.mkdir(parents=True) self.into = into self.collected = defaultdict(lambda: defaultdict(dict)) self.pip_cmd = [str(Path(sys.executable).parent / "pip")] self._cmd = [*self.pip_cmd, "download", "-q", "--no-deps", "--no-cache-dir", "--dest", str(self.into)] def run(self, target, versions): whl = self.build_sdist(target) todo = deque((version, None, whl) for version in versions) wheel_store = {} while todo: version, platform, dep = todo.popleft() dep_str = dep.name.split("-")[0] if isinstance(dep, Path) else dep.name if dep_str in self.collected[version] and platform in self.collected[version][dep_str]: continue whl = self._get_wheel(dep, platform[2:] if platform and platform.startswith("==") else None, version) if whl is None: if dep_str not in wheel_store: msg = f"failed to get {dep_str}, have {wheel_store}" raise RuntimeError(msg) whl = wheel_store[dep_str] else: wheel_store[dep_str] = whl self.collected[version][dep_str][platform] = whl todo.extend(self.get_dependencies(whl, version)) def _get_wheel(self, dep, platform, version): if isinstance(dep, Requirement): before = set(self.into.iterdir()) if self._download( platform, False, # noqa: FBT003 "--python-version", version, "--only-binary", ":all:", str(dep), ): self._download(platform, True, "--python-version", version, str(dep)) # noqa: FBT003 after = set(self.into.iterdir()) new_files = after - before assert len(new_files) <= 1 # noqa: S101 if not len(new_files): return None new_file = next(iter(new_files)) if new_file.suffix == ".whl": return new_file dep = new_file new_file = self.build_sdist(dep) assert new_file.suffix == ".whl" # noqa: S101 return new_file def _download(self, platform, stop_print_on_fail, *args): exe_cmd = self._cmd + list(args) if platform is not None: exe_cmd.extend(["--platform", platform]) return run_suppress_output(exe_cmd, stop_print_on_fail=stop_print_on_fail) @staticmethod def get_dependencies(whl, version): with zipfile.ZipFile(str(whl), "r") as zip_file: name = "/".join([f"{'-'.join(whl.name.split('-')[0:2])}.dist-info", "METADATA"]) with zip_file.open(name) as file_handler: metadata = message_from_string(file_handler.read().decode("utf-8")) deps = metadata.get_all("Requires-Dist") if deps is None: return for dep in deps: req = Requirement(dep) markers = getattr(req.marker, "_markers", ()) or () if any( m for m in markers if isinstance(m, tuple) and len(m) == 3 and m[0].value == "extra" # noqa: PLR2004 ): continue py_versions = WheelDownloader._marker_at(markers, "python_version") if py_versions: marker = Marker('python_version < "1"') marker._markers = [ # noqa: SLF001 markers[ver] for ver in sorted(i for i in set(py_versions) | {i - 1 for i in py_versions} if i >= 0) ] matches_python = marker.evaluate({"python_version": version}) if not matches_python: continue deleted = 0 for ver in py_versions: deleted += WheelDownloader._del_marker_at(markers, ver - deleted) platforms = [] platform_positions = WheelDownloader._marker_at(markers, "sys_platform") deleted = 0 for pos in platform_positions: # can only be or meaningfully platform = f"{markers[pos][1].value}{markers[pos][2].value}" deleted += WheelDownloader._del_marker_at(markers, pos - deleted) platforms.append(platform) if not platforms: platforms.append(None) for platform in platforms: yield version, platform, req @staticmethod def _marker_at(markers, key): return [ i for i, m in enumerate(markers) if isinstance(m, tuple) and len(m) == 3 and m[0].value == key # noqa: PLR2004 ] @staticmethod def _del_marker_at(markers, at): del markers[at] deleted = 1 op = max(at - 1, 0) if markers and isinstance(markers[op], str): del markers[op] deleted += 1 return deleted def build_sdist(self, target): if target.is_dir(): # pip 20.1 no longer guarantees this to be parallel safe, need to copy/lock with TemporaryDirectory() as temp_folder: folder = Path(temp_folder) / target.name shutil.copytree( str(target), str(folder), ignore=shutil.ignore_patterns(".tox", ".tox4", "venv", "__pycache__", "*.pyz"), ) try: return self._build_sdist(self.into, folder) finally: # permission error on Windows <3.7 https://bugs.python.org/issue26660 def onerror(func, path, exc_info): # noqa: ARG001 os.chmod(path, S_IWUSR) func(path) shutil.rmtree(str(folder), onerror=onerror) else: return self._build_sdist(target.parent / target.stem, target) def _build_sdist(self, folder, target): if not folder.exists() or not list(folder.iterdir()): cmd = [*self.pip_cmd, "wheel", "-w", str(folder), "--no-deps", str(target), "-q"] run_suppress_output(cmd, stop_print_on_fail=True) return next(iter(folder.iterdir())) def run_suppress_output(cmd, stop_print_on_fail=False): # noqa: FBT002 process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, encoding="utf-8", ) out, err = process.communicate() if stop_print_on_fail and process.returncode != 0: print(f"exit with {process.returncode} of {' '.join(quote(i) for i in cmd)}", file=sys.stdout) # noqa: T201 if out: print(out, file=sys.stdout) # noqa: T201 if err: print(err, file=sys.stderr) # noqa: T201 raise SystemExit(process.returncode) return process.returncode def get_wheels_for_support_versions(folder): downloader = WheelDownloader(folder / "wheel-store") downloader.run(HERE.parent, VERSIONS) packages = defaultdict(lambda: defaultdict(lambda: defaultdict(WheelForVersion))) for version, collected in downloader.collected.items(): for pkg, platform_to_wheel in collected.items(): name = Requirement(pkg).name for platform, wheel in platform_to_wheel.items(): pl = platform or "==any" wheel_versions = packages[name][pl][wheel.name] wheel_versions.versions.append(version) wheel_versions.wheel = wheel for name, p_w_v in packages.items(): for platform, w_v in p_w_v.items(): print(f"{name} - {platform}") # noqa: T201 for wheel, wheel_versions in w_v.items(): print(f"{' '.join(wheel_versions.versions)} of {wheel} (use {wheel_versions.wheel})") # noqa: T201 return packages
WheelDownloader
python
PrefectHQ__prefect
src/integrations/prefect-snowflake/prefect_snowflake/credentials.py
{ "start": 1193, "end": 15050 }
class ____(CredentialsBlock): """ Block used to manage authentication with Snowflake. Args: account (str): The snowflake account name. user (str): The user name used to authenticate. password (SecretStr): The password used to authenticate. private_key (SecretStr): The PEM used to authenticate. authenticator (str): The type of authenticator to use for initializing connection (oauth, externalbrowser, etc); refer to [Snowflake documentation](https://docs.snowflake.com/en/user-guide/python-connector-api.html#connect) for details, and note that `externalbrowser` will only work in an environment where a browser is available. workload_identity_provider (str): The workload identity provider to use when authenticator is set to `workload_identity`. token (SecretStr): The OAuth or JWT Token to provide when authenticator is set to `oauth`, or workload_identity_provider is set to `oidc`. endpoint (str): The Okta endpoint to use when authenticator is set to `okta_endpoint`, e.g. `https://<okta_account_name>.okta.com`. role (str): The name of the default role to use. autocommit (bool): Whether to automatically commit. Example: Load stored Snowflake credentials: ```python from prefect_snowflake import SnowflakeCredentials snowflake_credentials_block = SnowflakeCredentials.load("BLOCK_NAME") ``` """ # noqa E501 _block_type_name = "Snowflake Credentials" _logo_url = "https://cdn.sanity.io/images/3ugk85nk/production/bd359de0b4be76c2254bd329fe3a267a1a3879c2-250x250.png" # noqa _documentation_url = "https://docs.prefect.io/integrations/prefect-snowflake" # noqa account: str = Field( ..., description="The snowflake account name.", examples=["nh12345.us-east-2.aws"], ) user: str | None = Field( default=None, description="The user name used to authenticate." ) password: SecretStr | None = Field( default=None, description="The password used to authenticate." ) private_key: SecretBytes | None = Field( default=None, description="The PEM used to authenticate." ) private_key_path: Path | None = Field( default=None, description="The path to the private key." ) private_key_passphrase: SecretStr | None = Field( default=None, description="The password to use for the private key." ) authenticator: Literal[ "snowflake", "snowflake_jwt", "externalbrowser", "okta_endpoint", "oauth", "username_password_mfa", "workload_identity", ] = Field( # noqa default="snowflake", description=("The type of authenticator to use for initializing connection."), ) workload_identity_provider: Literal["aws", "azure", "gcp", "oidc"] | None = Field( default=None, description=( "The workload identity provider to use for initializing the connection." ), ) token: SecretStr | None = Field( default=None, description=( "The OAuth or JWT Token to provide when authenticator is set to `oauth`." ), ) endpoint: str | None = Field( default=None, description=( "The Okta endpoint to use when authenticator is set to `okta_endpoint`." ), ) role: str | None = Field( default=None, description="The name of the default role to use." ) autocommit: bool | None = Field( default=None, description="Whether to automatically commit." ) @model_validator(mode="before") def _validate_auth_kwargs(cls, values): """ Ensure an authorization value has been provided by the user. """ auth_params = ( "password", "private_key", "private_key_path", "authenticator", "token", "workload_identity_provider", ) if not any(values.get(param) for param in auth_params): auth_str = ", ".join(auth_params) raise ValueError( f"One of the authentication keys must be provided: {auth_str}\n" ) elif values.get("private_key") and values.get("private_key_path"): raise ValueError( "Do not provide both private_key and private_key_path; select one." ) elif values.get("password") and values.get("private_key_passphrase"): raise ValueError( "Do not provide both password and private_key_passphrase; " "specify private_key_passphrase only instead." ) return values @model_validator(mode="before") def _validate_token_kwargs(cls, values): """ Ensure an authorization value has been provided by the user. """ authenticator = values.get("authenticator") token = values.get("token") if authenticator == "oauth" and not token: raise ValueError( "If authenticator is set to `oauth`, `token` must be provided" ) return values @model_validator(mode="before") def _validate_okta_kwargs(cls, values): """ Ensure an authorization value has been provided by the user. """ authenticator = values.get("authenticator") # did not want to make a breaking change so we will allow both # see https://github.com/PrefectHQ/prefect-snowflake/issues/44 if "okta_endpoint" in values.keys(): warnings.warn( "Please specify `endpoint` instead of `okta_endpoint`; " "`okta_endpoint` will be removed March 31, 2023.", DeprecationWarning, stacklevel=2, ) # remove okta endpoint from fields okta_endpoint = values.pop("okta_endpoint") if "endpoint" not in values.keys(): values["endpoint"] = okta_endpoint endpoint = values.get("endpoint") if authenticator == "okta_endpoint" and not endpoint: raise ValueError( "If authenticator is set to `okta_endpoint`, " "`endpoint` must be provided" ) return values @model_validator(mode="before") def _validate_workload_identity_kwargs(cls, values): """ Ensure a workload identity provider value has been provided by the user. """ authenticator = values.get("authenticator") workload_identity_provider = values.get("workload_identity_provider") if authenticator == "workload_identity" and not workload_identity_provider: raise ValueError( "If authenticator is set to `workload_identity`, " "`workload_identity_provider` must be provided" ) token = values.get("token") if ( authenticator == "workload_identity" and workload_identity_provider == "oidc" and not token ): raise ValueError( "If workload_identity_provider is set to `oidc`, `token` must be " "provided" ) return values @model_validator(mode="before") def _validate_user_kwargs(cls, values): """ Ensure a user value is provided for all authenticators except `workload_identity`. """ authenticator = values.get("authenticator") if authenticator != "workload_identity" and not values.get("user"): raise ValueError( f"If authenticator is set to `{authenticator}`, `user` must be provided" ) return values def resolve_private_key(self) -> bytes | None: """ Converts a PEM encoded private key into a DER binary key. Returns: DER encoded key if private_key has been provided otherwise returns None. Raises: InvalidPemFormat: If private key is not in PEM format. """ if self.private_key_path is None and self.private_key is None: return None elif self.private_key_path: private_key = self.private_key_path.read_bytes() else: private_key = self._decode_secret(self.private_key) if self.private_key_passphrase is not None: password = self._decode_secret(self.private_key_passphrase) elif self.password is not None: warnings.warn( "Using the password field for private_key is deprecated " "and will not work after March 31, 2023; please use " "private_key_passphrase instead", DeprecationWarning, stacklevel=2, ) password = self._decode_secret(self.password) else: password = None composed_private_key = self._compose_pem(private_key) return load_pem_private_key( data=composed_private_key, password=password, backend=default_backend(), ).private_bytes( encoding=Encoding.DER, format=PrivateFormat.PKCS8, encryption_algorithm=NoEncryption(), ) @staticmethod def _decode_secret(secret: SecretStr | SecretBytes) -> bytes | None: """ Decode the provided secret into bytes. If the secret is not a string or bytes, or it is whitespace, then return None. Args: secret: The value to decode. Returns: The decoded secret as bytes or None. """ if isinstance(secret, (SecretStr, SecretBytes)): secret = secret.get_secret_value() if not isinstance(secret, (bytes, str)) or len(secret) == 0 or secret.isspace(): return None return secret if isinstance(secret, bytes) else secret.encode() @staticmethod def _compose_pem(private_key: bytes) -> bytes: """Validate structure of PEM certificate. The original key passed from Prefect is sometimes malformed. This function recomposes the key into a valid key that will pass the serialization step when resolving the key to a DER. Args: private_key: A valid PEM format byte encoded string. Returns: byte encoded certificate. Raises: InvalidPemFormat: if private key is an invalid format. """ try: decoded_key = private_key.decode() except UnicodeDecodeError as e: raise InvalidPemFormat("Key could not be decoded.") from e # Strip leading/trailing whitespace from decoded key before matching pem_parts = re.match(_SIMPLE_PEM_CERTIFICATE_REGEX, decoded_key.strip()) if pem_parts is None: raise InvalidPemFormat() try: # Simplify body handling: Just strip leading/trailing whitespace body = pem_parts[2].strip() result = f"{pem_parts[1]}\n{body}\n{pem_parts[3]}".encode() return result except Exception: raise def get_client( self, **connect_kwargs: Any ) -> snowflake.connector.SnowflakeConnection: """ Returns an authenticated connection that can be used to query Snowflake databases. Any additional arguments passed to this method will be used to configure the SnowflakeConnection. For available parameters, please refer to the [Snowflake Python connector documentation](https://docs.snowflake.com/en/user-guide/python-connector-api.html#connect). Args: **connect_kwargs: Additional arguments to pass to `snowflake.connector.connect`. Returns: An authenticated Snowflake connection. Example: Get Snowflake connection with only block configuration: ```python from prefect_snowflake import SnowflakeCredentials snowflake_credentials_block = SnowflakeCredentials.load("BLOCK_NAME") connection = snowflake_credentials_block.get_client() ``` Get Snowflake connector scoped to a specified database: ```python from prefect_snowflake import SnowflakeCredentials snowflake_credentials_block = SnowflakeCredentials.load("BLOCK_NAME") connection = snowflake_credentials_block.get_client(database="my_database") ``` """ # noqa connect_params = { # required to track task's usage in the Snowflake Partner Network Portal "application": "Prefect_Snowflake_Collection", **self.model_dump(exclude_unset=True, exclude={"block_type_slug"}), **connect_kwargs, } for key, value in connect_params.items(): if isinstance(value, (SecretStr, SecretBytes)): connect_params[key] = connect_params[key].get_secret_value() # set authenticator to the actual okta_endpoint if connect_params.get("authenticator") == "okta_endpoint": endpoint = connect_params.pop("endpoint", None) or connect_params.pop( "okta_endpoint", None ) # okta_endpoint is deprecated connect_params["authenticator"] = endpoint private_der_key = self.resolve_private_key() if private_der_key is not None: connect_params["private_key"] = private_der_key connect_params.pop("password", None) connect_params.pop("private_key_passphrase", None) return snowflake.connector.connect(**connect_params)
SnowflakeCredentials
python
pytorch__pytorch
torch/_inductor/codegen/triton.py
{ "start": 79143, "end": 220892 }
class ____(SIMDKernel[TritonCSEVariable]): """A class to represent a triton kernel and helpers to generate triton kernel programmatically """ overrides = TritonKernelOverrides # type: ignore[assignment] helper_functions: HelperFunctions kexpr: Callable[[sympy.Expr], str] = texpr allow_block_ptr = True tma_compatibility_checker_cls = TMACompatibilityChecker def __init__( self, tiling: dict[str, sympy.Expr], min_elem_per_thread=0, optimize_mask=True, fixed_config: Optional[FixedTritonConfig] = None, hint_override: Optional[int] = None, **kwargs, ) -> None: self.optimize_mask: bool = optimize_mask self.fixed_config = fixed_config super().__init__(tiling, **kwargs) self.cse = TritonCSE(self.newvar_prefix, self.suffix) # Cache of values that can be reused for the prologue. self.prologue_cache: dict[str, str] = {} self.prologue: IndentedBuffer = IndentedBuffer() self.post_loop_combine: IndentedBuffer = IndentedBuffer() self.post_loop_store: IndentedBuffer = IndentedBuffer() self.outside_loop_vars = OrderedSet[Any]() self.min_elem_per_thread = min_elem_per_thread self.block_ptr_id = itertools.count() self.block_ptr_to_buffer = dict[str, str]() self.helper_functions = HelperFunctions() self.pointer_advancements: dict[SymT, dict[str, list[sympy.Expr]]] = ( collections.defaultdict(dict) ) self.tma_min_block_sizes = dict[str, int]() self.hint_override = hint_override self._load_counts: collections.Counter[str] = collections.Counter() self._load_index = 0 # A set of autotuning hints to pass as part of triton_meta self.autotune_hints = OrderedSet[AutotuneHint]() self.triton_meta: Optional[dict[str, Any]] = None if self.inside_reduction: self.codegen_reduction_numels(self.body) if self.cooperative_reduction: self.init_cooperative_reduction() self.codegen_range_tree() if self.cooperative_reduction: self.init_cooperative_reduction_mask() self.has_load_with_contiguous_rdim = False # We track the store name since a store can be canceled later self.stores_with_contiguous_rdim: list[str] = [] @staticmethod def _has_stride1_on_rdim(index) -> bool: # These analysis is only needed in deterministic mode so far # to filter triton configs. Return false immediately to avoid # increasing compilation time when the mode is off. if not ( config.deterministic or config.test_configs.force_filter_reduction_configs ): return False support_vars = index.free_symbols reduce_vars = [ var for var in support_vars if symbol_is_type(var, TritonSymbols.reduction_types) ] if len(reduce_vars) == 0: return False # for expression "x0 + 150528*((x1//(s27*s38))) + 3*(ModularIndexing(x1, 1, s38)) + 672*(ModularIndexing(x1, s38, s27))" # stride_vars will results in DivisionByZero error try: stride_vars = V.graph.sizevars.stride_vars(index, reduce_vars, support_vars) except ZeroDivisionError: return False return any(stride == 1 for stride in stride_vars) @property def has_store_with_contiguous_rdim(self) -> bool: return not all( is_buffer_removed(name) for name in self.stores_with_contiguous_rdim ) def dtype_to_str(self, dtype: torch.dtype) -> str: return triton_type(dtype) def should_use_cooperative_reduction(self) -> bool: return self.inside_reduction and V.choices.should_use_cooperative_reduction( self.features ) def init_cooperative_reduction(self): """One time setup code for cooperative reductions.""" assert self.cooperative_reduction # shift all the grids over since tl.program_id(0) is for rsplit for tree in self.range_trees: if tree.grid_dim is not None: tree.grid_dim += 1 sem_count = self.numels["x"] if self.fixed_config: sem_count = CeilDiv(sem_count, self.fixed_config["XBLOCK"]) self.semaphores_name = self.args.semaphores(sem_count) self.cooperative_reduction_workspace_cache = CooperativeReductionWorkspaceCache( self.args ) self.body.splice( """\ RSPLIT_NEXT_POWER_OF_2: tl.constexpr = triton_helpers.constexpr_next_power_of_2(RSPLIT) RSPLIT_IS_POWER_OF_2: tl.constexpr = RSPLIT == RSPLIT_NEXT_POWER_OF_2 HAS_RSPLIT: tl.constexpr = RSPLIT > 1 rsplit_id = tl.program_id(0) num_rblocks = (rnumel + RBLOCK - 1) // RBLOCK rsplit_chunk = (num_rblocks + RSPLIT - 1) // RSPLIT * RBLOCK rsplit_start = rsplit_chunk * rsplit_id rsplit_end = rsplit_chunk * (rsplit_id + 1) """, ) if any( not self._has_constant_mask(tree) for tree in self.range_trees if tree.is_reduction ): self.body.writeline( "rsplit_end = tl.where(rsplit_end < rnumel, rsplit_end, rnumel)" ) def init_cooperative_reduction_mask(self): rsplit_arange = "tl.arange(0, RSPLIT_NEXT_POWER_OF_2)" if not self.no_x_dim: rsplit_arange = f"{rsplit_arange}[None, :]" self.body.writeline(f"rsplit_arange = {rsplit_arange}") if self._has_constant_xmask(): self.body.splice( """\ if RSPLIT_IS_POWER_OF_2: rsplit_mask: tl.constexpr = None else: rsplit_mask = rsplit_arange < RSPLIT """ ) else: assert not self.no_x_dim self.body.writeline( "rsplit_mask = xmask if RSPLIT_IS_POWER_OF_2 else ((rsplit_arange < RSPLIT) & xmask)" ) def codegen_range_tree(self): for tree in self.range_trees: # reduction indexing goes inside a loop if not tree.is_loop: self.iteration_ranges_codegen_header(tree, self.body) elif self.inside_reduction: # workaround for this issue: # https://gist.github.com/jansel/6527126f781559095c5531f98a4235a7 self.body.writeline( f"{tree.prefix}base = {self.iteration_ranges_ranges_code(tree)}" ) if self.inside_reduction: if any(tree.is_loop for tree in self.range_trees): # If the kernel contains loops, compute rbase. rn_bases = self._get_reduction_symbols( "base", integer=True, nonnegative=True ) rbase = self._flatten_reduction_indices(rn_bases) self.body.splice(f"rbase = {self.index_to_str(rbase)}") else: # For looped reductions, indexing is deferred to the innermost loop. self.codegen_reduction_indices(self.body) def need_numel_args(self): """ Indicate whether we need provide numel as arguments for the generated kernel calls in the benchmark. Should be true for pointwise/reduction kernels but false for triton matmul kernels. """ return True def should_use_persistent_reduction(self) -> bool: return self.inside_reduction and V.choices.should_use_persistent_reduction( self.features, self.cooperative_reduction ) def want_no_x_dim(self): return ( self.persistent_reduction and len(self.numels) == self.num_reduction_dims + 1 and self.fixed_config and self.fixed_config["XBLOCK"] == 1 ) @property def assert_function(self) -> str: return "tl.device_assert" def indexing( self, index: sympy.Expr, *, copy_shape: Optional[Union[str, tuple[str]]] = None, dense_indexing=False, override_mask=None, block_ptr=False, tma_compatibility_checker: Optional[TMACompatibilityChecker] = None, ): """ Compute the index and mask to pass to tl.load() or tl.store() """ index = self.prepare_indexing(index) index_vars = index.free_symbols has_rindex = False mask_vars: OrderedSet[str] = OrderedSet() for var in sorted(index_vars, key=operator.attrgetter("name")): assert isinstance(var, sympy.Symbol) has_rindex = has_rindex or symbol_is_type( var, TritonSymbols.reduction_types ) if override_mask: pass elif symbol_is_type(var, SymT.TMP): # indirect indexing cse_var = self.cse.varname_map[var.name] mask_vars.update(cse_var.mask_vars) elif symbol_is_type( var, ( SymT.UNBACKED_INT, SymT.SIZE, SymT.PRECOMPUTED_SIZE, SymT.INDEX, SymT.FLOAT, SymT.UNBACKED_FLOAT, ), ): pass else: # var is one of xN, yN, r0_N or r1_N prefix_matches = [ prefix_str[symt] for symt in TritonSymbols.block_types if symbol_is_type(var, symt) ] if len(prefix_matches) == 0: pass assert len(prefix_matches) == 1, f"Ambiguous type: {var.name}" mask_vars.add(f"{prefix_matches[0]}mask") need_dense = ( config.triton.dense_indexing or dense_indexing or self._load_mask is not None ) and index != 0 have_dense = True have_loop_vars = False dense_mask_vars: OrderedSet[str] = OrderedSet() for tree in self.active_range_trees(): if index_vars.intersection(tree.var_list): have_loop_vars = True else: have_dense = False dense_mask_vars.add(f"{tree.prefix}mask") if ( ( (block_ptr and self.allow_block_ptr and config.triton.use_block_ptr) or ( tma_compatibility_checker and tma_compatibility_checker.can_use_tma() ) ) and not override_mask and not self._load_mask and len(mask_vars - dense_mask_vars) == 0 and not self.is_indirect_indexing(index) and have_loop_vars # workaround https://github.com/triton-lang/triton/issues/2821 and self.index_dtype == "tl.int32" ): def match_affine_block( index: sympy.Expr, range_tree: IterationRangesRoot ) -> Optional[BlockParameters]: """ Matches expressions of the form: idx = s * xindex This implies stride (s,), and shape (XBLOCK,). """ stride = BlockPatternMatcher.match_affine_block_expr( index, range_tree.symbol() ) if stride is None: return None return BlockParameters( shape=[range_tree.numel], block_shape=[TritonSymbols.get_block_size(range_tree)], strides=[stride], offsets=[TritonSymbols.get_block_offset(range_tree)], ) def match_mod_div_block( index: sympy.Expr, range_tree: IterationRangesRoot ) -> Optional[BlockParameters]: """ Matches higher-dimensional blocks coming from FloorDiv and ModularIndexing. Example expression to match: sN * ((rindex//(d1 * ... * d(N-1)))) + s1 * ModularIndexing(rindex, 1, d1) + ... + s(N-1) * ModularIndexing(rindex, d1 * ... * d(N-2), d(N-1)) This iterates over a block of shape (dN, ..., d1) and stride (sN, ..., s1). (d1,...,d(N-1)) and (s1,...,sN) are wildcards that we match. Note that dN does not appear in the expression, but we solve for it using range tree numels and the other dims. """ index_var = range_tree.symbol() # Bound the possible number of dims. We use the following heuristics: # - At least one dim for each range tree node. # - At least one dim for every FloorDiv or ModularIndexing op. # - At least 2 dims to pattern match. denom, modulo = sympy.symbols( "denom modulo", cls=functools.partial(sympy.Wild, exclude=[index_var]), ) num_dims = max( 2, # range_tree.nodes only includes the entries for the range tree # len(range_tree.nodes) <= self.range_tree_nodes len(range_tree.nodes), ( index.count(FloorDiv(index_var, denom)) + index.count(ModularIndexing(index_var, denom, modulo)) ), ) match_result = BlockPatternMatcher.match_mod_div_block_expr( index, index_var, range_tree.numel, num_dims ) if match_result is None: return None ( dims, strides, block_index_exprs, ) = match_result slice_numels = BlockPatternMatcher.get_slice_numels(dims) # Check for applicable iteration range sizes. # When mapping a 1D block into an ND one, we need to know that # the number of elements is not changed. This means the slice numels of # the ND iteration range must evenly divide the length of the 1D block. # There are two cases where we can guarantee this: # 1. Numels are powers of 2. If numel == 2 ** n, and we know XBLOCK == 2 ** m, # with n and m integers, then either numel is a multiple of XBLOCK, or numel # is less than XBLOCK. (If numel is less than XBLOCK, we round up to 1 below.) # 2. Numels are multiples of the maximum possible block size. sizevars = V.graph.sizevars max_block = self.max_block(range_tree.prefix) if any( not sizevars.statically_known_multiple_of(numel, max_block) and not sizevars.statically_known_power_of_2(numel) for numel in slice_numels ): return None # Compute the ND block shape from the linear block size. # Use CielDiv to round leading dimensions up to 1. # Non-leading dimensions are clamped to the size of the iteration range, # while the leading dimension can exceed this to accommodate a larger # block size. linear_block_size = TritonSymbols.get_block_size(range_tree) block_shape: list[sympy.Expr] = [ CeilDiv(linear_block_size, slice_numels[0]) ] + [ sympy.Min(CeilDiv(linear_block_size, numel), dim) for numel, dim in zip(slice_numels[1:], dims[1:]) ] # Compute block offsets from {xyzr}offset and the matched expressions. block_offsets: list[sympy.Expr] = [ sympy_subs( expr, {index_var: TritonSymbols.get_block_offset(range_tree)} ) for expr in block_index_exprs ] return BlockParameters( shape=dims, block_shape=block_shape, strides=strides, offsets=block_offsets, ) def match_block_subexpr( expr: sympy.Expr, range_tree: IterationRangesRoot ) -> Optional[BlockParameters]: """ Match a block indexing subexpression involving a single range tree. """ for match_func in ( match_affine_block, match_mod_div_block, ): match = match_func(expr, range_tree) if match is not None: return match return None def match_block_expr() -> Optional[BlockDescriptorOptions]: index_relative_to_xyr_index = sympy_subs( index, {v: t.expr for v, t in self.range_tree_nodes.items()} ) range_trees = self.active_range_trees() # Partition the index into subexpressions pertaining to each range tree. # For example xindex * 5 + r0_index * 3 is partitioned to # (xindex * 5, r0_index * 3). index_subexprs = [ BlockPatternMatcher.get_subexpr_involving_symbol( index_relative_to_xyr_index, tree.symbol() ) for tree in range_trees ] # Match each range tree's subexpression separately. range_symbols = OrderedSet(tree.symbol() for tree in range_trees) block_params = BlockParameters() for tree, subexpr in zip(range_trees, index_subexprs): # Reject mixed terms, e.g. xindex * r0_index. # NB: the zero expression is allowed, for broadcasting. if len(range_symbols.intersection(subexpr.free_symbols)) > 1: return None # Match the subexpression for this range tree. params = match_block_subexpr(subexpr, tree) if params is None: return None block_params += params # Collect leftover terms as a constant offset. offset = index_relative_to_xyr_index - sum(index_subexprs) # Form the block pointer or TMA descriptor. self.filter_masks(mask_vars) options_class = ( BlockPtrOptions if config.triton.use_block_ptr else TensorDescriptorOptions ) nonlocal tma_compatibility_checker if config.triton.use_block_ptr: can_lift = False transpose_contiguous = False else: tma_compatibility_checker = cast( TMACompatibilityChecker, tma_compatibility_checker ) can_lift = tma_compatibility_checker.can_lift() # Only try transpose if we know the output shape # in case we need to transpose the data. transpose_contiguous = copy_shape is not None options = options_class.create( params=block_params, constant_offset=offset, range_trees=range_trees, mask_vars=mask_vars, get_max_block=self.max_block, can_lift=can_lift, transpose_contiguous=transpose_contiguous, ) if options_class == TensorDescriptorOptions: tma_compatibility_checker = cast( TMACompatibilityChecker, tma_compatibility_checker ) if not tma_compatibility_checker.are_block_parameters_compatible( options.params ): return None return options # Return a block pointer, if indexing matches the pattern. options = match_block_expr() if options is not None: return options expand_str = None expand_shape: BlockShapeType = None index_str = self.index_to_str(index) def _get_expand_str(): if copy_shape: if isinstance(copy_shape, str): return f"{copy_shape}.shape", None else: return "[" + ", ".join(str(c) for c in copy_shape) + "]", copy_shape else: return self.dense_size_str(), tuple(self.dense_size_list()) if is_sympy_integer_like(index): # Integer indexing produces a size-1 scalar tensor with the same shape # as the dense dimension. E.g, if dense_size = [YBLOCK, XBLOCK, R0_BLOCK], # then we create tl.full([1, 1, 1], int). # # Exceptions: # 1. If copy_shape is explicitly provided, use copy_shape expansion instead. # 2. If the dense tensor has only one dimension (e.g., [XBLOCK]), # broadcasting does not apply. For example: # tl.arange(0, XBLOCK) + tl.full([1], int) # -> broadcasting error # In this case, we fall back to dense indexing: # tl.full([XBLOCK], int) if copy_shape or len(self.dense_size_list()) == 1: expand_str, expand_shape = _get_expand_str() else: expand_str = str([1] * len(self.dense_size_list())) expand_shape = tuple([1] * len(self.dense_size_list())) index_str = f"tl.full({expand_str}, {index_str}, tl.int32)" if self.fixed_config and not self._has_constant_xmask(): mask_vars = OrderedSet(["xmask"]) else: mask_vars = OrderedSet() if self._load_mask: mask_vars.add(self._load_mask) return IndexingOptions( index_str, mask_vars, expand_str, has_rindex, index, expand_shape=expand_shape, ) if need_dense and not have_dense: if self.inside_reduction and self.is_native_matmul: # This avoids full broadcasting (need_dense) when performing native matmul. # For example, self._load_mask previously required tl.broadcast_to() in index_str. # Due to the restrictions of tl.dot semantics, we only want to expand the block # shape for the necessary axes. # # Previously: # tmp1 = tl.load(ptr + tl.broadcast_to(r0, [YBLOCK, XBLOCK, R0_BLOCK]), # r0_mask & tmp0 & xmask) # # Now: # tmp1 = tl.load(ptr + tl.broadcast_to(r0, [1, 1, R0_BLOCK]), # r0_mask & tmp0 & xmask) # # We achieve this by determining the required block shape through mask inspection. # When a temporary variable appears in the mask (e.g., self._load_mask), we retrieve # its true shape by inspecting tmp.mask_vars tracked by TritonCSEVariable. # # Caution: it may miss the correct block shape if the specific mask was constant # and thus not tracked in TritonCSEVariable.mask_vars. # # TODO: Once the shape propagation PR lands, reimplement this logic: # https://github.com/pytorch/pytorch/pull/152198 mask_shape = mask_vars.copy() if self._load_mask: mask_shape.add(self._load_mask) xyzr = OrderedSet(["xmask", "ymask", "zmask", "r0_mask"]) while not mask_shape.issubset(xyzr): tmp_masks = mask_shape.difference(xyzr) tmp = tmp_masks.pop() assert isinstance(tmp, TritonCSEVariable) mask_shape.discard(tmp) mask_shape.update(tmp.mask_vars) # e.g., expand_list becomes ['ZBLOCK', 1, 1, 'R0_BLOCK'] expand_list = ["1"] * len(self.dense_size_list()) for mask in mask_shape: assert isinstance(mask, str) for tree in self.active_range_trees(): if mask.startswith(tree.prefix): dim = tree.tensor_dim assert isinstance(dim, int) expand_list[dim] = self.dense_size_list()[dim] expand_str = "[" + ",".join(map(str, expand_list)) + "]" expand_shape = tuple(expand_list) index_str = f"tl.broadcast_to({index_str}, {expand_str})" else: expand_str, expand_shape = _get_expand_str() index_str = f"tl.broadcast_to({index_str}, {expand_str})" mask_vars = dense_mask_vars elif not have_loop_vars and copy_shape: expand_shape_str, expand_shape = _get_expand_str() index_str = f"tl.broadcast_to({index_str}, {expand_shape_str})" mask_vars = dense_mask_vars if expand_shape is None: if need_dense or have_dense: _, expand_shape = _get_expand_str() else: expand_shape = () if override_mask: mask_vars = OrderedSet([override_mask]) if self._load_mask: mask_vars.add(self._load_mask) self.filter_masks(mask_vars) return IndexingOptions( index_str, mask_vars, expand_str, has_rindex, index, expand_shape=expand_shape, ) def codegen_block_ptr( self, name: str, var: str, indexing: Union[BlockPtrOptions, TensorDescriptorOptions], other="", ) -> tuple[str, str]: """Generate a block pointer or tensor descriptor for Triton kernel operations. This method creates either a block pointer (for regular Triton operations) or a tensor descriptor (for TMA operations) based on the indexing type. It handles caching and reuse of descriptors for performance optimization. Args: name: The name of the buffer/tensor being accessed var: The variable name for the pointer indexing: Block pointer options or tensor descriptor options containing indexing information and boundary check settings other: Additional parameters string (e.g., padding options) Returns: A tuple containing: - block_descriptor: The generated block pointer or tensor descriptor variable name - other: Modified additional parameters string with boundary check options """ check = indexing.boundary_check() if isinstance(indexing, TensorDescriptorOptions): if check and other: # The TMA API currently does not support padding values # but the default is zero assert other == ", other=0.0" other = "" else: if not check: # workaround https://github.com/triton-lang/triton/issues/2813 other = "" elif other: assert other == ", other=0.0" other = f", boundary_check={check!r}, padding_option='zero'" else: other = f", boundary_check={check!r}" if ( self.inside_reduction and self.range_trees[-1].is_loop and indexing.has_rindex() ) or indexing.can_lift: if indexing.can_lift and var in self.prologue_cache: # Check for epilogue subtiling to reuse the same # tensor descriptor. block_descriptor = self.prologue_cache[var] else: block_ptr_line = indexing.format(var, roffset=False) block_var = self.cse.try_get(block_ptr_line) # Early return if block descriptor already exists if block_var: return str(block_var), other block_descriptor_id = next(self.block_ptr_id) if isinstance(indexing, BlockPtrOptions): block_descriptor = f"block_ptr{block_descriptor_id}" else: block_descriptor = f"tma_descriptor{block_descriptor_id}" named_var = self.cse.namedvar( block_descriptor, dtype=torch.uint64, shape=[] ) self.cse.put(block_ptr_line, named_var) line_body = DeferredLine(name, f"{block_descriptor} = {block_ptr_line}") if indexing.can_lift: self.prologue.writeline(line_body) # Cache the descriptor for epilogue subtiling self.prologue_cache[var] = block_descriptor else: self.body.writeline(line_body) if isinstance(indexing, BlockPtrOptions): # Store for later use. If the buffer is removed the below advancements # are no longer necessary self.block_ptr_to_buffer[block_descriptor] = name # Generate block pointer advancements, for later use. for symt in TritonSymbols.reduction_types: advance_offsets = indexing.advance_roffset(symt) # Ignore identity advancements. if all( V.graph.sizevars.statically_known_equals( offset, sympy.Integer(0) ) for offset in advance_offsets ): continue advancements = self.pointer_advancements[symt] assert block_descriptor not in advancements, ( f"duplicate advancement for pointer '{block_descriptor}' at type '{symt}'" ) advancements[block_descriptor] = advance_offsets else: block_descriptor = indexing.format(var) return block_descriptor, other def codegen_block_ptr_store_line(self, name, indexing, block_ptr, value, other=""): def stringify_shape(shape): return tuple( symt.name if isinstance(symt, sympy.Symbol) else str(symt) for symt in shape ) if value.shape: value_forward_shape = stringify_shape(value.shape) value_reverse_shape = stringify_shape(value.shape[::-1]) else: value_forward_shape = None value_reverse_shape = None final_shape = stringify_shape(indexing.final_shape) # TODO: Generalize to N Dimensions if ( value_forward_shape != final_shape and value_reverse_shape == final_shape and len(final_shape) == 2 ): # TMA stores may require transposing the data to ensure we are contiguous along # the final dimension. This applies to Block-pointers generally, but should only practically # be reached with TMA. value = f"tl.trans({value})" # Stores require an explicit broadcast. We do this in two phases: # 1. Broadcast the operand to the final shape of the range trees, e.g. [ZBLOCK, # YBLOCK, XBLOCK]. This protects against implicit broadcasting from loads. # 2. In case the block pointer / tma descriptor has different dimensionality, broadcast/reshape the # result to the shape of the pointer. value = f"tl.broadcast_to({value}, {indexing.final_shape})" # These dims no longer need broadcasting. for idx, (dim, broadcast_dim) in enumerate( zip(indexing.final_shape, indexing.broadcast_shape) ): if V.graph.sizevars.statically_known_equals(dim, broadcast_dim): indexing.broadcasting_dims[idx] = False value = indexing.codegen_broadcast_and_reshape( value, indexing.final_shape, indexing.block_shape, False ) # workaround https://github.com/triton-lang/triton/issues/2814 value = f"{value}.to({triton_store_type(V.graph.get_dtype(name))})" if isinstance(indexing, BlockPtrOptions): return f"tl.store({block_ptr}, {value}{other})" return f"{block_ptr}.store({V.kernel.index_to_str(indexing.offsets)}, {value})" def check_bounds( self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool, ): if not (lower or upper): return assert isinstance(expr, sympy.Expr) indexing = self.indexing(expr, block_ptr=False, tma_compatibility_checker=None) assert isinstance(indexing, IndexingOptions) index_str = indexing.index_str mask_str = indexing.mask_str if indexing.has_mask() else None size_str = texpr(self.rename_indexing(size)) if upper else None # expr is already wrapped line = self.indirect_assert( index_str, "0" if lower else None, size_str, mask_str ) buffer = self.get_load_buffer(indexing) self.cse.generate(buffer, line, assignment=False, dtype=torch.int32) def get_load_buffer(self, indexing): if indexing.has_indirect() or indexing.has_tmpmask(): # Masked loads must come after the mask is computed return self.compute elif ( self.inside_reduction and self.range_trees[-1].is_loop and not indexing.has_rindex() ): # can lift a common load outside of reduction loop # One exception is when this is an indirect_load. return self.body else: return self.loads def _handle_pdl_before_load(self, wait_buffer): GDC_WAIT = "tl.extra.cuda.gdc_wait()" self._load_index += 1 if self.inside_reduction: wait_buffer = self.body if enable_pdl_codegen(): if self._load_index == 1: wait_buffer.writeline(GDC_WAIT) def _handle_pdl_after_load(self, launch_buffer, result_var): GDC_LAUNCH = "tl.extra.cuda.gdc_launch_dependents()" if self.inside_reduction: launch_buffer = self.post_loop_combine if enable_pdl_codegen(): current_load_index = self._load_index launch_if_last_load = DelayMaybeLine( lambda: current_load_index == self._load_index, f"0; {GDC_LAUNCH} # gdc launch for {result_var}", ) self.cse.generate(launch_buffer, launch_if_last_load, dtype=torch.int32) def partial_accumulate( self, name: str, reduction_type, val, extra_meta: dict[str, Any] ): self.saved_partial_accumulate.append( PartialAccumulate(name, reduction_type, val) ) def load(self, name: str, index: sympy.Expr): """ Load from the memory location 'name', offset by some indexing expression 'index'. """ var = self.args.input(name) load_counts = self._load_counts load_counts[name] += 1 make_line: Callable[[str], Union[str, DelayReplaceLine]] = identity indirect_indexing = self.is_indirect_indexing(index) original_index = index dtype = V.graph.get_dtype(name) indexing = self.indexing( index, block_ptr=True, tma_compatibility_checker=self.tma_compatibility_checker_cls( self, dtype, for_store=False, force=False, ), ) if isinstance(indexing, IndexingOptions) and self._has_stride1_on_rdim( indexing.index ): self.has_load_with_contiguous_rdim = True has_rindex = indexing.has_rindex() has_tmpmask = indexing.has_tmpmask() # Keep the variable in cache if were going to reuse it. Equiv., if any of the following hold # 1) We are doing broadcasting # 2) It is a non-coalesced load. The intuition is that if it's # non-coalesced, we will likely load each element multiple times in # practice. # 3) It will be used later and it won't be CSE'd. Equiv., if all the following hold # 3.1) We are in a reduction loop # 3.2) Its not its last use # 3.3) This load will not be lifted to the body # is_coalesced = any( i == 1 for i in self.get_strides_of_load(original_index).values() ) if self.is_broadcasted(original_index): ep = ", eviction_policy='evict_last'" elif not is_coalesced: ep = ", eviction_policy='evict_last'" elif self.inside_reduction and self.range_trees[-1].is_loop: def decide_later(): if load_counts[name] > expected_count and ( has_rindex or indirect_indexing ): return "evict_last" return "evict_first" expected_count = load_counts[name] ep = ", eviction_policy='<EP>'" make_line = functools.partial(DelayReplaceLine, "<EP>", decide_later) else: ep = "" if (has_tmpmask or has_rindex) and indexing.has_mask(): if self._load_other: other = f", other={constant_repr(self._load_other)}" else: other = ", other=0.0" else: other = "" """Check if the buffer we're about to load, has more than one read dependency NOTE: enabled with env variable TORCHINDUCTOR_SKIP_L1 """ has_read_deps = True if config.triton.skip_l1_cache: buffer_read_counts = self.features.buffer_read_counts() has_read_deps = buffer_read_counts[name] > 1 """Skip L1 cache if we're (pretty?) sure the data is used only once """ skip_l1_cache = ( not self.is_broadcasted(original_index) and not self.inside_reduction and not has_read_deps and is_coalesced # for indirect loads is_coalesced is False? ) cachemod = "" if skip_l1_cache: cachemod = ", cache_modifier='.cg'" append_broadcast = None shape: BlockShapeType = None if should_unwrap_unspec_arg(name): line = var # unwrapped bf16/fp16 0d tensors are passed in as float32 scalars # see triton_utils.py:signature_of if dtype in (torch.float16, torch.bfloat16): if config.triton.codegen_upcast_to_fp32: dtype = torch.float32 else: line += f".to({triton_type(dtype)})" shape = () else: if isinstance(indexing, (BlockPtrOptions, TensorDescriptorOptions)): block_descriptor, other = self.codegen_block_ptr( name, var, indexing, other ) if isinstance(indexing, BlockPtrOptions): line = f"tl.load({block_descriptor}{other}{ep}{cachemod})" else: line = f"{block_descriptor}.load({V.kernel.index_to_str(indexing.offsets)})" line = indexing.codegen_broadcast_and_reshape( line, indexing.block_shape, indexing.final_shape, True ) shape = indexing.final_shape elif is_sympy_integer_like(original_index): line = f"tl.load({var} + ({original_index}))" append_broadcast = indexing.expand_str shape = () else: line = f"tl.load({var} + ({indexing.index_str}), {indexing.mask_str}{ep}{other}{cachemod})" # The block shape of tl.load depends on the indexing expression. # Inferring shape solely from the mask may miss cases where the mask is constant. # Inferring from indexing.expand_shape alone may also fail when dense indexing is absent. # so, iterate over variables in the indexexpr to accurately infer the block shape. if indexing.expand_shape: shape = indexing.expand_shape else: shape = TritonSymbols.get_block_shape(indexing.index) if ( dtype in (torch.float16, torch.bfloat16) and config.triton.codegen_upcast_to_fp32 ): line += ".to(tl.float32)" dtype = torch.float32 if dtype == torch.bool and torch.version.hip is None: # Workaround for https://github.com/triton-lang/triton/issues/2151 # tl.load returns int8 when loading from pointer to int1 # NOTE: Currently causes hangs on bool UTs for ROCm line += ".to(tl.int1)" dtype = torch.bool load_buffer = self.get_load_buffer(indexing) self._handle_pdl_before_load(load_buffer) result_var = self.cse.generate( load_buffer, make_line(line), dtype=dtype, shape=shape ) self._handle_pdl_after_load(load_buffer, result_var) if result_var.use_count > 1: load_counts[name] -= 1 # don't double count cache hit assert isinstance(result_var, TritonCSEVariable) result_var.mask_vars = indexing.mask_vars # type: ignore[assignment] if append_broadcast: line = f"tl.broadcast_to({result_var}, {append_broadcast})" result_var = self.cse.generate( load_buffer, line, dtype=dtype, shape=indexing.expand_shape ) if indexing.mask_vars: if dtype.is_floating_point: zero = "0.0" elif dtype == torch.bool: zero = "True" else: zero = "0" other_val = ( constant_repr(self._load_other) if self._load_other else zero ) line = f"tl.where({indexing.mask_str}, {result_var}, {other_val})" result_var = self.cse.generate( load_buffer, line, dtype=dtype, shape=result_var.shape ) if not self.inside_reduction or (not indexing.has_rmask() and not has_rindex): self.outside_loop_vars.add(result_var) return result_var def store( self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None ) -> None: """ store the 'value' to the memory location 'name', offset by some indexing expression 'index'. """ var = self.args.output(name) original_index = index dtype = V.graph.get_dtype(name) tma_compatibility_checker = None if mode is None or mode == "tma": force = mode == "tma" tma_compatibility_checker = self.tma_compatibility_checker_cls( self, dtype, for_store=True, force=force, ) indexing = self.indexing( index, dense_indexing=True, block_ptr=mode is None, tma_compatibility_checker=tma_compatibility_checker, ) if isinstance(indexing, IndexingOptions) and self._has_stride1_on_rdim( indexing.index ): self.stores_with_contiguous_rdim.append(name) # Guard against write-after-read corruption in triton. # See # https://github.com/triton-lang/triton/issues/1615 # This triton bug means that a load which is broadcasted over multiple # warps may see the result of a store that happens later in the triton # program. The workaround is to add a barrier before storing, which # enforces that all warps have already read the data. is_inplace = name in self.args.inplace_buffers is_broadcasted = self.is_broadcasted(original_index) if is_inplace and is_broadcasted: self.stores.writeline(DeferredLine(name, "tl.debug_barrier()")) if isinstance(indexing, (BlockPtrOptions, TensorDescriptorOptions)): block_descriptor, other = self.codegen_block_ptr(name, var, indexing) # block_ptr / tma descriptor stores don't do implicit casting line = self.codegen_block_ptr_store_line( name, indexing, block_descriptor, value, other ) elif mode is None: # If indexing is an integer and value has block shape larger than one, # broadcasting fails. So, we manually broadcast indexing to the value shape. # Without broadcast : # tl.store(out_ptr0 + (tl.full([1, 1], 0, tl.int32)), tmp4, xmask) # Fail # # With broadcast: # tl.store(out_ptr0 + (tl.full([1, 1], 0, tl.int32).broadcast_to((XBLOCK,1)), tmp4, xmask) indexing_str = indexing.index_str if ( is_sympy_integer_like(index) and value.shape is not None and not all(str(x) == "1" for x in value.shape) ): value_shape = ", ".join(map(str, value.shape)) indexing_str += f".broadcast_to({value_shape})" line = f"tl.store({var} + ({indexing_str}), {value}, {indexing.mask_str})" elif mode == "atomic_add": self.atomic_add_found = True indexing_str = indexing.index_str if ( is_sympy_integer_like(index) and value.shape is not None and not all(str(x) == "1" for x in value.shape) ): value_shape = ", ".join(map(str, value.shape)) indexing_str += f".broadcast_to({value_shape})" line = f"tl.atomic_add({var} + ({indexing_str}), {value}, {indexing.mask_str}, sem='relaxed')" else: raise NotImplementedError(f"store mode={mode}") exit_stack = contextlib.ExitStack() if not self.inside_reduction and self.cooperative_reduction: exit_stack.enter_context(self.guard_cooperative_store(name, self.stores)) self.stores.writeline(DeferredLine(name, line)) if not self.inside_reduction: self.outside_loop_vars.add(value) exit_stack.close() def device_assert_async(self, cond, msg) -> None: self.compute.writeline(f"tl.device_assert({cond}, {repr(msg)})") def guard_cooperative_store(self, name, buffer): """ For cooperative reductions only one thread block should write out the result. We rotate which thread block does each write for better parallelism """ idx = self.cooperative_reduction_workspace_cache.increment_store_count() buffer.writeline(DeferredLine(name, f"if rsplit_id == ({idx} % RSPLIT):")) return buffer.indent() def _combine_masks(self, *variables: Optional[CSEVariable]): masks = None for elem in variables: if elem is None: continue if hasattr(elem, "mask_vars"): if masks is None: masks = elem.mask_vars else: masks = masks | elem.mask_vars return masks def bucketize( self, values: CSEVariable, boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr], boundary_indices: CSEVariable, indexing_dtype: torch.dtype, right: bool, sorter: Optional[tuple[str, sympy.Expr]] = None, sorter_indices: Optional[CSEVariable] = None, ) -> CSEVariable: """ See [Note: Inductor bucketize op] """ # Triton performance for bucketize_binary_search is much better when the number # of threads equals the number of elements. # If we're trying to use a bucketize kernel, we should make sure that an # autotuning config with num_elements_per_warp=(warp_size) exists. self.autotune_hints.add(AutotuneHint.ONE_ELEMENT_PER_THREAD) boundaries_ptr = self.args.input(boundaries[0]) boundary_size = self.index_to_str(boundaries[1]) boundaries_underlying_numel = self.index_to_str(boundaries[2]) boundary_stride = self.index_to_str(boundaries[3]) sorter_ptr = self.args.input(sorter[0]) if sorter else "None" sorter_stride = self.index_to_str(sorter[1]) if sorter else "None" if indexing_dtype == torch.int32: triton_dtype = "tl.int32" elif indexing_dtype == torch.int64: triton_dtype = "tl.int64" else: raise NotImplementedError( "Bucketize only supports indexing with int32 and int64" ) self._handle_pdl_before_load(self.compute) result = self.cse.generate( self.compute, f"triton_helpers.bucketize_binary_search({values}, " f"{boundaries_ptr}, {boundary_size}, {boundaries_underlying_numel}, {boundary_stride}, " f"{boundary_indices}, " f"{triton_dtype}, " f"{right}, " f"{sorter_ptr}, {sorter_stride}, " f"{sorter_indices}, " ")", dtype=indexing_dtype, # type: ignore[attr-defined] shape=values.shape, ) self._handle_pdl_after_load(self.compute, result) masks = self._combine_masks(values, boundary_indices, sorter_indices) result.mask_vars = masks # type: ignore[attr-defined] return result def reduction_resize(self, value) -> str: ndims = self.triton_tensor_ndim() if ndims == 1: return f"triton_helpers.promote_to_tensor({value})" nreduce = self.num_reduction_dims sizes = [":"] * (ndims - nreduce) + ["None"] * nreduce return f"{value}[{', '.join(sizes)}]" def reduction_resize_and_shape(self, value, shape) -> tuple[str, BlockShapeType]: ndims = self.triton_tensor_ndim() if ndims == 1: return f"triton_helpers.promote_to_tensor({value})", shape nreduce = self.num_reduction_dims sizes = [":"] * (ndims - nreduce) + ["None"] * nreduce new_shape = ( (*shape[: (ndims - nreduce)], *[1] * nreduce) if shape is not None else None ) return f"{value}[{', '.join(sizes)}]", new_shape def reduction_collapse_dims( self, buffer, value: CSEVariable, dtype: torch.dtype ) -> CSEVariable: """ Reshape to RBLOCK, collapsing all reduction dims. """ # This is not needed for 1D reductions. if self.num_reduction_dims == 1: return value target_ndim = self.triton_tensor_ndim() - self.num_reduction_dims initial_shape = self.dense_size_list() target_shape = initial_shape[:target_ndim] + ["RBLOCK"] return self.cse.generate( buffer, triton_reshape(str(value), initial_shape, target_shape), dtype=dtype, shape=tuple(target_shape), ) def reduction( self, dtype: torch.dtype, src_dtype: torch.dtype, reduction_type: ReductionType, value: Union[CSEVariable, tuple[CSEVariable, ...]], ) -> Union[CSEVariable, tuple[CSEVariable, ...]]: """ codegen reduction of value to Triton according the reduction_type """ def maybe_upcast(value: CSEVariable) -> CSEVariable: # Math reductions in FP16/BF16 are less accurate because the Triton compiler does not # automatically promote to FP32 for accumulation. Additionally, max/min reductions # do not support FP16/BF16. We manually promote to FP32 here. return ( ops.to_dtype(value, torch.float32) if value.dtype in [ torch.float16, torch.bfloat16, ] else value ) original_dtypes = [val.dtype for val in pytree.tree_leaves(value)] value = pytree.tree_map(maybe_upcast, value) if any(x in [torch.float16, torch.bfloat16] for x in original_dtypes): # Only promote FB16/BF16; do not promote other integer/boolean dtypes src_dtype = torch.promote_types(src_dtype, torch.float32) dtype = torch.promote_types(dtype, torch.float32) assert self.inside_reduction masks = OrderedSet(f"{tree.prefix}mask" for tree in self.range_trees) self.filter_masks(masks) masks = sorted(masks) if self._load_mask: masks.append(self._load_mask) reduction_range_prefix = self.range_trees[-1].prefix[0] # When we do native matmtul codegen, # we don't want to keep the R0_BLOCK/R1_BLOCK in the accumulator. # so instead of naively calling dense_size_str(), we filter out # reduction block from accumulator and only keep (Y,X). # In bmm (Z,Y,R)x(Z,R,X) case, we also remove z dimension from accumulator # because 3d (Z,Y,X) tl.dot is somehow slower than 2d tl.dot. # Instead, we force ZBLOCK to be always 1 during autotune. dense_size_str: str if self.is_native_matmul: dense_sizes = self.dense_size_list() assert len(dense_sizes) >= 3 xy_sizes_only = [size for size in dense_sizes if "X" in size or "Y" in size] dense_size_str = f"[{', '.join(xy_sizes_only)}]" value_shape = tuple(xy_sizes_only) else: dense_size_str = self.dense_size_str() value_shape = tuple(self.dense_size_list()) # Say we have # tmp0 = ops.constant(1, torch.int64) # tmp1 = ops.reduction(torch.int64, torch.int64, "sum", tmp0) # tmp0 in the triton code is either a scalar, or single-element tensor # so if we emit tl.sum directly, it will only give 1 instead of RBLOCK * 1 # To avoid this, we broadcast to the expected shape first. value = self._map_tuple_or_scalar( lambda v: self.cse.generate( self.compute, f"tl.broadcast_to({v}, {dense_size_str})", dtype=v.dtype, shape=value_shape, ), value, ) logical_index = None if reduction_type in ("argmin", "argmax"): if isinstance(value, tuple): value, logical_index = value dim = self.triton_tensor_ndim() - self.num_reduction_dims root_op: str def final_reduction( buffer, value: CSEVariable, result_type: Optional[torch.dtype], ) -> tuple[str, Optional[torch.dtype], BlockShapeType]: """ Helper to generate a reduction call, e.g. tl.sum. """ triton_reduction_fn = get_triton_reduction_function(reduction_type) value = self.reduction_collapse_dims(buffer, value, dtype) if reduction_type == "dot": # Native matmul is a special case because accumulator shape is fixed to (Y,X) is_bmm = len(self.dense_size_list()) == 4 assert value.shape is not None if is_bmm: result = f"{value}[None,:,:,None]" # (Y,X) to (Z=1,Y,X,R=1) shape = [1, *value.shape, 1] else: result = f"{value}[:,:,None]" # (Y,X) to (Y,X,R=1) shape = [*value.shape, 1] else: result, shape = self.reduction_resize_and_shape( # type: ignore[assignment] f"{triton_reduction_fn}({value}, {dim})", value.shape ) if result_type is not None: result = f"{result}.to({self.dtype_to_str(result_type)})" else: result_type = value.dtype return result, result_type, shape def final_reduction_define( buffer, result_var: CSEVariable, value: CSEVariable, result_type: Optional[torch.dtype], ) -> None: """ Generate a reduction and assign it to an existing variable. """ value, _, _ = final_reduction(buffer, value, result_type) buffer.splice(f"{result_var} = {value}") def final_argreduce(buffer, result_var, value, index): value = self.reduction_collapse_dims(buffer, value, dtype) index = self.reduction_collapse_dims(buffer, index, dtype) buffer.splice( f"""\ {result_var}_val, {result_var}_idx = triton_helpers.{root_op}_with_index({value}, {index}, {dim}) {result_var} = {self.reduction_resize(f"{result_var}_idx")} """ ) cache_key = (src_dtype, reduction_type, value) if cache_key in self.cse.reduction_cache: return self.cse.reduction_cache[cache_key] acc_type = triton_acc_type(src_dtype) torch_acc_type = upcast_acc_dtype(src_dtype) result_shape = list(self.dense_size_list()) result_shape[dim] = "1" result_var: Any = self.cse.newvar( dtype=torch_acc_type, shape=tuple(result_shape) ) result_var.mask_vars = OrderedSet( var for var in masks if not prefix_is_reduction(var[0]) ) cond = " & ".join(masks) def where_cond(tval, fval): if not cond: return tval return TritonKernelOverrides.where(cond, tval, fval) if self.persistent_reduction: default = ir.Reduction.default_value(reduction_type, src_dtype) def update_constant_dtype(constant, src_dtype, dst_dtype): "update reduction constant mask value to match dst_dtype" # int is the only mask which may not fit within lower bitwidth, # because float uses inf/-inf if src_dtype.is_floating_point or src_dtype == torch.bool: return constant if src_dtype == dst_dtype or constant == 0: return constant if constant == torch.iinfo(src_dtype).max: return torch.iinfo(dst_dtype).max elif constant == torch.iinfo(src_dtype).min: return torch.iinfo(dst_dtype).min else: return constant def _mask_value(value, default) -> CSEVariable: default = update_constant_dtype(default, src_dtype, value.dtype) default_str = self._map_tuple_or_scalar(constant_repr, default) return self.cse.generate( self.compute, where_cond(value, default_str), dtype=value.dtype, shape=value.shape, ) masked_value: Union[CSEVariable, Sequence[CSEVariable]] if reduction_type == "online_softmax_reduce": # Don't generate mask value for online_softmax since we # will fallback below pass elif isinstance(value, tuple): masked_value = [_mask_value(v, d) for v, d in zip(value, default)] # type: ignore[arg-type] elif reduction_type == "dot": # Here, we don't perform the masking. # Masking w/ where condition in native matmul is handled in ops.dot codegen. # Since tl.dot performs reduction within the triton block, # masking should happen before the tl.dot is called. masked_value = self.cse.generate(self.compute, value, dtype=value.dtype) else: masked_value = _mask_value(value, default) if reduction_type in ("argmax", "argmin"): assert isinstance(masked_value, CSEVariable) accumulator_dtype = V.kernel.get_index_dtype_as_torch_dtype() if logical_index: accumulator_index = f"({str(logical_index)}).to({self.dtype_to_str(accumulator_dtype)})" else: accumulator_index = str( self.cse.generate( self.compute, f"tl.broadcast_to({reduction_range_prefix}index, {masked_value}.shape)", dtype=accumulator_dtype, shape=masked_value.shape, ) ) root_op = {"argmax": "max", "argmin": "min"}[reduction_type] final_argreduce( self.compute, result_var, masked_value, accumulator_index ) result_var.dtype = accumulator_dtype elif reduction_type == "welford_reduce": if self.cooperative_reduction: # cooperative reductions require full welford for correctness result_var = self.welford_reduce( result_var, reduction_type, value, where_cond, acc_type, dtype ) else: # For persistent reductions, don't bother with # welford's algorithm since it uses more registers, and # taking two reductions doesn't increase memory usage. result_var = self.welford_reduce_fallback(dtype, value) elif reduction_type == "welford_combine": assert isinstance(masked_value, Sequence) (mean, m2, weight) = masked_value result_var = tuple( self.cse.generate(self.compute, value, dtype=dtype, shape=shape) for value, shape in self._welford( self.compute, mean, m2, weight, dim, dtype ) ) elif reduction_type == "online_softmax_reduce": # All data is loaded to register anyway, no need to do # online softmax result_var = self.prepare_softmax_twopass_fallback(dtype, value) else: assert isinstance(masked_value, CSEVariable) _result, _dtype, _shape = final_reduction( self.compute, masked_value, masked_value.dtype ) result_var = self.cse.generate( self.compute, _result, dtype=_dtype, shape=_shape ) else: accumulator = self.cse.namedvar( f"_{result_var}", dtype=torch_acc_type, shape=tuple(self.dense_size_list()), ) default = ir.Reduction.default_accumulator(reduction_type, src_dtype) default = self._map_tuple_or_scalar(constant_repr, default) if not isinstance(default, tuple): if reduction_type == "dot": dense_sizes = self.dense_size_list() assert len(dense_sizes) >= 3 xy_sizes_only = [ size for size in dense_sizes if "X" in size or "Y" in size ] accumulator.shape = tuple(xy_sizes_only) dense_size_str = f"[{', '.join(xy_sizes_only)}]" self.body.writeline( f"{accumulator} = tl.full({dense_size_str}, {default}, {acc_type})" ) else: self.body.writeline( f"{accumulator} = tl.full({self.dense_size_str()}, {default}, {acc_type})" ) if reduction_type in ("argmax", "argmin"): accumulator_index = f"_{result_var}_index" index_dtype = self.features.select_index_dtype() self.body.writeline( f"{accumulator_index} = tl.full({self.dense_size_str()}, " f"{torch.iinfo(index_dtype).max}, {self.dtype_to_str(index_dtype)})" ) root_op = {"argmax": "max", "argmin": "min"}[reduction_type] # Use logical_index if it was unpacked, otherwise fall back to physical index index_var = ( f"({str(logical_index)}).to({self.dtype_to_str(index_dtype)})" if logical_index is not None else f"{reduction_range_prefix}index" ) self.compute.splice( f"""\ {accumulator}_next, {accumulator_index}_next = triton_helpers.{root_op}imum_with_index( {accumulator}, {accumulator_index}, {value}, {index_var} ) {accumulator} = {where_cond(f"{accumulator}_next", accumulator)} {accumulator_index} = {where_cond(f"{accumulator_index}_next", accumulator_index)} """ ) final_argreduce( self.post_loop_combine, result_var, accumulator, accumulator_index ) elif is_welford_reduction(reduction_type): result_var = self.welford_reduce( result_var, reduction_type, value, where_cond, acc_type, dtype ) elif reduction_type == "online_softmax_reduce": accumulator_max = f"_{result_var}_max" accumulator_sum = f"_{result_var}_sum" # setup accumulator self.body.writeline( f"{accumulator_max} = tl.full({self.dense_size_str()}, float('-inf'), {acc_type})" ) self.body.writeline( f"{accumulator_sum} = tl.zeros({self.dense_size_str()}, {acc_type})" ) # combine # Note, we pass config.use_fast_math to the JITFunction # since a triton kernel can not access a config. self.compute.splice( f""" {accumulator_max}_next, {accumulator_sum}_next = triton_helpers.online_softmax_combine( {accumulator_max}, {accumulator_sum}, {value}, {config.use_fast_math} ) """ ) # mask self.compute.splice( f""" {accumulator_max} = {where_cond(f"{accumulator_max}_next", accumulator_max)} {accumulator_sum} = {where_cond(f"{accumulator_sum}_next", accumulator_sum)} """ ) # reduce. Similar to the final reduction for coopereative # reduction result_max = result_var result_sum = self.cse.newvar(dtype=dtype, shape=result_max.shape) result_var = self.online_softmax_reduce_final_reduction( self.post_loop_combine, result_max, result_sum, accumulator_max, accumulator_sum, dim, dtype, ) else: combine_fn = ir.get_reduction_combine_fn(reduction_type, src_dtype) updated = combine_fn(accumulator, value) if reduction_type == "dot": self.compute.writeline(f"{accumulator} = {updated}") else: self.compute.writeline( f"{accumulator} = {where_cond(updated, accumulator)}" ) if src_dtype == torch.bool: # This is only really used for aten.any. It changes the # final reduction of a non-persistent reduction from # tmp5 = triton_helpers.max(_tmp5, 1)[:, None] # to # tmp5 = triton_helpers.max(_tmp5.to(tl.int8), 1)[:, None].to(tl.int1) # which is needed because tl.reduce doesn't support tl.int1 accumulator = self.cse.generate( self.post_loop_combine, f"{accumulator}.to(tl.int8)", dtype=torch.int8, shape=accumulator.shape, ) final_reduction_define( self.post_loop_combine, result_var, accumulator, None ) if self.cooperative_reduction: default = ir.Reduction.default_accumulator(reduction_type, src_dtype) exit_stack = contextlib.ExitStack() for buf in (self.post_loop_combine, self.post_loop_store): # only do cooperative reduction combines if we have more than one thread block buf.writeline("if HAS_RSPLIT:") exit_stack.enter_context(buf.indent()) if reduction_type in ("argmax", "argmin"): self.post_loop_combine.writeline( f"{result_var}_bval = {self.reduction_resize(f'{result_var}_val')}" ) peer_val = self.codegen_cooperative_reduction_peer_combine( f"{result_var}_bval", src_dtype, default ) index_dtype = self.features.select_index_dtype() peer_idx = self.codegen_cooperative_reduction_peer_combine( result_var, index_dtype, torch.iinfo(index_dtype).max ) final_argreduce(self.post_loop_store, result_var, peer_val, peer_idx) elif is_welford_reduction(reduction_type): assert reduction_type == "welford_reduce" result_mean, result_m2, result_weight = result_var peer_mean = self.codegen_cooperative_reduction_peer_combine( result_mean, upcast_acc_dtype(src_dtype), default[0], # type: ignore[index] ) peer_m2 = self.codegen_cooperative_reduction_peer_combine( result_m2, upcast_acc_dtype(src_dtype), default[1], # type: ignore[index] ) peer_weight = self.codegen_cooperative_reduction_peer_combine( result_weight, upcast_acc_dtype(src_dtype), default[2], # type: ignore[index] ) self.welford_reduce_final_reduction( self.post_loop_store, result_mean, result_m2, result_weight, peer_mean, peer_m2, peer_weight, dim, dtype, ) elif reduction_type == "online_softmax_reduce": result_max, result_sum = result_var assert isinstance(default, Sequence) peer_max = self.codegen_cooperative_reduction_peer_combine( result_max, upcast_acc_dtype(src_dtype), default[0] ) peer_sum = self.codegen_cooperative_reduction_peer_combine( result_sum, upcast_acc_dtype(src_dtype), default[1] ) self.online_softmax_reduce_final_reduction( self.post_loop_store, result_max, result_sum, peer_max, peer_sum, dim, dtype, ) else: peers = self.codegen_cooperative_reduction_peer_combine( result_var, upcast_acc_dtype(src_dtype), default ) final_reduction_define(self.post_loop_store, result_var, peers, None) exit_stack.close() self.cse.reduction_cache[cache_key] = result_var if isinstance(result_var, tuple): assert all(isinstance(x, TritonCSEVariable) for x in result_var) self.outside_loop_vars.update(result_var) # Match output dtype with input dtype if reduction_type in ("welford_reduce", "online_softmax_reduce"): assert len(original_dtypes) == 1 original_dtypes = len(result_var) * original_dtypes assert len(result_var) == len(original_dtypes) for var, orig_dtype in zip(result_var, original_dtypes): assert orig_dtype is not None if var.dtype != orig_dtype: self.post_loop_combine.writeline( f"{var} = {var}.to({triton_compute_type(orig_dtype)})" ) else: assert isinstance(result_var, TritonCSEVariable) self.outside_loop_vars.add(result_var) # Match output dtype with input dtype if result_var.dtype != original_dtypes[0]: assert original_dtypes[0] is not None self.post_loop_combine.writeline( f"{result_var} = {result_var}.to({triton_compute_type(original_dtypes[0])})" ) return result_var def _online_softmax_reduce( self, buffer, accumulator_max, accumulator_sum, dim, dtype: torch.dtype ): accumulator_max = self.reduction_collapse_dims(buffer, accumulator_max, dtype) accumulator_sum = self.reduction_collapse_dims(buffer, accumulator_sum, dtype) result_max, result_sum = [str(self.cse.newvar(dtype=dtype)) for _ in range(2)] buffer.splice( f""" {result_max}, {result_sum} = triton_helpers.online_softmax_reduce( {accumulator_max}, {accumulator_sum}, {dim}, {config.use_fast_math}) {result_max} = {self.reduction_resize(f"{result_max}")} {result_sum} = {self.reduction_resize(f"{result_sum}")} """ ) return result_max, result_sum def _welford(self, buffer, mean, m2, weight, dim, dtype: torch.dtype): """ Helper to codegen triton_helpers.welford. """ mean, m2, weight = ( self.reduction_collapse_dims(buffer, value, dtype) for value in (mean, m2, weight) ) welford = f"triton_helpers.welford({mean}, {m2}, {weight}, {dim})" def reduced_shape(shape): return tuple(shape[0:dim] + shape[dim + 1 :]) welford_results = [ self.cse.newvar(dtype=dtype, shape=reduced_shape(value.shape)) for value in (mean, m2, weight) ] buffer.writeline(f"{', '.join([str(r) for r in welford_results])} = {welford}") return tuple( self.reduction_resize_and_shape(value, value.shape) for value in welford_results ) def welford_reduce( self, result_var, reduction_type, value, where_cond, acc_type, dtype ): """Helper to codegen a welford reduction""" dim = self.triton_tensor_ndim() - self.num_reduction_dims accumulator = TritonCSEVariable( f"{result_var}_mean", shape=tuple(self.dense_size_list()), dtype=acc_type, bounds=ValueRanges.unknown(), ) accumulator_m2 = TritonCSEVariable( f"{result_var}_m2", shape=tuple(self.dense_size_list()), dtype=acc_type, bounds=ValueRanges.unknown(), ) accumulator_weight = TritonCSEVariable( f"{result_var}_weight", shape=tuple(self.dense_size_list()), dtype=acc_type, bounds=ValueRanges.unknown(), ) self.body.writeline( f"{accumulator} = tl.zeros({self.dense_size_str()}, {acc_type})" ) self.body.writeline( f"{accumulator_m2} = tl.zeros({self.dense_size_str()}, {acc_type})" ) self.body.writeline( f"{accumulator_weight} = tl.zeros({self.dense_size_str()}, {acc_type})" ) if reduction_type == "welford_combine": mean, m2, weight = value self.compute.splice( f"""\ {accumulator}_next, {accumulator_m2}_next, {accumulator_weight}_next = triton_helpers.welford_combine( {accumulator}, {accumulator_m2}, {accumulator_weight}, {mean}, {m2}, {weight} ) """ ) else: assert reduction_type == "welford_reduce" self.compute.splice( f"""\ {accumulator}_next, {accumulator_m2}_next, {accumulator_weight}_next = triton_helpers.welford_reduce( {value}, {accumulator}, {accumulator_m2}, {accumulator_weight}, roffset == 0 ) """ ) self.compute.splice( f"""\ {accumulator} = {where_cond(f"{accumulator}_next", accumulator)} {accumulator_m2} = {where_cond(f"{accumulator_m2}_next", accumulator_m2)} {accumulator_weight} = {where_cond(f"{accumulator_weight}_next", accumulator_weight)} """ ) result_mean = result_var return self.welford_reduce_final_reduction( self.post_loop_combine, result_mean, None, None, accumulator, accumulator_m2, accumulator_weight, dim, dtype, ) def welford_reduce_final_reduction( self, buffer, result_mean, result_m2, result_weight, mean, m2, weight, dim, dtype, ): """Helper to codegen call to triton_helpers.welford""" values = list(self._welford(buffer, mean, m2, weight, dim, dtype)) result_exprs = [result_mean, result_m2, result_weight] for i, (result_expr, (value, shape)) in enumerate(zip(result_exprs, values)): if result_expr is None: result_expr = self.cse.newvar(dtype=dtype, shape=shape) result_exprs[i] = result_expr buffer.splice(f"{result_expr} = {value}") return tuple(result_exprs) def online_softmax_reduce_final_reduction( self, buffer, result_max, result_sum, peer_max, peer_sum, dim, dtype ): accumulator_max = self.reduction_collapse_dims(buffer, peer_max, dtype) accumulator_sum = self.reduction_collapse_dims(buffer, peer_sum, dtype) buffer.splice( f""" {result_max}, {result_sum} = triton_helpers.online_softmax_reduce( {accumulator_max}, {accumulator_sum}, {dim}, {config.use_fast_math}) {result_max} = {self.reduction_resize(f"{result_max}")} {result_sum} = {self.reduction_resize(f"{result_sum}")} """ ) return result_max, result_sum def max_rsplit(self): if self.fixed_config: return self.fixed_config["RSPLIT"] return TRITON_MAX_RSPLIT def codegen_cooperative_reduction_peer_combine( self, result_var, dtype, default_val ) -> CSEVariable: """ Generate code to save a [XBLOCK, RSPLIT] temporary workspace, where each thread block writes a different column. After the barrier, every thread block loads the completed value so that it can compute the final value independently. """ xnumel = self.numels["x"] mask = "xindex < xnumel" if not self._has_constant_xmask() else None nbytes = xnumel * dtype.itemsize * self.max_rsplit() ws_name, ws_offset = self.cooperative_reduction_workspace_cache.allocate(nbytes) self.post_loop_combine.splice( f""" {result_var}_ws = ({ws_name} + {self.index_to_str(ws_offset)}).to(tl.pointer_type({triton_type(dtype)})) tl.store({result_var}_ws + (xindex * RSPLIT + rsplit_id), {result_var}, {mask}) """, strip=True, ) peers = self.create_cse_var( f"{result_var}_peers", shape=["XBLOCK", "RSPLIT"], dtype=dtype, bounds=ValueRanges.unknown(), ) self.post_loop_store.writeline( f"{peers} = tl.load({result_var}_ws + (xindex * RSPLIT + rsplit_arange), " f"rsplit_mask, eviction_policy='evict_first', other=triton_helpers.if_mask(rsplit_mask, {constant_repr(default_val)}))" ) return peers def store_reduction( self, name: str, index: sympy.Expr, value: CSEVariable, ): assert self.inside_reduction self.inside_reduction = False dtype = V.graph.get_dtype(name) indexing = self.indexing( index, block_ptr=True, tma_compatibility_checker=self.tma_compatibility_checker_cls( kernel=self, dtype=dtype, for_store=True, force=False, ), ) self.inside_reduction = True var = self.args.output(name) exit_stack = contextlib.ExitStack() if self.cooperative_reduction: exit_stack.enter_context( self.guard_cooperative_store(name, self.post_loop_store) ) if isinstance(indexing, (BlockPtrOptions, TensorDescriptorOptions)): self.post_loop_store.writeline( DeferredLine( name, self.codegen_block_ptr_store_line( name, indexing, indexing.format(var), value, f", boundary_check={indexing.boundary_check()!r}", ), ) ) else: assert isinstance(indexing, IndexingOptions) indexing_str = indexing.index_str if ( is_sympy_integer_like(index) and value.shape is not None and not all(str(x) == "1" for x in value.shape) ): value_shape = ", ".join(map(str, value.shape)) indexing_str += f".broadcast_to({value_shape})" self.post_loop_store.writeline( DeferredLine( name, f"tl.store({var} + ({indexing_str}), {value}, {indexing.mask_str})", ) ) exit_stack.close() def _lift_helper( self, fn, values: tuple[CSEVariable, ...], dtypes: tuple[torch.dtype, ...] ) -> str: # Lift IR function for scan operations into a triton function # in the global namespace helper = IndentedBuffer() helper.writeline("@triton.jit") cse = CSE() args = [ tuple( cse.namedvar(f"arg{i}_{n}", dtype=dtype, shape=value.shape) for n, (value, dtype) in enumerate(zip(values, dtypes)) ) for i in range(2) ] signature = ", ".join(str(x) for x in itertools.chain.from_iterable(args)) helper.writeline(f"def {{name}}({signature}):") overrides = TritonOverrides() # Build a name that changes depending on fn to workaround a triton bug # where the combine_fn to reduce and scan is not hashed, and so different # scan ops may collide in the triton cache. # This is fixed with the latest triton pin, but not the triton-rocm pin. helper_name = "_triton_helper_fn" from torch._inductor.dtype_propagation import DtypePropagationOpsHandler from torch._inductor.shape_propagation import ShapePropagationOpsHandler shape_handler = ShapePropagationOpsHandler() dtype_handler = DtypePropagationOpsHandler() class CSEProxy(DefaultHandler): def _default( self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any] ) -> Any: nonlocal helper_name helper_name += f"_{name}" output_dtype = getattr( dtype_handler, name, )(*args, **kwargs) output_shape = getattr( shape_handler, name, )(*args, **kwargs) return cse.generate( helper, getattr(overrides, name)(*args, **kwargs), dtype=output_dtype, shape=output_shape, ) with helper.indent(), V.set_ops_handler(CSEProxy()): outputs = fn(*args) outputs = ", ".join(str(output) for output in outputs) helper.writeline(f"return {outputs}") return self.helper_functions.add(helper.getvalue(), base_name=helper_name) def scan( self, dtypes: tuple[torch.dtype, ...], combine_fn: Callable[ [tuple[CSEVariable, ...], tuple[CSEVariable, ...]], tuple[CSEVariable, ...] ], values: tuple[CSEVariable, ...], ) -> tuple[CSEVariable, ...]: """ Perform an associative scan on 'values'. """ assert self.inside_reduction assert not self.cooperative_reduction, "TODO" masks = OrderedSet(f"{tree.prefix}mask" for tree in self.range_trees) self.filter_masks(masks) masks = sorted(masks) assert not self._load_mask, "ops.scan not supported inside ops.masked" broadcasted_values = [] accumulators = [] dtypes = tuple(upcast_compute_type(dtype) for dtype in dtypes) cse_compute = functools.partial(self.cse.generate, self.compute) combine_helper_fn = self._lift_helper(combine_fn, values, dtypes) dim = self.triton_tensor_ndim() - self.num_reduction_dims for value, dtype in zip(values, dtypes): value_dtype = self.cse.generate( self.compute, f"{value}.to({triton_compute_type(dtype)})", dtype=dtype, shape=value.shape, ) value = self.cse.generate( self.compute, f"tl.broadcast_to({value_dtype}, {self.dense_size_str()})", dtype=dtype, shape=tuple(self.dense_size_list()), ) broadcasted_values.append(value) acc_type = triton_acc_type(dtype) if not self.persistent_reduction: reduced_size = self.dense_size_list() reduced_size[-1] = "1" accumulator = self.cse.newvar(dtype=dtype, shape=reduced_size) reduced_size_str = f"[{', '.join(reduced_size)}]" default = "float('nan')" if dtype.is_floating_point else "-1" self.body.writeline( f"{accumulator} = tl.full({reduced_size_str}, {default}, {acc_type})" ) accumulators.append(accumulator) def csv(values): return " ".join(f"{value}," for value in values) def cse_multiple(line, values, masks, dtypes): n = len(values) cache_keys = [f"{line}, {i}, {masks}" for i in range(n)] if all(self.cse.contains(cache_key) for cache_key in cache_keys): return [self.cse.get(cache_key) for cache_key in cache_keys] result_vars = [ self.cse.newvar(dtype=dtype, shape=value.shape) for (dtype, value) in zip(dtypes, values) ] self.compute.writeline( f"{csv(result_vars)} = {line}", ) for result_var, cache_key in zip(result_vars, cache_keys): if masks: result_var.mask_vars = masks # type: ignore[attr-defined] self.cse.put(cache_key, result_var) return tuple(result_vars) partial_scan_vars = cse_multiple( f"tl.associative_scan(({csv(broadcasted_values)}), {dim}, {combine_helper_fn})", broadcasted_values, masks, dtypes, ) if not self.persistent_reduction: # tl.reduce doesn't work for non-commutative operators, so instead # of repeating the scan op as a reduction, we use sum to select the # last scan value def _partial_scan_shape(var): if var.shape is None: return None else: shape = list(var.shape) shape[-1] = "1" return shape partial_reduce_vars = [ cse_compute( f"triton_helpers.select_one(({partial_scan_var}), rbase == (RBLOCK - 1), dim=-1, keep_dims=True)", dtype=upcast_compute_type(partial_scan_var.dtype), shape=_partial_scan_shape(partial_scan_var), ) for partial_scan_var in partial_scan_vars ] accs_next = combine_fn(tuple(accumulators), tuple(partial_reduce_vars)) full_scan_vars = combine_fn(tuple(accumulators), partial_scan_vars) result_vars = [ cse_compute( f"tl.where(roffset > 0, {full_scan}, {partial_scan})", dtype=partial_scan.dtype, shape=partial_scan.shape, ) for full_scan, partial_scan in zip(full_scan_vars, partial_scan_vars) ] for acc_next, accumulator, partial_reduce in zip( accs_next, accumulators, partial_reduce_vars ): self.compute.writeline( f"{accumulator} = tl.where(roffset > 0, {acc_next}, {partial_reduce})" ) else: result_vars = partial_scan_vars for result_var in result_vars: assert isinstance(result_var, TritonCSEVariable) result_var.mask_vars = OrderedSet(masks) return tuple(result_vars) def sort( self, dtypes: tuple[torch.dtype, ...], values: tuple[CSEVariable, ...], stable: bool, descending: bool, ) -> tuple[CSEVariable, ...]: assert self.inside_reduction assert not self.cooperative_reduction, "TODO" masks = OrderedSet(f"{tree.prefix}mask" for tree in self.range_trees) self.filter_masks(masks) masks = sorted(masks) assert not self._load_mask, "ops.sort not supported inside ops.masked" assert self.persistent_reduction, ( "ops.sort is only supported in persistent reductions" ) cse_compute = functools.partial(self.cse.generate, self.compute) dim = self.triton_tensor_ndim() - self.num_reduction_dims dtypes = tuple(upcast_compute_type(dtype) for dtype in dtypes) assert len(dtypes) == len(values) broadcasted_values = [ cse_compute( f"tl.broadcast_to({value}, {self.dense_size_str()})", dtype=dtypes[i], shape=tuple(self.dense_size_list()), ) for i, value in enumerate(values) ] def csv(values): return " ".join(f"{value}," for value in values) def cse_multiple(line, broadcasted_values, masks, dtypes): n = len(broadcasted_values) cache_keys = [f"{line}, {i}, {masks}" for i in range(n)] if all(self.cse.contains(cache_key) for cache_key in cache_keys): return [self.cse.get(cache_key) for cache_key in cache_keys] result_vars = [ self.cse.newvar(dtype=dtype, shape=value.shape) for dtype, value in zip(dtypes, broadcasted_values) ] # type: ignore[attr-defined] self.compute.writeline( f"{csv(result_vars)} = {line}", ) for result_var, cache_key in zip(result_vars, cache_keys): if masks: result_var.mask_vars = masks # type: ignore[attr-defined] self.cse.put(cache_key, result_var) return tuple(result_vars) assert self.range_trees[-1].is_reduction rnumel = "None" if self._has_constant_mask(self.range_trees[-1]) else "rnumel" if len(values) == 2: line = ( f"triton_helpers.sort_with_index({broadcasted_values[0]}, {broadcasted_values[1]}," f" {rnumel}, {dim}, stable={stable}, descending={descending})" ) result_vars = cse_multiple(line, broadcasted_values, masks, dtypes) else: raise AssertionError("Unhandled sort") for result_var, input_var in zip(result_vars, values): result_var.mask_vars = masks # type: ignore[attr-defined] result_var.bounds = input_var.bounds return tuple(result_vars) def codegen_prologue(self, code: IndentedBuffer): """ Generate the output from prologue. This should be extracted from the subgraph, which is why this is partitioned from codegen_body. """ if not self.prologue: return code.splice(self.prologue) self.prologue.clear() self.prologue_cache.clear() def codegen_body(self): """ Concat output code from index_code, loads, compute, stores, suffix into self.body. For pointwise kernels, this is called just once at the end. For reduction kernels, this generates a loop over the reduction axis. """ if not ( self.indexing_code or self.loads or self.stores or self.compute or self.post_loop_combine or self.post_loop_store ): return loop_trees = [tree for tree in self.range_trees if tree.is_loop] if self.mix_order_reduction: assert self.persistent_reduction, ( "Mix order reduction requires persistent reduction" ) accumname2var = {} for idx, partial_accum in enumerate(self.saved_partial_accumulate): reduction_type = partial_accum.reduction_type default = ir.Reduction.default_accumulator(reduction_type, torch.float) default = self._map_tuple_or_scalar(constant_repr, default) name = f"accum{idx}" self.body.writeline( f"{name} = tl.full([R0_BLOCK], {default}, tl.float32)[None, :]" ) accumname2var[name] = self.cse.namedvar(name, dtype=torch.float) self.body.writeline("split_size = min(RSPLIT_SIZE, xnumel - xoffset)") self.body.writeline( "for _ in tl.range(0, split_size, XBLOCK, num_stages=NUM_STAGES):" ) with self.body.indent(offset=1): # generate xmask if it's not constant if not self._has_constant_xmask(): entry = self.range_trees[0] assert entry.prefix == "x" x = entry.prefix self.body.writeline(f"{x}mask = {entry.name} < {x}numel") self.body.splice(self.indexing_code) self.body.writelines( [ "xindex += XBLOCK", ] ) self.body.splice(self.loads) self.body.splice(self.compute) self.body.splice(self.stores) self.body.splice(self.post_loop_store) # no need to sum if XBLOCK == 1, or does that matter? for idx, partial_accum in enumerate(self.saved_partial_accumulate): var = partial_accum.value name = f"accum{idx}" combine_fn = ir.get_reduction_combine_fn( partial_accum.reduction_type, torch.float ) triton_reduction_function = get_triton_reduction_function( partial_accum.reduction_type, ) newval = self.cse.generate( self.body, f"{triton_reduction_function}({var}, 0)", dtype=var.dtype, ) import unittest with unittest.mock.patch.object(self, "compute", self.body): updated = combine_fn( accumname2var[name], newval, ) self.body.writeline(f"{name} = {updated}") for idx in range(len(self.saved_partial_accumulate)): self.body.writeline( f"tl.store(ws_ptr + (tl.program_id(0) + {idx} * tl.num_programs(0)) * r0_numel + r0_index, accum{idx}, r0_mask)" ) elif self.inside_reduction and len(loop_trees) > 0: # Write the loop headers. for level, tree in enumerate(loop_trees): with self.body.indent(offset=level): prefix = tree.prefix loop_start = "rsplit_start" if self.cooperative_reduction else "0" loop_end = ( "rsplit_end" if self.cooperative_reduction else f"{prefix}numel" ) num_stages = ", num_stages = 2" if torch.version.hip else "" self.body.writeline( f"for {prefix}offset in tl.range({loop_start}, {loop_end}, {prefix.upper()}BLOCK{num_stages}):" ) with self.body.indent(offset=level + 1): self.iteration_ranges_codegen_header(tree, self.body) # The innermost loop performs the reduction. with self.body.indent(offset=len(loop_trees)): self.codegen_reduction_indices(self.body) self.body.splice(self.indexing_code) self.body.splice(self.loads) self.body.splice(self.compute) self.body.splice(self.stores) # Write loop suffixes. for level, tree in reversed([*enumerate(loop_trees)]): with self.body.indent(offset=level + 1): # Advance pointers at the end of each loop. for block_ptr, advancement in self.pointer_advancements[ tree.symt ].items(): # Subtract any advancements made in the previous loop level. if level < len(loop_trees) - 1: prev_tree = loop_trees[level + 1] prev_advancement = self.pointer_advancements[ prev_tree.symt ][block_ptr] prev_block = TritonSymbols.get_block_size(prev_tree) prev_num_iter = CeilDiv(prev_tree.numel, prev_block) advancement = [ cur - prev * prev_num_iter for cur, prev in zip(advancement, prev_advancement) ] self.body.writeline( DeferredLine( self.block_ptr_to_buffer[block_ptr], f"{block_ptr} = tl.advance({block_ptr}, {V.kernel.index_to_str(advancement)})", ) ) # Invalidate any cache entries that came from inside the loop. self.cse.invalidate(self.outside_loop_vars) tree.cache_clear() else: self.body.splice(self.indexing_code) self.body.splice(self.loads) self.body.splice(self.compute) self.body.splice(self.stores) self.body.splice(self.post_loop_combine) if self.cooperative_reduction and ( self.post_loop_combine or self.post_loop_store ): sem_ptr = f"{self.semaphores_name} + tl.program_id(1)" self.body.splice( f""" if HAS_RSPLIT: triton_helpers.x_grid_barrier({sem_ptr}) """, strip=True, ) self.cooperative_reduction_workspace_cache.on_loop_end() if not self.mix_order_reduction: self.body.splice(self.post_loop_store) self.indexing_code.clear() self.loads.clear() self.compute.clear() self.stores.clear() self.post_loop_combine.clear() self.post_loop_store.clear() def kernel_benchmark_extra_args(self) -> list[str]: args = [] if self.need_numel_args(): numel_args: list[sympy.Expr] = [] self.add_numel_to_call_args("", numel_args, []) for arg in numel_args: if isinstance(arg, int): args.append(str(arg)) elif isinstance(arg, SymbolicCallArg): hint = V.graph.sizevars.size_hint( arg.inner_expr, hint_override=self.hint_override, fallback=config.unbacked_symint_fallback, ) args.append(str(hint)) elif isinstance(arg, sympy.Expr): hint = V.graph.sizevars.size_hint( arg, hint_override=self.hint_override, fallback=config.unbacked_symint_fallback, ) args.append(str(hint)) else: raise ValueError(f"Unsupported numel argument type: {type(arg)}") return args def codegen_kernel_benchmark(self, num_gb: Optional[float]) -> IndentedBuffer: """ Generates Python code for benchmarking this Triton kernel. - Creates example inputs (random tensors, constants, sizes). - Runs the kernel on the current GPU/stream. - Prints runtime (ms) and throughput (GB/s) using `num_gb`. Args: num_gb (float): The number of gigabytes to use for throughput calculation. Returns: IndentedBuffer: A buffer containing the generated Python benchmark code. """ result = IndentedBuffer() _argdefs, call_args, signature, _ = self.args.python_argdefs() result.writelines(["", "", "def get_args():"]) with result.indent(): name_cnt = itertools.count() var_names = [] for arg_name, arg_sig in zip(call_args, signature): var_name = f"arg_{next(name_cnt)}" buf = V.graph.try_get_buffer(arg_name) if buf: size = V.graph.sizevars.size_hints( buf.get_size(), hint_override=self.hint_override, fallback=config.unbacked_symint_fallback, ) stride = V.graph.sizevars.size_hints( buf.get_stride(), hint_override=self.hint_override, fallback=config.unbacked_symint_fallback, ) result.writeline( f"{var_name} = rand_strided({size}, {stride}, device='{buf.get_device()}', dtype={buf.get_dtype()})" # noqa: B950 line too long ) elif arg_name in V.graph.constants: # note that random seed is put in V.graph.constants const_tensor = V.graph.constants[arg_name] size = V.graph.sizevars.size_hints( const_tensor.size(), hint_override=self.hint_override, fallback=config.unbacked_symint_fallback, ) stride = V.graph.sizevars.size_hints( const_tensor.stride(), hint_override=self.hint_override, fallback=config.unbacked_symint_fallback, ) result.writeline( f"{var_name} = rand_strided({size}, {stride}, device='{const_tensor.device}', dtype={const_tensor.dtype})" # type: ignore[arg-type] # noqa: B950 line too long ) elif isinstance(arg_sig, SizeArg): symval_hint = V.graph.sizevars.size_hint( arg_sig.expr, hint_override=self.hint_override, fallback=config.unbacked_symint_fallback, ) # Force the seed_offset to be 0 so calls to the same kernel # using different seed offset will have the same benchmark harness. # We can dedup kernel definitions in this case. if "seed_offset" in arg_sig.name: symval_hint = 0 result.writeline(f"{var_name} = {symval_hint}") elif isinstance(arg_sig, WorkspaceArg): device = V.graph.get_current_device_or_throw() count = V.graph.sizevars.size_hint( arg_sig.count, hint_override=self.hint_override ) result.writeline( f"{var_name} = torch.zeros({count}, device='{device}', dtype={arg_sig.dtype})" ) else: raise KeyError( f"Don't find the buffer or const tensor for {arg_name}" ) var_names.append(var_name) var_names.extend(self.kernel_benchmark_extra_args()) result.writeline(f"return {', '.join(var_names)},") result.writelines(["\n", "\n", "def call(args):"]) current_device = V.graph.get_current_device_or_throw() index = current_device.index with result.indent(): result.writeline(f"with {V.graph.device_ops.device_guard(index)}:") with result.indent(): result.writeline( V.graph.device_ops.set_device(index) ) # no-op to ensure context stream_name = f"stream{index}" result.writeline(f"{stream_name} = get_raw_stream({index})") result.writeline( f"{str(Placeholder.KERNEL_NAME)}.run(*args, stream={stream_name})" ) # benchmark all configs result.writelines(["\n", "\n", "def benchmark_all_configs(args):"]) with result.indent(): result.writeline(f"with {V.graph.device_ops.device_guard(index)}:") with result.indent(): result.writeline( V.graph.device_ops.set_device(index) ) # no-op to ensure context result.writeline( f"return {str(Placeholder.KERNEL_NAME)}.benchmark_all_configs(*args)" ) result.writelines(["\n", "\n", "if __name__ == '__main__':"]) with result.indent(): result.writeline( "from torch._inductor.runtime.benchmarking import benchmarker" ) result.writeline("") result.writeline("args = get_args()") result.writeline( f"ms = benchmarker.benchmark(lambda: call(args), device={V.graph.get_current_device_or_throw().type}, rep=40)" # noqa: B950 line too long ) result.writeline(f"num_gb = {num_gb}") result.writeline("gb_per_s = num_gb / (ms / 1e3)") result.writeline( 'print(f"{ms:.3f}ms {num_gb:.3f}GB {gb_per_s:.2f}GB/s")' ) return result def imports_for_benchmark_kernel(self): return textwrap.dedent( """ from torch._dynamo.testing import rand_strided {} import torch """.format(V.graph.device_ops.import_get_raw_stream_as("get_raw_stream")) ) def _get_heuristic(self): if self.fixed_config: return "fixed_config" elif self.cooperative_reduction: return "cooperative_reduction" elif self.persistent_reduction: assert self.inside_reduction return "persistent_reduction" elif self.inside_reduction: return "reduction" return "pointwise" @staticmethod def inductor_meta_common(): inductor_meta = { "backend_hash": torch.utils._triton.triton_hash_with_backend(), "assert_indirect_indexing": config.assert_indirect_indexing, "autotune_local_cache": config.autotune_local_cache, "autotune_pointwise": config.triton.autotune_pointwise, "autotune_remote_cache": config.autotune_remote_cache, "force_disable_caches": config.force_disable_caches, "dynamic_scale_rblock": config.dynamic_scale_rblock, "max_autotune": config.max_autotune, "max_autotune_pointwise": config.max_autotune_pointwise, "min_split_scan_rblock": config.triton.min_split_scan_rblock, "spill_threshold": config.triton.spill_threshold, "store_cubin": config.triton.store_cubin, "deterministic": config.deterministic, "force_filter_reduction_configs": config.test_configs.force_filter_reduction_configs, } if config.write_are_deterministic_algorithms_enabled: inductor_meta["are_deterministic_algorithms_enabled"] = ( torch.are_deterministic_algorithms_enabled() ) if torch.version.hip is not None: inductor_meta["is_hip"] = True if config.is_fbcode(): inductor_meta["is_fbcode"] = True if config.profile_bandwidth: inductor_meta["profile_bandwidth"] = config.profile_bandwidth inductor_meta["profile_bandwidth_regex"] = config.profile_bandwidth_regex inductor_meta["profile_bandwidth_output"] = config.profile_bandwidth_output inductor_meta["profile_bandwidth_with_do_bench_using_profiling"] = ( config.profile_bandwidth_with_do_bench_using_profiling ) if config.coordinate_descent_tuning: inductor_meta["coordinate_descent_tuning"] = ( config.coordinate_descent_tuning ) inductor_meta["coordinate_descent_search_radius"] = ( config.coordinate_descent_search_radius ) inductor_meta["coordinate_descent_check_all_directions"] = ( config.coordinate_descent_check_all_directions ) return inductor_meta def codegen_kernel(self, name=None) -> str: """ Convert the TritonKernel from Inductor SIMD IR to triton code, including inductor triton heuristics, imports, metadata, and benchmarking infra. """ code = IndentedBuffer() size_hints = {} for prefix, numel in self.numels.items(): if prefix_is_reduction(prefix) and not self.inside_reduction: continue numel_hint = V.graph.sizevars.symbolic_hint(numel) if not isinstance(numel_hint, (int, sympy.Integer)): # This default heuristic hint was picked carefully: it is # large, to ensure that we don't shrink the block size (since # if you don't have many elements, it'd be wasteful to pick a # large block size). Since we don't know how many elements we # might have, we should be OK with some inefficiency to make # sure we handle the large case well. 8192 is the largest # block size we support, so we pick that. # # If we have a better hint for unbacked SymInts (e.g., because # a user told us, or we are tracking upper bounds) we could # use that here. size_hint = 8192 else: size_hint = next_power_of_2(int(numel_hint)) size_hints[prefix] = size_hint if name is None: code.splice(gen_common_triton_imports()) device_type = V.graph.get_current_device_or_throw().type if device_type == "cpu": code.splice("triton_helpers.set_driver_to_cpu()") else: code.splice("triton_helpers.set_driver_to_gpu()") if config.benchmark_kernel: code.splice(self.imports_for_benchmark_kernel()) argdefs, _, signature, _ = self.args.python_argdefs() # maps actual expression to SizeArg if it is in sizevars replacements for i, arg in enumerate(signature): if isinstance(arg, SizeArg): # mypy is unhappy about the sympy.Expr # type for the key of the dict below symbol = cast(sympy.Symbol, arg.expr) if symbol in V.graph.sizevars.inv_precomputed_replacements: signature[i] = SizeArg( arg.name, V.graph.sizevars.inv_precomputed_replacements[symbol] ) mutated_args: OrderedSet[str] = OrderedSet() for mutation in self.mutations: if mutation in self.args.input_buffers: mutated_args.add(self.args.input_buffers[mutation]) if ( mutation in self.args.inplace_buffers and mutation not in V.graph.removed_buffers and mutation not in self.removed_buffers ): mutated_args.add( cast(InplacedBuffer, self.args.inplace_buffers[mutation]).inner_name ) if mutation in self.args.output_buffers: mutation_arg = self.args.output_buffers[mutation] assert not isinstance(mutation_arg, RemovedArg) mutated_args.add(mutation_arg) # Note: [Workspace Mutation] # workspace arguments are mutated, but are not marked as mutations in self.mutations # because their buffers are added during codegen, and aren't tracked during # lowering/scheduling. So we add them as mutated_args explicitly below. # # In the logic below, we only mark the workspaces a mutated if they are marked with # zero_fill: that's because, if we don't expect the buffer to be pre-filled with # zeros, then, although we still mutate the data, we don't care about those # mutations because we don't make any assumptions about the contents of the # workspace buffer. Similarly, ZERO_PER_GRAPH requires the kernel to return # the buffer back to its original state. for argname, arg in zip(argdefs, signature): if ( isinstance(arg, WorkspaceArg) and arg.zero_mode == WorkspaceZeroMode.ZERO_ON_CALL ): mutated_args.add(argname.name) mutated_args = sorted(mutated_args) for tree in self.active_range_trees(): sizearg = SizeArg(f"{tree.prefix}numel", tree.numel) signature.append(sizearg) argdefs.append(ArgName(sizearg.name)) # constexpr version causes issues, see # https://github.com/pytorch/torchdynamo/pull/1362 # triton_meta["constants"][len(argdefs)] = V.graph.sizevars.size_hint( # tree.numel # ) # argdefs.append(f"{tree.prefix}numel: tl.constexpr") def add_constexpr_arg(arg_name): # new versions (but not old versions) of Triton need constexprs included in the signature if triton_version_uses_attrs_dict(): signature.append(ConstexprArg(arg_name)) argdefs.append(ArgName(arg_name, is_constexpr=True)) for tree in self.range_trees: if tree.is_reduction and self.persistent_reduction: # Rn_BLOCK for persistent_reduction is defined in codegen_static_numels continue if tree.tensor_dim is None: continue add_constexpr_arg(f"{tree.prefix.upper()}BLOCK") if self.cooperative_reduction: add_constexpr_arg("RSPLIT") if self.mix_order_reduction: add_constexpr_arg("RSPLIT_SIZE") add_constexpr_arg("NUM_STAGES") triton_meta_signature = signature_to_meta( signature, size_dtype=self.index_dtype, argdefs=argdefs ) triton_meta: dict[str, Any] = { "signature": triton_meta_signature, "device": DeviceProperties.create(V.graph.get_current_device_or_throw()), "constants": {}, "native_matmul": ( torch._inductor.config.triton.native_matmul and ("tl.dot" in str(self.body) or "tl.dot" in str(self.compute)) ), } # Skip memory optimization for forward of the training loop where we expect # every new node will increase the peak memory and our greedy approach would # introduce a lot of unnecessary cpu copies. optimize_mem = V.graph.is_inference or V.graph.is_backward inductor_meta = { "grid_type": self._get_grid_type().__name__, # Triton will not accept an OrderedSet for autotune_hints "autotune_hints": set(self.autotune_hints), # noqa: set_linter "kernel_name": str(Placeholder.DESCRIPTIVE_NAME), "mutated_arg_names": mutated_args, "optimize_mem": optimize_mem, "no_x_dim": self.no_x_dim, "atomic_add_found": self.atomic_add_found, "num_load": self.num_load, "num_store": self.num_store, "num_reduction": self.num_reduction, **self.inductor_meta_common(), } if self.mix_order_reduction: inductor_meta["RSPLIT_SIZE"] = self.rsplit_size if config.deterministic or config.test_configs.force_filter_reduction_configs: inductor_meta["has_loadstore_with_contiguous_rdim"] = ( self.has_load_with_contiguous_rdim or self.has_store_with_contiguous_rdim ) # Bail on 3d tiling, which has more complicated coalesce patterns looped_red = V.kernel.features.is_reduction() and not self.persistent_reduction tiling_scores = self.tiling_scores two_d_red = len(self.tiling) == 2 if looped_red and two_d_red: memory_stats = self.features.memory_stats(self.tiling) dim_stats = memory_stats.persistent.memory.dim[0] mem_ops_per_thread = dim_stats.count_per_thread if ( tiling_scores is not None and "x" in tiling_scores and "r0_" in tiling_scores ): # large rblock inhibits xblock size, dont attempt if there is a decent amount of # reads coalesced by xblock r_coalesce_ratio = tiling_scores["r0_"] / max(tiling_scores["x"], 1) contiguous_red = r_coalesce_ratio >= 8.0 else: from torch._inductor.runtime.hints import ReductionHint contiguous_red = ( self.features.get_reduction_hint() == ReductionHint.INNER ) looped_mem = memory_stats.looped.memory.bytes persistent_mem = memory_stats.persistent.memory.bytes # check that we save significant memory by doing persistent saved_bytes_ratio = V.graph.sizevars.size_hint( looped_mem, fallback=config.unbacked_symint_fallback ) / max( V.graph.sizevars.size_hint( persistent_mem, fallback=config.unbacked_symint_fallback ), 1, ) # TODO - rnumel should be reasonably close to power of 2 if ( # significant memory bandwidth savings saved_bytes_ratio >= 1.3 and contiguous_red # TODO - need more detailed register analysis and V.graph.sizevars.statically_known_leq( self.features.reduction_numel, 32768 ) # We will already generate a persistent config in this case and V.graph.sizevars.statically_known_gt( self.features.reduction_numel, 2048 ) and mem_ops_per_thread <= 10 ): inductor_meta["add_persistent_rblock"] = True if self.tiling_scores: inductor_meta["tiling_scores"] = self.tiling_scores if self.tma_min_block_sizes: inductor_meta["tma_min_block_sizes"] = self.tma_min_block_sizes if self.cooperative_reduction: inductor_meta["persistent_reduction"] = self.persistent_reduction num_gb = None if config.benchmark_kernel or config.profile_bandwidth: num_gb = self.estimate_kernel_num_bytes() / 1e9 if num_gb is not None: inductor_meta["kernel_num_gb"] = num_gb if config.benchmark_kernel: flops = self.estimate_flops() if flops is not None: inductor_meta["kernel_flop"] = flops triton_meta["configs"] = [config_of(signature)] if enable_pdl_codegen(): triton_meta["launch_pdl"] = True # Triton compiler includes equal_to_1 args into constants even # when they are not constexpr. otherwise there may be a segfault # during launching the Inductor-compiled Triton kernel. # https://github.com/pytorch/pytorch/issues/120478#issuecomment-1962822307 # https://github.com/triton-lang/triton/blob/231efe9ed2d200be0f69a07c298e4342b08efe3d/python/triton/runtime/jit.py#L384 for arg_num in equal_1_arg_indices(signature): # type: ignore[index] triton_meta["constants"][signature[arg_num].name] = 1 # type: ignore[index,union-attr] triton_meta["enable_fp_fusion"] = not config.emulate_precision_casts self.triton_meta = triton_meta self.codegen_prologue(self.body) self.codegen_body() for helper in self.helper_functions: code.writeline("") code.splice(helper) if self.fixed_config: heuristics_line = f""" @triton_heuristics.{self._get_heuristic()}( config={self.fixed_config.config!r}, filename=__file__, triton_meta={triton_meta!r}, inductor_meta={inductor_meta!r} ) @triton.jit """ elif self.inside_reduction: reduction_hint = self.features.get_reduction_hint() heuristics_line = f""" @triton_heuristics.{self._get_heuristic()}( size_hints={size_hints!r}, reduction_hint={reduction_hint}, filename=__file__, triton_meta={triton_meta!r}, inductor_meta={inductor_meta!r} ) @triton.jit """ else: tile_hint = "" if len(size_hints) == 2: if ( len(non_constexpr_signature(signature)) == 4 ): # input, output and 2 args tile_hint = "tile_hint=TileHint.SQUARE," else: tile_hint = "tile_hint=TileHint.DEFAULT," heuristics_line = f""" @triton_heuristics.{self._get_heuristic()}( size_hints={size_hints!r}, {tile_hint} filename=__file__, triton_meta={triton_meta!r}, inductor_meta={inductor_meta!r}, min_elem_per_thread={self.min_elem_per_thread} ) @triton.jit """ code.splice(heuristics_line) code.writeline( f"def {name or str(Placeholder.KERNEL_NAME)}({', '.join(x.full_name() for x in argdefs)}):" ) with code.indent(): self.codegen_static_numels(code) for old, new in self.args.aliases(): code.writeline(f"{old} = {new}") code.splice(self.body) if config.benchmark_kernel: code.splice(self.codegen_kernel_benchmark(num_gb)) return code.getvalue() @staticmethod def _get_persistent_RBLOCK(rnumel): rnumel = V.graph.sizevars.simplify(rnumel) if isinstance(rnumel, (sympy.Integer, int)): val = int(rnumel) val = next_power_of_2(val) else: val = 2 while not V.graph.sizevars.statically_known_leq(rnumel, val): if val > 16 * 1024: raise ValueError(f"Failed to find static RBLOCK for {rnumel}") val *= 2 return val return val @staticmethod def has_persistent_RBLOCK(rnumel): try: TritonKernel._get_persistent_RBLOCK(rnumel) return True except ValueError: return False def codegen_static_numels(self, code): """ We get a small speedup from hard coding numels if they are static. This code stomps on the passed-in values by writing an constant to the top of the kernel. In a kernel like: def KERNEL_NAME(in_ptr0, in_ptr1, out_ptr2, xnumel, r0_numel, XBLOCK : tl.constexpr, R0_BLOCK : tl.constexpr): We would add xnumel = 4096 r0_numel = 768 After the signature, before the kernel code, if we decided to make these static. As its hardcoded, it becomes a better signal to triton on how to unroll and do some static indexing. So, it's not so much that downstream knows that its a static numel, as that you just plop a constant into the kernel. """ def is_static_integer(expr: sympy.Expr) -> bool: return isinstance(expr, (sympy.Integer, int)) for tree in self.range_trees: if not tree.is_reduction or self.inside_reduction: simplified_tree_numel = V.graph.sizevars.simplify(tree.numel) if is_static_integer(simplified_tree_numel): code.writeline(f"{tree.prefix}numel = {int(simplified_tree_numel)}") if tree.is_reduction and self.persistent_reduction: if self.cooperative_reduction: numel = self.kexpr(self.rename_indexing(tree.numel)) val = f"triton_helpers.constexpr_next_power_of_2(({numel} + RSPLIT - 1) // RSPLIT)" else: val = self._get_persistent_RBLOCK(tree.numel) if self.is_native_matmul: # tl.dot only supports shapes >= 16 val = max(val, 16) code.writeline(f"{tree.prefix.upper()}BLOCK: tl.constexpr = {val}") if tree.prefix == "x" and self.no_x_dim: code.writeline("XBLOCK: tl.constexpr = 1") def _get_grid_type(self) -> type[triton_heuristics.GridExpr]: n = sum([int(not tree.is_reduction) for tree in self.range_trees]) if self.mix_order_reduction: assert n == 1 return triton_heuristics.MixOrderReductionGrid elif self.cooperative_reduction: assert n == 1 return triton_heuristics.CooperativeReductionGrid elif n == 1: return triton_heuristics.Grid1D elif n == 2: if any(map(self.needs_yz_grid_overflow, self.range_trees)): return triton_heuristics.Grid2DWithYZOverflow return triton_heuristics.Grid2D elif n == 3: return triton_heuristics.Grid3D raise ValueError(f"Unsupported number of dimensions: {n}") def add_numel_to_call_args(self, name, call_args, arg_types): # TODO(jansel): if there are constants, we shouldn't bother passing them as args for tree in self.range_trees: if isinstance(tree.numel, (sympy.Integer, sympy.Symbol)): expr = tree.numel else: expr = V.graph.wrapper_code.generate_numel_expr(name, tree) if not tree.is_reduction or self.inside_reduction: call_args.append(expr) arg_types.append(type(expr)) def call_kernel( self, name: str, node: Optional[IRNode] = None, deallocate_ws: bool = True ): wrapper = V.graph.wrapper_code wrapper.write_triton_header_once() _, call_args, _, arg_types = self.args.python_argdefs() self.add_numel_to_call_args(name, call_args, arg_types) for ws in self.args.workspace_args: wrapper.generate_workspace_allocation(ws) wrapper.generate_kernel_call( name, call_args, triton=True, arg_types=arg_types, triton_meta=self.triton_meta, ) if deallocate_ws: self.deallocate_workspaces() def codegen_nan_check(self) -> None: wrapper = V.graph.wrapper_code _, call_args, arg_signatures, _ = self.args.python_argdefs() for arg, arg_signature in zip(call_args, arg_signatures): if isinstance(arg_signature, TensorArg): if V.graph.cpp_wrapper: wrapper.writeline( f'AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_check_inf_and_nan("{arg}", {arg}));' ) else: line = f"assert not {arg}.isnan().any().item()" wrapper.writeline(line) line = f"assert not {arg}.isinf().any().item()" wrapper.writeline(line) def create_cse_var(self, *args, **kwargs) -> TritonCSEVariable: return TritonCSEVariable(*args, **kwargs) def codegen_iteration_ranges_entry(self, entry: IterationRangesEntry): line = f"{entry.name} = {self.kexpr(self.rename_indexing(entry.expr))}" # mix order reduction introduces an extra loop across the x # dimension if entry.root.is_loop or (self.mix_order_reduction and entry.prefix == "x"): self.indexing_code.writeline(line) else: # lift non-reduction stores outside loop self.body.writeline(line) def iteration_ranges_ranges_code(self, entry: IterationRangesRoot) -> str: assert entry.tensor_dim is not None size = self.indexing_size_str(entry.tensor_dim) index_dtype = self.index_dtype suffix = f".to({index_dtype})" if index_dtype != "tl.int32" else "" if ( self.cooperative_reduction and self.persistent_reduction and entry.is_reduction ): suffix = f"{suffix} + rsplit_start" return f"tl.arange(0, {entry.prefix.upper()}BLOCK){size}{suffix}" def iteration_ranges_scalar_code( self, entry: IterationRangesRoot, value: Any ) -> str: index_dtype = self.index_dtype ndim = self.triton_tensor_ndim() size = [1] * ndim return f"tl.full({size}, {value}, {index_dtype})" def iteration_ranges_get_pid(self, entry: IterationRangesRoot) -> str: assert entry.grid_dim is not None key = f"tl.program_id({entry.grid_dim})" # y_grid has a limit, so express it in terms of y and z in case of overflow. # z grid is only exercised when max_tiles == 3 (off by default). if self.needs_yz_grid_overflow(entry): # For ynumel larger than max_ygrid, we need to use zdim. # For each z dimension, there are tl.num_programs(1) yblocks which is passed by grad(x,y,z). # So, we need to add tl.program_id(z) * tl.num_programs(y) *YBLOCK to get the correct yoffset. key = f"({key} + tl.program_id({entry.grid_dim + 1}) * tl.num_programs({entry.grid_dim}))" pid = entry.pid_cache.get(key, key) if self.index_dtype != "tl.int32": return f"{pid}.to({self.index_dtype})" return pid def needs_yz_grid_overflow(self, entry: IterationRangesRoot) -> bool: return ( entry.grid_dim == 1 and not entry.has_zdim and not self.cooperative_reduction and not V.graph.sizevars.statically_known_leq(entry.numel, get_max_y_grid()) ) def max_block(self, prefix: str) -> int: if self.fixed_config: return self.fixed_config[f"{prefix.upper()}BLOCK"] return TRITON_MAX_BLOCK[prefix.upper()] def _has_constant_mask(self, tree: IterationRangesRoot) -> bool: if self.is_native_matmul: # tl.dot requires the shape to be >= 16, # so when matmul shape is smaller than 16, we always keep the mask. if V.graph.sizevars.statically_known_lt(tree.numel, 16): return False if not self.optimize_mask: return False if self.fixed_config and f"{tree.prefix.upper()}BLOCK" in self.fixed_config: if self.fixed_config[f"{tree.prefix.upper()}BLOCK"] == 1: return True else: if V.graph.sizevars.statically_known_equals(tree.numel, 1): return True # Masks are superfluous if numel is a multiple of BLOCK # (We use the fact that BLOCK is required by triton to be a power of 2) if tree.is_reduction and self.persistent_reduction: max_block = self._get_persistent_RBLOCK(tree.numel) elif tree.prefix == "x" and self.no_x_dim: max_block = 1 else: max_block = self.max_block(tree.prefix) if tree.is_reduction and self.cooperative_reduction: max_block = max_block * self.max_rsplit() # [Note: Constant mask optimisation] # Optional optimization: if block divides numel exactly, we will # never need to do a masked load to handle stragglers at the end. # If this tree is for the y dimension, we should only use a constant # mask if it can be guaranteed that: # 1. (ynumel / YBLOCK) < max_ygrid or # 2. (ynumel / YBLOCK) % max_ygrid == 0 # Because YBLOCK is not constant, use a conservative heuristic: # only use a constant mask if ynumel < max_ygrid. # It's faster to avoid masking at all. But it is sound to always # mask. if V.graph.sizevars.statically_known_multiple_of(tree.numel, max_block): return ( tree.grid_dim != 1 or tree.has_zdim or V.graph.sizevars.statically_known_leq(tree.numel, get_max_y_grid()) ) return False def _has_constant_xmask(self) -> bool: xtree = self.range_trees[0] assert xtree.prefix == "x" return self._has_constant_mask(xtree) def filter_masks(self, mask_vars: OrderedSet[str]) -> None: for tree in self.range_trees: if self._has_constant_mask(tree): mask_vars.discard(f"{tree.prefix}mask") # can be added as an override_mask mask_vars.discard("None") @cache_on_self def get_reduction_prefixes(self) -> list[str]: return [ prefix_str[symt] for symt in list(TritonSymbols.reduction_types)[: self.num_reduction_dims] ] def codegen_reduction_numels(self, buffer: IndentedBuffer) -> None: """ Generates code that flattens ND reduction numels, block sizes, etc. into 1D. """ # rnumel = r0_numel * ... * r(n-1)_numel reduction_trees = [tree for tree in self.range_trees if tree.is_reduction] rnumel = " * ".join(sorted(f"{tree.prefix}numel" for tree in reduction_trees)) buffer.splice(f"rnumel = {self.kexpr(rnumel)}") # RBLOCK = R0_BLOCK * ... * R(N-1)_BLOCK rn_blocks = [ TritonSymbols.block_sizes[tree.symt] for tree in self.range_trees if tree.is_reduction ] rblock = sympy_product(rn_blocks) buffer.splice(f"RBLOCK: tl.constexpr = {self.kexpr(rblock)}") def _get_reduction_symbols(self, suffix: str, **kwargs) -> list[sympy.Symbol]: """ Helper to initialize symbols like rn_numel, rn_base, etc. """ rn_prefixes = self.get_reduction_prefixes() return [sympy.Symbol(f"{prefix}{suffix}", **kwargs) for prefix in rn_prefixes] @cache_on_self def _get_reduction_index_coeffs(self) -> list[sympy.Expr]: """ Compute coefficients to convert ND reduction indices to linear indices. For example: rindex = r0_index * r1_numel * ... * rn_numel + ... + rn_index. """ rn_prefixes = self.get_reduction_prefixes() rn_numels = self._get_reduction_symbols("numel", integer=True, positive=True) return [ sympy_product(rn_numels[idx + 1 :]) for idx in range(len(rn_prefixes) - 1) ] + [sympy.Integer(1)] def _flatten_reduction_indices(self, multi_inds: list[sympy.Expr]) -> sympy.Expr: """ Compute linear reduction indices from N dimensional ones. """ coeffs = self._get_reduction_index_coeffs() return sympy_dot(coeffs, multi_inds) def codegen_reduction_indices(self, buffer: IndentedBuffer) -> None: """ Generates code that converts ND reduction indices into linear indices. """ # Gather relevant numels, indices, etc. rn_offsets = self._get_reduction_symbols( "offset", integer=True, nonnegative=True ) rn_inds = self._get_reduction_symbols("index", integer=True, nonnegative=True) # Compute roffset and rindex. roffset = self._flatten_reduction_indices(rn_offsets) buffer.splice(f"roffset = {self.index_to_str(roffset)}") rindex = self._flatten_reduction_indices(rn_inds) buffer.splice(f"rindex = {self.index_to_str(rindex)}") def iteration_ranges_codegen_header( self, entry: IterationRangesRoot, code: IndentedBuffer ) -> None: x = entry.prefix if entry.is_loop: code.writeline(f"{entry.name} = {x}offset + {x}base") elif entry.grid_dim is None: # no need to "{x}offset = " code.writeline(f"{entry.name} = {self.iteration_ranges_ranges_code(entry)}") code.writeline(f"{x}offset = 0") else: if entry.tensor_dim is not None: line = f"{x}offset + {self.iteration_ranges_ranges_code(entry)}" else: line = self.iteration_ranges_scalar_code(entry, f"{x}offset") block_size = ( f"{x.upper()}BLOCK" if not self.mix_order_reduction else "RSPLIT_SIZE" ) code.writelines( [ f"{x}offset = {self.iteration_ranges_get_pid(entry)} * {block_size}", f"{entry.name} = {line}", ] ) if self._has_constant_mask(entry): code.writeline(self.create_constant_mask(entry)) elif not (x == "x" and self.mix_order_reduction): # mix order reduction should generate xmask inside the loop code.writeline(f"{x}mask = {entry.name} < {x}numel")
TritonKernel
python
sympy__sympy
sympy/functions/combinatorial/numbers.py
{ "start": 10023, "end": 11534 }
class ____(DefinedFunction): """ Lucas numbers Lucas numbers satisfy a recurrence relation similar to that of the Fibonacci sequence, in which each term is the sum of the preceding two. They are generated by choosing the initial values `L_0 = 2` and `L_1 = 1`. * ``lucas(n)`` gives the `n^{th}` Lucas number Examples ======== >>> from sympy import lucas >>> [lucas(x) for x in range(11)] [2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123] See Also ======== bell, bernoulli, catalan, euler, fibonacci, harmonic, genocchi, partition, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Lucas_number .. [2] https://mathworld.wolfram.com/LucasNumber.html """ @classmethod def eval(cls, n): if n is S.Infinity: return S.Infinity if n.is_Integer: return fibonacci(n + 1) + fibonacci(n - 1) def _eval_rewrite_as_sqrt(self, n, **kwargs): from sympy.functions.elementary.miscellaneous import sqrt return 2**(-n)*((1 + sqrt(5))**n + (-sqrt(5) + 1)**n) #----------------------------------------------------------------------------# # # # Tribonacci numbers # # # #----------------------------------------------------------------------------#
lucas
python
walkccc__LeetCode
solutions/2513. Minimize the Maximum of Two Arrays/2513.py
{ "start": 0, "end": 755 }
class ____: def minimizeSet( self, divisor1: int, divisor2: int, uniqueCnt1: int, uniqueCnt2: int, ) -> int: divisorLcm = math.lcm(divisor1, divisor2) l = 0 r = 2**31 - 1 def isPossible(m: int) -> bool: """ Returns True if we can take uniqueCnt1 integers from [1..m] to arr1 and take uniqueCnt2 integers from [1..m] to arr2. """ cnt1 = m - m // divisor1 cnt2 = m - m // divisor2 totalCnt = m - m // divisorLcm return (cnt1 >= uniqueCnt1 and cnt2 >= uniqueCnt2 and totalCnt >= uniqueCnt1 + uniqueCnt2) while l < r: m = (l + r) // 2 if isPossible(m): r = m else: l = m + 1 return l
Solution
python
doocs__leetcode
solution/0200-0299/0275.H-Index II/Solution.py
{ "start": 0, "end": 330 }
class ____: def hIndex(self, citations: List[int]) -> int: n = len(citations) left, right = 0, n while left < right: mid = (left + right + 1) >> 1 if citations[n - mid] >= mid: left = mid else: right = mid - 1 return left
Solution
python
kamyu104__LeetCode-Solutions
Python/subarrays-distinct-element-sum-of-squares-i.py
{ "start": 6289, "end": 6680 }
class ____(object): def sumCounts(self, nums): """ :type nums: List[int] :rtype: int """ MOD = 10**9+7 result = 0 for i in xrange(len(nums)): lookup = set() for j in reversed(xrange(i+1)): lookup.add(nums[j]) result = (result+len(lookup)**2) % MOD return result
Solution3
python
marshmallow-code__marshmallow
src/marshmallow/validate.py
{ "start": 15054, "end": 15933 }
class ____(Validator): """Validator which succeeds if the ``value`` passed to it is equal to ``comparable``. :param comparable: The object to compare to. :param error: Error message to raise in case of a validation error. Can be interpolated with `{input}` and `{other}`. """ default_message = "Must be equal to {other}." def __init__(self, comparable, *, error: str | None = None): self.comparable = comparable self.error: str = error or self.default_message def _repr_args(self) -> str: return f"comparable={self.comparable!r}" def _format_error(self, value: _T) -> str: return self.error.format(input=value, other=self.comparable) def __call__(self, value: _T) -> _T: if value != self.comparable: raise ValidationError(self._format_error(value)) return value
Equal
python
google__pytype
pytype/tests/test_typevar2.py
{ "start": 28505, "end": 31992 }
class ____(test_base.BaseTest): """Tests for TypeVar in Python 3.""" def test_use_constraints_from_pyi(self): with test_utils.Tempdir() as d: d.create_file( "foo.pyi", """ from typing import AnyStr, TypeVar T = TypeVar("T", int, float) def f(x: T) -> T: ... def g(x: AnyStr) -> AnyStr: ... """, ) _, errors = self.InferWithErrors( """ import foo foo.f("") # wrong-arg-types[e1] foo.g(0) # wrong-arg-types[e2] """, pythonpath=[d.path], ) self.assertErrorRegexes( errors, { "e1": r"Union\[float, int\].*str", "e2": r"Union\[bytes, str\].*int", }, ) def test_subprocess(self): ty = self.Infer(""" import subprocess from typing import List def run(args: List[str]): result = subprocess.run( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) if result.returncode: raise subprocess.CalledProcessError( result.returncode, args, result.stdout) return result.stdout """) self.assertTypesMatchPytd( ty, """ import subprocess from typing import List def run(args: List[str]) -> str: ... """, ) def test_abstract_classmethod(self): self.Check(""" from abc import ABC, abstractmethod from typing import Type, TypeVar T = TypeVar('T', bound='Foo') class Foo(ABC): @classmethod @abstractmethod def f(cls: Type[T]) -> T: return cls() """) def test_split(self): self.Check(""" from typing import AnyStr, Generic class Foo(Generic[AnyStr]): def __init__(self, x: AnyStr): if isinstance(x, str): self.x = x else: self.x = x.decode('utf-8') """) def test_typevar_in_variable_annotation(self): self.Check(""" from typing import TypeVar T = TypeVar('T') def f(x: T): y: T = x """) def test_none_constraint(self): self.CheckWithErrors(""" from typing import TypeVar T = TypeVar('T', float, None) def f(x: T) -> T: return x f(0.0) f(None) f("oops") # wrong-arg-types """) def test_builtin_dict_constraint(self): with self.DepTree([( "foo.pyi", """ from typing import TypeVar T = TypeVar('T', int, dict[str, int]) class C: def f(self, x: T) -> T: ... """, )]): self.Check(""" import foo from typing import TypeVar T = TypeVar('T', int, dict[str, int]) class C(foo.C): def f(self, x: T) -> T: return x """) def test_check_type_param_against_param_spec(self): self.Check(""" import multiprocessing.pool from typing import Callable, ParamSpec, TypeVar, Any _T = TypeVar('_T') _Args = ParamSpec('_Args') def decorator() -> Callable[[Callable[_Args, _T]], Callable[_Args, _T]]: pass # pytype: disable=bad-return-type def foo(): @decorator() def f(i: int): return i with multiprocessing.pool.ThreadPool(10) as pool: a: list[Any] = pool.map(f, list(range(10))) # TODO: Should be list[int] """) if __name__ == "__main__": test_base.main()
TypeVarTestPy3
python
keras-team__keras
keras/src/layers/core/wrapper_test.py
{ "start": 290, "end": 2589 }
class ____(testing.TestCase): @pytest.mark.requires_trainable_backend def test_wrapper_basics(self): self.run_layer_test( ExampleWrapper, init_kwargs={ "layer": layers.Dense(2), }, input_shape=(2, 3), expected_output_shape=(2, 2), expected_num_trainable_weights=2, expected_num_non_trainable_weights=0, expected_num_seed_generators=0, expected_num_losses=0, supports_masking=False, ) self.run_layer_test( ExampleWrapper, init_kwargs={ "layer": layers.Dense(2, activity_regularizer="l2"), }, input_shape=(2, 3), expected_output_shape=(2, 2), expected_num_trainable_weights=2, expected_num_non_trainable_weights=0, expected_num_seed_generators=0, expected_num_losses=1, supports_masking=False, ) self.run_layer_test( ExampleWrapper, init_kwargs={ "layer": layers.Dense(2), "activity_regularizer": "l2", }, input_shape=(2, 3), expected_output_shape=(2, 2), expected_num_trainable_weights=2, expected_num_non_trainable_weights=0, expected_num_seed_generators=0, expected_num_losses=1, supports_masking=False, ) self.run_layer_test( ExampleWrapper, init_kwargs={ "layer": layers.BatchNormalization(), }, input_shape=(2, 3), expected_output_shape=(2, 3), expected_num_trainable_weights=2, expected_num_non_trainable_weights=2, expected_num_seed_generators=0, expected_num_losses=0, supports_masking=False, ) def test_wrapper_invalid_layer(self): invalid_layer = "This is not a valid Keras layer." with self.assertRaisesRegex( ValueError, "Layer .* supplied to Wrapper isn't a supported layer type. " "Please ensure wrapped layer is a valid Keras layer.", ): layers.Wrapper(invalid_layer)
WrapperTest
python
pytorch__pytorch
torch/_inductor/runtime/triton_heuristics.py
{ "start": 143860, "end": 144510 }
class ____(ComboKernelGrid): def combo_x_grid( self, xnumels: list[int | str], no_x_dims: list[bool], meta: dict[str, int], ) -> str: assert len(xnumels) == len(no_x_dims) num_kernels = self.inductor_meta["combo_grid_meta"]["num_kernels"] exprs = [x for x, no_x_dim in zip(xnumels, no_x_dims) if no_x_dim] xnumels_x_dim = [x for x, no_x_dim in zip(xnumels, no_x_dims) if not no_x_dim] if xnumels_x_dim: exprs.append(self.ceildiv(self.maximum(xnumels_x_dim), meta.get("XBLOCK"))) return f"({self.maximum(exprs)}) * {num_kernels}"
RoundRobinComboKernelGrid
python
urllib3__urllib3
test/test_response.py
{ "start": 4594, "end": 53630 }
class ____: def test_cache_content(self) -> None: r = HTTPResponse(b"foo") assert r._body == b"foo" assert r.data == b"foo" assert r._body == b"foo" def test_cache_content_preload_false(self) -> None: fp = BytesIO(b"foo") r = HTTPResponse(fp, preload_content=False) assert not r._body assert r.data == b"foo" assert r._body == b"foo" # type: ignore[comparison-overlap] assert r.data == b"foo" def test_default(self) -> None: r = HTTPResponse() assert r.data is None def test_none(self) -> None: r = HTTPResponse(None) # type: ignore[arg-type] assert r.data is None def test_preload(self) -> None: fp = BytesIO(b"foo") r = HTTPResponse(fp, preload_content=True) assert fp.tell() == len(b"foo") assert r.data == b"foo" def test_no_preload(self) -> None: fp = BytesIO(b"foo") r = HTTPResponse(fp, preload_content=False) assert fp.tell() == 0 assert r.data == b"foo" assert fp.tell() == len(b"foo") def test_no_shutdown(self) -> None: r = HTTPResponse() with pytest.raises( ValueError, match="Cannot shutdown socket as self._sock_shutdown is not set" ): r.shutdown() def test_decode_bad_data(self) -> None: fp = BytesIO(b"\x00" * 10) with pytest.raises(DecodeError): HTTPResponse(fp, headers={"content-encoding": "deflate"}) def test_reference_read(self) -> None: fp = BytesIO(b"foo") r = HTTPResponse(fp, preload_content=False) assert r.read(0) == b"" assert r.read(1) == b"f" assert r.read(2) == b"oo" assert r.read() == b"" assert r.read() == b"" @pytest.mark.parametrize("read_args", ((), (None,), (-1,))) def test_reference_read_until_eof(self, read_args: tuple[typing.Any, ...]) -> None: fp = BytesIO(b"foo") r = HTTPResponse(fp, preload_content=False) assert r.read(*read_args) == b"foo" def test_reference_read1(self) -> None: fp = BytesIO(b"foobar") r = HTTPResponse(fp, preload_content=False) assert r.read1(0) == b"" assert r.read1(1) == b"f" assert r.read1(2) == b"oo" assert r.read1() == b"bar" assert r.read1() == b"" @pytest.mark.parametrize("read1_args", ((), (None,), (-1,))) def test_reference_read1_without_limit( self, read1_args: tuple[typing.Any, ...] ) -> None: fp = BytesIO(b"foo") r = HTTPResponse(fp, preload_content=False) assert r.read1(*read1_args) == b"foo" def test_reference_read1_nodecode(self) -> None: fp = BytesIO(b"foobar") r = HTTPResponse(fp, preload_content=False, decode_content=False) assert r.read1(0) == b"" assert r.read1(1) == b"f" assert r.read1(2) == b"oo" assert r.read1() == b"bar" assert r.read1() == b"" def test_decoding_read1(self) -> None: data = zlib.compress(b"foobar") fp = BytesIO(data) r = HTTPResponse( fp, headers={"content-encoding": "deflate"}, preload_content=False ) assert r.read1(1) == b"f" assert r.read1(2) == b"oo" assert r.read1() == b"bar" assert r.read1() == b"" def test_decode_deflate(self) -> None: data = zlib.compress(b"foo") fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "deflate"}) assert r.data == b"foo" def test_decode_deflate_case_insensitve(self) -> None: data = zlib.compress(b"foo") fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "DeFlAtE"}) assert r.data == b"foo" def test_chunked_decoding_deflate(self) -> None: data = zlib.compress(b"foo") fp = BytesIO(data) r = HTTPResponse( fp, headers={"content-encoding": "deflate"}, preload_content=False ) assert r.read(1) == b"f" assert r.read(2) == b"oo" assert r.read() == b"" assert r.read() == b"" def test_chunked_decoding_deflate2(self) -> None: compress = zlib.compressobj(6, zlib.DEFLATED, -zlib.MAX_WBITS) data = compress.compress(b"foo") data += compress.flush() fp = BytesIO(data) r = HTTPResponse( fp, headers={"content-encoding": "deflate"}, preload_content=False ) assert r.read(1) == b"f" assert r.read(2) == b"oo" assert r.read() == b"" assert r.read() == b"" @pytest.mark.parametrize("content_encoding", ["gzip", "x-gzip"]) def test_chunked_decoding_gzip(self, content_encoding: str) -> None: compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(b"foo") data += compress.flush() fp = BytesIO(data) r = HTTPResponse( fp, headers={"content-encoding": content_encoding}, preload_content=False ) assert r.read(1) == b"f" assert r.read(2) == b"oo" assert r.read() == b"" assert r.read() == b"" def test_decode_gzip_multi_member(self) -> None: compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(b"foo") data += compress.flush() data = data * 3 fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "gzip"}) assert r.data == b"foofoofoo" def test_decode_gzip_error(self) -> None: fp = BytesIO(b"foo") with pytest.raises(DecodeError): HTTPResponse(fp, headers={"content-encoding": "gzip"}) def test_decode_gzip_swallow_garbage(self) -> None: # When data comes from multiple calls to read(), data after # the first zlib error (here triggered by garbage) should be # ignored. compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(b"foo") data += compress.flush() data = data * 3 + b"foo" fp = BytesIO(data) r = HTTPResponse( fp, headers={"content-encoding": "gzip"}, preload_content=False ) ret = b"" for _ in range(100): ret += r.read(1) if r.closed: break assert ret == b"foofoofoo" def test_chunked_decoding_gzip_swallow_garbage(self) -> None: compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(b"foo") data += compress.flush() data = data * 3 + b"foo" fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "gzip"}) assert r.data == b"foofoofoo" @onlyBrotli() def test_decode_brotli(self) -> None: data = brotli.compress(b"foo") fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "br"}) assert r.data == b"foo" @onlyBrotli() def test_chunked_decoding_brotli(self) -> None: data = brotli.compress(b"foobarbaz") fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "br"}, preload_content=False) ret = b"" for _ in range(100): ret += r.read(1) if r.closed: break assert ret == b"foobarbaz" @onlyBrotli() def test_decode_brotli_error(self) -> None: fp = BytesIO(b"foo") with pytest.raises(DecodeError): HTTPResponse(fp, headers={"content-encoding": "br"}) @onlyZstd() def test_decode_zstd(self) -> None: data = zstd_compress(b"foo") fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "zstd"}) assert r.data == b"foo" @onlyZstd() def test_decode_multiframe_zstd(self) -> None: data = ( # Zstandard frame zstd_compress(b"foo") # skippable frame (must be ignored) + bytes.fromhex( "50 2A 4D 18" # Magic_Number (little-endian) "07 00 00 00" # Frame_Size (little-endian) "00 00 00 00 00 00 00" # User_Data ) # Zstandard frame + zstd_compress(b"bar") ) fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "zstd"}) assert r.data == b"foobar" @onlyZstd() def test_chunked_decoding_zstd(self) -> None: data = zstd_compress(b"foobarbaz") fp = BytesIO(data) r = HTTPResponse( fp, headers={"content-encoding": "zstd"}, preload_content=False ) ret = b"" for _ in range(100): ret += r.read(1) if r.closed: break assert ret == b"foobarbaz" decode_param_set = [ b"foo", b"x" * 100, ] @onlyZstd() @pytest.mark.parametrize("data", decode_param_set) def test_decode_zstd_error(self, data: bytes) -> None: fp = BytesIO(data) with pytest.raises(DecodeError): HTTPResponse(fp, headers={"content-encoding": "zstd"}) @onlyZstd() @pytest.mark.parametrize("data", decode_param_set) def test_decode_zstd_incomplete_preload_content(self, data: bytes) -> None: data = zstd_compress(data) fp = BytesIO(data[:-1]) with pytest.raises(DecodeError): HTTPResponse(fp, headers={"content-encoding": "zstd"}) @onlyZstd() @pytest.mark.parametrize("data", decode_param_set) def test_decode_zstd_incomplete_read(self, data: bytes) -> None: data = zstd_compress(data) fp = BytesIO(data[:-1]) # shorten the data to trigger DecodeError # create response object without(!) reading/decoding the content r = HTTPResponse( fp, headers={"content-encoding": "zstd"}, preload_content=False ) # read/decode, expecting DecodeError with pytest.raises(DecodeError): r.read(decode_content=True) @onlyZstd() @pytest.mark.parametrize("data", decode_param_set) def test_decode_zstd_incomplete_read1(self, data: bytes) -> None: data = zstd_compress(data) fp = BytesIO(data[:-1]) r = HTTPResponse( fp, headers={"content-encoding": "zstd"}, preload_content=False ) # read/decode via read1(!), expecting DecodeError with pytest.raises(DecodeError): amt_decoded = 0 # loop, as read1() may return just partial data while amt_decoded < len(data): part = r.read1(decode_content=True) amt_decoded += len(part) @onlyZstd() @pytest.mark.parametrize("data", decode_param_set) def test_decode_zstd_read1(self, data: bytes) -> None: encoded_data = zstd_compress(data) fp = BytesIO(encoded_data) r = HTTPResponse( fp, headers={"content-encoding": "zstd"}, preload_content=False ) amt_decoded = 0 decoded_data = b"" # loop, as read1() may return just partial data while amt_decoded < len(data): part = r.read1(decode_content=True) amt_decoded += len(part) decoded_data += part assert decoded_data == data def test_multi_decoding_deflate_deflate(self) -> None: data = zlib.compress(zlib.compress(b"foo")) fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "deflate, deflate"}) assert r.data == b"foo" def test_multi_decoding_deflate_gzip(self) -> None: compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(zlib.compress(b"foo")) data += compress.flush() fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "deflate, gzip"}) assert r.data == b"foo" def test_multi_decoding_gzip_gzip(self) -> None: compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(b"foo") data += compress.flush() compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(data) data += compress.flush() fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "gzip, gzip"}) assert r.data == b"foo" def test_read_multi_decoding_deflate_deflate(self) -> None: msg = b"foobarbaz" * 42 data = zlib.compress(zlib.compress(msg)) fp = BytesIO(data) r = HTTPResponse( fp, headers={"content-encoding": "deflate, deflate"}, preload_content=False ) assert r.read(3) == b"foo" assert r.read(3) == b"bar" assert r.read(3) == b"baz" assert r.read(9) == b"foobarbaz" assert r.read(9 * 3) == b"foobarbaz" * 3 assert r.read(9 * 37) == b"foobarbaz" * 37 assert r.read() == b"" def test_body_blob(self) -> None: resp = HTTPResponse(b"foo") assert resp.data == b"foo" assert resp.closed @pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") def test_base_io(self) -> None: resp = BaseHTTPResponse( status=200, version=11, version_string="HTTP/1.1", reason=None, decode_content=False, request_url=None, ) assert not resp.closed assert not resp.readable() assert not resp.writable() with pytest.raises(NotImplementedError): resp.read() with pytest.raises(NotImplementedError): resp.close() def test_io(self, sock: socket.socket) -> None: fp = BytesIO(b"foo") resp = HTTPResponse(fp, preload_content=False) assert not resp.closed assert resp.readable() assert not resp.writable() with pytest.raises(IOError): resp.fileno() resp.close() assert resp.closed # Try closing with an `httplib.HTTPResponse`, because it has an # `isclosed` method. try: hlr = httplib.HTTPResponse(sock) resp2 = HTTPResponse(hlr, preload_content=False) assert not resp2.closed resp2.close() assert resp2.closed finally: hlr.close() # also try when only data is present. resp3 = HTTPResponse("foodata") with pytest.raises(IOError): resp3.fileno() resp3._fp = 2 # A corner case where _fp is present but doesn't have `closed`, # `isclosed`, or `fileno`. Unlikely, but possible. assert resp3.closed with pytest.raises(IOError): resp3.fileno() def test_io_closed_consistently_by_read(self, sock: socket.socket) -> None: try: hlr = httplib.HTTPResponse(sock) hlr.fp = BytesIO(b"foo") # type: ignore[assignment] hlr.chunked = 0 # type: ignore[assignment] hlr.length = 3 with HTTPResponse(hlr, preload_content=False) as resp: assert not resp.closed assert resp._fp is not None assert not resp._fp.isclosed() assert not is_fp_closed(resp._fp) assert not resp.isclosed() resp.read() assert resp.closed assert resp._fp.isclosed() assert is_fp_closed(resp._fp) assert resp.isclosed() finally: hlr.close() @pytest.mark.parametrize("read_amt", (None, 3)) @pytest.mark.parametrize("length_known", (True, False)) def test_io_closed_consistently_by_read1( self, sock: socket.socket, length_known: bool, read_amt: int | None ) -> None: with httplib.HTTPResponse(sock) as hlr: hlr.fp = BytesIO(b"foo") # type: ignore[assignment] hlr.chunked = 0 # type: ignore[assignment] hlr.length = 3 if length_known else None with HTTPResponse(hlr, preload_content=False) as resp: if length_known: resp.length_remaining = 3 assert not resp.closed assert resp._fp is not None assert not resp._fp.isclosed() assert not is_fp_closed(resp._fp) assert not resp.isclosed() resp.read1(read_amt) # If content length is unknown, IO is not closed until # the next read returning zero bytes. if not length_known: assert not resp.closed assert resp._fp is not None assert not resp._fp.isclosed() assert not is_fp_closed(resp._fp) assert not resp.isclosed() resp.read1(read_amt) assert resp.closed assert resp._fp.isclosed() assert is_fp_closed(resp._fp) assert resp.isclosed() @pytest.mark.parametrize("length_known", (True, False)) def test_io_not_closed_until_all_data_is_read( self, sock: socket.socket, length_known: bool ) -> None: with httplib.HTTPResponse(sock) as hlr: hlr.fp = BytesIO(b"foo") # type: ignore[assignment] hlr.chunked = 0 # type: ignore[assignment] length_remaining = 3 hlr.length = length_remaining if length_known else None with HTTPResponse(hlr, preload_content=False) as resp: if length_known: resp.length_remaining = length_remaining while length_remaining: assert not resp.closed assert resp._fp is not None assert not resp._fp.isclosed() assert not is_fp_closed(resp._fp) assert not resp.isclosed() data = resp.read(1) assert len(data) == 1 length_remaining -= 1 # If content length is unknown, IO is not closed until # the next read returning zero bytes. if not length_known: assert not resp.closed assert resp._fp is not None assert not resp._fp.isclosed() assert not is_fp_closed(resp._fp) assert not resp.isclosed() data = resp.read(1) assert len(data) == 0 assert resp.closed assert resp._fp.isclosed() # type: ignore[union-attr] assert is_fp_closed(resp._fp) assert resp.isclosed() @pytest.mark.parametrize("length_known", (True, False)) def test_io_not_closed_after_requesting_0_bytes( self, sock: socket.socket, length_known: bool ) -> None: with httplib.HTTPResponse(sock) as hlr: hlr.fp = BytesIO(b"foo") # type: ignore[assignment] hlr.chunked = 0 # type: ignore[assignment] length_remaining = 3 hlr.length = length_remaining if length_known else None with HTTPResponse(hlr, preload_content=False) as resp: if length_known: resp.length_remaining = length_remaining assert not resp.closed assert resp._fp is not None assert not resp._fp.isclosed() assert not is_fp_closed(resp._fp) assert not resp.isclosed() data = resp.read(0) assert data == b"" assert not resp.closed assert resp._fp is not None assert not resp._fp.isclosed() assert not is_fp_closed(resp._fp) assert not resp.isclosed() def test_io_bufferedreader(self) -> None: fp = BytesIO(b"foo") resp = HTTPResponse(fp, preload_content=False) br = BufferedReader(resp) # type: ignore[type-var] assert br.read() == b"foo" br.close() assert resp.closed # HTTPResponse.read() by default closes the response # https://github.com/urllib3/urllib3/issues/1305 fp = BytesIO(b"hello\nworld") resp = HTTPResponse(fp, preload_content=False) with pytest.raises(ValueError, match="readline of closed file"): list(BufferedReader(resp)) # type: ignore[type-var] b = b"fooandahalf" fp = BytesIO(b) resp = HTTPResponse(fp, preload_content=False) br = BufferedReader(resp, 5) # type: ignore[type-var] br.read(1) # sets up the buffer, reading 5 assert len(fp.read()) == (len(b) - 5) # This is necessary to make sure the "no bytes left" part of `readinto` # gets tested. while not br.closed: br.read(5) def test_io_not_autoclose_bufferedreader(self) -> None: fp = BytesIO(b"hello\nworld") resp = HTTPResponse(fp, preload_content=False, auto_close=False) reader = BufferedReader(resp) # type: ignore[type-var] assert list(reader) == [b"hello\n", b"world"] assert not reader.closed assert not resp.closed with pytest.raises(StopIteration): next(reader) reader.close() assert reader.closed assert resp.closed with pytest.raises(ValueError, match="readline of closed file"): next(reader) def test_io_textiowrapper(self) -> None: fp = BytesIO(b"\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f") resp = HTTPResponse(fp, preload_content=False) br = TextIOWrapper(resp, encoding="utf8") # type: ignore[type-var] assert br.read() == "äöüß" br.close() assert resp.closed # HTTPResponse.read() by default closes the response # https://github.com/urllib3/urllib3/issues/1305 fp = BytesIO( b"\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f\n\xce\xb1\xce\xb2\xce\xb3\xce\xb4" ) resp = HTTPResponse(fp, preload_content=False) with pytest.raises(ValueError, match="I/O operation on closed file.?"): list(TextIOWrapper(resp)) # type: ignore[type-var] def test_io_not_autoclose_textiowrapper(self) -> None: fp = BytesIO( b"\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f\n\xce\xb1\xce\xb2\xce\xb3\xce\xb4" ) resp = HTTPResponse(fp, preload_content=False, auto_close=False) reader = TextIOWrapper(resp, encoding="utf8") # type: ignore[type-var] assert list(reader) == ["äöüß\n", "αβγδ"] assert not reader.closed assert not resp.closed with pytest.raises(StopIteration): next(reader) reader.close() assert reader.closed assert resp.closed with pytest.raises(ValueError, match="I/O operation on closed file.?"): next(reader) def test_read_with_illegal_mix_decode_toggle(self) -> None: data = zlib.compress(b"foo") fp = BytesIO(data) resp = HTTPResponse( fp, headers={"content-encoding": "deflate"}, preload_content=False ) assert resp.read(1) == b"f" with pytest.raises( RuntimeError, match=( r"Calling read\(decode_content=False\) is not supported after " r"read\(decode_content=True\) was called" ), ): resp.read(1, decode_content=False) with pytest.raises( RuntimeError, match=( r"Calling read\(decode_content=False\) is not supported after " r"read\(decode_content=True\) was called" ), ): resp.read(decode_content=False) def test_read1_with_illegal_mix_decode_toggle(self) -> None: data = zlib.compress(b"foo") fp = BytesIO(data) resp = HTTPResponse( fp, headers={"content-encoding": "deflate"}, preload_content=False ) assert resp.read1(1) == b"f" with pytest.raises( RuntimeError, match=( r"Calling read1\(decode_content=False\) is not supported after " r"read1\(decode_content=True\) was called" ), ): resp.read1(1, decode_content=False) with pytest.raises( RuntimeError, match=( r"Calling read1\(decode_content=False\) is not supported after " r"read1\(decode_content=True\) was called" ), ): resp.read1(decode_content=False) def test_read_with_mix_decode_toggle(self) -> None: data = zlib.compress(b"foo") fp = BytesIO(data) resp = HTTPResponse( fp, headers={"content-encoding": "deflate"}, preload_content=False ) assert resp.read(2, decode_content=False) is not None assert resp.read(1, decode_content=True) == b"f" def test_streaming(self) -> None: fp = BytesIO(b"foo") resp = HTTPResponse(fp, preload_content=False) stream = resp.stream(2, decode_content=False) assert next(stream) == b"fo" assert next(stream) == b"o" with pytest.raises(StopIteration): next(stream) def test_streaming_tell(self) -> None: fp = BytesIO(b"foo") resp = HTTPResponse(fp, preload_content=False) stream = resp.stream(2, decode_content=False) position = 0 position += len(next(stream)) assert 2 == position assert position == resp.tell() position += len(next(stream)) assert 3 == position assert position == resp.tell() with pytest.raises(StopIteration): next(stream) def test_gzipped_streaming(self) -> None: compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(b"foo") data += compress.flush() fp = BytesIO(data) resp = HTTPResponse( fp, headers={"content-encoding": "gzip"}, preload_content=False ) stream = resp.stream(2) assert next(stream) == b"fo" assert next(stream) == b"o" with pytest.raises(StopIteration): next(stream) def test_gzipped_streaming_tell(self) -> None: compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) uncompressed_data = b"foo" data = compress.compress(uncompressed_data) data += compress.flush() fp = BytesIO(data) resp = HTTPResponse( fp, headers={"content-encoding": "gzip"}, preload_content=False ) stream = resp.stream() # Read everything payload = next(stream) assert payload == uncompressed_data assert len(data) == resp.tell() with pytest.raises(StopIteration): next(stream) def test_deflate_streaming_tell_intermediate_point(self) -> None: # Ensure that ``tell()`` returns the correct number of bytes when # part-way through streaming compressed content. NUMBER_OF_READS = 10 PART_SIZE = 64 class MockCompressedDataReading(BytesIO): """ A BytesIO-like reader returning ``payload`` in ``NUMBER_OF_READS`` calls to ``read``. """ def __init__(self, payload: bytes, payload_part_size: int) -> None: self.payloads = [ payload[i * payload_part_size : (i + 1) * payload_part_size] for i in range(NUMBER_OF_READS + 1) ] assert b"".join(self.payloads) == payload def read(self, _: int) -> bytes: # type: ignore[override] # Amount is unused. if len(self.payloads) > 0: return self.payloads.pop(0) return b"" def read1(self, amt: int) -> bytes: # type: ignore[override] return self.read(amt) uncompressed_data = zlib.decompress(ZLIB_PAYLOAD) payload_part_size = len(ZLIB_PAYLOAD) // NUMBER_OF_READS fp = MockCompressedDataReading(ZLIB_PAYLOAD, payload_part_size) resp = HTTPResponse( fp, headers={"content-encoding": "deflate"}, preload_content=False ) stream = resp.stream(PART_SIZE) parts_positions = [(part, resp.tell()) for part in stream] end_of_stream = resp.tell() with pytest.raises(StopIteration): next(stream) parts, positions = zip(*parts_positions) # Check that the payload is equal to the uncompressed data payload = b"".join(parts) assert uncompressed_data == payload # Check that the positions in the stream are correct # It is difficult to determine programmatically what the positions # returned by `tell` will be because the `HTTPResponse.read` method may # call socket `read` a couple of times if it doesn't have enough data # in the buffer or not call socket `read` at all if it has enough. All # this depends on the message, how it was compressed, what is # `PART_SIZE` and `payload_part_size`. # So for simplicity the expected values are hardcoded. expected = (92, 184, 230, 276, 322, 368, 414, 460) assert expected == positions # Check that the end of the stream is in the correct place assert len(ZLIB_PAYLOAD) == end_of_stream # Check that all parts have expected length expected_last_part_size = len(uncompressed_data) % PART_SIZE whole_parts = len(uncompressed_data) // PART_SIZE if expected_last_part_size == 0: expected_lengths = [PART_SIZE] * whole_parts else: expected_lengths = [PART_SIZE] * whole_parts + [expected_last_part_size] assert expected_lengths == [len(part) for part in parts] def test_deflate_streaming(self) -> None: data = zlib.compress(b"foo") fp = BytesIO(data) resp = HTTPResponse( fp, headers={"content-encoding": "deflate"}, preload_content=False ) stream = resp.stream(2) assert next(stream) == b"fo" assert next(stream) == b"o" with pytest.raises(StopIteration): next(stream) def test_deflate2_streaming(self) -> None: compress = zlib.compressobj(6, zlib.DEFLATED, -zlib.MAX_WBITS) data = compress.compress(b"foo") data += compress.flush() fp = BytesIO(data) resp = HTTPResponse( fp, headers={"content-encoding": "deflate"}, preload_content=False ) stream = resp.stream(2) assert next(stream) == b"fo" assert next(stream) == b"o" with pytest.raises(StopIteration): next(stream) def test_empty_stream(self) -> None: fp = BytesIO(b"") resp = HTTPResponse(fp, preload_content=False) stream = resp.stream(2, decode_content=False) with pytest.raises(StopIteration): next(stream) @pytest.mark.parametrize( "preload_content, amt, read_meth", [ (True, None, "read"), (False, None, "read"), (False, 10 * 2**20, "read"), (False, None, "read1"), (False, 10 * 2**20, "read1"), ], ) @pytest.mark.limit_memory("25 MB", current_thread_only=True) def test_buffer_memory_usage_decode_one_chunk( self, preload_content: bool, amt: int, read_meth: str ) -> None: content_length = 10 * 2**20 # 10 MiB fp = BytesIO(zlib.compress(bytes(content_length))) resp = HTTPResponse( fp, preload_content=preload_content, headers={"content-encoding": "deflate"}, ) data = resp.data if preload_content else getattr(resp, read_meth)(amt) assert len(data) == content_length @pytest.mark.parametrize( "preload_content, amt, read_meth", [ (True, None, "read"), (False, None, "read"), (False, 10 * 2**20, "read"), (False, None, "read1"), (False, 10 * 2**20, "read1"), ], ) @pytest.mark.limit_memory("10.5 MB", current_thread_only=True) def test_buffer_memory_usage_no_decoding( self, preload_content: bool, amt: int, read_meth: str ) -> None: content_length = 10 * 2**20 # 10 MiB fp = BytesIO(bytes(content_length)) resp = HTTPResponse(fp, preload_content=preload_content, decode_content=False) data = resp.data if preload_content else getattr(resp, read_meth)(amt) assert len(data) == content_length def test_length_no_header(self) -> None: fp = BytesIO(b"12345") resp = HTTPResponse(fp, preload_content=False) assert resp.length_remaining is None def test_length_w_valid_header(self) -> None: headers = {"content-length": "5"} fp = BytesIO(b"12345") resp = HTTPResponse(fp, headers=headers, preload_content=False) assert resp.length_remaining == 5 def test_length_w_bad_header(self) -> None: garbage = {"content-length": "foo"} fp = BytesIO(b"12345") resp = HTTPResponse(fp, headers=garbage, preload_content=False) assert resp.length_remaining is None garbage["content-length"] = "-10" resp = HTTPResponse(fp, headers=garbage, preload_content=False) assert resp.length_remaining is None def test_length_when_chunked(self) -> None: # This is expressly forbidden in RFC 7230 sec 3.3.2 # We fall back to chunked in this case and try to # handle response ignoring content length. headers = {"content-length": "5", "transfer-encoding": "chunked"} fp = BytesIO(b"12345") resp = HTTPResponse(fp, headers=headers, preload_content=False) assert resp.length_remaining is None def test_length_with_multiple_content_lengths(self) -> None: headers = {"content-length": "5, 5, 5"} garbage = {"content-length": "5, 42"} fp = BytesIO(b"abcde") resp = HTTPResponse(fp, headers=headers, preload_content=False) assert resp.length_remaining == 5 with pytest.raises(InvalidHeader): HTTPResponse(fp, headers=garbage, preload_content=False) def test_length_after_read(self) -> None: headers = {"content-length": "5"} # Test no defined length fp = BytesIO(b"12345") resp = HTTPResponse(fp, preload_content=False) resp.read() assert resp.length_remaining is None # Test our update from content-length fp = BytesIO(b"12345") resp = HTTPResponse(fp, headers=headers, preload_content=False) resp.read() assert resp.length_remaining == 0 # Test partial read fp = BytesIO(b"12345") resp = HTTPResponse(fp, headers=headers, preload_content=False) data = resp.stream(2) next(data) assert resp.length_remaining == 3 def test_mock_httpresponse_stream(self) -> None: # Mock out a HTTP Request that does enough to make it through urllib3's # read() and close() calls, and also exhausts and underlying file # object. class MockHTTPRequest: def __init__(self) -> None: self.fp: BytesIO | None = None def read(self, amt: int) -> bytes: assert self.fp is not None data = self.fp.read(amt) if not data: self.fp = None return data def read1(self, amt: int) -> bytes: return self.read(1) def close(self) -> None: self.fp = None bio = BytesIO(b"foo") fp = MockHTTPRequest() fp.fp = bio resp = HTTPResponse(fp, preload_content=False) # type: ignore[arg-type] stream = resp.stream(2) assert next(stream) == b"fo" assert next(stream) == b"o" with pytest.raises(StopIteration): next(stream) def test_mock_transfer_encoding_chunked(self) -> None: stream = [b"fo", b"o", b"bar"] fp = MockChunkedEncodingResponse(stream) r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type] r.fp = fp # type: ignore[assignment] resp = HTTPResponse( r, preload_content=False, headers={"transfer-encoding": "chunked"} ) for i, c in enumerate(resp.stream()): assert c == stream[i] def test_mock_gzipped_transfer_encoding_chunked_decoded(self) -> None: """Show that we can decode the gzipped and chunked body.""" def stream() -> typing.Generator[bytes]: # Set up a generator to chunk the gzipped body compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(b"foobar") data += compress.flush() for i in range(0, len(data), 2): yield data[i : i + 2] fp = MockChunkedEncodingResponse(list(stream())) r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type] r.fp = fp # type: ignore[assignment] headers = {"transfer-encoding": "chunked", "content-encoding": "gzip"} resp = HTTPResponse(r, preload_content=False, headers=headers) data = b"" for c in resp.stream(decode_content=True): data += c assert b"foobar" == data def test_mock_transfer_encoding_chunked_custom_read(self) -> None: stream = [b"foooo", b"bbbbaaaaar"] fp = MockChunkedEncodingResponse(stream) r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type] r.fp = fp # type: ignore[assignment] r.chunked = True r.chunk_left = None resp = HTTPResponse( r, preload_content=False, headers={"transfer-encoding": "chunked"} ) expected_response = [b"fo", b"oo", b"o", b"bb", b"bb", b"aa", b"aa", b"ar"] response = list(resp.read_chunked(2)) assert expected_response == response @pytest.mark.parametrize("read_chunked_args", ((), (None,), (-1,))) def test_mock_transfer_encoding_chunked_unlmtd_read( self, read_chunked_args: tuple[typing.Any, ...] ) -> None: stream = [b"foooo", b"bbbbaaaaar"] fp = MockChunkedEncodingResponse(stream) r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type] r.fp = fp # type: ignore[assignment] r.chunked = True r.chunk_left = None resp = HTTPResponse( r, preload_content=False, headers={"transfer-encoding": "chunked"} ) assert stream == list(resp.read_chunked(*read_chunked_args)) def test_read_not_chunked_response_as_chunks(self) -> None: fp = BytesIO(b"foo") resp = HTTPResponse(fp, preload_content=False) r = resp.read_chunked() with pytest.raises(ResponseNotChunked): next(r) def test_read_chunked_not_supported(self) -> None: fp = BytesIO(b"foo") resp = HTTPResponse( fp, preload_content=False, headers={"transfer-encoding": "chunked"} ) r = resp.read_chunked() with pytest.raises(BodyNotHttplibCompatible): next(r) def test_buggy_incomplete_read(self) -> None: # Simulate buggy versions of Python (<2.7.4) # See http://bugs.python.org/issue16298 content_length = 1337 fp = BytesIO(b"") resp = HTTPResponse( fp, headers={"content-length": str(content_length)}, preload_content=False, enforce_content_length=True, ) with pytest.raises(ProtocolError) as ctx: resp.read(3) orig_ex = ctx.value.args[1] assert isinstance(orig_ex, IncompleteRead) assert orig_ex.partial == 0 assert orig_ex.expected == content_length def test_incomplete_chunk(self) -> None: stream = [b"foooo", b"bbbbaaaaar"] fp = MockChunkedIncompleteRead(stream) r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type] r.fp = fp # type: ignore[assignment] r.chunked = True r.chunk_left = None resp = HTTPResponse( r, preload_content=False, headers={"transfer-encoding": "chunked"} ) with pytest.raises(ProtocolError) as ctx: next(resp.read_chunked()) orig_ex = ctx.value.args[1] assert isinstance(orig_ex, httplib_IncompleteRead) def test_invalid_chunk_length(self) -> None: stream = [b"foooo", b"bbbbaaaaar"] fp = MockChunkedInvalidChunkLength(stream) r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type] r.fp = fp # type: ignore[assignment] r.chunked = True r.chunk_left = None resp = HTTPResponse( r, preload_content=False, headers={"transfer-encoding": "chunked"} ) with pytest.raises(ProtocolError) as ctx: next(resp.read_chunked()) orig_ex = ctx.value.args[1] msg = ( "(\"Connection broken: InvalidChunkLength(got length b'ZZZ\\\\r\\\\n', 0 bytes read)\", " "InvalidChunkLength(got length b'ZZZ\\r\\n', 0 bytes read))" ) assert str(ctx.value) == msg assert isinstance(orig_ex, InvalidChunkLength) assert orig_ex.length == fp.BAD_LENGTH_LINE.encode() def test_truncated_before_chunk(self) -> None: stream = [b"foooo", b"bbbbaaaaar"] fp = MockChunkedNoChunks(stream) r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type] r.fp = fp # type: ignore[assignment] r.chunked = True r.chunk_left = None resp = HTTPResponse( r, preload_content=False, headers={"transfer-encoding": "chunked"} ) with pytest.raises(ProtocolError) as ctx: next(resp.read_chunked()) assert str(ctx.value) == "Response ended prematurely" def test_chunked_response_without_crlf_on_end(self) -> None: stream = [b"foo", b"bar", b"baz"] fp = MockChunkedEncodingWithoutCRLFOnEnd(stream) r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type] r.fp = fp # type: ignore[assignment] r.chunked = True r.chunk_left = None resp = HTTPResponse( r, preload_content=False, headers={"transfer-encoding": "chunked"} ) assert stream == list(resp.stream()) def test_chunked_response_with_extensions(self) -> None: stream = [b"foo", b"bar"] fp = MockChunkedEncodingWithExtensions(stream) r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type] r.fp = fp # type: ignore[assignment] r.chunked = True r.chunk_left = None resp = HTTPResponse( r, preload_content=False, headers={"transfer-encoding": "chunked"} ) assert stream == list(resp.stream()) def test_chunked_head_response(self) -> None: r = httplib.HTTPResponse(MockSock, method="HEAD") # type: ignore[arg-type] r.chunked = True r.chunk_left = None resp = HTTPResponse( "", preload_content=False, headers={"transfer-encoding": "chunked"}, original_response=r, ) assert resp.chunked is True setattr(resp, "supports_chunked_reads", lambda: True) setattr(resp, "release_conn", mock.Mock()) for _ in resp.stream(): continue resp.release_conn.assert_called_once_with() # type: ignore[attr-defined] def test_get_case_insensitive_headers(self) -> None: headers = {"host": "example.com"} r = HTTPResponse(headers=headers) assert r.headers.get("host") == "example.com" assert r.headers.get("Host") == "example.com" def test_retries(self) -> None: fp = BytesIO(b"") resp = HTTPResponse(fp) assert resp.retries is None retry = Retry() resp = HTTPResponse(fp, retries=retry) assert resp.retries == retry def test_geturl(self) -> None: fp = BytesIO(b"") request_url = "https://example.com" resp = HTTPResponse(fp, request_url=request_url) assert resp.geturl() == request_url def test_url(self) -> None: fp = BytesIO(b"") request_url = "https://example.com" resp = HTTPResponse(fp, request_url=request_url) assert resp.url == request_url resp.url = "https://anotherurl.com" assert resp.url == "https://anotherurl.com" def test_geturl_retries(self) -> None: fp = BytesIO(b"") resp = HTTPResponse(fp, request_url="http://example.com") request_histories = ( RequestHistory( method="GET", url="http://example.com", error=None, status=301, redirect_location="https://example.com/", ), RequestHistory( method="GET", url="https://example.com/", error=None, status=301, redirect_location="https://www.example.com", ), ) retry = Retry(history=request_histories) resp = HTTPResponse(fp, retries=retry) assert resp.geturl() == "https://www.example.com" @pytest.mark.parametrize( ["payload", "expected_stream"], [ (b"", []), (b"\n", [b"\n"]), (b"\n\n\n", [b"\n", b"\n", b"\n"]), (b"abc\ndef", [b"abc\n", b"def"]), (b"Hello\nworld\n\n\n!", [b"Hello\n", b"world\n", b"\n", b"\n", b"!"]), ], ) def test__iter__(self, payload: bytes, expected_stream: list[bytes]) -> None: actual_stream = [] for chunk in HTTPResponse(BytesIO(payload), preload_content=False): actual_stream.append(chunk) assert actual_stream == expected_stream def test__iter__decode_content(self) -> None: def stream() -> typing.Generator[bytes]: # Set up a generator to chunk the gzipped body compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(b"foo\nbar") data += compress.flush() for i in range(0, len(data), 2): yield data[i : i + 2] fp = MockChunkedEncodingResponse(list(stream())) r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type] r.fp = fp # type: ignore[assignment] headers = {"transfer-encoding": "chunked", "content-encoding": "gzip"} resp = HTTPResponse(r, preload_content=False, headers=headers) data = b"" for c in resp: data += c assert b"foo\nbar" == data def test_non_timeout_ssl_error_on_read(self) -> None: mac_error = ssl.SSLError( "SSL routines", "ssl3_get_record", "decryption failed or bad record mac" ) @contextlib.contextmanager def make_bad_mac_fp() -> typing.Generator[BytesIO]: fp = BytesIO(b"") with mock.patch.object(fp, "read") as fp_read: # mac/decryption error fp_read.side_effect = mac_error yield fp with make_bad_mac_fp() as fp: with pytest.raises(SSLError) as e: HTTPResponse(fp) assert e.value.args[0] == mac_error with make_bad_mac_fp() as fp: resp = HTTPResponse(fp, preload_content=False) with pytest.raises(SSLError) as e: resp.read() assert e.value.args[0] == mac_error def test_unexpected_body(self) -> None: with pytest.raises(ProtocolError) as excinfo: fp = BytesIO(b"12345") headers = {"content-length": "5"} resp = HTTPResponse(fp, status=204, headers=headers) resp.read(16) assert "Response may not contain content" in str(excinfo.value) with pytest.raises(ProtocolError): fp = BytesIO(b"12345") headers = {"content-length": "0"} resp = HTTPResponse(fp, status=204, headers=headers) resp.read(16) assert "Response may not contain content" in str(excinfo.value) with pytest.raises(ProtocolError): fp = BytesIO(b"12345") resp = HTTPResponse(fp, status=204) resp.read(16) assert "Response may not contain content" in str(excinfo.value)
TestResponse
python
PyCQA__pylint
tests/functional/t/too/too_few_public_methods_excluded.py
{ "start": 161, "end": 336 }
class ____(Control): """This class inherits from a class that doesn't have enough methods, and its parent is excluded via config, so it doesn't raise."""
InheritedInModule
python
modin-project__modin
modin/experimental/core/io/sql/utils.py
{ "start": 7413, "end": 7526 }
class ____(Exception): """Exception that should be raised if invalid query statement was found."""
InvalidQuery
python
fastapi__sqlmodel
docs_src/tutorial/fastapi/relationships/tutorial001.py
{ "start": 1256, "end": 1334 }
class ____(HeroPublic): team: Optional[TeamPublic] = None
HeroPublicWithTeam
python
kamyu104__LeetCode-Solutions
Python/count-beautiful-substrings-i.py
{ "start": 976, "end": 1486 }
class ____(object): def beautifulSubstrings(self, s, k): """ :type s: str :type k: int :rtype: int """ VOWELS = set("aeiou") result = 0 for i in xrange(len(s)): c = v = 0 for j in xrange(i, len(s)): if s[j] in VOWELS: v += 1 else: c += 1 if c == v and (c*v)%k == 0: result += 1 return result
Solution2
python
matplotlib__matplotlib
lib/mpl_toolkits/mplot3d/art3d.py
{ "start": 2620, "end": 6591 }
class ____(mtext.Text): """ Text object with 3D position and direction. Parameters ---------- x, y, z : float The position of the text. text : str The text string to display. zdir : {'x', 'y', 'z', None, 3-tuple} The direction of the text. See `.get_dir_vector` for a description of the values. axlim_clip : bool, default: False Whether to hide text outside the axes view limits. .. versionadded:: 3.10 Other Parameters ---------------- **kwargs All other parameters are passed on to `~matplotlib.text.Text`. """ def __init__(self, x=0, y=0, z=0, text='', zdir='z', axlim_clip=False, **kwargs): mtext.Text.__init__(self, x, y, text, **kwargs) self.set_3d_properties(z, zdir, axlim_clip) def get_position_3d(self): """Return the (x, y, z) position of the text.""" return self._x, self._y, self._z def set_position_3d(self, xyz, zdir=None): """ Set the (*x*, *y*, *z*) position of the text. Parameters ---------- xyz : (float, float, float) The position in 3D space. zdir : {'x', 'y', 'z', None, 3-tuple} The direction of the text. If unspecified, the *zdir* will not be changed. See `.get_dir_vector` for a description of the values. """ super().set_position(xyz[:2]) self.set_z(xyz[2]) if zdir is not None: self._dir_vec = get_dir_vector(zdir) def set_z(self, z): """ Set the *z* position of the text. Parameters ---------- z : float """ self._z = z self.stale = True def set_3d_properties(self, z=0, zdir='z', axlim_clip=False): """ Set the *z* position and direction of the text. Parameters ---------- z : float The z-position in 3D space. zdir : {'x', 'y', 'z', 3-tuple} The direction of the text. Default: 'z'. See `.get_dir_vector` for a description of the values. axlim_clip : bool, default: False Whether to hide text outside the axes view limits. .. versionadded:: 3.10 """ self._z = z self._dir_vec = get_dir_vector(zdir) self._axlim_clip = axlim_clip self.stale = True @artist.allow_rasterization def draw(self, renderer): if self._axlim_clip: mask = _viewlim_mask(self._x, self._y, self._z, self.axes) pos3d = np.ma.array([self._x, self._y, self._z], mask=mask, dtype=float).filled(np.nan) else: pos3d = np.array([self._x, self._y, self._z], dtype=float) proj = proj3d._proj_trans_points([pos3d, pos3d + self._dir_vec], self.axes.M) dx = proj[0][1] - proj[0][0] dy = proj[1][1] - proj[1][0] angle = math.degrees(math.atan2(dy, dx)) with cbook._setattr_cm(self, _x=proj[0][0], _y=proj[1][0], _rotation=_norm_text_angle(angle)): mtext.Text.draw(self, renderer) self.stale = False def get_tightbbox(self, renderer=None): # Overwriting the 2d Text behavior which is not valid for 3d. # For now, just return None to exclude from layout calculation. return None def text_2d_to_3d(obj, z=0, zdir='z', axlim_clip=False): """ Convert a `.Text` to a `.Text3D` object. Parameters ---------- z : float The z-position in 3D space. zdir : {'x', 'y', 'z', 3-tuple} The direction of the text. Default: 'z'. See `.get_dir_vector` for a description of the values. axlim_clip : bool, default: False Whether to hide text outside the axes view limits. .. versionadded:: 3.10 """ obj.__class__ = Text3D obj.set_3d_properties(z, zdir, axlim_clip)
Text3D
python
kubernetes-client__python
kubernetes/client/models/events_v1_event_series.py
{ "start": 383, "end": 5001 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'count': 'int', 'last_observed_time': 'datetime' } attribute_map = { 'count': 'count', 'last_observed_time': 'lastObservedTime' } def __init__(self, count=None, last_observed_time=None, local_vars_configuration=None): # noqa: E501 """EventsV1EventSeries - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._count = None self._last_observed_time = None self.discriminator = None self.count = count self.last_observed_time = last_observed_time @property def count(self): """Gets the count of this EventsV1EventSeries. # noqa: E501 count is the number of occurrences in this series up to the last heartbeat time. # noqa: E501 :return: The count of this EventsV1EventSeries. # noqa: E501 :rtype: int """ return self._count @count.setter def count(self, count): """Sets the count of this EventsV1EventSeries. count is the number of occurrences in this series up to the last heartbeat time. # noqa: E501 :param count: The count of this EventsV1EventSeries. # noqa: E501 :type: int """ if self.local_vars_configuration.client_side_validation and count is None: # noqa: E501 raise ValueError("Invalid value for `count`, must not be `None`") # noqa: E501 self._count = count @property def last_observed_time(self): """Gets the last_observed_time of this EventsV1EventSeries. # noqa: E501 lastObservedTime is the time when last Event from the series was seen before last heartbeat. # noqa: E501 :return: The last_observed_time of this EventsV1EventSeries. # noqa: E501 :rtype: datetime """ return self._last_observed_time @last_observed_time.setter def last_observed_time(self, last_observed_time): """Sets the last_observed_time of this EventsV1EventSeries. lastObservedTime is the time when last Event from the series was seen before last heartbeat. # noqa: E501 :param last_observed_time: The last_observed_time of this EventsV1EventSeries. # noqa: E501 :type: datetime """ if self.local_vars_configuration.client_side_validation and last_observed_time is None: # noqa: E501 raise ValueError("Invalid value for `last_observed_time`, must not be `None`") # noqa: E501 self._last_observed_time = last_observed_time def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, EventsV1EventSeries): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, EventsV1EventSeries): return True return self.to_dict() != other.to_dict()
EventsV1EventSeries
python
huggingface__transformers
tests/models/beit/test_modeling_beit.py
{ "start": 14802, "end": 21417 }
class ____(unittest.TestCase): @cached_property def default_image_processor(self): return BeitImageProcessor.from_pretrained("microsoft/beit-base-patch16-224") if is_vision_available() else None @slow def test_inference_masked_image_modeling_head(self): model = BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k").to(torch_device) image_processor = self.default_image_processor image = prepare_img() pixel_values = image_processor(images=image, return_tensors="pt").pixel_values.to(torch_device) # prepare bool_masked_pos bool_masked_pos = torch.ones((1, 196), dtype=torch.bool).to(torch_device) # forward pass with torch.no_grad(): outputs = model(pixel_values=pixel_values, bool_masked_pos=bool_masked_pos) logits = outputs.logits # verify the logits expected_shape = torch.Size((1, 196, 8192)) self.assertEqual(logits.shape, expected_shape) expected_slice = torch.tensor( [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]] ).to(torch_device) torch.testing.assert_close(logits[bool_masked_pos][:3, :3], expected_slice, rtol=1e-2, atol=1e-2) @slow def test_inference_image_classification_head_imagenet_1k(self): model = BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224").to(torch_device) image_processor = self.default_image_processor image = prepare_img() inputs = image_processor(images=image, return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) logits = outputs.logits # verify the logits expected_shape = torch.Size((1, 1000)) self.assertEqual(logits.shape, expected_shape) expected_slice = torch.tensor([-1.2385, -1.0987, -1.0108]).to(torch_device) torch.testing.assert_close(logits[0, :3], expected_slice, rtol=1e-4, atol=1e-4) expected_class_idx = 281 self.assertEqual(logits.argmax(-1).item(), expected_class_idx) @slow def test_inference_image_classification_head_imagenet_22k(self): model = BeitForImageClassification.from_pretrained("microsoft/beit-large-patch16-224-pt22k-ft22k").to( torch_device ) image_processor = self.default_image_processor image = prepare_img() inputs = image_processor(images=image, return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) logits = outputs.logits # verify the logits expected_shape = torch.Size((1, 21841)) self.assertEqual(logits.shape, expected_shape) expected_slice = torch.tensor([1.6881, -0.2787, 0.5901]).to(torch_device) torch.testing.assert_close(logits[0, :3], expected_slice, rtol=1e-4, atol=1e-4) expected_class_idx = 2396 self.assertEqual(logits.argmax(-1).item(), expected_class_idx) @slow def test_inference_semantic_segmentation(self): model = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640") model = model.to(torch_device) image_processor = BeitImageProcessor(do_resize=True, size=640, do_center_crop=False) ds = load_dataset("hf-internal-testing/fixtures_ade20k", split="test") image = ds[0]["image"].convert("RGB") inputs = image_processor(images=image, return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) logits = outputs.logits # verify the logits expected_shape = torch.Size((1, 150, 160, 160)) self.assertEqual(logits.shape, expected_shape) expected_slice = torch.tensor( [ [[-4.8960, -2.3688, -3.0355], [-2.8479, -0.9836, -1.7418], [-2.9449, -1.3333, -2.1456]], [[-5.8081, -3.4124, -4.1006], [-3.8561, -2.2081, -3.0323], [-3.8365, -2.4601, -3.3669]], [[-0.0309, 3.9868, 4.0540], [2.9640, 4.6877, 4.9976], [3.2081, 4.7690, 4.9942]], ], device=torch_device, ) torch.testing.assert_close(logits[0, :3, :3, :3], expected_slice, rtol=1e-4, atol=1e-4) @slow def test_post_processing_semantic_segmentation(self): model = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640") model = model.to(torch_device) image_processor = BeitImageProcessor(do_resize=True, size=640, do_center_crop=False) ds = load_dataset("hf-internal-testing/fixtures_ade20k", split="test") image = ds[0]["image"].convert("RGB") inputs = image_processor(images=image, return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) outputs.logits = outputs.logits.detach().cpu() segmentation = image_processor.post_process_semantic_segmentation(outputs=outputs, target_sizes=[(500, 300)]) expected_shape = torch.Size((500, 300)) self.assertEqual(segmentation[0].shape, expected_shape) segmentation = image_processor.post_process_semantic_segmentation(outputs=outputs) expected_shape = torch.Size((160, 160)) self.assertEqual(segmentation[0].shape, expected_shape) @slow def test_inference_interpolate_pos_encoding(self): model_name = "microsoft/beit-base-patch16-224-pt22k" model = BeitModel.from_pretrained(model_name, **{"use_absolute_position_embeddings": True}).to(torch_device) image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") processor = BeitImageProcessor.from_pretrained(model_name) inputs = processor(images=image, return_tensors="pt", size={"height": 480, "width": 480}) pixel_values = inputs.pixel_values.to(torch_device) # with interpolate_pos_encoding being True the model should process the higher resolution image # successfully and produce the expected output. with torch.no_grad(): outputs = model(pixel_values, interpolate_pos_encoding=True) # num_cls_tokens + (height / patch_size) * (width / patch_size) # 1 + (480 / 16) * (480 / 16) = 1 + 30 * 30 = 901 expected_shape = torch.Size((1, 901, 768)) self.assertEqual(outputs.last_hidden_state.shape, expected_shape) @require_torch
BeitModelIntegrationTest
python
getsentry__sentry
tests/sentry/newsletter/test_base.py
{ "start": 190, "end": 1124 }
class ____(TestCase): def test_defaults(self) -> None: assert newsletter.DEFAULT_LISTS == newsletter.get_default_list_ids() assert newsletter.DEFAULT_LIST_ID == newsletter.get_default_list_id() def test_update_subscription(self) -> None: user = self.create_user("subscriber@example.com") newsletter.update_subscription(user) assert newsletter.get_subscriptions(user) is None assert newsletter.create_or_update_subscription(user) is None assert newsletter.create_or_update_subscriptions(user) is None def test_update_subscriptions(self) -> None: user = self.create_user("subscriber@example.com") newsletter.update_subscriptions(user) assert newsletter.get_subscriptions(user) is None assert newsletter.create_or_update_subscription(user) is None assert newsletter.create_or_update_subscriptions(user) is None
BaseNewsletterTest
python
python-openxml__python-docx
src/docx/image/exceptions.py
{ "start": 162, "end": 281 }
class ____(Exception): """EOF was unexpectedly encountered while reading an image stream."""
UnexpectedEndOfFileError
python
realpython__materials
hashtable/06_insertion_order/hashtable.py
{ "start": 137, "end": 3454 }
class ____: @classmethod def from_dict(cls, dictionary, capacity=None): hash_table = cls(capacity or len(dictionary)) for key, value in dictionary.items(): hash_table[key] = value return hash_table def __init__(self, capacity=8, load_factor_threshold=0.6): if capacity < 1: raise ValueError("Capacity must be a positive number") if not (0 < load_factor_threshold <= 1): raise ValueError("Load factor must be a number between (0, 1]") self._keys = [] self._buckets = [deque() for _ in range(capacity)] self._load_factor_threshold = load_factor_threshold def __len__(self): return len(self.pairs) def __iter__(self): yield from self.keys def __delitem__(self, key): match self._find(key): case bucket, index, _: del bucket[index] self._keys.remove(key) case _: raise KeyError(key) def __setitem__(self, key, value): if self.load_factor >= self._load_factor_threshold: self._resize_and_rehash() match self._find(key): case deque() as bucket, index, (key, _): bucket[index] = Pair(key, value) case bucket: bucket.append(Pair(key, value)) self._keys.append(key) def __getitem__(self, key): match self._find(key): case _, _, pair: return pair.value case _: raise KeyError(key) def __contains__(self, key): try: self[key] except KeyError: return False else: return True def __eq__(self, other): if self is other: return True if type(self) is not type(other): return False return set(self.pairs) == set(other.pairs) def __str__(self): pairs = [] for key, value in self.pairs: pairs.append(f"{key!r}: {value!r}") return "{" + ", ".join(pairs) + "}" def __repr__(self): cls = self.__class__.__name__ return f"{cls}.from_dict({str(self)})" def copy(self): return HashTable.from_dict(dict(self.pairs), self.capacity) def get(self, key, default=None): try: return self[key] except KeyError: return default @property def pairs(self): return [(key, self[key]) for key in self.keys] @property def values(self): return [self[key] for key in self.keys] @property def keys(self): return self._keys.copy() @property def capacity(self): return len(self._buckets) @property def load_factor(self): return len(self) / self.capacity def _index(self, key): return hash(key) % self.capacity def _resize_and_rehash(self): copy = HashTable(capacity=self.capacity * 2) for key, value in self.pairs: copy[key] = value self._buckets = copy._buckets def _find(self, key): bucket = self._buckets[self._index(key)] for index, pair in enumerate(bucket): if pair.key == key: return bucket, index, pair return bucket
HashTable
python
scrapy__scrapy
tests/test_cmdline_crawl_with_pipeline/__init__.py
{ "start": 117, "end": 956 }
class ____: def _execute(self, spname): args = (sys.executable, "-m", "scrapy.cmdline", "crawl", spname) cwd = Path(__file__).resolve().parent proc = Popen(args, stdout=PIPE, stderr=PIPE, cwd=cwd) _, stderr = proc.communicate() return proc.returncode, stderr def test_open_spider_normally_in_pipeline(self): returncode, _ = self._execute("normal") assert returncode == 0 def test_exception_at_open_spider_in_pipeline(self): returncode, stderr = self._execute("exception") # An unhandled exception in a pipeline should not stop the crawl assert returncode == 0 if TWISTED_KEEPS_TRACEBACKS: assert b'RuntimeError("exception")' in stderr else: assert b"RuntimeError: exception" in stderr
TestCmdlineCrawlPipeline
python
getsentry__sentry
tests/sentry/notifications/api/endpoints/test_user_notification_details.py
{ "start": 101, "end": 286 }
class ____(APITestCase): endpoint = "sentry-api-0-user-notifications" def setUp(self) -> None: self.login_as(self.user) @control_silo_test
UserNotificationDetailsTestBase
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/ErrorBarItem.py
{ "start": 157, "end": 5472 }
class ____(GraphicsObject): def __init__(self, **opts): """ All keyword arguments are passed to setData(). """ GraphicsObject.__init__(self) self.opts = dict( x=None, y=None, height=None, width=None, top=None, bottom=None, left=None, right=None, beam=None, pen=None ) self.setVisible(False) self.setData(**opts) def setData(self, **opts): """ Update the data in the item. All arguments are optional. Valid keyword options are: x, y, height, width, top, bottom, left, right, beam, pen * x and y must be numpy arrays specifying the coordinates of data points. * height, width, top, bottom, left, right, and beam may be numpy arrays, single values, or None to disable. All values should be positive. * top, bottom, left, and right specify the lengths of bars extending in each direction. * If height is specified, it overrides top and bottom. * If width is specified, it overrides left and right. * beam specifies the width of the beam at the end of each bar. * pen may be any single argument accepted by pg.mkPen(). This method was added in version 0.9.9. For prior versions, use setOpts. """ self.opts.update(opts) self.setVisible(all(self.opts[ax] is not None for ax in ['x', 'y'])) self.path = None self.update() self.prepareGeometryChange() self.informViewBoundsChanged() def setOpts(self, **opts): # for backward compatibility self.setData(**opts) def drawPath(self): p = QtGui.QPainterPath() x, y = self.opts['x'], self.opts['y'] if x is None or y is None: self.path = p return beam = self.opts['beam'] height, top, bottom = self.opts['height'], self.opts['top'], self.opts['bottom'] if height is not None or top is not None or bottom is not None: ## draw vertical error bars if height is not None: y1 = y - height/2. y2 = y + height/2. else: if bottom is None: y1 = y else: y1 = y - bottom if top is None: y2 = y else: y2 = y + top xs = fn.interweaveArrays(x, x) y1_y2 = fn.interweaveArrays(y1, y2) verticalLines = fn.arrayToQPath(xs, y1_y2, connect="pairs") p.addPath(verticalLines) if beam is not None and beam > 0: x1 = x - beam/2. x2 = x + beam/2. x1_x2 = fn.interweaveArrays(x1, x2) if height is not None or top is not None: y2s = fn.interweaveArrays(y2, y2) topEnds = fn.arrayToQPath(x1_x2, y2s, connect="pairs") p.addPath(topEnds) if height is not None or bottom is not None: y1s = fn.interweaveArrays(y1, y1) bottomEnds = fn.arrayToQPath(x1_x2, y1s, connect="pairs") p.addPath(bottomEnds) width, right, left = self.opts['width'], self.opts['right'], self.opts['left'] if width is not None or right is not None or left is not None: ## draw vertical error bars if width is not None: x1 = x - width/2. x2 = x + width/2. else: if left is None: x1 = x else: x1 = x - left if right is None: x2 = x else: x2 = x + right ys = fn.interweaveArrays(y, y) x1_x2 = fn.interweaveArrays(x1, x2) ends = fn.arrayToQPath(x1_x2, ys, connect='pairs') p.addPath(ends) if beam is not None and beam > 0: y1 = y - beam/2. y2 = y + beam/2. y1_y2 = fn.interweaveArrays(y1, y2) if width is not None or right is not None: x2s = fn.interweaveArrays(x2, x2) rightEnds = fn.arrayToQPath(x2s, y1_y2, connect="pairs") p.addPath(rightEnds) if width is not None or left is not None: x1s = fn.interweaveArrays(x1, x1) leftEnds = fn.arrayToQPath(x1s, y1_y2, connect="pairs") p.addPath(leftEnds) self.path = p self.prepareGeometryChange() def paint(self, p, *args): if self.path is None: self.drawPath() pen = self.opts['pen'] if pen is None: pen = getConfigOption('foreground') p.setPen(fn.mkPen(pen)) p.drawPath(self.path) def boundingRect(self): if self.path is None: self.drawPath() return self.path.boundingRect()
ErrorBarItem
python
google__jax
tests/lax_test.py
{ "start": 163874, "end": 164537 }
class ____: # handlers @staticmethod def physical_element_aval(dtype) -> core.ShapedArray: return core.ShapedArray((2,), jnp.dtype('uint32')) @staticmethod def result_handler(sticky_device, aval): def handler(_, buf): buf.aval = core.ShapedArray(buf.shape, buf.dtype) return FooArray(aval.shape, buf) return handler @staticmethod def global_sharded_result_handler(aval, out_sharding, committed): def handler(arr): from jax._src.array import ArrayImpl if isinstance(arr, ArrayImpl): buf, = arr._arrays else: buf, = arr return FooArray(aval.shape, buf) return handler
FooTyRules
python
facelessuser__pymdown-extensions
tools/collapse_code.py
{ "start": 2620, "end": 3436 }
class ____(BlocksExtension): """Admonition Blocks Extension.""" def __init__(self, *args, **kwargs): """Initialize.""" self.config = { 'expand_text': ['Expand', "Set the text for the expand button."], 'collapse_text': ['Collapse', "Set the text for the collapse button."], 'expand_title': ['expand', "Set the text for the expand title."], 'collapse_title': ['collapse', "Set the text for the collapse title."] } super().__init__(*args, **kwargs) def extendMarkdownBlocks(self, md, blocks): """Extend Markdown blocks.""" blocks.register(CollapseCode, self.getConfigs()) def makeExtension(*args, **kwargs): """Return extension.""" return CollapseCodeExtension(*args, **kwargs)
CollapseCodeExtension
python
django__django
tests/schema/models.py
{ "start": 1747, "end": 2034 }
class ____(models.Model): author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=100, db_index=True) pub_date = models.DateTimeField() # tags = models.ManyToManyField("Tag", related_name="books") class Meta: apps = new_apps
Book
python
gevent__gevent
src/greentest/3.10/test_signal.py
{ "start": 4190, "end": 6238 }
class ____(unittest.TestCase): def test_valid_signals(self): s = signal.valid_signals() self.assertIsInstance(s, set) self.assertGreaterEqual(len(s), 6) self.assertIn(signal.Signals.SIGINT, s) self.assertNotIn(0, s) self.assertNotIn(signal.NSIG, s) self.assertLess(len(s), signal.NSIG) def test_issue9324(self): # Updated for issue #10003, adding SIGBREAK handler = lambda x, y: None checked = set() for sig in (signal.SIGABRT, signal.SIGBREAK, signal.SIGFPE, signal.SIGILL, signal.SIGINT, signal.SIGSEGV, signal.SIGTERM): # Set and then reset a handler for signals that work on windows. # Issue #18396, only for signals without a C-level handler. if signal.getsignal(sig) is not None: signal.signal(sig, signal.signal(sig, handler)) checked.add(sig) # Issue #18396: Ensure the above loop at least tested *something* self.assertTrue(checked) with self.assertRaises(ValueError): signal.signal(-1, handler) with self.assertRaises(ValueError): signal.signal(7, handler) @unittest.skipUnless(sys.executable, "sys.executable required.") def test_keyboard_interrupt_exit_code(self): """KeyboardInterrupt triggers an exit using STATUS_CONTROL_C_EXIT.""" # We don't test via os.kill(os.getpid(), signal.CTRL_C_EVENT) here # as that requires setting up a console control handler in a child # in its own process group. Doable, but quite complicated. (see # @eryksun on https://github.com/python/cpython/pull/11862) process = subprocess.run( [sys.executable, "-c", "raise KeyboardInterrupt"], stderr=subprocess.PIPE) self.assertIn(b"KeyboardInterrupt", process.stderr) STATUS_CONTROL_C_EXIT = 0xC000013A self.assertEqual(process.returncode, STATUS_CONTROL_C_EXIT)
WindowsSignalTests
python
pyinstaller__pyinstaller
bootloader/waflib/Tools/c.py
{ "start": 1184, "end": 1220 }
class ____(stlink_task): pass
cstlib
python
kamyu104__LeetCode-Solutions
Python/maximize-sum-of-at-most-k-distinct-elements.py
{ "start": 61, "end": 329 }
class ____(object): def maxKDistinct(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ return heapq.nlargest(k, set(nums)) # Time: O(nlogk) # Space: O(k) import heapq # heap, sort
Solution
python
Textualize__rich
rich/markdown.py
{ "start": 10766, "end": 12448 }
class ____(TextElement): """An item in a list.""" style_name = "markdown.item" def __init__(self) -> None: self.elements: Renderables = Renderables() def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: self.elements.append(child) return False def render_bullet(self, console: Console, options: ConsoleOptions) -> RenderResult: render_options = options.update(width=options.max_width - 3) lines = console.render_lines(self.elements, render_options, style=self.style) bullet_style = console.get_style("markdown.item.bullet", default="none") bullet = Segment(" • ", bullet_style) padding = Segment(" " * 3, bullet_style) new_line = Segment("\n") for first, line in loop_first(lines): yield bullet if first else padding yield from line yield new_line def render_number( self, console: Console, options: ConsoleOptions, number: int, last_number: int ) -> RenderResult: number_width = len(str(last_number)) + 2 render_options = options.update(width=options.max_width - number_width) lines = console.render_lines(self.elements, render_options, style=self.style) number_style = console.get_style("markdown.item.number", default="none") new_line = Segment("\n") padding = Segment(" " * number_width, number_style) numeral = Segment(f"{number}".rjust(number_width - 1) + " ", number_style) for first, line in loop_first(lines): yield numeral if first else padding yield from line yield new_line
ListItem
python
run-llama__llama_index
llama-index-core/llama_index/core/evaluation/retrieval/metrics.py
{ "start": 14877, "end": 17593 }
class ____(BaseRetrievalMetric): """Cohere rerank relevancy metric.""" metric_name: ClassVar[str] = "cohere_rerank_relevancy" model: str = Field(description="Cohere model name.") _client: Any = PrivateAttr() def __init__( self, model: str = "rerank-english-v2.0", api_key: Optional[str] = None, ): try: api_key = api_key or os.environ["COHERE_API_KEY"] except IndexError: raise ValueError( "Must pass in cohere api key or " "specify via COHERE_API_KEY environment variable " ) try: from cohere import Client # pants: no-infer-dep except ImportError: raise ImportError( "Cannot import cohere package, please `pip install cohere`." ) super().__init__(model=model) self._client = Client(api_key=api_key) def _get_agg_func(self, agg: Literal["max", "median", "mean"]) -> Callable: """Get agg func.""" return _AGG_FUNC[agg] def compute( self, query: Optional[str] = None, expected_ids: Optional[List[str]] = None, retrieved_ids: Optional[List[str]] = None, expected_texts: Optional[List[str]] = None, retrieved_texts: Optional[List[str]] = None, agg: Literal["max", "median", "mean"] = "max", **kwargs: Any, ) -> RetrievalMetricResult: """Compute metric.""" del expected_texts # unused if retrieved_texts is None: raise ValueError("Retrieved texts must be provided") results = self._client.rerank( model=self.model, top_n=len( retrieved_texts ), # i.e. get a rank score for each retrieved chunk query=query, documents=retrieved_texts, ) relevance_scores = [r.relevance_score for r in results.results] agg_func = self._get_agg_func(agg) return RetrievalMetricResult( score=agg_func(relevance_scores), metadata={"agg": agg} ) METRIC_REGISTRY: Dict[str, Type[BaseRetrievalMetric]] = { "hit_rate": HitRate, "mrr": MRR, "precision": Precision, "recall": Recall, "ap": AveragePrecision, "ndcg": NDCG, "cohere_rerank_relevancy": CohereRerankRelevancyMetric, } def resolve_metrics(metrics: List[str]) -> List[Type[BaseRetrievalMetric]]: """Resolve metrics from list of metric names.""" for metric in metrics: if metric not in METRIC_REGISTRY: raise ValueError(f"Invalid metric name: {metric}") return [METRIC_REGISTRY[metric] for metric in metrics]
CohereRerankRelevancyMetric
python
ray-project__ray
python/ray/data/_internal/datasource/csv_datasource.py
{ "start": 225, "end": 2778 }
class ____(FileBasedDatasource): """CSV datasource, for reading and writing CSV files.""" _FILE_EXTENSIONS = [ "csv", "csv.gz", # gzip-compressed files "csv.br", # Brotli-compressed files "csv.zst", # Zstandard-compressed files "csv.lz4", # lz4-compressed files ] def __init__( self, paths: Union[str, List[str]], arrow_csv_args: Optional[Dict[str, Any]] = None, **file_based_datasource_kwargs, ): from pyarrow import csv super().__init__(paths, **file_based_datasource_kwargs) if arrow_csv_args is None: arrow_csv_args = {} self.read_options = arrow_csv_args.pop( "read_options", csv.ReadOptions(use_threads=False) ) self.parse_options = arrow_csv_args.pop("parse_options", csv.ParseOptions()) self.arrow_csv_args = arrow_csv_args def _read_stream(self, f: "pyarrow.NativeFile", path: str) -> Iterator[Block]: import pyarrow as pa from pyarrow import csv # Re-init invalid row handler: https://issues.apache.org/jira/browse/ARROW-17641 if hasattr(self.parse_options, "invalid_row_handler"): self.parse_options.invalid_row_handler = ( self.parse_options.invalid_row_handler ) filter_expr = ( self._predicate_expr.to_pyarrow() if self._predicate_expr is not None else None ) try: reader = csv.open_csv( f, read_options=self.read_options, parse_options=self.parse_options, **self.arrow_csv_args, ) schema = None while True: try: batch = reader.read_next_batch() table = pa.Table.from_batches([batch], schema=schema) if schema is None: schema = table.schema if filter_expr is not None: table = table.filter(filter_expr) yield table except StopIteration: return except pa.lib.ArrowInvalid as e: raise ValueError( f"Failed to read CSV file: {path}. " "Please check the CSV file has correct format, or filter out non-CSV " "file with 'partition_filter' field. See read_csv() documentation for " "more details." ) from e
CSVDatasource
python
pypa__pipenv
pipenv/vendor/click/core.py
{ "start": 4897, "end": 31503 }
class ____: """The context is a special internal object that holds state relevant for the script execution at every single level. It's normally invisible to commands unless they opt-in to getting access to it. The context is useful as it can pass internal objects around and can control special execution features such as reading data from environment variables. A context can be used as context manager in which case it will call :meth:`close` on teardown. :param command: the command class for this context. :param parent: the parent context. :param info_name: the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it is usually the name of the script, for commands below it it's the name of the script. :param obj: an arbitrary object of user data. :param auto_envvar_prefix: the prefix to use for automatic environment variables. If this is `None` then reading from environment variables is disabled. This does not affect manually set environment variables which are always read. :param default_map: a dictionary (like object) with default values for parameters. :param terminal_width: the width of the terminal. The default is inherit from parent context. If no context defines the terminal width then auto detection will be applied. :param max_content_width: the maximum width for content rendered by Click (this currently only affects help pages). This defaults to 80 characters if not overridden. In other words: even if the terminal is larger than that, Click will not format things wider than 80 characters by default. In addition to that, formatters might add some safety mapping on the right. :param resilient_parsing: if this flag is enabled then Click will parse without any interactivity or callback invocation. Default values will also be ignored. This is useful for implementing things such as completion support. :param allow_extra_args: if this is set to `True` then extra arguments at the end will not raise an error and will be kept on the context. The default is to inherit from the command. :param allow_interspersed_args: if this is set to `False` then options and arguments cannot be mixed. The default is to inherit from the command. :param ignore_unknown_options: instructs click to ignore options it does not know and keeps them for later processing. :param help_option_names: optionally a list of strings that define how the default help parameter is named. The default is ``['--help']``. :param token_normalize_func: an optional function that is used to normalize tokens (options, choices, etc.). This for instance can be used to implement case insensitive behavior. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are used in texts that Click prints which is by default not the case. This for instance would affect help output. :param show_default: Show the default value for commands. If this value is not set, it defaults to the value from the parent context. ``Command.show_default`` overrides this default for the specific command. .. versionchanged:: 8.1 The ``show_default`` parameter is overridden by ``Command.show_default``, instead of the other way around. .. versionchanged:: 8.0 The ``show_default`` parameter defaults to the value from the parent context. .. versionchanged:: 7.1 Added the ``show_default`` parameter. .. versionchanged:: 4.0 Added the ``color``, ``ignore_unknown_options``, and ``max_content_width`` parameters. .. versionchanged:: 3.0 Added the ``allow_extra_args`` and ``allow_interspersed_args`` parameters. .. versionchanged:: 2.0 Added the ``resilient_parsing``, ``help_option_names``, and ``token_normalize_func`` parameters. """ #: The formatter class to create with :meth:`make_formatter`. #: #: .. versionadded:: 8.0 formatter_class: t.Type["HelpFormatter"] = HelpFormatter def __init__( self, command: "Command", parent: t.Optional["Context"] = None, info_name: t.Optional[str] = None, obj: t.Optional[t.Any] = None, auto_envvar_prefix: t.Optional[str] = None, default_map: t.Optional[t.MutableMapping[str, t.Any]] = None, terminal_width: t.Optional[int] = None, max_content_width: t.Optional[int] = None, resilient_parsing: bool = False, allow_extra_args: t.Optional[bool] = None, allow_interspersed_args: t.Optional[bool] = None, ignore_unknown_options: t.Optional[bool] = None, help_option_names: t.Optional[t.List[str]] = None, token_normalize_func: t.Optional[t.Callable[[str], str]] = None, color: t.Optional[bool] = None, show_default: t.Optional[bool] = None, ) -> None: #: the parent context or `None` if none exists. self.parent = parent #: the :class:`Command` for this context. self.command = command #: the descriptive information name self.info_name = info_name #: Map of parameter names to their parsed values. Parameters #: with ``expose_value=False`` are not stored. self.params: t.Dict[str, t.Any] = {} #: the leftover arguments. self.args: t.List[str] = [] #: protected arguments. These are arguments that are prepended #: to `args` when certain parsing scenarios are encountered but #: must be never propagated to another arguments. This is used #: to implement nested parsing. self.protected_args: t.List[str] = [] #: the collected prefixes of the command's options. self._opt_prefixes: t.Set[str] = set(parent._opt_prefixes) if parent else set() if obj is None and parent is not None: obj = parent.obj #: the user object stored. self.obj: t.Any = obj self._meta: t.Dict[str, t.Any] = getattr(parent, "meta", {}) #: A dictionary (-like object) with defaults for parameters. if ( default_map is None and info_name is not None and parent is not None and parent.default_map is not None ): default_map = parent.default_map.get(info_name) self.default_map: t.Optional[t.MutableMapping[str, t.Any]] = default_map #: This flag indicates if a subcommand is going to be executed. A #: group callback can use this information to figure out if it's #: being executed directly or because the execution flow passes #: onwards to a subcommand. By default it's None, but it can be #: the name of the subcommand to execute. #: #: If chaining is enabled this will be set to ``'*'`` in case #: any commands are executed. It is however not possible to #: figure out which ones. If you require this knowledge you #: should use a :func:`result_callback`. self.invoked_subcommand: t.Optional[str] = None if terminal_width is None and parent is not None: terminal_width = parent.terminal_width #: The width of the terminal (None is autodetection). self.terminal_width: t.Optional[int] = terminal_width if max_content_width is None and parent is not None: max_content_width = parent.max_content_width #: The maximum width of formatted content (None implies a sensible #: default which is 80 for most things). self.max_content_width: t.Optional[int] = max_content_width if allow_extra_args is None: allow_extra_args = command.allow_extra_args #: Indicates if the context allows extra args or if it should #: fail on parsing. #: #: .. versionadded:: 3.0 self.allow_extra_args = allow_extra_args if allow_interspersed_args is None: allow_interspersed_args = command.allow_interspersed_args #: Indicates if the context allows mixing of arguments and #: options or not. #: #: .. versionadded:: 3.0 self.allow_interspersed_args: bool = allow_interspersed_args if ignore_unknown_options is None: ignore_unknown_options = command.ignore_unknown_options #: Instructs click to ignore options that a command does not #: understand and will store it on the context for later #: processing. This is primarily useful for situations where you #: want to call into external programs. Generally this pattern is #: strongly discouraged because it's not possibly to losslessly #: forward all arguments. #: #: .. versionadded:: 4.0 self.ignore_unknown_options: bool = ignore_unknown_options if help_option_names is None: if parent is not None: help_option_names = parent.help_option_names else: help_option_names = ["--help"] #: The names for the help options. self.help_option_names: t.List[str] = help_option_names if token_normalize_func is None and parent is not None: token_normalize_func = parent.token_normalize_func #: An optional normalization function for tokens. This is #: options, choices, commands etc. self.token_normalize_func: t.Optional[ t.Callable[[str], str] ] = token_normalize_func #: Indicates if resilient parsing is enabled. In that case Click #: will do its best to not cause any failures and default values #: will be ignored. Useful for completion. self.resilient_parsing: bool = resilient_parsing # If there is no envvar prefix yet, but the parent has one and # the command on this level has a name, we can expand the envvar # prefix automatically. if auto_envvar_prefix is None: if ( parent is not None and parent.auto_envvar_prefix is not None and self.info_name is not None ): auto_envvar_prefix = ( f"{parent.auto_envvar_prefix}_{self.info_name.upper()}" ) else: auto_envvar_prefix = auto_envvar_prefix.upper() if auto_envvar_prefix is not None: auto_envvar_prefix = auto_envvar_prefix.replace("-", "_") self.auto_envvar_prefix: t.Optional[str] = auto_envvar_prefix if color is None and parent is not None: color = parent.color #: Controls if styling output is wanted or not. self.color: t.Optional[bool] = color if show_default is None and parent is not None: show_default = parent.show_default #: Show option default values when formatting help text. self.show_default: t.Optional[bool] = show_default self._close_callbacks: t.List[t.Callable[[], t.Any]] = [] self._depth = 0 self._parameter_source: t.Dict[str, ParameterSource] = {} self._exit_stack = ExitStack() def to_info_dict(self) -> t.Dict[str, t.Any]: """Gather information that could be useful for a tool generating user-facing documentation. This traverses the entire CLI structure. .. code-block:: python with Context(cli) as ctx: info = ctx.to_info_dict() .. versionadded:: 8.0 """ return { "command": self.command.to_info_dict(self), "info_name": self.info_name, "allow_extra_args": self.allow_extra_args, "allow_interspersed_args": self.allow_interspersed_args, "ignore_unknown_options": self.ignore_unknown_options, "auto_envvar_prefix": self.auto_envvar_prefix, } def __enter__(self) -> "Context": self._depth += 1 push_context(self) return self def __exit__( self, exc_type: t.Optional[t.Type[BaseException]], exc_value: t.Optional[BaseException], tb: t.Optional[TracebackType], ) -> None: self._depth -= 1 if self._depth == 0: self.close() pop_context() @contextmanager def scope(self, cleanup: bool = True) -> t.Iterator["Context"]: """This helper method can be used with the context object to promote it to the current thread local (see :func:`get_current_context`). The default behavior of this is to invoke the cleanup functions which can be disabled by setting `cleanup` to `False`. The cleanup functions are typically used for things such as closing file handles. If the cleanup is intended the context object can also be directly used as a context manager. Example usage:: with ctx.scope(): assert get_current_context() is ctx This is equivalent:: with ctx: assert get_current_context() is ctx .. versionadded:: 5.0 :param cleanup: controls if the cleanup functions should be run or not. The default is to run these functions. In some situations the context only wants to be temporarily pushed in which case this can be disabled. Nested pushes automatically defer the cleanup. """ if not cleanup: self._depth += 1 try: with self as rv: yield rv finally: if not cleanup: self._depth -= 1 @property def meta(self) -> t.Dict[str, t.Any]: """This is a dictionary which is shared with all the contexts that are nested. It exists so that click utilities can store some state here if they need to. It is however the responsibility of that code to manage this dictionary well. The keys are supposed to be unique dotted strings. For instance module paths are a good choice for it. What is stored in there is irrelevant for the operation of click. However what is important is that code that places data here adheres to the general semantics of the system. Example usage:: LANG_KEY = f'{__name__}.lang' def set_language(value): ctx = get_current_context() ctx.meta[LANG_KEY] = value def get_language(): return get_current_context().meta.get(LANG_KEY, 'en_US') .. versionadded:: 5.0 """ return self._meta def make_formatter(self) -> HelpFormatter: """Creates the :class:`~click.HelpFormatter` for the help and usage output. To quickly customize the formatter class used without overriding this method, set the :attr:`formatter_class` attribute. .. versionchanged:: 8.0 Added the :attr:`formatter_class` attribute. """ return self.formatter_class( width=self.terminal_width, max_width=self.max_content_width ) def with_resource(self, context_manager: t.ContextManager[V]) -> V: """Register a resource as if it were used in a ``with`` statement. The resource will be cleaned up when the context is popped. Uses :meth:`contextlib.ExitStack.enter_context`. It calls the resource's ``__enter__()`` method and returns the result. When the context is popped, it closes the stack, which calls the resource's ``__exit__()`` method. To register a cleanup function for something that isn't a context manager, use :meth:`call_on_close`. Or use something from :mod:`contextlib` to turn it into a context manager first. .. code-block:: python @click.group() @click.option("--name") @click.pass_context def cli(ctx): ctx.obj = ctx.with_resource(connect_db(name)) :param context_manager: The context manager to enter. :return: Whatever ``context_manager.__enter__()`` returns. .. versionadded:: 8.0 """ return self._exit_stack.enter_context(context_manager) def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: """Register a function to be called when the context tears down. This can be used to close resources opened during the script execution. Resources that support Python's context manager protocol which would be used in a ``with`` statement should be registered with :meth:`with_resource` instead. :param f: The function to execute on teardown. """ return self._exit_stack.callback(f) def close(self) -> None: """Invoke all close callbacks registered with :meth:`call_on_close`, and exit all context managers entered with :meth:`with_resource`. """ self._exit_stack.close() # In case the context is reused, create a new exit stack. self._exit_stack = ExitStack() @property def command_path(self) -> str: """The computed command path. This is used for the ``usage`` information on the help page. It's automatically created by combining the info names of the chain of contexts to the root. """ rv = "" if self.info_name is not None: rv = self.info_name if self.parent is not None: parent_command_path = [self.parent.command_path] if isinstance(self.parent.command, Command): for param in self.parent.command.get_params(self): parent_command_path.extend(param.get_usage_pieces(self)) rv = f"{' '.join(parent_command_path)} {rv}" return rv.lstrip() def find_root(self) -> "Context": """Finds the outermost context.""" node = self while node.parent is not None: node = node.parent return node def find_object(self, object_type: t.Type[V]) -> t.Optional[V]: """Finds the closest object of a given type.""" node: t.Optional["Context"] = self while node is not None: if isinstance(node.obj, object_type): return node.obj node = node.parent return None def ensure_object(self, object_type: t.Type[V]) -> V: """Like :meth:`find_object` but sets the innermost object to a new instance of `object_type` if it does not exist. """ rv = self.find_object(object_type) if rv is None: self.obj = rv = object_type() return rv @t.overload def lookup_default( self, name: str, call: "te.Literal[True]" = True ) -> t.Optional[t.Any]: ... @t.overload def lookup_default( self, name: str, call: "te.Literal[False]" = ... ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]: ... def lookup_default(self, name: str, call: bool = True) -> t.Optional[t.Any]: """Get the default for a parameter from :attr:`default_map`. :param name: Name of the parameter. :param call: If the default is a callable, call it. Disable to return the callable instead. .. versionchanged:: 8.0 Added the ``call`` parameter. """ if self.default_map is not None: value = self.default_map.get(name) if call and callable(value): return value() return value return None def fail(self, message: str) -> "te.NoReturn": """Aborts the execution of the program with a specific error message. :param message: the error message to fail with. """ raise UsageError(message, self) def abort(self) -> "te.NoReturn": """Aborts the script.""" raise Abort() def exit(self, code: int = 0) -> "te.NoReturn": """Exits the application with a given exit code.""" raise Exit(code) def get_usage(self) -> str: """Helper method to get formatted usage string for the current context and command. """ return self.command.get_usage(self) def get_help(self) -> str: """Helper method to get formatted help page for the current context and command. """ return self.command.get_help(self) def _make_sub_context(self, command: "Command") -> "Context": """Create a new context of the same type as this context, but for a new command. :meta private: """ return type(self)(command, info_name=command.name, parent=self) @t.overload def invoke( __self, # noqa: B902 __callback: "t.Callable[..., V]", *args: t.Any, **kwargs: t.Any, ) -> V: ... @t.overload def invoke( __self, # noqa: B902 __callback: "Command", *args: t.Any, **kwargs: t.Any, ) -> t.Any: ... def invoke( __self, # noqa: B902 __callback: t.Union["Command", "t.Callable[..., V]"], *args: t.Any, **kwargs: t.Any, ) -> t.Union[t.Any, V]: """Invokes a command callback in exactly the way it expects. There are two ways to invoke this method: 1. the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function. 2. the first argument is a click command object. In that case all arguments are forwarded as well but proper click parameters (options and click arguments) must be keyword arguments and Click will fill in defaults. Note that before Click 3.2 keyword arguments were not properly filled in against the intention of this code and no context was created. For more information about this change and why it was done in a bugfix release see :ref:`upgrade-to-3.2`. .. versionchanged:: 8.0 All ``kwargs`` are tracked in :attr:`params` so they will be passed if :meth:`forward` is called at multiple levels. """ if isinstance(__callback, Command): other_cmd = __callback if other_cmd.callback is None: raise TypeError( "The given command does not have a callback that can be invoked." ) else: __callback = t.cast("t.Callable[..., V]", other_cmd.callback) ctx = __self._make_sub_context(other_cmd) for param in other_cmd.params: if param.name not in kwargs and param.expose_value: kwargs[param.name] = param.type_cast_value( # type: ignore ctx, param.get_default(ctx) ) # Track all kwargs as params, so that forward() will pass # them on in subsequent calls. ctx.params.update(kwargs) else: ctx = __self with augment_usage_errors(__self): with ctx: return __callback(*args, **kwargs) def forward( __self, __cmd: "Command", *args: t.Any, **kwargs: t.Any # noqa: B902 ) -> t.Any: """Similar to :meth:`invoke` but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands. .. versionchanged:: 8.0 All ``kwargs`` are tracked in :attr:`params` so they will be passed if ``forward`` is called at multiple levels. """ # Can only forward to other commands, not direct callbacks. if not isinstance(__cmd, Command): raise TypeError("Callback is not a command.") for param in __self.params: if param not in kwargs: kwargs[param] = __self.params[param] return __self.invoke(__cmd, *args, **kwargs) def set_parameter_source(self, name: str, source: ParameterSource) -> None: """Set the source of a parameter. This indicates the location from which the value of the parameter was obtained. :param name: The name of the parameter. :param source: A member of :class:`~click.core.ParameterSource`. """ self._parameter_source[name] = source def get_parameter_source(self, name: str) -> t.Optional[ParameterSource]: """Get the source of a parameter. This indicates the location from which the value of the parameter was obtained. This can be useful for determining when a user specified a value on the command line that is the same as the default value. It will be :attr:`~click.core.ParameterSource.DEFAULT` only if the value was actually taken from the default. :param name: The name of the parameter. :rtype: ParameterSource .. versionchanged:: 8.0 Returns ``None`` if the parameter was not provided from any source. """ return self._parameter_source.get(name)
Context
python
skorch-dev__skorch
examples/word_language_model/model.py
{ "start": 59, "end": 2560 }
class ____(nn.Module): """Container module with an encoder, a recurrent module, and a decoder.""" def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, tie_weights=False): super(RNNModel, self).__init__() self.drop = nn.Dropout(dropout) self.encoder = nn.Embedding(ntoken, ninp) if rnn_type in ['LSTM', 'GRU']: self.rnn = getattr(nn, rnn_type)(ninp, nhid, nlayers, dropout=dropout) else: try: nonlinearity = {'RNN_TANH': 'tanh', 'RNN_RELU': 'relu'}[rnn_type] except KeyError: raise ValueError( """An invalid option for `--model` was supplied, options are ['LSTM', 'GRU', 'RNN_TANH' or 'RNN_RELU']""") self.rnn = nn.RNN(ninp, nhid, nlayers, nonlinearity=nonlinearity, dropout=dropout) self.decoder = nn.Linear(nhid, ntoken) # Optionally tie weights as in: # "Using the Output Embedding to Improve Language Models" (Press & Wolf 2016) # https://arxiv.org/abs/1608.05859 # and # "Tying Word Vectors and Word Classifiers: A Loss Framework for Language Modeling" (Inan et al. 2016) # https://arxiv.org/abs/1611.01462 if tie_weights: if nhid != ninp: raise ValueError('When using the tied flag, nhid must be equal to emsize') self.decoder.weight = self.encoder.weight self.init_weights() self.rnn_type = rnn_type self.nhid = nhid self.nlayers = nlayers def init_weights(self): initrange = 0.1 self.encoder.weight.data.uniform_(-initrange, initrange) self.decoder.bias.data.fill_(0) self.decoder.weight.data.uniform_(-initrange, initrange) def forward(self, input, hidden): emb = self.drop(self.encoder(input)) output, hidden = self.rnn(emb, hidden) output = self.drop(output) decoded = self.decoder(output.view(output.size(0)*output.size(1), output.size(2))) return decoded.view(output.size(0), output.size(1), decoded.size(1)), hidden def init_hidden(self, bsz): weight = next(self.parameters()).data if self.rnn_type == 'LSTM': return (Variable(weight.new(self.nlayers, bsz, self.nhid).zero_()), Variable(weight.new(self.nlayers, bsz, self.nhid).zero_())) else: return Variable(weight.new(self.nlayers, bsz, self.nhid).zero_())
RNNModel
python
huggingface__transformers
src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py
{ "start": 29675, "end": 38277 }
class ____(Qwen2VLForConditionalGeneration): # Reference: fix gemma3 grad acc #37208 accepts_loss_kwargs = False def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, pixel_values: Optional[torch.Tensor] = None, pixel_values_videos: Optional[torch.FloatTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, rope_deltas: Optional[torch.LongTensor] = None, cache_position: Optional[torch.LongTensor] = None, second_per_grid_ts: Optional[torch.Tensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, Qwen2_5_VLCausalLMOutputWithPast]: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): The temporal, height and width of feature shape of each image in LLM. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*): The temporal, height and width of feature shape of each video in LLM. rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*): The rope index difference between sequence length and multimodal rope. second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*): The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs. Example: ```python >>> from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration >>> model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct") >>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct") >>> messages = [ { "role": "user", "content": [ { "type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg", }, {"type": "text", "text": "Describe the image."}, ], } ] >>> inputs = processor.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt" ) >>> # Generate >>> generated_ids = model.generate(**inputs, max_new_tokens=1024) >>> generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)] >>> output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] >>> print(output_text) ``` """ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) outputs = self.model( input_ids=input_ids, pixel_values=pixel_values, pixel_values_videos=pixel_values_videos, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, second_per_grid_ts=second_per_grid_ts, position_ids=position_ids, attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=True, cache_position=cache_position, **kwargs, ) hidden_states = outputs[0] # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: loss = self.loss_function( logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs ) return Qwen2_5_VLCausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, rope_deltas=outputs.rope_deltas, ) def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, position_ids=None, use_cache=True, pixel_values=None, pixel_values_videos=None, image_grid_thw=None, video_grid_thw=None, second_per_grid_ts=None, **kwargs, ): # Overwritten -- in specific circumstances we don't want to forward image inputs to the model model_inputs = super().prepare_inputs_for_generation( input_ids, past_key_values=past_key_values, attention_mask=attention_mask, inputs_embeds=inputs_embeds, cache_position=cache_position, position_ids=position_ids, pixel_values=pixel_values, pixel_values_videos=pixel_values_videos, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, second_per_grid_ts=second_per_grid_ts, use_cache=use_cache, **kwargs, ) # Qwen2-5-VL position_ids are prepared with rope_deltas if position_ids is None: # Calculate RoPE index once per generation in the pre-fill stage only. # When compiling, we can't check tensor values thus we check only input length # It is safe to assume that `length!=1` means we're in pre-fill because compiled # models currently cannot do assisted decoding if cache_position[0] == 0 or self.model.rope_deltas is None: vision_positions, rope_deltas = self.model.get_rope_index( model_inputs.get("input_ids", None), image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, second_per_grid_ts=second_per_grid_ts, attention_mask=attention_mask, ) self.model.rope_deltas = rope_deltas # then use the prev pre-calculated rope-deltas to get the correct position ids elif "position_ids" in model_inputs: batch_size, seq_length = model_inputs["position_ids"].shape device = model_inputs["position_ids"].device position_ids = torch.arange(seq_length, device=device) position_ids = position_ids.view(1, 1, -1).expand(3, batch_size, -1) delta = cache_position[0] + self.model.rope_deltas delta = delta.repeat_interleave(batch_size // delta.shape[0], dim=0) vision_positions = position_ids + delta.expand_as(position_ids) # Concatenate "text + vision" positions into [4, bs, seq-len] text_positions = model_inputs["position_ids"][None, ...] model_inputs["position_ids"] = torch.cat([text_positions, vision_positions], dim=0) if cache_position[0] != 0: model_inputs["pixel_values"] = None model_inputs["pixel_values_videos"] = None return model_inputs
Qwen2_5_VLForConditionalGeneration
python
numpy__numpy
numpy/f2py/symbolic.py
{ "start": 2830, "end": 3397 }
class ____(Enum): """ Used as Expr.tostring precedence argument. """ ATOM = 0 POWER = 1 UNARY = 2 PRODUCT = 3 SUM = 4 LT = 6 EQ = 7 LAND = 11 LOR = 12 TERNARY = 13 ASSIGN = 14 TUPLE = 15 NONE = 100 integer_types = (int,) number_types = (int, float) def _pairs_add(d, k, v): # Internal utility method for updating terms and factors data. c = d.get(k) if c is None: d[k] = v else: c = c + v if c: d[k] = c else: del d[k]
Precedence
python
oauthlib__oauthlib
tests/test_common.py
{ "start": 1920, "end": 3070 }
class ____(TestCase): def test_extract_params_dict(self): self.assertCountEqual(extract_params(PARAMS_DICT), PARAMS_TWOTUPLE) def test_extract_params_twotuple(self): self.assertCountEqual(extract_params(PARAMS_TWOTUPLE), PARAMS_TWOTUPLE) def test_extract_params_formencoded(self): self.assertCountEqual(extract_params(PARAMS_FORMENCODED), PARAMS_TWOTUPLE) def test_extract_params_blank_string(self): self.assertCountEqual(extract_params(''), []) def test_extract_params_empty_list(self): self.assertCountEqual(extract_params([]), []) def test_extract_non_formencoded_string(self): self.assertIsNone(extract_params('not a formencoded string')) def test_extract_invalid(self): self.assertIsNone(extract_params(object())) self.assertIsNone(extract_params([('')])) def test_add_params_to_uri(self): correct = '{}?{}'.format(URI, PARAMS_FORMENCODED) self.assertURLEqual(add_params_to_uri(URI, PARAMS_DICT), correct) self.assertURLEqual(add_params_to_uri(URI, PARAMS_TWOTUPLE), correct)
ParameterTest
python
pandas-dev__pandas
pandas/tests/series/test_formats.py
{ "start": 264, "end": 8878 }
class ____: def test_multilevel_name_print_0(self): # GH#55415 None does not get printed, but 0 does # (matching DataFrame and flat index behavior) mi = pd.MultiIndex.from_product([range(2, 3), range(3, 4)], names=[0, None]) ser = Series(1.5, index=mi) res = repr(ser) expected = "0 \n2 3 1.5\ndtype: float64" assert res == expected def test_multilevel_name_print(self, lexsorted_two_level_string_multiindex): index = lexsorted_two_level_string_multiindex ser = Series(range(len(index)), index=index, name="sth") expected = [ "first second", "foo one 0", " two 1", " three 2", "bar one 3", " two 4", "baz two 5", " three 6", "qux one 7", " two 8", " three 9", "Name: sth, dtype: int64", ] expected = "\n".join(expected) assert repr(ser) == expected def test_small_name_printing(self): # Test small Series. s = Series([0, 1, 2]) s.name = "test" assert "Name: test" in repr(s) s.name = None assert "Name:" not in repr(s) def test_big_name_printing(self): # Test big Series (diff code path). s = Series(range(1000)) s.name = "test" assert "Name: test" in repr(s) s.name = None assert "Name:" not in repr(s) def test_empty_name_printing(self): s = Series(index=date_range("20010101", "20020101"), name="test", dtype=object) assert "Name: test" in repr(s) @pytest.mark.parametrize("args", [(), (0, -1)]) def test_float_range(self, args): str( Series( np.random.default_rng(2).standard_normal(1000), index=np.arange(1000, *args), ) ) def test_empty_object(self): # empty str(Series(dtype=object)) def test_string(self, string_series): str(string_series) str(string_series.astype(int)) # with NaNs string_series[5:7] = np.nan str(string_series) def test_object(self, object_series): str(object_series) def test_datetime(self, datetime_series): str(datetime_series) # with Nones ots = datetime_series.astype("O") ots[::2] = None repr(ots) @pytest.mark.parametrize( "name", [ "", 1, 1.2, "foo", "\u03b1\u03b2\u03b3", "loooooooooooooooooooooooooooooooooooooooooooooooooooong", ("foo", "bar", "baz"), (1, 2), ("foo", 1, 2.3), ("\u03b1", "\u03b2", "\u03b3"), ("\u03b1", "bar"), ], ) def test_various_names(self, name, string_series): # various names string_series.name = name repr(string_series) def test_tuple_name(self): biggie = Series( np.random.default_rng(2).standard_normal(1000), index=np.arange(1000), name=("foo", "bar", "baz"), ) repr(biggie) @pytest.mark.parametrize("arg", [100, 1001]) def test_tidy_repr_name_0(self, arg): # tidy repr ser = Series(np.random.default_rng(2).standard_normal(arg), name=0) rep_str = repr(ser) assert "Name: 0" in rep_str def test_newline(self, any_string_dtype): ser = Series( ["a\n\r\tb"], name="a\n\r\td", index=Index(["a\n\r\tf"], dtype=any_string_dtype), dtype=any_string_dtype, ) assert "\t" not in repr(ser) assert "\r" not in repr(ser) assert "a\n" not in repr(ser) @pytest.mark.parametrize( "name, expected", [ ["foo", "Series([], Name: foo, dtype: int64)"], [None, "Series([], dtype: int64)"], ], ) def test_empty_int64(self, name, expected): # with empty series (#4651) s = Series([], dtype=np.int64, name=name) assert repr(s) == expected def test_repr_bool_fails(self, capsys): s = Series( [ DataFrame(np.random.default_rng(2).standard_normal((2, 2))) for i in range(5) ] ) # It works (with no Cython exception barf)! repr(s) captured = capsys.readouterr() assert captured.err == "" def test_repr_name_iterable_indexable(self): s = Series([1, 2, 3], name=np.int64(3)) # it works! repr(s) s.name = ("\u05d0",) * 2 repr(s) def test_repr_max_rows(self): # GH 6863 with option_context("display.max_rows", None): str(Series(range(1001))) # should not raise exception def test_unicode_string_with_unicode(self): df = Series(["\u05d0"], name="\u05d1") str(df) ser = Series(["\u03c3"] * 10) repr(ser) ser2 = Series(["\u05d0"] * 1000) ser2.name = "title1" repr(ser2) def test_str_to_bytes_raises(self): # GH 26447 df = Series(["abc"], name="abc") msg = "^'str' object cannot be interpreted as an integer$" with pytest.raises(TypeError, match=msg): bytes(df) def test_timeseries_repr_object_dtype(self): index = Index( [datetime(2000, 1, 1) + timedelta(i) for i in range(1000)], dtype=object ) ts = Series(np.random.default_rng(2).standard_normal(len(index)), index) repr(ts) ts = Series( np.arange(20, dtype=np.float64), index=date_range("2020-01-01", periods=20) ) assert repr(ts).splitlines()[-1].startswith("Freq:") ts2 = ts.iloc[np.random.default_rng(2).integers(0, len(ts) - 1, 400)] repr(ts2).splitlines()[-1] def test_latex_repr(self): pytest.importorskip("jinja2") # uses Styler implementation result = r"""\begin{tabular}{ll} \toprule & 0 \\ \midrule 0 & $\alpha$ \\ 1 & b \\ 2 & c \\ \bottomrule \end{tabular} """ with option_context( "styler.format.escape", None, "styler.render.repr", "latex" ): s = Series([r"$\alpha$", "b", "c"]) assert result == s._repr_latex_() assert s._repr_latex_() is None def test_index_repr_in_frame_with_nan(self): # see gh-25061 i = Index([1, np.nan]) s = Series([1, 2], index=i) exp = """1.0 1\nNaN 2\ndtype: int64""" assert repr(s) == exp def test_series_repr_nat(self): series = Series([0, 1000, 2000, pd.NaT._value], dtype="M8[ns]") result = repr(series) expected = ( "0 1970-01-01 00:00:00.000000\n" "1 1970-01-01 00:00:00.000001\n" "2 1970-01-01 00:00:00.000002\n" "3 NaT\n" "dtype: datetime64[ns]" ) assert result == expected def test_float_repr(self): # GH#35603 # check float format when cast to object ser = Series([1.0]).astype(object) expected = "0 1.0\ndtype: object" assert repr(ser) == expected def test_different_null_objects(self): # GH#45263 ser = Series([1, 2, 3, 4], [True, None, np.nan, pd.NaT]) result = repr(ser) expected = "True 1\nNone 2\nNaN 3\nNaT 4\ndtype: int64" assert result == expected def test_2d_extension_type(self): # GH#33770 # Define a stub extension type with just enough code to run Series.__repr__() class DtypeStub(pd.api.extensions.ExtensionDtype): @property def type(self): return np.ndarray @property def name(self): return "DtypeStub" class ExtTypeStub(pd.api.extensions.ExtensionArray): def __len__(self) -> int: return 2 def __getitem__(self, ix): return [ix == 1, ix == 0] @property def dtype(self): return DtypeStub() series = Series(ExtTypeStub(), copy=False) res = repr(series) # This line crashed before GH#33770 was fixed. expected = "\n".join( ["0 [False True]", "1 [True False]", "dtype: DtypeStub"] ) assert res == expected
TestSeriesRepr
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-text-embeddings-inference/llama_index/embeddings/text_embeddings_inference/base.py
{ "start": 413, "end": 5361 }
class ____(BaseEmbedding): base_url: str = Field( default=DEFAULT_URL, description="Base URL for the text embeddings service.", ) query_instruction: Optional[str] = Field( description="Instruction to prepend to query text." ) text_instruction: Optional[str] = Field( description="Instruction to prepend to text." ) timeout: float = Field( default=60.0, description="Timeout in seconds for the request.", ) truncate_text: bool = Field( default=True, description="Whether to truncate text or not when generating embeddings.", ) auth_token: Optional[Union[str, Callable[[str], str]]] = Field( default=None, description="Authentication token or authentication token generating function for authenticated requests", ) endpoint: str = Field( default=DEFAULT_ENDPOINT, description="Endpoint for the text embeddings service.", ) def __init__( self, model_name: str, base_url: str = DEFAULT_URL, text_instruction: Optional[str] = None, query_instruction: Optional[str] = None, embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE, timeout: float = 60.0, truncate_text: bool = True, callback_manager: Optional[CallbackManager] = None, auth_token: Optional[Union[str, Callable[[str], str]]] = None, endpoint: str = DEFAULT_ENDPOINT, ): super().__init__( base_url=base_url, model_name=model_name, text_instruction=text_instruction, query_instruction=query_instruction, embed_batch_size=embed_batch_size, timeout=timeout, truncate_text=truncate_text, callback_manager=callback_manager, auth_token=auth_token, endpoint=endpoint, ) @classmethod def class_name(cls) -> str: return "TextEmbeddingsInference" def _call_api(self, texts: List[str]) -> List[List[float]]: import httpx headers = {"Content-Type": "application/json"} if self.auth_token is not None: if callable(self.auth_token): auth_token = self.auth_token(self.base_url) else: auth_token = self.auth_token headers["Authorization"] = f"Bearer {auth_token}" json_data = {"inputs": texts, "truncate": self.truncate_text} with httpx.Client() as client: response = client.post( f"{self.base_url}{self.endpoint}", headers=headers, json=json_data, timeout=self.timeout, ) return response.json() async def _acall_api(self, texts: List[str]) -> List[List[float]]: import httpx headers = {"Content-Type": "application/json"} if self.auth_token is not None: if callable(self.auth_token): auth_token = self.auth_token(self.base_url) else: auth_token = self.auth_token headers["Authorization"] = f"Bearer {auth_token}" json_data = {"inputs": texts, "truncate": self.truncate_text} async with httpx.AsyncClient() as client: response = await client.post( f"{self.base_url}{self.endpoint}", headers=headers, json=json_data, timeout=self.timeout, ) return response.json() def _get_query_embedding(self, query: str) -> List[float]: """Get query embedding.""" query = format_query(query, self.model_name, self.query_instruction) return self._call_api([query])[0] def _get_text_embedding(self, text: str) -> List[float]: """Get text embedding.""" text = format_text(text, self.model_name, self.text_instruction) return self._call_api([text])[0] def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]: """Get text embeddings.""" texts = [ format_text(text, self.model_name, self.text_instruction) for text in texts ] return self._call_api(texts) async def _aget_query_embedding(self, query: str) -> List[float]: """Get query embedding async.""" query = format_query(query, self.model_name, self.query_instruction) return (await self._acall_api([query]))[0] async def _aget_text_embedding(self, text: str) -> List[float]: """Get text embedding async.""" text = format_text(text, self.model_name, self.text_instruction) return (await self._acall_api([text]))[0] async def _aget_text_embeddings(self, texts: List[str]) -> List[Embedding]: texts = [ format_text(text, self.model_name, self.text_instruction) for text in texts ] return await self._acall_api(texts)
TextEmbeddingsInference
python
huggingface__transformers
src/transformers/models/splinter/modeling_splinter.py
{ "start": 20003, "end": 25340 }
class ____(SplinterPreTrainedModel): def __init__(self, config): super().__init__(config) self.splinter = SplinterModel(config) self.splinter_qass = QuestionAwareSpanSelectionHead(config) self.question_token_id = config.question_token_id # Initialize weights and apply final processing self.post_init() @auto_docstring def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, start_positions: Optional[torch.LongTensor] = None, end_positions: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, question_positions: Optional[torch.LongTensor] = None, ) -> Union[tuple, QuestionAnsweringModelOutput]: r""" token_type_ids (`torch.LongTensor` of shape `batch_size, sequence_length`, *optional*): Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`: - 0 corresponds to a *sentence A* token, - 1 corresponds to a *sentence B* token. [What are token type IDs?](../glossary#token-type-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) question_positions (`torch.LongTensor` of shape `(batch_size, num_questions)`, *optional*): The positions of all question tokens. If given, start_logits and end_logits will be of shape `(batch_size, num_questions, sequence_length)`. If None, the first question token in each sequence in the batch will be the only one for which start_logits and end_logits are calculated and they will be of shape `(batch_size, sequence_length)`. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict question_positions_were_none = False if question_positions is None: if input_ids is not None: question_position_for_each_example = torch.argmax( (torch.eq(input_ids, self.question_token_id)).int(), dim=-1 ) else: question_position_for_each_example = torch.zeros( inputs_embeds.size(0), dtype=torch.long, layout=inputs_embeds.layout, device=inputs_embeds.device ) question_positions = question_position_for_each_example.unsqueeze(-1) question_positions_were_none = True outputs = self.splinter( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] start_logits, end_logits = self.splinter_qass(sequence_output, question_positions) if question_positions_were_none: start_logits, end_logits = start_logits.squeeze(1), end_logits.squeeze(1) if attention_mask is not None: start_logits = start_logits + (1 - attention_mask) * torch.finfo(start_logits.dtype).min end_logits = end_logits + (1 - attention_mask) * torch.finfo(end_logits.dtype).min total_loss = None if start_positions is not None and end_positions is not None: # If we are on multi-GPU, split add a dimension if len(start_positions.size()) > 1: start_positions = start_positions.squeeze(-1) if len(end_positions.size()) > 1: end_positions = end_positions.squeeze(-1) # sometimes the start/end positions are outside our model inputs, we ignore these terms ignored_index = start_logits.size(1) start_positions.clamp_(0, ignored_index) end_positions.clamp_(0, ignored_index) loss_fct = CrossEntropyLoss(ignore_index=ignored_index) start_loss = loss_fct(start_logits, start_positions) end_loss = loss_fct(end_logits, end_positions) total_loss = (start_loss + end_loss) / 2 if not return_dict: output = (start_logits, end_logits) + outputs[1:] return ((total_loss,) + output) if total_loss is not None else output return QuestionAnsweringModelOutput( loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @dataclass @auto_docstring( custom_intro=""" Class for outputs of Splinter as a span selection model. """ )
SplinterForQuestionAnswering
python
tensorflow__tensorflow
tensorflow/python/eager/core.py
{ "start": 2258, "end": 2744 }
class ____(Exception): """Exception class to handle use of symbolic tensors when executing eagerly. `keras.Input()` creates symbolic tensors (in a FuncGraph managed by the Keras backend) while in eager execution. This exception is used to identify this case (raised in `convert_to_tensor` cause generated functions for ops to construct graphs instead of executing the kernel). """ pass pywrap_tfe.TFE_Py_RegisterFallbackExceptionClass(_FallbackException)
_SymbolicException
python
django__django
tests/indexes/models.py
{ "start": 1563, "end": 1678 }
class ____(models.Model): headline = models.CharField(max_length=100) body = models.TextField()
IndexedArticle2
python
keras-team__keras
keras/src/metrics/correlation_metrics_test.py
{ "start": 237, "end": 3234 }
class ____(testing.TestCase): def _get_data(self): # Sample data for testing y_true = np.array( [[0, 1, 0.5], [1, 1, 0.2], [1, 1, 0.1], [0.1, 0.7, 0.0]], dtype="float32", ) y_pred = np.array( [[0.1, 0.9, 0.5], [1, 0.9, 0.2], [0.2, 0.8, 0], [0.3, 0.3, 0.9]], dtype="float32", ) ccc_expected = np.array( [0.97560976, 0.98765432, 0.46511628, -0.46376812] ) # pcc_expected = np.array([1, 0.99339927, 0.69337525, -0.60999428]) pcc_expected = np.array( [pearsonr(yt, yp).statistic for yt, yp in zip(y_true, y_pred)] ) return y_true, y_pred, ccc_expected, pcc_expected def test_pearson_function(self): """Test the functional API for Pearson Correlation Coefficient.""" y_true, y_pred, _, pcc_expected = self._get_data() result = correlation_metrics.pearson_correlation( y_true, y_pred, axis=-1 ) self.assertAllClose(result, pcc_expected) def test_concordance_function(self): """Test the functional API for Concordance Correlation Coefficient.""" y_true, y_pred, ccc_expected, _ = self._get_data() result = correlation_metrics.concordance_correlation( y_true, y_pred, axis=-1 ) self.assertAllClose(result, ccc_expected) def test_pearson_class(self): """Test the PearsonCorrelation metric class.""" y_true, y_pred, _, pcc_expected = self._get_data() m = PearsonCorrelation(axis=-1, dtype="float32") m.update_state(y_true[:2], y_pred[:2]) self.assertAllClose(m.result(), np.mean(pcc_expected[:2])) m.update_state(y_true[2:], y_pred[2:]) self.assertAllClose(m.result(), np.mean(pcc_expected)) def test_concordance_class(self): """Test the ConcordanceCorrelation metric class.""" y_true, y_pred, ccc_expected, _ = self._get_data() m = ConcordanceCorrelation(axis=-1, dtype="float32") m.update_state(y_true[:2], y_pred[:2]) self.assertAllClose(m.result(), np.mean(ccc_expected[:2])) m.update_state(y_true[2:], y_pred[2:]) self.assertAllClose(m.result(), np.mean(ccc_expected)) def test_pearson_config(self): """Test the get_config method for PearsonCorrelation.""" m = PearsonCorrelation(axis=-1, dtype="float16") config = m.get_config() self.assertEqual(config["axis"], -1) self.assertEqual(config["dtype"], "float16") self.assertEqual(config["name"], "pearson_correlation") def test_concordance_config(self): """Test the get_config method for ConcordanceCorrelation.""" m = ConcordanceCorrelation(axis=-1, dtype="float32") config = m.get_config() self.assertEqual(config["axis"], -1) self.assertEqual(config["dtype"], "float32") self.assertEqual(config["name"], "concordance_correlation")
CorrelationsTest
python
getsentry__sentry
src/sentry/lang/native/symbolicator.py
{ "start": 1146, "end": 1586 }
class ____(Enum): """The order in which stack frames are sent to and returned from Symbolicator.""" # Caller frames come before callee frames. This is the # order in which stack frames are stored in events. caller_first = "caller_first" # Callee frames come before caller frames. This is the # order in which stack frames are usually displayed. callee_first = "callee_first" @dataclass(frozen=True)
FrameOrder
python
PyCQA__isort
isort/exceptions.py
{ "start": 6217, "end": 6498 }
class ____(ISortError): """Raised when isort encounters an encoding error while trying to read a file""" def __init__(self, filename: str | Path): super().__init__(f"Unknown or unsupported encoding in {filename}") self.filename = filename
UnsupportedEncoding
python
pypa__pip
src/pip/_vendor/urllib3/util/queue.py
{ "start": 228, "end": 498 }
class ____(queue.Queue): def _init(self, _): self.queue = collections.deque() def _qsize(self, len=len): return len(self.queue) def _put(self, item): self.queue.append(item) def _get(self): return self.queue.pop()
LifoQueue
python
plotly__plotly.py
plotly/graph_objs/layout/ternary/_baxis.py
{ "start": 235, "end": 53738 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.ternary" _path_str = "layout.ternary.baxis" _valid_props = { "color", "dtick", "exponentformat", "gridcolor", "griddash", "gridwidth", "hoverformat", "labelalias", "layer", "linecolor", "linewidth", "min", "minexponent", "nticks", "separatethousands", "showexponent", "showgrid", "showline", "showticklabels", "showtickprefix", "showticksuffix", "tick0", "tickangle", "tickcolor", "tickfont", "tickformat", "tickformatstopdefaults", "tickformatstops", "ticklabelstep", "ticklen", "tickmode", "tickprefix", "ticks", "ticksuffix", "ticktext", "ticktextsrc", "tickvals", "tickvalssrc", "tickwidth", "title", "uirevision", } @property def color(self): """ Sets default for all colors associated with this axis all at once: line, font, tick, and grid colors. Grid color is lightened by blending this with the plot background Individual pieces can override this. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def dtick(self): """ Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" The 'dtick' property accepts values of any type Returns ------- Any """ return self["dtick"] @dtick.setter def dtick(self, val): self["dtick"] = val @property def exponentformat(self): """ Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. "SI" uses prefixes from "femto" f (10^-15) to "tera" T (10^12). *SI extended* covers instead the full SI range from "quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or *SI extended* is used and the exponent is beyond the above ranges, the formatting rule will automatically be switched to the power notation. The 'exponentformat' property is an enumeration that may be specified as: - One of the following enumeration values: ['none', 'e', 'E', 'power', 'SI', 'B', 'SI extended'] Returns ------- Any """ return self["exponentformat"] @exponentformat.setter def exponentformat(self, val): self["exponentformat"] = val @property def gridcolor(self): """ Sets the color of the grid lines. The 'gridcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["gridcolor"] @gridcolor.setter def gridcolor(self, val): self["gridcolor"] = val @property def griddash(self): """ Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). The 'griddash' property is an enumeration that may be specified as: - One of the following dash styles: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'] - A string containing a dash length list in pixels or percentages (e.g. '5px 10px 2px 2px', '5, 10, 2, 2', '10% 20% 40%', etc.) Returns ------- str """ return self["griddash"] @griddash.setter def griddash(self, val): self["griddash"] = val @property def gridwidth(self): """ Sets the width (in px) of the grid lines. The 'gridwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["gridwidth"] @gridwidth.setter def gridwidth(self, val): self["gridwidth"] = val @property def hoverformat(self): """ Sets the hover text formatting rule using d3 formatting mini- languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" The 'hoverformat' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["hoverformat"] @hoverformat.setter def hoverformat(self, val): self["hoverformat"] = val @property def labelalias(self): """ Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use −1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html- like tags or MathJax. The 'labelalias' property accepts values of any type Returns ------- Any """ return self["labelalias"] @labelalias.setter def labelalias(self, val): self["labelalias"] = val @property def layer(self): """ Sets the layer on which this axis is displayed. If *above traces*, this axis is displayed above all the subplot's traces If *below traces*, this axis is displayed below all the subplot's traces, but above the grid lines. Useful when used together with scatter-like traces with `cliponaxis` set to False to show markers and/or text nodes above this axis. The 'layer' property is an enumeration that may be specified as: - One of the following enumeration values: ['above traces', 'below traces'] Returns ------- Any """ return self["layer"] @layer.setter def layer(self, val): self["layer"] = val @property def linecolor(self): """ Sets the axis line color. The 'linecolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["linecolor"] @linecolor.setter def linecolor(self, val): self["linecolor"] = val @property def linewidth(self): """ Sets the width (in px) of the axis line. The 'linewidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["linewidth"] @linewidth.setter def linewidth(self, val): self["linewidth"] = val @property def min(self): """ The minimum value visible on this axis. The maximum is determined by the sum minus the minimum values of the other two axes. The full view corresponds to all the minima set to zero. The 'min' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["min"] @min.setter def min(self, val): self["min"] = val @property def minexponent(self): """ Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". The 'minexponent' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["minexponent"] @minexponent.setter def minexponent(self, val): self["minexponent"] = val @property def nticks(self): """ Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". The 'nticks' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 9223372036854775807] Returns ------- int """ return self["nticks"] @nticks.setter def nticks(self, val): self["nticks"] = val @property def separatethousands(self): """ If "true", even 4-digit integers are separated The 'separatethousands' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["separatethousands"] @separatethousands.setter def separatethousands(self, val): self["separatethousands"] = val @property def showexponent(self): """ If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. The 'showexponent' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showexponent"] @showexponent.setter def showexponent(self, val): self["showexponent"] = val @property def showgrid(self): """ Determines whether or not grid lines are drawn. If True, the grid lines are drawn at every tick mark. The 'showgrid' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showgrid"] @showgrid.setter def showgrid(self, val): self["showgrid"] = val @property def showline(self): """ Determines whether or not a line bounding this axis is drawn. The 'showline' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showline"] @showline.setter def showline(self, val): self["showline"] = val @property def showticklabels(self): """ Determines whether or not the tick labels are drawn. The 'showticklabels' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showticklabels"] @showticklabels.setter def showticklabels(self, val): self["showticklabels"] = val @property def showtickprefix(self): """ If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. The 'showtickprefix' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showtickprefix"] @showtickprefix.setter def showtickprefix(self, val): self["showtickprefix"] = val @property def showticksuffix(self): """ Same as `showtickprefix` but for tick suffixes. The 'showticksuffix' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showticksuffix"] @showticksuffix.setter def showticksuffix(self, val): self["showticksuffix"] = val @property def tick0(self): """ Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. The 'tick0' property accepts values of any type Returns ------- Any """ return self["tick0"] @tick0.setter def tick0(self, val): self["tick0"] = val @property def tickangle(self): """ Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. The 'tickangle' property is a angle (in degrees) that may be specified as a number between -180 and 180. Numeric values outside this range are converted to the equivalent value (e.g. 270 is converted to -90). Returns ------- int|float """ return self["tickangle"] @tickangle.setter def tickangle(self, val): self["tickangle"] = val @property def tickcolor(self): """ Sets the tick color. The 'tickcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["tickcolor"] @tickcolor.setter def tickcolor(self, val): self["tickcolor"] = val @property def tickfont(self): """ Sets the tick font. The 'tickfont' property is an instance of Tickfont that may be specified as: - An instance of :class:`plotly.graph_objs.layout.ternary.baxis.Tickfont` - A dict of string/value properties that will be passed to the Tickfont constructor Returns ------- plotly.graph_objs.layout.ternary.baxis.Tickfont """ return self["tickfont"] @tickfont.setter def tickfont(self, val): self["tickfont"] = val @property def tickformat(self): """ Sets the tick label formatting rule using d3 formatting mini- languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" The 'tickformat' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["tickformat"] @tickformat.setter def tickformat(self, val): self["tickformat"] = val @property def tickformatstops(self): """ The 'tickformatstops' property is a tuple of instances of Tickformatstop that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.ternary.baxis.Tickformatstop - A list or tuple of dicts of string/value properties that will be passed to the Tickformatstop constructor Returns ------- tuple[plotly.graph_objs.layout.ternary.baxis.Tickformatstop] """ return self["tickformatstops"] @tickformatstops.setter def tickformatstops(self, val): self["tickformatstops"] = val @property def tickformatstopdefaults(self): """ When used in a template (as layout.template.layout.ternary.baxis.tickformatstopdefaults), sets the default property values to use for elements of layout.ternary.baxis.tickformatstops The 'tickformatstopdefaults' property is an instance of Tickformatstop that may be specified as: - An instance of :class:`plotly.graph_objs.layout.ternary.baxis.Tickformatstop` - A dict of string/value properties that will be passed to the Tickformatstop constructor Returns ------- plotly.graph_objs.layout.ternary.baxis.Tickformatstop """ return self["tickformatstopdefaults"] @tickformatstopdefaults.setter def tickformatstopdefaults(self, val): self["tickformatstopdefaults"] = val @property def ticklabelstep(self): """ Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". The 'ticklabelstep' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 9223372036854775807] Returns ------- int """ return self["ticklabelstep"] @ticklabelstep.setter def ticklabelstep(self, val): self["ticklabelstep"] = val @property def ticklen(self): """ Sets the tick length (in px). The 'ticklen' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["ticklen"] @ticklen.setter def ticklen(self, val): self["ticklen"] = val @property def tickmode(self): """ Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). The 'tickmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['auto', 'linear', 'array'] Returns ------- Any """ return self["tickmode"] @tickmode.setter def tickmode(self, val): self["tickmode"] = val @property def tickprefix(self): """ Sets a tick label prefix. The 'tickprefix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["tickprefix"] @tickprefix.setter def tickprefix(self, val): self["tickprefix"] = val @property def ticks(self): """ Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. The 'ticks' property is an enumeration that may be specified as: - One of the following enumeration values: ['outside', 'inside', ''] Returns ------- Any """ return self["ticks"] @ticks.setter def ticks(self, val): self["ticks"] = val @property def ticksuffix(self): """ Sets a tick label suffix. The 'ticksuffix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["ticksuffix"] @ticksuffix.setter def ticksuffix(self, val): self["ticksuffix"] = val @property def ticktext(self): """ Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. The 'ticktext' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["ticktext"] @ticktext.setter def ticktext(self, val): self["ticktext"] = val @property def ticktextsrc(self): """ Sets the source reference on Chart Studio Cloud for `ticktext`. The 'ticktextsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["ticktextsrc"] @ticktextsrc.setter def ticktextsrc(self, val): self["ticktextsrc"] = val @property def tickvals(self): """ Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. The 'tickvals' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["tickvals"] @tickvals.setter def tickvals(self, val): self["tickvals"] = val @property def tickvalssrc(self): """ Sets the source reference on Chart Studio Cloud for `tickvals`. The 'tickvalssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["tickvalssrc"] @tickvalssrc.setter def tickvalssrc(self, val): self["tickvalssrc"] = val @property def tickwidth(self): """ Sets the tick width (in px). The 'tickwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["tickwidth"] @tickwidth.setter def tickwidth(self, val): self["tickwidth"] = val @property def title(self): """ The 'title' property is an instance of Title that may be specified as: - An instance of :class:`plotly.graph_objs.layout.ternary.baxis.Title` - A dict of string/value properties that will be passed to the Title constructor Returns ------- plotly.graph_objs.layout.ternary.baxis.Title """ return self["title"] @title.setter def title(self, val): self["title"] = val @property def uirevision(self): """ Controls persistence of user-driven changes in axis `min`, and `title` if in `editable: true` configuration. Defaults to `ternary<N>.uirevision`. The 'uirevision' property accepts values of any type Returns ------- Any """ return self["uirevision"] @uirevision.setter def uirevision(self, val): self["uirevision"] = val @property def _prop_descriptions(self): return """\ color Sets default for all colors associated with this axis all at once: line, font, tick, and grid colors. Grid color is lightened by blending this with the plot background Individual pieces can override this. dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. "SI" uses prefixes from "femto" f (10^-15) to "tera" T (10^12). *SI extended* covers instead the full SI range from "quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or *SI extended* is used and the exponent is beyond the above ranges, the formatting rule will automatically be switched to the power notation. gridcolor Sets the color of the grid lines. griddash Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). gridwidth Sets the width (in px) of the grid lines. hoverformat Sets the hover text formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" labelalias Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use −1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html-like tags or MathJax. layer Sets the layer on which this axis is displayed. If *above traces*, this axis is displayed above all the subplot's traces If *below traces*, this axis is displayed below all the subplot's traces, but above the grid lines. Useful when used together with scatter-like traces with `cliponaxis` set to False to show markers and/or text nodes above this axis. linecolor Sets the axis line color. linewidth Sets the width (in px) of the axis line. min The minimum value visible on this axis. The maximum is determined by the sum minus the minimum values of the other two axes. The full view corresponds to all the minima set to zero. minexponent Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". separatethousands If "true", even 4-digit integers are separated showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showgrid Determines whether or not grid lines are drawn. If True, the grid lines are drawn at every tick mark. showline Determines whether or not a line bounding this axis is drawn. showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the tick font. tickformat Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.layout.ternary. baxis.Tickformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.layout.tern ary.baxis.tickformatstopdefaults), sets the default property values to use for elements of layout.ternary.baxis.tickformatstops ticklabelstep Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for `ticktext`. tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for `tickvals`. tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.layout.ternary.baxis.Title ` instance or dict with compatible properties uirevision Controls persistence of user-driven changes in axis `min`, and `title` if in `editable: true` configuration. Defaults to `ternary<N>.uirevision`. """ def __init__( self, arg=None, color=None, dtick=None, exponentformat=None, gridcolor=None, griddash=None, gridwidth=None, hoverformat=None, labelalias=None, layer=None, linecolor=None, linewidth=None, min=None, minexponent=None, nticks=None, separatethousands=None, showexponent=None, showgrid=None, showline=None, showticklabels=None, showtickprefix=None, showticksuffix=None, tick0=None, tickangle=None, tickcolor=None, tickfont=None, tickformat=None, tickformatstops=None, tickformatstopdefaults=None, ticklabelstep=None, ticklen=None, tickmode=None, tickprefix=None, ticks=None, ticksuffix=None, ticktext=None, ticktextsrc=None, tickvals=None, tickvalssrc=None, tickwidth=None, title=None, uirevision=None, **kwargs, ): """ Construct a new Baxis object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.layout.ternary.Baxis` color Sets default for all colors associated with this axis all at once: line, font, tick, and grid colors. Grid color is lightened by blending this with the plot background Individual pieces can override this. dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. "SI" uses prefixes from "femto" f (10^-15) to "tera" T (10^12). *SI extended* covers instead the full SI range from "quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or *SI extended* is used and the exponent is beyond the above ranges, the formatting rule will automatically be switched to the power notation. gridcolor Sets the color of the grid lines. griddash Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). gridwidth Sets the width (in px) of the grid lines. hoverformat Sets the hover text formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" labelalias Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use −1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html-like tags or MathJax. layer Sets the layer on which this axis is displayed. If *above traces*, this axis is displayed above all the subplot's traces If *below traces*, this axis is displayed below all the subplot's traces, but above the grid lines. Useful when used together with scatter-like traces with `cliponaxis` set to False to show markers and/or text nodes above this axis. linecolor Sets the axis line color. linewidth Sets the width (in px) of the axis line. min The minimum value visible on this axis. The maximum is determined by the sum minus the minimum values of the other two axes. The full view corresponds to all the minima set to zero. minexponent Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". separatethousands If "true", even 4-digit integers are separated showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showgrid Determines whether or not grid lines are drawn. If True, the grid lines are drawn at every tick mark. showline Determines whether or not a line bounding this axis is drawn. showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the tick font. tickformat Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.layout.ternary. baxis.Tickformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.layout.tern ary.baxis.tickformatstopdefaults), sets the default property values to use for elements of layout.ternary.baxis.tickformatstops ticklabelstep Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for `ticktext`. tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for `tickvals`. tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.layout.ternary.baxis.Title ` instance or dict with compatible properties uirevision Controls persistence of user-driven changes in axis `min`, and `title` if in `editable: true` configuration. Defaults to `ternary<N>.uirevision`. Returns ------- Baxis """ super().__init__("baxis") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.layout.ternary.Baxis constructor must be a dict or an instance of :class:`plotly.graph_objs.layout.ternary.Baxis`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("dtick", arg, dtick) self._set_property("exponentformat", arg, exponentformat) self._set_property("gridcolor", arg, gridcolor) self._set_property("griddash", arg, griddash) self._set_property("gridwidth", arg, gridwidth) self._set_property("hoverformat", arg, hoverformat) self._set_property("labelalias", arg, labelalias) self._set_property("layer", arg, layer) self._set_property("linecolor", arg, linecolor) self._set_property("linewidth", arg, linewidth) self._set_property("min", arg, min) self._set_property("minexponent", arg, minexponent) self._set_property("nticks", arg, nticks) self._set_property("separatethousands", arg, separatethousands) self._set_property("showexponent", arg, showexponent) self._set_property("showgrid", arg, showgrid) self._set_property("showline", arg, showline) self._set_property("showticklabels", arg, showticklabels) self._set_property("showtickprefix", arg, showtickprefix) self._set_property("showticksuffix", arg, showticksuffix) self._set_property("tick0", arg, tick0) self._set_property("tickangle", arg, tickangle) self._set_property("tickcolor", arg, tickcolor) self._set_property("tickfont", arg, tickfont) self._set_property("tickformat", arg, tickformat) self._set_property("tickformatstops", arg, tickformatstops) self._set_property("tickformatstopdefaults", arg, tickformatstopdefaults) self._set_property("ticklabelstep", arg, ticklabelstep) self._set_property("ticklen", arg, ticklen) self._set_property("tickmode", arg, tickmode) self._set_property("tickprefix", arg, tickprefix) self._set_property("ticks", arg, ticks) self._set_property("ticksuffix", arg, ticksuffix) self._set_property("ticktext", arg, ticktext) self._set_property("ticktextsrc", arg, ticktextsrc) self._set_property("tickvals", arg, tickvals) self._set_property("tickvalssrc", arg, tickvalssrc) self._set_property("tickwidth", arg, tickwidth) self._set_property("title", arg, title) self._set_property("uirevision", arg, uirevision) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Baxis
python
ray-project__ray
doc/source/custom_directives.py
{ "start": 14663, "end": 15079 }
class ____(ExampleEnum): RAY_TEAM = "Maintained by the Ray Team" COMMUNITY = "Contributed by the Ray Community" @property def tag(self): if self == Contributor.RAY_TEAM: return "ray-team" return "community" @classmethod def formatted_name(cls): return "All Examples" @classmethod def key(cls: type) -> str: return "contributor"
Contributor
python
numpy__numpy
numpy/_core/tests/test_stringdtype.py
{ "start": 7880, "end": 50192 }
class ____: def test_unicode_casts(self, dtype, strings): arr = np.array(strings, dtype=np.str_).astype(dtype) expected = np.array(strings, dtype=dtype) assert_array_equal(arr, expected) arr_as_U8 = expected.astype("U8") assert_array_equal(arr_as_U8, np.array(strings, dtype="U8")) assert_array_equal(arr_as_U8.astype(dtype), arr) arr_as_U3 = expected.astype("U3") assert_array_equal(arr_as_U3, np.array(strings, dtype="U3")) assert_array_equal( arr_as_U3.astype(dtype), np.array([s[:3] for s in strings], dtype=dtype), ) def test_void_casts(self, dtype, strings): sarr = np.array(strings, dtype=dtype) utf8_bytes = [s.encode("utf-8") for s in strings] void_dtype = f"V{max(len(s) for s in utf8_bytes)}" varr = np.array(utf8_bytes, dtype=void_dtype) assert_array_equal(varr, sarr.astype(void_dtype)) assert_array_equal(varr.astype(dtype), sarr) def test_bytes_casts(self, dtype, strings): sarr = np.array(strings, dtype=dtype) try: utf8_bytes = [s.encode("ascii") for s in strings] bytes_dtype = f"S{max(len(s) for s in utf8_bytes)}" barr = np.array(utf8_bytes, dtype=bytes_dtype) assert_array_equal(barr, sarr.astype(bytes_dtype)) assert_array_equal(barr.astype(dtype), sarr) if dtype.coerce: barr = np.array(utf8_bytes, dtype=dtype) assert_array_equal(barr, sarr) barr = np.array(utf8_bytes, dtype="O") assert_array_equal(barr.astype(dtype), sarr) else: with pytest.raises(ValueError): np.array(utf8_bytes, dtype=dtype) except UnicodeEncodeError: with pytest.raises(UnicodeEncodeError): sarr.astype("S20") def test_additional_unicode_cast(dtype): string_list = random_unicode_string_list() arr = np.array(string_list, dtype=dtype) # test that this short-circuits correctly assert_array_equal(arr, arr.astype(arr.dtype)) # tests the casts via the comparison promoter assert_array_equal(arr, arr.astype(string_list.dtype)) def test_insert_scalar(dtype, string_list): """Test that inserting a scalar works.""" arr = np.array(string_list, dtype=dtype) scalar_instance = "what" arr[1] = scalar_instance assert_array_equal( arr, np.array(string_list[:1] + ["what"] + string_list[2:], dtype=dtype), ) comparison_operators = [ np.equal, np.not_equal, np.greater, np.greater_equal, np.less, np.less_equal, ] @pytest.mark.parametrize("op", comparison_operators) @pytest.mark.parametrize("o_dtype", [np.str_, object, StringDType()]) def test_comparisons(string_list, dtype, op, o_dtype): sarr = np.array(string_list, dtype=dtype) oarr = np.array(string_list, dtype=o_dtype) # test that comparison operators work res = op(sarr, sarr) ores = op(oarr, oarr) # test that promotion works as well orres = op(sarr, oarr) olres = op(oarr, sarr) assert_array_equal(res, ores) assert_array_equal(res, orres) assert_array_equal(res, olres) # test we get the correct answer for unequal length strings sarr2 = np.array([s + "2" for s in string_list], dtype=dtype) oarr2 = np.array([s + "2" for s in string_list], dtype=o_dtype) res = op(sarr, sarr2) ores = op(oarr, oarr2) olres = op(oarr, sarr2) orres = op(sarr, oarr2) assert_array_equal(res, ores) assert_array_equal(res, olres) assert_array_equal(res, orres) res = op(sarr2, sarr) ores = op(oarr2, oarr) olres = op(oarr2, sarr) orres = op(sarr2, oarr) assert_array_equal(res, ores) assert_array_equal(res, olres) assert_array_equal(res, orres) def test_isnan(dtype, string_list): if not hasattr(dtype, "na_object"): pytest.skip("no na support") sarr = np.array(string_list + [dtype.na_object], dtype=dtype) is_nan = isinstance(dtype.na_object, float) and np.isnan(dtype.na_object) bool_errors = 0 try: bool(dtype.na_object) except TypeError: bool_errors = 1 if is_nan or bool_errors: # isnan is only true when na_object is a NaN assert_array_equal( np.isnan(sarr), np.array([0] * len(string_list) + [1], dtype=np.bool), ) else: assert not np.any(np.isnan(sarr)) def test_pickle(dtype, string_list): arr = np.array(string_list, dtype=dtype) with tempfile.NamedTemporaryFile("wb", delete=False) as f: pickle.dump([arr, dtype], f) with open(f.name, "rb") as f: res = pickle.load(f) assert_array_equal(res[0], arr) assert res[1] == dtype os.remove(f.name) def test_stdlib_copy(dtype, string_list): arr = np.array(string_list, dtype=dtype) assert_array_equal(copy.copy(arr), arr) assert_array_equal(copy.deepcopy(arr), arr) @pytest.mark.parametrize( "strings", [ ["left", "right", "leftovers", "righty", "up", "down"], [ "left" * 10, "right" * 10, "leftovers" * 10, "righty" * 10, "up" * 10, ], ["🤣🤣", "🤣", "📵", "😰"], ["🚜", "🙃", "😾"], ["😹", "🚠", "🚌"], ["A¢☃€ 😊", " A☃€¢😊", "☃€😊 A¢", "😊☃A¢ €"], ], ) def test_sort(dtype, strings): """Test that sorting matches python's internal sorting.""" def test_sort(strings, arr_sorted): arr = np.array(strings, dtype=dtype) na_object = getattr(arr.dtype, "na_object", "") if na_object is None and None in strings: with pytest.raises( ValueError, match="Cannot compare null that is not a nan-like value", ): np.argsort(arr) argsorted = None elif na_object is pd_NA or na_object != '': argsorted = None else: argsorted = np.argsort(arr) np.random.default_rng().shuffle(arr) if na_object is None and None in strings: with pytest.raises( ValueError, match="Cannot compare null that is not a nan-like value", ): arr.sort() else: arr.sort() assert np.array_equal(arr, arr_sorted, equal_nan=True) if argsorted is not None: assert np.array_equal(argsorted, np.argsort(strings)) # make a copy so we don't mutate the lists in the fixture strings = strings.copy() arr_sorted = np.array(sorted(strings), dtype=dtype) test_sort(strings, arr_sorted) if not hasattr(dtype, "na_object"): return # make sure NAs get sorted to the end of the array and string NAs get # sorted like normal strings strings.insert(0, dtype.na_object) strings.insert(2, dtype.na_object) # can't use append because doing that with NA converts # the result to object dtype if not isinstance(dtype.na_object, str): arr_sorted = np.array( arr_sorted.tolist() + [dtype.na_object, dtype.na_object], dtype=dtype, ) else: arr_sorted = np.array(sorted(strings), dtype=dtype) test_sort(strings, arr_sorted) @pytest.mark.parametrize( "strings", [ ["A¢☃€ 😊", " A☃€¢😊", "☃€😊 A¢", "😊☃A¢ €"], ["A¢☃€ 😊", "", " ", " "], ["", "a", "😸", "ááðfáíóåéë"], ], ) def test_nonzero(strings, na_object): dtype = get_dtype(na_object) arr = np.array(strings, dtype=dtype) is_nonzero = np.array( [i for i, item in enumerate(strings) if len(item) != 0]) assert_array_equal(arr.nonzero()[0], is_nonzero) if na_object is not pd_NA and na_object == 'unset': return strings_with_na = np.array(strings + [na_object], dtype=dtype) is_nan = np.isnan(np.array([dtype.na_object], dtype=dtype))[0] if is_nan: assert strings_with_na.nonzero()[0][-1] == 4 else: assert strings_with_na.nonzero()[0][-1] == 3 # check that the casting to bool and nonzero give consistent results assert_array_equal(strings_with_na[strings_with_na.nonzero()], strings_with_na[strings_with_na.astype(bool)]) def test_where(string_list, na_object): dtype = get_dtype(na_object) a = np.array(string_list, dtype=dtype) b = a[::-1] res = np.where([True, False, True, False, True, False], a, b) assert_array_equal(res, [a[0], b[1], a[2], b[3], a[4], b[5]]) def test_fancy_indexing(string_list): sarr = np.array(string_list, dtype="T") assert_array_equal(sarr, sarr[np.arange(sarr.shape[0])]) inds = [ [True, True], [0, 1], ..., np.array([0, 1], dtype='uint8'), ] lops = [ ['a' * 25, 'b' * 25], ['', ''], ['hello', 'world'], ['hello', 'world' * 25], ] # see gh-27003 and gh-27053 for ind in inds: for lop in lops: a = np.array(lop, dtype="T") assert_array_equal(a[ind], a) rop = ['d' * 25, 'e' * 25] for b in [rop, np.array(rop, dtype="T")]: a[ind] = b assert_array_equal(a, b) assert a[0] == 'd' * 25 # see gh-29279 data = [ ["AAAAAAAAAAAAAAAAA"], ["BBBBBBBBBBBBBBBBBBBBBBBBBBBBB"], ["CCCCCCCCCCCCCCCCC"], ["DDDDDDDDDDDDDDDDD"], ] sarr = np.array(data, dtype=np.dtypes.StringDType()) uarr = np.array(data, dtype="U30") for ind in [[0], [1], [2], [3], [[0, 0]], [[1, 1, 3]], [[1, 1]]]: assert_array_equal(sarr[ind], uarr[ind]) def test_flatiter_indexing(): # see gh-29659 arr = np.array(['hello', 'world'], dtype='T') arr.flat[:] = 9223372036854775 assert_array_equal(arr, np.array([9223372036854775] * 2, dtype='T')) def test_creation_functions(): assert_array_equal(np.zeros(3, dtype="T"), ["", "", ""]) assert_array_equal(np.empty(3, dtype="T"), ["", "", ""]) assert np.zeros(3, dtype="T")[0] == "" assert np.empty(3, dtype="T")[0] == "" def test_concatenate(string_list): sarr = np.array(string_list, dtype="T") sarr_cat = np.array(string_list + string_list, dtype="T") assert_array_equal(np.concatenate([sarr], axis=0), sarr) def test_resize_method(string_list): sarr = np.array(string_list, dtype="T") if IS_PYPY: sarr.resize(len(string_list) + 3, refcheck=False) else: sarr.resize(len(string_list) + 3) assert_array_equal(sarr, np.array(string_list + [''] * 3, dtype="T")) def test_create_with_copy_none(string_list): arr = np.array(string_list, dtype=StringDType()) # create another stringdtype array with an arena that has a different # in-memory layout than the first array arr_rev = np.array(string_list[::-1], dtype=StringDType()) # this should create a copy and the resulting array # shouldn't share an allocator or arena with arr_rev, despite # explicitly passing arr_rev.dtype arr_copy = np.array(arr, copy=None, dtype=arr_rev.dtype) np.testing.assert_array_equal(arr, arr_copy) assert arr_copy.base is None with pytest.raises(ValueError, match="Unable to avoid copy"): np.array(arr, copy=False, dtype=arr_rev.dtype) # because we're using arr's dtype instance, the view is safe arr_view = np.array(arr, copy=None, dtype=arr.dtype) np.testing.assert_array_equal(arr, arr) np.testing.assert_array_equal(arr_view[::-1], arr_rev) assert arr_view is arr def test_astype_copy_false(): orig_dt = StringDType() arr = np.array(["hello", "world"], dtype=StringDType()) assert not arr.astype(StringDType(coerce=False), copy=False).dtype.coerce assert arr.astype(orig_dt, copy=False).dtype is orig_dt @pytest.mark.parametrize( "strings", [ ["left", "right", "leftovers", "righty", "up", "down"], ["🤣🤣", "🤣", "📵", "😰"], ["🚜", "🙃", "😾"], ["😹", "🚠", "🚌"], ["A¢☃€ 😊", " A☃€¢😊", "☃€😊 A¢", "😊☃A¢ €"], ], ) def test_argmax(strings): """Test that argmax/argmin matches what python calculates.""" arr = np.array(strings, dtype="T") assert np.argmax(arr) == strings.index(max(strings)) assert np.argmin(arr) == strings.index(min(strings)) @pytest.mark.parametrize( "arrfunc,expected", [ [np.sort, None], [np.nonzero, (np.array([], dtype=np.int_),)], [np.argmax, 0], [np.argmin, 0], ], ) def test_arrfuncs_zeros(arrfunc, expected): arr = np.zeros(10, dtype="T") result = arrfunc(arr) if expected is None: expected = arr assert_array_equal(result, expected, strict=True) @pytest.mark.parametrize( ("strings", "cast_answer", "any_answer", "all_answer"), [ [["hello", "world"], [True, True], True, True], [["", ""], [False, False], False, False], [["hello", ""], [True, False], True, False], [["", "world"], [False, True], True, False], ], ) def test_cast_to_bool(strings, cast_answer, any_answer, all_answer): sarr = np.array(strings, dtype="T") assert_array_equal(sarr.astype("bool"), cast_answer) assert np.any(sarr) == any_answer assert np.all(sarr) == all_answer @pytest.mark.parametrize( ("strings", "cast_answer"), [ [[True, True], ["True", "True"]], [[False, False], ["False", "False"]], [[True, False], ["True", "False"]], [[False, True], ["False", "True"]], ], ) def test_cast_from_bool(strings, cast_answer): barr = np.array(strings, dtype=bool) assert_array_equal(barr.astype("T"), np.array(cast_answer, dtype="T")) @pytest.mark.parametrize("bitsize", [8, 16, 32, 64]) @pytest.mark.parametrize("signed", [True, False]) def test_sized_integer_casts(bitsize, signed): idtype = f"int{bitsize}" if signed: inp = [-(2**p - 1) for p in reversed(range(bitsize - 1))] inp += [2**p - 1 for p in range(1, bitsize - 1)] else: idtype = "u" + idtype inp = [2**p - 1 for p in range(bitsize)] ainp = np.array(inp, dtype=idtype) assert_array_equal(ainp, ainp.astype("T").astype(idtype)) # safe casting works ainp.astype("T", casting="safe") with pytest.raises(TypeError): ainp.astype("T").astype(idtype, casting="safe") oob = [str(2**bitsize), str(-(2**bitsize))] with pytest.raises(OverflowError): np.array(oob, dtype="T").astype(idtype) with pytest.raises(ValueError): np.array(["1", np.nan, "3"], dtype=StringDType(na_object=np.nan)).astype(idtype) @pytest.mark.parametrize("typename", ["byte", "short", "int", "longlong"]) @pytest.mark.parametrize("signed", ["", "u"]) def test_unsized_integer_casts(typename, signed): idtype = f"{signed}{typename}" inp = [1, 2, 3, 4] ainp = np.array(inp, dtype=idtype) assert_array_equal(ainp, ainp.astype("T").astype(idtype)) @pytest.mark.parametrize( "typename", [ pytest.param( "longdouble", marks=pytest.mark.xfail( np.dtypes.LongDoubleDType() != np.dtypes.Float64DType(), reason="numpy lacks an ld2a implementation", strict=True, ), ), "float64", "float32", "float16", ], ) def test_float_casts(typename): inp = [1.1, 2.8, -3.2, 2.7e4] ainp = np.array(inp, dtype=typename) assert_array_equal(ainp, ainp.astype("T").astype(typename)) inp = [0.1] sres = np.array(inp, dtype=typename).astype("T") res = sres.astype(typename) assert_array_equal(np.array(inp, dtype=typename), res) assert sres[0] == "0.1" if typename == "longdouble": # let's not worry about platform-dependent rounding of longdouble return fi = np.finfo(typename) inp = [1e-324, fi.smallest_subnormal, -1e-324, -fi.smallest_subnormal] eres = [0, fi.smallest_subnormal, -0, -fi.smallest_subnormal] res = np.array(inp, dtype=typename).astype("T").astype(typename) assert_array_equal(eres, res) inp = [2e308, fi.max, -2e308, fi.min] eres = [np.inf, fi.max, -np.inf, fi.min] res = np.array(inp, dtype=typename).astype("T").astype(typename) assert_array_equal(eres, res) def test_float_nan_cast_na_object(): # gh-28157 dt = np.dtypes.StringDType(na_object=np.nan) arr1 = np.full((1,), fill_value=np.nan, dtype=dt) arr2 = np.full_like(arr1, fill_value=np.nan) assert arr1.item() is np.nan assert arr2.item() is np.nan inp = [1.2, 2.3, np.nan] arr = np.array(inp).astype(dt) assert arr[2] is np.nan assert arr[0] == '1.2' @pytest.mark.parametrize( "typename", [ "csingle", "cdouble", pytest.param( "clongdouble", marks=pytest.mark.xfail( np.dtypes.CLongDoubleDType() != np.dtypes.Complex128DType(), reason="numpy lacks an ld2a implementation", strict=True, ), ), ], ) def test_cfloat_casts(typename): inp = [1.1 + 1.1j, 2.8 + 2.8j, -3.2 - 3.2j, 2.7e4 + 2.7e4j] ainp = np.array(inp, dtype=typename) assert_array_equal(ainp, ainp.astype("T").astype(typename)) inp = [0.1 + 0.1j] sres = np.array(inp, dtype=typename).astype("T") res = sres.astype(typename) assert_array_equal(np.array(inp, dtype=typename), res) assert sres[0] == "(0.1+0.1j)" def test_take(string_list): sarr = np.array(string_list, dtype="T") res = sarr.take(np.arange(len(string_list))) assert_array_equal(sarr, res) # make sure it also works for out out = np.empty(len(string_list), dtype="T") out[0] = "hello" res = sarr.take(np.arange(len(string_list)), out=out) assert res is out assert_array_equal(sarr, res) @pytest.mark.parametrize("use_out", [True, False]) @pytest.mark.parametrize( "ufunc_name,func", [ ("min", min), ("max", max), ], ) def test_ufuncs_minmax(string_list, ufunc_name, func, use_out): """Test that the min/max ufuncs match Python builtin min/max behavior.""" arr = np.array(string_list, dtype="T") uarr = np.array(string_list, dtype=str) res = np.array(func(string_list), dtype="T") assert_array_equal(getattr(arr, ufunc_name)(), res) ufunc = getattr(np, ufunc_name + "imum") if use_out: res = ufunc(arr, arr, out=arr) else: res = ufunc(arr, arr) assert_array_equal(uarr, res) assert_array_equal(getattr(arr, ufunc_name)(), func(string_list)) def test_max_regression(): arr = np.array(['y', 'y', 'z'], dtype="T") assert arr.max() == 'z' @pytest.mark.parametrize("use_out", [True, False]) @pytest.mark.parametrize( "other_strings", [ ["abc", "def" * 500, "ghi" * 16, "🤣" * 100, "📵", "😰"], ["🚜", "🙃", "😾", "😹", "🚠", "🚌"], ["🥦", "¨", "⨯", "∰ ", "⨌ ", "⎶ "], ], ) def test_ufunc_add(dtype, string_list, other_strings, use_out): arr1 = np.array(string_list, dtype=dtype) arr2 = np.array(other_strings, dtype=dtype) result = np.array([a + b for a, b in zip(arr1, arr2)], dtype=dtype) if use_out: res = np.add(arr1, arr2, out=arr1) else: res = np.add(arr1, arr2) assert_array_equal(res, result) if not hasattr(dtype, "na_object"): return is_nan = isinstance(dtype.na_object, float) and np.isnan(dtype.na_object) is_str = isinstance(dtype.na_object, str) bool_errors = 0 try: bool(dtype.na_object) except TypeError: bool_errors = 1 arr1 = np.array([dtype.na_object] + string_list, dtype=dtype) arr2 = np.array(other_strings + [dtype.na_object], dtype=dtype) if is_nan or bool_errors or is_str: res = np.add(arr1, arr2) assert_array_equal(res[1:-1], arr1[1:-1] + arr2[1:-1]) if not is_str: assert res[0] is dtype.na_object and res[-1] is dtype.na_object else: assert res[0] == dtype.na_object + arr2[0] assert res[-1] == arr1[-1] + dtype.na_object else: with pytest.raises(ValueError): np.add(arr1, arr2) def test_ufunc_add_reduce(dtype): values = ["a", "this is a long string", "c"] arr = np.array(values, dtype=dtype) out = np.empty((), dtype=dtype) expected = np.array("".join(values), dtype=dtype) assert_array_equal(np.add.reduce(arr), expected) np.add.reduce(arr, out=out) assert_array_equal(out, expected) def test_add_promoter(string_list): arr = np.array(string_list, dtype=StringDType()) lresult = np.array(["hello" + s for s in string_list], dtype=StringDType()) rresult = np.array([s + "hello" for s in string_list], dtype=StringDType()) for op in ["hello", np.str_("hello"), np.array(["hello"])]: assert_array_equal(op + arr, lresult) assert_array_equal(arr + op, rresult) # The promoter should be able to handle things if users pass `dtype=` res = np.add("hello", string_list, dtype=StringDType) assert res.dtype == StringDType() # The promoter should not kick in if users override the input, # which means arr is cast, this fails because of the unknown length. with pytest.raises(TypeError, match="cannot cast dtype"): np.add(arr, "add", signature=("U", "U", None), casting="unsafe") # But it must simply reject the following: with pytest.raises(TypeError, match=".*did not contain a loop"): np.add(arr, "add", signature=(None, "U", None)) with pytest.raises(TypeError, match=".*did not contain a loop"): np.add("a", "b", signature=("U", "U", StringDType)) def test_add_no_legacy_promote_with_signature(): # Possibly misplaced, but useful to test with string DType. We check that # if there is clearly no loop found, a stray `dtype=` doesn't break things # Regression test for the bad error in gh-26735 # (If legacy promotion is gone, this can be deleted...) with pytest.raises(TypeError, match=".*did not contain a loop"): np.add("3", 6, dtype=StringDType) def test_add_promoter_reduce(): # Exact TypeError could change, but ensure StringDtype doesn't match with pytest.raises(TypeError, match="the resolved dtypes are not"): np.add.reduce(np.array(["a", "b"], dtype="U")) # On the other hand, using `dtype=T` in the *ufunc* should work. np.add.reduce(np.array(["a", "b"], dtype="U"), dtype=np.dtypes.StringDType) def test_multiply_reduce(): # At the time of writing (NumPy 2.0) this is very limited (and rather # ridiculous anyway). But it works and actually makes some sense... # (NumPy does not allow non-scalar initial values) repeats = np.array([2, 3, 4]) val = "school-🚌" res = np.multiply.reduce(repeats, initial=val, dtype=np.dtypes.StringDType) assert res == val * np.prod(repeats) def test_multiply_two_string_raises(): arr = np.array(["hello", "world"], dtype="T") with pytest.raises(np._core._exceptions._UFuncNoLoopError): np.multiply(arr, arr) @pytest.mark.parametrize("use_out", [True, False]) @pytest.mark.parametrize("other", [2, [2, 1, 3, 4, 1, 3]]) @pytest.mark.parametrize( "other_dtype", [ None, "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", "short", "int", "intp", "long", "longlong", "ushort", "uint", "uintp", "ulong", "ulonglong", ], ) def test_ufunc_multiply(dtype, string_list, other, other_dtype, use_out): """Test the two-argument ufuncs match python builtin behavior.""" arr = np.array(string_list, dtype=dtype) if other_dtype is not None: other_dtype = np.dtype(other_dtype) try: len(other) result = [s * o for s, o in zip(string_list, other)] other = np.array(other) if other_dtype is not None: other = other.astype(other_dtype) except TypeError: if other_dtype is not None: other = other_dtype.type(other) result = [s * other for s in string_list] if use_out: arr_cache = arr.copy() lres = np.multiply(arr, other, out=arr) assert_array_equal(lres, result) arr[:] = arr_cache assert lres is arr arr *= other assert_array_equal(arr, result) arr[:] = arr_cache rres = np.multiply(other, arr, out=arr) assert rres is arr assert_array_equal(rres, result) else: lres = arr * other assert_array_equal(lres, result) rres = other * arr assert_array_equal(rres, result) if not hasattr(dtype, "na_object"): return is_nan = np.isnan(np.array([dtype.na_object], dtype=dtype))[0] is_str = isinstance(dtype.na_object, str) bool_errors = 0 try: bool(dtype.na_object) except TypeError: bool_errors = 1 arr = np.array(string_list + [dtype.na_object], dtype=dtype) try: len(other) other = np.append(other, 3) if other_dtype is not None: other = other.astype(other_dtype) except TypeError: pass if is_nan or bool_errors or is_str: for res in [arr * other, other * arr]: assert_array_equal(res[:-1], result) if not is_str: assert res[-1] is dtype.na_object else: try: assert res[-1] == dtype.na_object * other[-1] except (IndexError, TypeError): assert res[-1] == dtype.na_object * other else: with pytest.raises(TypeError): arr * other with pytest.raises(TypeError): other * arr def test_findlike_promoters(): r = "Wally" l = "Where's Wally?" s = np.int32(3) e = np.int8(13) for dtypes in [("T", "U"), ("U", "T")]: for function, answer in [ (np.strings.index, 8), (np.strings.endswith, True), ]: assert answer == function( np.array(l, dtype=dtypes[0]), np.array(r, dtype=dtypes[1]), s, e ) def test_strip_promoter(): arg = ["Hello!!!!", "Hello??!!"] strip_char = "!" answer = ["Hello", "Hello??"] for dtypes in [("T", "U"), ("U", "T")]: result = np.strings.strip( np.array(arg, dtype=dtypes[0]), np.array(strip_char, dtype=dtypes[1]) ) assert_array_equal(result, answer) assert result.dtype.char == "T" def test_replace_promoter(): arg = ["Hello, planet!", "planet, Hello!"] old = "planet" new = "world" answer = ["Hello, world!", "world, Hello!"] for dtypes in itertools.product("TU", repeat=3): if dtypes == ("U", "U", "U"): continue answer_arr = np.strings.replace( np.array(arg, dtype=dtypes[0]), np.array(old, dtype=dtypes[1]), np.array(new, dtype=dtypes[2]), ) assert_array_equal(answer_arr, answer) assert answer_arr.dtype.char == "T" def test_center_promoter(): arg = ["Hello", "planet!"] fillchar = "/" for dtypes in [("T", "U"), ("U", "T")]: answer = np.strings.center( np.array(arg, dtype=dtypes[0]), 9, np.array(fillchar, dtype=dtypes[1]) ) assert_array_equal(answer, ["//Hello//", "/planet!/"]) assert answer.dtype.char == "T" DATETIME_INPUT = [ np.datetime64("1923-04-14T12:43:12"), np.datetime64("1994-06-21T14:43:15"), np.datetime64("2001-10-15T04:10:32"), np.datetime64("NaT"), np.datetime64("1995-11-25T16:02:16"), np.datetime64("2005-01-04T03:14:12"), np.datetime64("2041-12-03T14:05:03"), ] TIMEDELTA_INPUT = [ np.timedelta64(12358, "s"), np.timedelta64(23, "s"), np.timedelta64(74, "s"), np.timedelta64("NaT"), np.timedelta64(23, "s"), np.timedelta64(73, "s"), np.timedelta64(7, "s"), ] @pytest.mark.parametrize( "input_data, input_dtype", [ (DATETIME_INPUT, "M8[s]"), (TIMEDELTA_INPUT, "m8[s]") ] ) def test_datetime_timedelta_cast(dtype, input_data, input_dtype): a = np.array(input_data, dtype=input_dtype) has_na = hasattr(dtype, "na_object") is_str = isinstance(getattr(dtype, "na_object", None), str) if not has_na or is_str: a = np.delete(a, 3) sa = a.astype(dtype) ra = sa.astype(a.dtype) if has_na and not is_str: assert sa[3] is dtype.na_object assert np.isnat(ra[3]) assert_array_equal(a, ra) if has_na and not is_str: # don't worry about comparing how NaT is converted sa = np.delete(sa, 3) a = np.delete(a, 3) if input_dtype.startswith("M"): assert_array_equal(sa, a.astype("U")) else: # The timedelta to unicode cast produces strings # that aren't round-trippable and we don't want to # reproduce that behavior in stringdtype assert_array_equal(sa, a.astype("int64").astype("U")) def test_nat_casts(): s = 'nat' all_nats = itertools.product(*zip(s.upper(), s.lower())) all_nats = list(map(''.join, all_nats)) NaT_dt = np.datetime64('NaT') NaT_td = np.timedelta64('NaT') for na_object in [np._NoValue, None, np.nan, 'nat', '']: # numpy treats empty string and all case combinations of 'nat' as NaT dtype = StringDType(na_object=na_object) arr = np.array([''] + all_nats, dtype=dtype) dt_array = arr.astype('M8[s]') td_array = arr.astype('m8[s]') assert_array_equal(dt_array, NaT_dt) assert_array_equal(td_array, NaT_td) if na_object is np._NoValue: output_object = 'NaT' else: output_object = na_object for arr in [dt_array, td_array]: assert_array_equal( arr.astype(dtype), np.array([output_object] * arr.size, dtype=dtype)) def test_nat_conversion(): for nat in [np.datetime64("NaT", "s"), np.timedelta64("NaT", "s")]: with pytest.raises(ValueError, match="string coercion is disabled"): np.array(["a", nat], dtype=StringDType(coerce=False)) def test_growing_strings(dtype): # growing a string leads to a heap allocation, this tests to make sure # we do that bookkeeping correctly for all possible starting cases data = [ "hello", # a short string "abcdefghijklmnopqestuvwxyz", # a medium heap-allocated string "hello" * 200, # a long heap-allocated string ] arr = np.array(data, dtype=dtype) uarr = np.array(data, dtype=str) for _ in range(5): arr = arr + arr uarr = uarr + uarr assert_array_equal(arr, uarr) def test_assign_medium_strings(): # see gh-29261 N = 9 src = np.array( ( ['0' * 256] * 3 + ['0' * 255] + ['0' * 256] + ['0' * 255] + ['0' * 256] * 2 + ['0' * 255] ), dtype='T') dst = np.array( ( ['0' * 255] + ['0' * 256] * 2 + ['0' * 255] + ['0' * 256] + ['0' * 255] + [''] * 5 ), dtype='T') dst[1:N + 1] = src assert_array_equal(dst[1:N + 1], src) UFUNC_TEST_DATA = [ "hello" * 10, "Ae¢☃€ 😊" * 20, "entry\nwith\nnewlines", "entry\twith\ttabs", ] @pytest.fixture def string_array(dtype): return np.array(UFUNC_TEST_DATA, dtype=dtype) @pytest.fixture def unicode_array(): return np.array(UFUNC_TEST_DATA, dtype=np.str_) NAN_PRESERVING_FUNCTIONS = [ "capitalize", "expandtabs", "lower", "lstrip", "rstrip", "splitlines", "strip", "swapcase", "title", "upper", ] BOOL_OUTPUT_FUNCTIONS = [ "isalnum", "isalpha", "isdigit", "islower", "isspace", "istitle", "isupper", "isnumeric", "isdecimal", ] UNARY_FUNCTIONS = [ "str_len", "capitalize", "expandtabs", "isalnum", "isalpha", "isdigit", "islower", "isspace", "istitle", "isupper", "lower", "lstrip", "rstrip", "splitlines", "strip", "swapcase", "title", "upper", "isnumeric", "isdecimal", "isalnum", "islower", "istitle", "isupper", ] UNIMPLEMENTED_VEC_STRING_FUNCTIONS = [ "capitalize", "expandtabs", "lower", "splitlines", "swapcase", "title", "upper", ] ONLY_IN_NP_CHAR = [ "join", "split", "rsplit", "splitlines" ] @pytest.mark.parametrize("function_name", UNARY_FUNCTIONS) def test_unary(string_array, unicode_array, function_name): if function_name in ONLY_IN_NP_CHAR: func = getattr(np.char, function_name) else: func = getattr(np.strings, function_name) dtype = string_array.dtype sres = func(string_array) ures = func(unicode_array) if sres.dtype == StringDType(): ures = ures.astype(StringDType()) assert_array_equal(sres, ures) if not hasattr(dtype, "na_object"): return is_nan = np.isnan(np.array([dtype.na_object], dtype=dtype))[0] is_str = isinstance(dtype.na_object, str) na_arr = np.insert(string_array, 0, dtype.na_object) if function_name in UNIMPLEMENTED_VEC_STRING_FUNCTIONS: if not is_str: # to avoid these errors we'd need to add NA support to _vec_string with pytest.raises((ValueError, TypeError)): func(na_arr) elif function_name == "splitlines": assert func(na_arr)[0] == func(dtype.na_object)[()] else: assert func(na_arr)[0] == func(dtype.na_object) return if function_name == "str_len" and not is_str: # str_len always errors for any non-string null, even NA ones because # it has an integer result with pytest.raises(ValueError): func(na_arr) return if function_name in BOOL_OUTPUT_FUNCTIONS: if is_nan: assert func(na_arr)[0] is np.False_ elif is_str: assert func(na_arr)[0] == func(dtype.na_object) else: with pytest.raises(ValueError): func(na_arr) return if not (is_nan or is_str): with pytest.raises(ValueError): func(na_arr) return res = func(na_arr) if is_nan and function_name in NAN_PRESERVING_FUNCTIONS: assert res[0] is dtype.na_object elif is_str: assert res[0] == func(dtype.na_object) unicode_bug_fail = pytest.mark.xfail( reason="unicode output width is buggy", strict=True ) # None means that the argument is a string array BINARY_FUNCTIONS = [ ("add", (None, None)), ("multiply", (None, 2)), ("mod", ("format: %s", None)), ("center", (None, 25)), ("count", (None, "A")), ("encode", (None, "UTF-8")), ("endswith", (None, "lo")), ("find", (None, "A")), ("index", (None, "e")), ("join", ("-", None)), ("ljust", (None, 12)), ("lstrip", (None, "A")), ("partition", (None, "A")), ("replace", (None, "A", "B")), ("rfind", (None, "A")), ("rindex", (None, "e")), ("rjust", (None, 12)), ("rsplit", (None, "A")), ("rstrip", (None, "A")), ("rpartition", (None, "A")), ("split", (None, "A")), ("strip", (None, "A")), ("startswith", (None, "A")), ("zfill", (None, 12)), ] PASSES_THROUGH_NAN_NULLS = [ "add", "center", "ljust", "multiply", "replace", "rjust", "strip", "lstrip", "rstrip", "replace" "zfill", ] NULLS_ARE_FALSEY = [ "startswith", "endswith", ] NULLS_ALWAYS_ERROR = [ "count", "find", "rfind", ] SUPPORTS_NULLS = ( PASSES_THROUGH_NAN_NULLS + NULLS_ARE_FALSEY + NULLS_ALWAYS_ERROR ) def call_func(func, args, array, sanitize=True): if args == (None, None): return func(array, array) if args[0] is None: if sanitize: san_args = tuple( np.array(arg, dtype=array.dtype) if isinstance(arg, str) else arg for arg in args[1:] ) else: san_args = args[1:] return func(array, *san_args) if args[1] is None: return func(args[0], array) # shouldn't ever happen assert 0 @pytest.mark.parametrize("function_name, args", BINARY_FUNCTIONS) def test_binary(string_array, unicode_array, function_name, args): if function_name in ONLY_IN_NP_CHAR: func = getattr(np.char, function_name) else: func = getattr(np.strings, function_name) sres = call_func(func, args, string_array) ures = call_func(func, args, unicode_array, sanitize=False) if not isinstance(sres, tuple) and sres.dtype == StringDType(): ures = ures.astype(StringDType()) assert_array_equal(sres, ures) dtype = string_array.dtype if function_name not in SUPPORTS_NULLS or not hasattr(dtype, "na_object"): return na_arr = np.insert(string_array, 0, dtype.na_object) is_nan = np.isnan(np.array([dtype.na_object], dtype=dtype))[0] is_str = isinstance(dtype.na_object, str) should_error = not (is_nan or is_str) if ( (function_name in NULLS_ALWAYS_ERROR and not is_str) or (function_name in PASSES_THROUGH_NAN_NULLS and should_error) or (function_name in NULLS_ARE_FALSEY and should_error) ): with pytest.raises((ValueError, TypeError)): call_func(func, args, na_arr) return res = call_func(func, args, na_arr) if is_str: assert res[0] == call_func(func, args, na_arr[:1]) elif function_name in NULLS_ARE_FALSEY: assert res[0] is np.False_ elif function_name in PASSES_THROUGH_NAN_NULLS: assert res[0] is dtype.na_object else: # shouldn't ever get here assert 0 @pytest.mark.parametrize("function, expected", [ (np.strings.find, [[2, -1], [1, -1]]), (np.strings.startswith, [[False, False], [True, False]])]) @pytest.mark.parametrize("start, stop", [ (1, 4), (np.int8(1), np.int8(4)), (np.array([1, 1], dtype='u2'), np.array([4, 4], dtype='u2'))]) def test_non_default_start_stop(function, start, stop, expected): a = np.array([["--🐍--", "--🦜--"], ["-🐍---", "-🦜---"]], "T") indx = function(a, "🐍", start, stop) assert_array_equal(indx, expected) @pytest.mark.parametrize("count", [2, np.int8(2), np.array([2, 2], 'u2')]) def test_replace_non_default_repeat(count): a = np.array(["🐍--", "🦜-🦜-"], "T") result = np.strings.replace(a, "🦜-", "🦜†", count) assert_array_equal(result, np.array(["🐍--", "🦜†🦜†"], "T")) def test_strip_ljust_rjust_consistency(string_array, unicode_array): rjs = np.char.rjust(string_array, 1000) rju = np.char.rjust(unicode_array, 1000) ljs = np.char.ljust(string_array, 1000) lju = np.char.ljust(unicode_array, 1000) assert_array_equal( np.char.lstrip(rjs), np.char.lstrip(rju).astype(StringDType()), ) assert_array_equal( np.char.rstrip(ljs), np.char.rstrip(lju).astype(StringDType()), ) assert_array_equal( np.char.strip(ljs), np.char.strip(lju).astype(StringDType()), ) assert_array_equal( np.char.strip(rjs), np.char.strip(rju).astype(StringDType()), ) def test_unset_na_coercion(): # a dtype instance with an unset na object is compatible # with a dtype that has one set # this test uses the "add" and "equal" ufunc but all ufuncs that # accept more than one string argument and produce a string should # behave this way # TODO: generalize to more ufuncs inp = ["hello", "world"] arr = np.array(inp, dtype=StringDType(na_object=None)) for op_dtype in [None, StringDType(), StringDType(coerce=False), StringDType(na_object=None)]: if op_dtype is None: op = "2" else: op = np.array("2", dtype=op_dtype) res = arr + op assert_array_equal(res, ["hello2", "world2"]) # dtype instances with distinct explicitly set NA objects are incompatible for op_dtype in [StringDType(na_object=pd_NA), StringDType(na_object="")]: op = np.array("2", dtype=op_dtype) with pytest.raises(TypeError): arr + op # comparisons only consider the na_object for op_dtype in [None, StringDType(), StringDType(coerce=True), StringDType(na_object=None)]: if op_dtype is None: op = inp else: op = np.array(inp, dtype=op_dtype) assert_array_equal(arr, op) for op_dtype in [StringDType(na_object=pd_NA), StringDType(na_object=np.nan)]: op = np.array(inp, dtype=op_dtype) with pytest.raises(TypeError): arr == op def test_repeat(string_array): res = string_array.repeat(1000) # Create an empty array with expanded dimension, and fill it. Then, # reshape it to the expected result. expected = np.empty_like(string_array, shape=string_array.shape + (1000,)) expected[...] = string_array[:, np.newaxis] expected = expected.reshape(-1) assert_array_equal(res, expected, strict=True) @pytest.mark.parametrize("tile", [1, 6, (2, 5)]) def test_accumulation(string_array, tile): """Accumulation is odd for StringDType but tests dtypes with references. """ # Fill with mostly empty strings to not create absurdly big strings arr = np.zeros_like(string_array, shape=(100,)) arr[:len(string_array)] = string_array arr[-len(string_array):] = string_array # Bloat size a bit (get above thresholds and test >1 ndim). arr = np.tile(string_array, tile) res = np.add.accumulate(arr, axis=0) res_obj = np.add.accumulate(arr.astype(object), axis=0) assert_array_equal(res, res_obj.astype(arr.dtype), strict=True) if arr.ndim > 1: res = np.add.accumulate(arr, axis=-1) res_obj = np.add.accumulate(arr.astype(object), axis=-1) assert_array_equal(res, res_obj.astype(arr.dtype), strict=True)
TestStringLikeCasts
python
PrefectHQ__prefect
tests/server/orchestration/api/ui/test_task_runs.py
{ "start": 10626, "end": 11821 }
class ____: async def test_read_task_run( self, flow_run: orm_models.FlowRun, task_run: orm_models.TaskRun, client: AsyncClient, ): response = await client.get(f"/ui/task_runs/{task_run.id}") assert response.status_code == status.HTTP_200_OK assert response.json()["id"] == str(task_run.id) assert response.json()["flow_run_id"] == str(flow_run.id) assert response.json()["flow_run_name"] == flow_run.name async def test_read_task_without_flow_run( self, task_run_without_flow_run: orm_models.TaskRun, client: AsyncClient ): response = await client.get(f"/ui/task_runs/{task_run_without_flow_run.id}") assert response.status_code == status.HTTP_200_OK assert response.json()["id"] == str(task_run_without_flow_run.id) assert response.json()["flow_run_id"] is None assert response.json()["flow_run_name"] is None async def test_read_task_run_returns_404_if_does_not_exist( self, client: AsyncClient ): response = await client.get(f"/ui/task_runs/{uuid4()}") assert response.status_code == status.HTTP_404_NOT_FOUND
TestReadTaskRun
python
numba__numba
numba/cuda/tests/cudapy/test_record_dtype.py
{ "start": 9106, "end": 18769 }
class ____(CUDATestCase): # These tests mirror those from # numba.tests.test_record_dtype.TestNestedArrays added in PR # #7359: https://github.com/numba/numba/pull/7359 # The code cannot be shared between the two classes without modification, # as the CUDA test implementations need to be launched (and in some cases # wrapped in an outer function to handle the return value). Otherwise, the # code here is kept as similar to that in the equivalent CPU tests as # possible. # Reading records / recarrays def get_cfunc(self, pyfunc, retty): # Create a host-callable function for testing CUDA device functions # that get a value from a record array inner = cuda.jit(device=True)(pyfunc) @cuda.jit def outer(arg0, res): res[0] = inner(arg0) def host(arg0): res = np.zeros(1, dtype=retty) outer[1, 1](arg0, res) return res[0] return host def test_record_read_array(self): # Test reading from a 1D array within a structured type nbval = np.recarray(1, dtype=recordwitharray) nbval[0].h[0] = 15.0 nbval[0].h[1] = 25.0 cfunc = self.get_cfunc(record_read_array0, np.float32) res = cfunc(nbval[0]) np.testing.assert_equal(res, nbval[0].h[0]) cfunc = self.get_cfunc(record_read_array1, np.float32) res = cfunc(nbval[0]) np.testing.assert_equal(res, nbval[0].h[1]) def test_record_read_2d_array(self): # Test reading from a 2D array within a structured type nbval = np.recarray(1, dtype=recordwith2darray) nbval[0].j = np.asarray([1.5, 2.5, 3.5, 4.5, 5.5, 6.5], np.float32).reshape(3, 2) cfunc = self.get_cfunc(record_read_2d_array00, np.float32) res = cfunc(nbval[0]) np.testing.assert_equal(res, nbval[0].j[0, 0]) cfunc = self.get_cfunc(record_read_2d_array01, np.float32) res = cfunc(nbval[0]) np.testing.assert_equal(res, nbval[0].j[0, 1]) cfunc = self.get_cfunc(record_read_2d_array10, np.float32) res = cfunc(nbval[0]) np.testing.assert_equal(res, nbval[0].j[1, 0]) def test_setitem(self): def gen(): nbarr1 = np.recarray(1, dtype=recordwith2darray) nbarr1[0] = np.array([(1, ((1, 2), (4, 5), (2, 3)))], dtype=recordwith2darray)[0] nbarr2 = np.recarray(1, dtype=recordwith2darray) nbarr2[0] = np.array([(10, ((10, 20), (40, 50), (20, 30)))], dtype=recordwith2darray)[0] return nbarr1[0], nbarr2[0] pyfunc = record_setitem_array pyargs = gen() pyfunc(*pyargs) cfunc = cuda.jit(pyfunc) cuargs = gen() cfunc[1, 1](*cuargs) np.testing.assert_equal(pyargs, cuargs) def test_getitem_idx(self): # Test __getitem__ with numerical index # This tests returning a record when passing an array and # returning the first item when passing a record nbarr = np.recarray(2, dtype=recordwitharray) nbarr[0] = np.array([(1, (2, 3))], dtype=recordwitharray)[0] for arg, retty in [(nbarr, recordwitharray), (nbarr[0], np.int32)]: pyfunc = recarray_getitem_return arr_expected = pyfunc(arg) cfunc = self.get_cfunc(pyfunc, retty) arr_res = cfunc(arg) np.testing.assert_equal(arr_res, arr_expected) # Writing to records / recarrays @skip_on_cudasim('Structured array attr access not supported in simulator') def test_set_record(self): # Test setting an entire record rec = np.ones(2, dtype=recordwith2darray).view(np.recarray)[0] nbarr = np.zeros(2, dtype=recordwith2darray).view(np.recarray) arr = np.zeros(2, dtype=recordwith2darray).view(np.recarray) pyfunc = recarray_set_record pyfunc(arr, rec) kernel = cuda.jit(pyfunc) kernel[1, 1](nbarr, rec) np.testing.assert_equal(nbarr, arr) def test_assign_array_to_nested(self): src = (np.arange(3) + 1).astype(np.int16) got = np.zeros(2, dtype=nested_array1_dtype) expected = np.zeros(2, dtype=nested_array1_dtype) pyfunc = assign_array_to_nested kernel = cuda.jit(pyfunc) kernel[1, 1](got[0], src) pyfunc(expected[0], src) np.testing.assert_array_equal(expected, got) def test_assign_array_to_nested_2d(self): src = (np.arange(6) + 1).astype(np.int16).reshape((3, 2)) got = np.zeros(2, dtype=nested_array2_dtype) expected = np.zeros(2, dtype=nested_array2_dtype) pyfunc = assign_array_to_nested_2d kernel = cuda.jit(pyfunc) kernel[1, 1](got[0], src) pyfunc(expected[0], src) np.testing.assert_array_equal(expected, got) def test_issue_7693(self): src_dtype = np.dtype([ ("user", np.float64), ("array", np.int16, (3,))], align=True) dest_dtype = np.dtype([ ("user1", np.float64), ("array1", np.int16, (3,))], align=True) @cuda.jit def copy(index, src, dest): dest['user1'] = src[index]['user'] dest['array1'] = src[index]['array'] source = np.zeros(2, dtype=src_dtype) got = np.zeros(2, dtype=dest_dtype) expected = np.zeros(2, dtype=dest_dtype) source[0] = (1.2, [1, 2, 3]) copy[1, 1](0, source, got[0]) copy.py_func(0, source, expected[0]) np.testing.assert_array_equal(expected, got) # Reading and returning arrays from recarrays - the following functions are # all xfailed because CUDA cannot handle returning arrays from device # functions (or creating arrays in general). @unittest.expectedFailure def test_getitem_idx_2darray(self): # Test __getitem__ with numerical index # # This test returning a record when passing an array and # return the first item when passing a record nbarr = np.recarray(2, dtype=recordwith2darray) nbarr[0] = np.array([(1, ((1,2),(4,5),(2,3)))], dtype=recordwith2darray)[0] for arg, retty in [(nbarr, recordwith2darray), (nbarr[0], (np.float32, (3, 2)))]: pyfunc = recarray_getitem_field_return2_2d arr_expected = pyfunc(arg) cfunc = self.get_cfunc(pyfunc, retty) arr_res = cfunc(arg) np.testing.assert_equal(arr_res, arr_expected) @unittest.expectedFailure def test_return_getattr_getitem_fieldname(self): # Test __getitem__ with field name and getattr .field_name # # This tests returning a array of nestedarrays when passing an array and # returning a nestedarray when passing a record nbarr = np.recarray(2, dtype=recordwitharray) nbarr[0] = np.array([(1, (2,3))], dtype=recordwitharray)[0] for arg, retty in [(nbarr, recordwitharray), (nbarr[0], np.float32)]: for pyfunc in [recarray_getitem_field_return, recarray_getitem_field_return2]: arr_expected = pyfunc(arg) cfunc = self.get_cfunc(pyfunc, retty) arr_res = cfunc(arg) np.testing.assert_equal(arr_res, arr_expected) @unittest.expectedFailure def test_record_read_arrays(self): # Test reading from a 1D array within a structured type nbval = np.recarray(2, dtype=recordwitharray) nbval[0].h[0] = 15.0 nbval[0].h[1] = 25.0 nbval[1].h[0] = 35.0 nbval[1].h[1] = 45.4 cfunc = self.get_cfunc(record_read_whole_array, np.float32) res = cfunc(nbval) np.testing.assert_equal(res, nbval.h) @unittest.expectedFailure def test_return_array(self): # Test getitem record AND array within record and returning it nbval = np.recarray(2, dtype=recordwitharray) nbval[0] = np.array([(1, (2,3))], dtype=recordwitharray)[0] pyfunc = record_read_array0 arr_expected = pyfunc(nbval) cfunc = self.get_cfunc(pyfunc, np.float32) arr_res = cfunc(nbval) np.testing.assert_equal(arr_expected, arr_res) @skip_on_cudasim('Will unexpectedly pass on cudasim') @unittest.expectedFailure def test_set_array(self): #Test setting an entire array within one record arr = np.zeros(2, dtype=recordwith2darray).view(np.recarray) rec = arr[0] nbarr = np.zeros(2, dtype=recordwith2darray).view(np.recarray) nbrec = nbarr[0] for pyfunc in (record_write_full_array, record_write_full_array_alt): pyfunc(rec) kernel = cuda.jit(pyfunc) kernel[1, 1](nbrec) np.testing.assert_equal(nbarr, arr) @unittest.expectedFailure def test_set_arrays(self): # Test setting an entire array of arrays (multiple records) arr = np.zeros(2, dtype=recordwith2darray).view(np.recarray) nbarr = np.zeros(2, dtype=recordwith2darray).view(np.recarray) for pyfunc in ( recarray_write_array_of_nestedarray_broadcast, recarray_write_array_of_nestedarray, ): arr_expected = pyfunc(arr) cfunc = self.get_cfunc(pyfunc, nbarr.dtype) arr_res = cfunc(nbarr) np.testing.assert_equal(arr_res, arr_expected) if __name__ == '__main__': unittest.main()
TestNestedArrays
python
viewflow__viewflow
tests/workflow/test_fields__token.py
{ "start": 204, "end": 792 }
class ____(TestCase): # noqa: D101 def test_crud(self): obj = TokenTestModel.objects.create(token=Token('start')) self.assertEqual(obj.token, Token('start')) obj = TokenTestModel.objects.get() self.assertEqual(obj.token, Token('start')) obj = TokenTestModel.objects.filter(token=Token('start')).first() self.assertEqual(obj.token, Token('start')) def test_forms(self): form = TokenTestForm(data={'token': 'start'}) form.is_valid() obj = form.save() self.assertEqual(obj.token, Token('start'))
Test
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zenloop/source_zenloop/source.py
{ "start": 346, "end": 469 }
class ____(YamlDeclarativeSource): def __init__(self): super().__init__(path_to_yaml="manifest.yaml")
SourceZenloop
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-wordlift/llama_index/vector_stores/wordlift/metadata_filters_to_filters.py
{ "start": 159, "end": 3298 }
class ____: @staticmethod def metadata_filters_to_filters(metadata_filters: MetadataFilters): # Return an empty list if there are no filters. if ( not hasattr(metadata_filters, "filters") or len(metadata_filters.filters) == 0 ): return [] # Only one filter. if len(metadata_filters.filters) == 1: metadata_filter = metadata_filters.filters[0] return [ Filter( key=metadata_filter.key, operator=MetadataFiltersToFilters.metadata_filter_operator_to_filter_operator( metadata_filter.operator ), value=FilterValue(metadata_filter.value), ) ] # Prepare the list of filters. filters = [] for metadata_filter in metadata_filters.filters: filters.append( Filter( key=metadata_filter.key, operator=MetadataFiltersToFilters.metadata_filter_operator_to_filter_operator( metadata_filter.operator ), value=FilterValue(metadata_filter.value), ) ) # Join the filters abed on the metadata filter condition. return [ Filter( operator=MetadataFiltersToFilters.metadata_filter_condition_to_filter_operators( metadata_filters.condition ), filters=filters, ) ] @staticmethod def metadata_filter_operator_to_filter_operator(filter_operator: FilterOperator): # 'EQ', 'GT', 'LT', 'NE', 'GTE', 'LTE', 'IN', 'NIN', 'AND', 'OR' if filter_operator == FilterOperator.EQ: return "EQ" # default operator (string, int, float) elif filter_operator == FilterOperator.GT: return "GT" # greater than (int, float) elif filter_operator == FilterOperator.LT: return "LT" # less than (int, float) elif filter_operator == FilterOperator.NE: return "NE" # not equal to (string, int, float) elif filter_operator == FilterOperator.GTE: return "GTE" # greater than or equal to (int, float) elif filter_operator == FilterOperator.LTE: return "LTE" # less than or equal to (int, float) elif filter_operator == FilterOperator.IN: return "IN" # In array (string or number) elif filter_operator == FilterOperator.NIN: return "NIN" # Not in array (string or number) else: raise ValueError(f"Invalid filter operator: {filter_operator}") @staticmethod def metadata_filter_condition_to_filter_operators( filter_condition: FilterCondition, ): if filter_condition == FilterCondition.AND: return "AND" elif filter_condition == FilterCondition.OR: return "OR" else: raise ValueError(f"Invalid filter condition: {filter_condition}")
MetadataFiltersToFilters
python
getsentry__sentry
src/sentry/integrations/source_code_management/metrics.py
{ "start": 1514, "end": 2362 }
class ____(IntegrationEventLifecycleMetric): """ An instance to be recorded of an SCM integration feature call. """ interaction_type: SCMIntegrationInteractionType provider_key: str integration_id: int | None = None organization_id: int | None = None def get_integration_domain(self) -> IntegrationDomain: return IntegrationDomain.SOURCE_CODE_MANAGEMENT def get_integration_name(self) -> str: return self.provider_key def get_interaction_type(self) -> str: return str(self.interaction_type) def get_extras(self) -> Mapping[str, Any]: return { "organization_id": (self.organization_id if self.organization_id else None), "integration_id": (self.integration_id if self.integration_id else None), } @dataclass
SCMIntegrationInteractionEvent
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 118561, "end": 118872 }
class ____(BaseModel): vector_data: Optional[Dict[str, "VectorDataConfig"]] = Field(default={}, description="") sparse_vector_data: Optional[Dict[str, "SparseVectorDataConfig"]] = Field(default=None, description="") payload_storage_type: "PayloadStorageType" = Field(..., description="")
SegmentConfig
python
sphinx-doc__sphinx
sphinx/domains/cpp/_ast.py
{ "start": 68295, "end": 69804 }
class ____(ASTBase): def __init__( self, arg: ASTTypeWithInit | ASTTemplateParamConstrainedTypeWithInit, ellipsis: bool = False, ) -> None: self.arg = arg self.ellipsis = ellipsis def __eq__(self, other: object) -> bool: if not isinstance(other, ASTFunctionParameter): return NotImplemented return self.arg == other.arg and self.ellipsis == other.ellipsis def __hash__(self) -> int: return hash((self.arg, self.ellipsis)) def get_id( self, version: int, objectType: str | None = None, symbol: Symbol | None = None ) -> str: # this is not part of the normal name mangling in C++ if symbol: # the anchor will be our parent return symbol.parent.declaration.get_id(version, prefixed=False) # else, do the usual if self.ellipsis: return 'z' else: return self.arg.get_id(version) def _stringify(self, transform: StringifyTransform) -> str: if self.ellipsis: return '...' else: return transform(self.arg) def describe_signature( self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol ) -> None: verify_description_mode(mode) if self.ellipsis: signode += addnodes.desc_sig_punctuation('...', '...') else: self.arg.describe_signature(signode, mode, env, symbol=symbol)
ASTFunctionParameter
python
kamyu104__LeetCode-Solutions
Python/find-closest-number-to-zero.py
{ "start": 37, "end": 226 }
class ____(object): def findClosestNumber(self, nums): """ :type nums: List[int] :rtype: int """ return max(nums, key=lambda x:(-abs(x), x))
Solution
python
huggingface__transformers
src/transformers/models/sew/modular_sew.py
{ "start": 18218, "end": 18390 }
class ____(Wav2Vec2ForSequenceClassification): pass __all__ = ["SEWForCTC", "SEWForSequenceClassification", "SEWModel", "SEWPreTrainedModel"]
SEWForSequenceClassification
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/engine/result.py
{ "start": 28295, "end": 29128 }
class ____: __slots__ = () _metadata: ResultMetaData # used mainly to share documentation on the keys method. def keys(self) -> RMKeyView: """Return an iterable view which yields the string keys that would be represented by each :class:`_engine.Row`. The keys can represent the labels of the columns returned by a core statement or the names of the orm classes returned by an orm execution. The view also can be tested for key containment using the Python ``in`` operator, which will test both for the string keys represented in the view, as well as for alternate keys such as column objects. .. versionchanged:: 1.4 a key view object is returned rather than a plain list. """ return self._metadata.keys
_WithKeys
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE807.py
{ "start": 159, "end": 302 }
class ____(BaseTable): foo = fields.ListField(default=lambda: []) # PIE807 bar = fields.ListField(default=lambda: {}) # PIE807
FooTable
python
ray-project__ray
rllib/core/testing/testing_learner.py
{ "start": 1830, "end": 2464 }
class ____(Learner): @override(Learner) def after_gradient_based_update(self, *, timesteps): # This is to check if in the multi-gpu case, the weights across workers are # the same. It is really only needed during testing. if self.config.report_mean_weights: for module_id in self.module.keys(): parameters = convert_to_numpy( self.get_parameters(self.module[module_id]) ) mean_ws = np.mean([w.mean() for w in parameters]) self.metrics.log_value((module_id, "mean_weight"), mean_ws, window=1)
BaseTestingLearner
python
conda__conda
conda/auxlib/entity.py
{ "start": 23505, "end": 25516 }
class ____(type): @staticmethod def __get_entity_subclasses(bases): try: return [base for base in bases if issubclass(base, Entity) and base is not Entity] except NameError: # NameError: global name 'Entity' is not defined return () def __new__(mcs, name, bases, dct): # if we're about to mask a field that's already been created with something that's # not a field, then assign it to an alternate variable name non_field_keys = ( key for key, value in dct.items() if not isinstance(value, Field) and not key.startswith("__") ) entity_subclasses = EntityType.__get_entity_subclasses(bases) if entity_subclasses: keys_to_override = [key for key in non_field_keys if any(isinstance(base.__dict__.get(key), Field) for base in entity_subclasses)] dct[KEY_OVERRIDES_MAP] = {key: dct.pop(key) for key in keys_to_override} else: dct[KEY_OVERRIDES_MAP] = {} return super().__new__(mcs, name, bases, dct) def __init__(cls, name, bases, attr): super().__init__(name, bases, attr) fields = odict() _field_sort_key = lambda x: x[1]._order_helper for clz in reversed(type.mro(cls)): clz_fields = ( (name, field.set_name(name)) for name, field in clz.__dict__.items() if isinstance(field, Field) ) fields.update(sorted(clz_fields, key=_field_sort_key)) cls.__fields__ = frozendict(fields) if hasattr(cls, '__register__'): cls.__register__() def __call__(cls, *args, **kwargs): instance = super().__call__(*args, **kwargs) setattr(instance, f"_{cls.__name__}__initd", True) return instance @property def fields(cls): return cls.__fields__.keys()
EntityType
python
spyder-ide__spyder
spyder/plugins/toolbar/container.py
{ "start": 1335, "end": 1593 }
class ____(QAction): """Wrapper class around QAction that allows to set/get an identifier.""" @property def action_id(self): return self._action_id @action_id.setter def action_id(self, act): self._action_id = act
QActionID
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 63380, "end": 63553 }
class ____(_PrintableStructure): _fields_ = [ ('version', c_uint), ('placementId', c_uint), ] VgpuPlacementId_v1 = 0x1000008
c_nvmlVgpuPlacementId_v1_t
python
readthedocs__readthedocs.org
readthedocs/config/models.py
{ "start": 789, "end": 864 }
class ____(ConfigBaseModel): version: str full_version: str
BuildTool
python
MongoEngine__mongoengine
mongoengine/fields.py
{ "start": 66448, "end": 69916 }
class ____(GridFSProxy): """Proxy for ImageField""" def put(self, file_obj, **kwargs): """ Insert a image in database applying field properties (size, thumbnail_size) """ field = self.instance._fields[self.key] # Handle nested fields if hasattr(field, "field") and isinstance(field.field, FileField): field = field.field try: img = Image.open(file_obj) img_format = img.format except Exception as e: raise ValidationError("Invalid image: %s" % e) # Progressive JPEG # TODO: fixme, at least unused, at worst bad implementation progressive = img.info.get("progressive") or False if ( kwargs.get("progressive") and isinstance(kwargs.get("progressive"), bool) and img_format == "JPEG" ): progressive = True else: progressive = False if field.size and ( img.size[0] > field.size["width"] or img.size[1] > field.size["height"] ): size = field.size if size["force"]: img = ImageOps.fit(img, (size["width"], size["height"]), LANCZOS) else: img.thumbnail((size["width"], size["height"]), LANCZOS) thumbnail = None if field.thumbnail_size: size = field.thumbnail_size if size["force"]: thumbnail = ImageOps.fit(img, (size["width"], size["height"]), LANCZOS) else: thumbnail = img.copy() thumbnail.thumbnail((size["width"], size["height"]), LANCZOS) if thumbnail: thumb_id = self._put_thumbnail(thumbnail, img_format, progressive) else: thumb_id = None w, h = img.size io = BytesIO() img.save(io, img_format, progressive=progressive) io.seek(0) return super().put( io, width=w, height=h, format=img_format, thumbnail_id=thumb_id, **kwargs ) def delete(self, *args, **kwargs): # deletes thumbnail out = self.get() if out and out.thumbnail_id: self.fs.delete(out.thumbnail_id, session=_get_session()) return super().delete() def _put_thumbnail(self, thumbnail, format, progressive, **kwargs): w, h = thumbnail.size io = BytesIO() thumbnail.save(io, format, progressive=progressive) io.seek(0) return self.fs.put(io, width=w, height=h, format=format, **kwargs) @property def size(self): """ return a width, height of image """ out = self.get() if out: return out.width, out.height @property def format(self): """ return format of image ex: PNG, JPEG, GIF, etc """ out = self.get() if out: return out.format @property def thumbnail(self): """ return a gridfs.grid_file.GridOut representing a thumbnail of Image """ out = self.get() if out and out.thumbnail_id: return self.fs.get(out.thumbnail_id, session=_get_session()) def write(self, *args, **kwargs): raise RuntimeError('Please use "put" method instead') def writelines(self, *args, **kwargs): raise RuntimeError('Please use "put" method instead')
ImageGridFsProxy
python
getsentry__sentry
src/sentry/discover/endpoints/discover_key_transactions.py
{ "start": 964, "end": 1188 }
class ____(OrganizationPermission): scope_map = { "GET": ["org:read"], "POST": ["org:read"], "PUT": ["org:read"], "DELETE": ["org:read"], } @region_silo_endpoint
KeyTransactionPermission
python
airbytehq__airbyte
airbyte-integrations/connectors/source-outbrain-amplify/source_outbrain_amplify/source.py
{ "start": 47302, "end": 52141 }
class ____(AbstractSource): def check_connection(self, logger, config) -> Tuple[bool, any]: url_base = OutbrainAmplifyStream.url_base auth = OutbrainAmplifyAuthenticator(url_base=url_base, config=config) try: auth.get_auth_header() marketer_stream = Marketers(authenticator=auth, config=config) next(marketer_stream.read_records(SyncMode.full_refresh)) return True, None except Exception as e: return False, e def streams(self, config: Mapping[str, Any]) -> List[Stream]: url_base = OutbrainAmplifyStream.url_base auth = OutbrainAmplifyAuthenticator(url_base=url_base, config=config) # Basic stream marketing # 1. All Marketing streams stream = [Marketers(authenticator=auth, config=config)] # Campaigns Streams. # 1. Campaigns by marketers (implemented). # 2. Camapings Geo Location (implemented). stream.extend( [ CampaignsByMarketers(authenticator=auth, config=config, parent=Marketers(authenticator=auth, config=config)), CampaignsGeoLocation( authenticator=auth, config=config, parent=CampaignsByMarketers(authenticator=auth, config=config, parent=Marketers(authenticator=auth, config=config)), ), ] ) # Budget for Marketers stream. # 1. Budget stream based on marketers id. (stream.extend([BudgetsForMarketers(authenticator=auth, config=config, parent=Marketers(authenticator=auth, config=config))]),) # Promoted Links stream. # 1. Promoted Links stream for campaigns. stream.extend( [ PromotedLinksForCampaigns( authenticator=auth, config=config, parent=CampaignsByMarketers(authenticator=auth, config=config, parent=Marketers(authenticator=auth, config=config)), ) ] ) # Promoted Links Sequences stream. # 1. Promoted Links Sequences stream for campaigns. stream.extend( [ PromotedLinksSequenceForCampaigns( authenticator=auth, config=config, parent=CampaignsByMarketers(authenticator=auth, config=config, parent=Marketers(authenticator=auth, config=config)), ) ] ) # Performance Reporting. # 1. Streams to retrieve performance statistics. stream.extend( [ PerformanceReportCampaignsByMarketers( authenticator=auth, config=config, parent=Marketers(authenticator=auth, config=config) ), PerformanceReportPeriodicByMarketers( authenticator=auth, config=config, parent=Marketers(authenticator=auth, config=config) ), PerformanceReportPeriodicByMarketersCampaign( authenticator=auth, config=config, parent=Marketers(authenticator=auth, config=config) ), PerformanceReportPeriodicContentByPromotedLinksCampaign( authenticator=auth, config=config, parent=CampaignsByMarketers(authenticator=auth, config=config, parent=Marketers(authenticator=auth, config=config)), ), PerformanceReportMarketersByPublisher( authenticator=auth, config=config, parent=Marketers(authenticator=auth, config=config) ), PerformanceReportPublishersByCampaigns( authenticator=auth, config=config, parent=Marketers(authenticator=auth, config=config) ), PerformanceReportMarketersByPlatforms( authenticator=auth, config=config, parent=Marketers(authenticator=auth, config=config) ), PerformanceReportMarketersCampaignsByPlatforms( authenticator=auth, config=config, parent=Marketers(authenticator=auth, config=config) ), PerformanceReportMarketersByGeoPerformance( authenticator=auth, config=config, parent=Marketers(authenticator=auth, config=config) ), PerformanceReportMarketersCampaignsByGeo( authenticator=auth, config=config, parent=Marketers(authenticator=auth, config=config) ), PerformanceReportMarketersByInterest( authenticator=auth, config=config, parent=Marketers(authenticator=auth, config=config) ), ] ) return stream
SourceOutbrainAmplify
python
pennersr__django-allauth
allauth/idp/oidc/adapter.py
{ "start": 612, "end": 4548 }
class ____(BaseAdapter): """The adapter class allows you to override various functionality of the ``allauth.idp.oidc`` app. To do so, point ``settings.IDP_OIDC_ADAPTER`` to your own class that derives from ``DefaultOIDCAdapter`` and override the behavior by altering the implementation of the methods according to your own needs. """ scope_display = { "openid": _("View your user ID"), "email": _("View your email address"), "profile": _("View your basic profile information"), } def generate_client_id(self) -> str: """ The client ID to use for newly created clients. """ return uuid.uuid4().hex def generate_client_secret(self) -> str: """ The client secret to use for newly created clients. """ return get_random_secret_key() def generate_user_code(self) -> str: return generate_user_code(length=8) def hash_token(self, token: str) -> str: """ We don't store tokens directly, only the hash of the token. This methods generates that hash. """ return hashlib.sha256(token.encode("utf-8")).hexdigest() def get_issuer(self) -> str: """ Returns the URL of the issuer. """ return self.request.build_absolute_uri("/").rstrip("/") def populate_id_token(self, id_token: dict, client, scopes, **kwargs) -> None: """ This method can be used to alter the ID token payload. It is already populated with basic values. Depending on the client and requested scopes, you can expose additional information here. """ pass def get_claims( self, purpose: Literal["id_token", "userinfo"], user, client, scopes: Iterable, email: Optional[str] = None, **kwargs, ) -> Dict[str, Any]: """ Return the claims to be included in the ID token or userinfo response. """ claims = {"sub": self.get_user_sub(client, user)} if "email" in scopes: if email: try: address = EmailAddress.objects.get_for_user(user, email) except EmailAddress.DoesNotExist: pass else: address = EmailAddress.objects.get_primary(user) if address: claims.update( { "email": address.email, "email_verified": address.verified, } ) if "profile" in scopes: full_name = user.get_full_name() last_name = getattr(user, "last_name", None) first_name = getattr(user, "first_name", None) username = user_username(user) profile_claims = { "name": full_name, "given_name": first_name, "family_name": last_name, "preferred_username": username, } for claim_key, claim_value in profile_claims.items(): if claim_value: claims[claim_key] = claim_value return claims def get_user_sub(self, client, user) -> str: """ Returns the "sub" (subject identifier) for the given user. """ return user_id_to_str(user) def get_user_by_sub(self, client, sub: str): """ Looks up a user, given its subject identifier. Returns `None` if no such user was found. """ try: pk = str_to_user_id(sub) except ValueError: return None user = get_user_model().objects.filter(pk=pk).first() if not user or not user.is_active: return None return user def get_adapter() -> DefaultOIDCAdapter: return import_attribute(app_settings.ADAPTER)()
DefaultOIDCAdapter
python
sqlalchemy__sqlalchemy
test/ext/test_associationproxy.py
{ "start": 28915, "end": 29543 }
class ____(_CollectionOperations): collection_class = ObjectCollection def test_basic(self): Parent = self.classes.Parent self.session = fixture_session() p = Parent("p1") self.assert_(len(list(p.children)) == 0) p.children.append("child") self.assert_(len(list(p.children)) == 1) p = self.roundtrip(p) self.assert_(len(list(p.children)) == 1) # We didn't provide an alternate _AssociationList implementation # for our ObjectCollection, so indexing will fail. assert_raises(TypeError, p.children.__getitem__, 1)
CustomObjectTest
python
jina-ai__jina
tests/integration/docarray_v2/test_issues.py
{ "start": 295, "end": 347 }
class ____(BaseDoc): nested: Nested2Doc
Nested1Doc
python
conda__conda
conda/models/match_spec.py
{ "start": 34431, "end": 34778 }
class ____(_StrMatchMixin, MatchInterface): __slots__ = ("_raw_value",) def __init__(self, value): super().__init__(value) def match(self, other): try: _other_val = other._raw_value except AttributeError: _other_val = str(other) return self._raw_value == _other_val
ExactStrMatch
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/clsregistry.py
{ "start": 12722, "end": 18274 }
class ____: __slots__ = ( "cls", "prop", "arg", "fallback", "_dict", "_resolvers", "tables_only", ) cls: Type[Any] prop: RelationshipProperty[Any] fallback: Mapping[str, Any] arg: str tables_only: bool _resolvers: Tuple[Callable[[str], Any], ...] def __init__( self, cls: Type[Any], prop: RelationshipProperty[Any], fallback: Mapping[str, Any], arg: str, tables_only: bool = False, ): self.cls = cls self.prop = prop self.arg = arg self.fallback = fallback self._dict = util.PopulateDict(self._access_cls) self._resolvers = () self.tables_only = tables_only def _access_cls(self, key: str) -> Any: cls = self.cls manager = attributes.manager_of_class(cls) decl_base = manager.registry assert decl_base is not None decl_class_registry = decl_base._class_registry metadata = decl_base.metadata if self.tables_only: if key in metadata.tables: return metadata.tables[key] elif key in metadata._schemas: return _GetTable(key, getattr(cls, "metadata", metadata)) if key in decl_class_registry: dt = _determine_container(key, decl_class_registry[key]) if self.tables_only: return dt.cls else: return dt if not self.tables_only: if key in metadata.tables: return metadata.tables[key] elif key in metadata._schemas: return _GetTable(key, getattr(cls, "metadata", metadata)) if "_sa_module_registry" in decl_class_registry and key in cast( _ModuleMarker, decl_class_registry["_sa_module_registry"] ): registry = cast( _ModuleMarker, decl_class_registry["_sa_module_registry"] ) return registry.resolve_attr(key) if self._resolvers: for resolv in self._resolvers: value = resolv(key) if value is not None: return value return self.fallback[key] def _raise_for_name(self, name: str, err: Exception) -> NoReturn: generic_match = re.match(r"(.+)\[(.+)\]", name) if generic_match: clsarg = generic_match.group(2).strip("'") raise exc.InvalidRequestError( f"When initializing mapper {self.prop.parent}, " f'expression "relationship({self.arg!r})" seems to be ' "using a generic class as the argument to relationship(); " "please state the generic argument " "using an annotation, e.g. " f'"{self.prop.key}: Mapped[{generic_match.group(1)}' f"['{clsarg}']] = relationship()\"" ) from err else: raise exc.InvalidRequestError( "When initializing mapper %s, expression %r failed to " "locate a name (%r). If this is a class name, consider " "adding this relationship() to the %r class after " "both dependent classes have been defined." % (self.prop.parent, self.arg, name, self.cls) ) from err def _resolve_name(self) -> Union[Table, Type[Any], _ModNS]: name = self.arg d = self._dict rval = None try: for token in name.split("."): if rval is None: rval = d[token] else: rval = getattr(rval, token) except KeyError as err: self._raise_for_name(name, err) except NameError as n: self._raise_for_name(n.args[0], n) else: if isinstance(rval, _GetColumns): return rval.cls else: if TYPE_CHECKING: assert isinstance(rval, (type, Table, _ModNS)) return rval def __call__(self) -> Any: if self.tables_only: try: return self._dict[self.arg] except KeyError as k: self._raise_for_name(self.arg, k) else: try: x = eval(self.arg, globals(), self._dict) if isinstance(x, _GetColumns): return x.cls else: return x except NameError as n: self._raise_for_name(n.args[0], n) _fallback_dict: Mapping[str, Any] = None # type: ignore def _resolver(cls: Type[Any], prop: RelationshipProperty[Any]) -> Tuple[ Callable[[str], Callable[[], Union[Type[Any], Table, _ModNS]]], Callable[[str, bool], _class_resolver], ]: global _fallback_dict if _fallback_dict is None: import sqlalchemy from . import foreign from . import remote _fallback_dict = util.immutabledict(sqlalchemy.__dict__).union( {"foreign": foreign, "remote": remote} ) def resolve_arg(arg: str, tables_only: bool = False) -> _class_resolver: return _class_resolver( cls, prop, _fallback_dict, arg, tables_only=tables_only ) def resolve_name( arg: str, ) -> Callable[[], Union[Type[Any], Table, _ModNS]]: return _class_resolver(cls, prop, _fallback_dict, arg)._resolve_name return resolve_name, resolve_arg
_class_resolver
python
django__django
tests/view_tests/tests/test_debug.py
{ "start": 83627, "end": 84993 }
class ____(SimpleTestCase): def test_sensitive_variables_not_called(self): msg = ( "sensitive_variables() must be called to use it as a decorator, " "e.g., use @sensitive_variables(), not @sensitive_variables." ) with self.assertRaisesMessage(TypeError, msg): @sensitive_variables def test_func(password): pass def test_sensitive_post_parameters_not_called(self): msg = ( "sensitive_post_parameters() must be called to use it as a " "decorator, e.g., use @sensitive_post_parameters(), not " "@sensitive_post_parameters." ) with self.assertRaisesMessage(TypeError, msg): @sensitive_post_parameters def test_func(request): return index_page(request) def test_sensitive_post_parameters_http_request(self): class MyClass: @sensitive_post_parameters() def a_view(self, request): return HttpResponse() msg = ( "sensitive_post_parameters didn't receive an HttpRequest object. " "If you are decorating a classmethod, make sure to use " "@method_decorator." ) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(HttpRequest())
DecoratorsTests